ada: Fix wrong resolution for hidden discriminant in predicate
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob2721251c4e4424ef85abf98d478a671877356e05
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.2.3.@*
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 , Jul 10, 2023
24 AdaCore
26 Copyright @copyright{} 2008-2023, 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.
1367 @item `Upper-Half Coding'
1369 @geindex Upper-Half Coding
1371 The wide character with encoding @code{16#abcd#} where the upper bit is on
1372 (in other words, ‘a’ is in the range 8-F) is represented as two bytes,
1373 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1374 character, but is not required to be in the upper half. This method can
1375 be also used for shift-JIS or EUC, where the internal coding matches the
1376 external coding.
1378 @item `Shift JIS Coding'
1380 @geindex Shift JIS Coding
1382 A wide character is represented by a two-character sequence,
1383 @code{16#ab#} and
1384 @code{16#cd#}, with the restrictions described for upper-half encoding as
1385 described above. The internal character code is the corresponding JIS
1386 character according to the standard algorithm for Shift-JIS
1387 conversion. Only characters defined in the JIS code set table can be
1388 used with this encoding method.
1390 @item `EUC Coding'
1392 @geindex EUC Coding
1394 A wide character is represented by a two-character sequence
1395 @code{16#ab#} and
1396 @code{16#cd#}, with both characters being in the upper half. The internal
1397 character code is the corresponding JIS character according to the EUC
1398 encoding algorithm. Only characters defined in the JIS code set table
1399 can be used with this encoding method.
1401 @item `UTF-8 Coding'
1403 A wide character is represented using
1404 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1405 10646-1/Am.2. Depending on the character value, the representation
1406 is a one, two, or three byte sequence:
1408 @example
1409 16#0000#-16#007f#: 2#0xxxxxxx#
1410 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1411 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1412 @end example
1414 where the @code{xxx} bits correspond to the left-padded bits of the
1415 16-bit character value. Note that all lower half ASCII characters
1416 are represented as ASCII bytes and all upper half characters and
1417 other wide characters are represented as sequences of upper-half
1418 (The full UTF-8 scheme allows for encoding 31-bit characters as
1419 6-byte sequences, and in the following section on wide wide
1420 characters, the use of these sequences is documented).
1422 @item `Brackets Coding'
1424 In this encoding, a wide character is represented by the following eight
1425 character sequence:
1427 @example
1428 [ " a b c d " ]
1429 @end example
1431 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1432 characters (using uppercase letters) of the wide character code. For
1433 example, [‘A345’] is used to represent the wide character with code
1434 @code{16#A345#}. It is also possible (though not required) to use the
1435 Brackets coding for upper half characters. For example, the code
1436 @code{16#A3#} can be represented as @code{['A3']}.
1438 This scheme is compatible with use of the full Wide_Character set,
1439 and is also the method used for wide character encoding in some standard
1440 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1441 @end table
1443 @cartouche
1444 @quotation Note 
1445 Some of these coding schemes do not permit the full use of the
1446 Ada character set. For example, neither Shift JIS nor EUC allow the
1447 use of the upper half of the Latin-1 set.
1448 @end quotation
1449 @end cartouche
1451 @node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1452 @anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{38}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{39}
1453 @subsection Wide_Wide_Character Encodings
1456 GNAT allows wide wide character codes to appear in character and string
1457 literals, and also optionally in identifiers, by means of the following
1458 possible encoding schemes:
1461 @table @asis
1463 @item `UTF-8 Coding'
1465 A wide character is represented using
1466 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1467 10646-1/Am.2. Depending on the character value, the representation
1468 of character codes with values greater than 16#FFFF# is a
1469 is a four, five, or six byte sequence:
1471 @example
1472 16#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1473                              10xxxxxx
1474 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1475                              10xxxxxx 10xxxxxx
1476 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1477                              10xxxxxx 10xxxxxx 10xxxxxx
1478 @end example
1480 where the @code{xxx} bits correspond to the left-padded bits of the
1481 32-bit character value.
1483 @item `Brackets Coding'
1485 In this encoding, a wide wide character is represented by the following ten or
1486 twelve byte character sequence:
1488 @example
1489 [ " a b c d e f " ]
1490 [ " a b c d e f g h " ]
1491 @end example
1493 where @code{a-h} are the six or eight hexadecimal
1494 characters (using uppercase letters) of the wide wide character code. For
1495 example, [“1F4567”] is used to represent the wide wide character with code
1496 @code{16#001F_4567#}.
1498 This scheme is compatible with use of the full Wide_Wide_Character set,
1499 and is also the method used for wide wide character encoding in some standard
1500 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1501 @end table
1503 @node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1504 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{24}@anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{3a}
1505 @section File Naming Topics and Utilities
1508 GNAT has a default file naming scheme and also provides the user with
1509 a high degree of control over how the names and extensions of the
1510 source files correspond to the Ada compilation units that they contain.
1512 @menu
1513 * File Naming Rules:: 
1514 * Using Other File Names:: 
1515 * Alternative File Naming Schemes:: 
1516 * Handling Arbitrary File Naming Conventions with gnatname:: 
1517 * File Name Krunching with gnatkr:: 
1518 * Renaming Files with gnatchop:: 
1520 @end menu
1522 @node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1523 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{3b}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{3c}
1524 @subsection File Naming Rules
1527 The default file name is determined by the name of the unit that the
1528 file contains. The name is formed by taking the full expanded name of
1529 the unit and replacing the separating dots with hyphens and using
1530 lowercase for all letters.
1532 An exception arises if the file name generated by the above rules starts
1533 with one of the characters
1534 @code{a}, @code{g}, @code{i}, or @code{s}, and the second character is a
1535 minus. In this case, the character tilde is used in place
1536 of the minus. The reason for this special rule is to avoid clashes with
1537 the standard names for child units of the packages System, Ada,
1538 Interfaces, and GNAT, which use the prefixes
1539 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
1540 respectively.
1542 The file extension is @code{.ads} for a spec and
1543 @code{.adb} for a body. The following table shows some
1544 examples of these rules.
1546 @quotation
1549 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
1550 @item
1552 Source File
1554 @tab
1556 Ada Compilation Unit
1558 @item
1560 @code{main.ads}
1562 @tab
1564 Main (spec)
1566 @item
1568 @code{main.adb}
1570 @tab
1572 Main (body)
1574 @item
1576 @code{arith_functions.ads}
1578 @tab
1580 Arith_Functions (package spec)
1582 @item
1584 @code{arith_functions.adb}
1586 @tab
1588 Arith_Functions (package body)
1590 @item
1592 @code{func-spec.ads}
1594 @tab
1596 Func.Spec (child package spec)
1598 @item
1600 @code{func-spec.adb}
1602 @tab
1604 Func.Spec (child package body)
1606 @item
1608 @code{main-sub.adb}
1610 @tab
1612 Sub (subunit of Main)
1614 @item
1616 @code{a~bad.adb}
1618 @tab
1620 A.Bad (child package body)
1622 @end multitable
1624 @end quotation
1626 Following these rules can result in excessively long
1627 file names if corresponding
1628 unit names are long (for example, if child units or subunits are
1629 heavily nested). An option is available to shorten such long file names
1630 (called file name ‘krunching’). This may be particularly useful when
1631 programs being developed with GNAT are to be used on operating systems
1632 with limited file name lengths. @ref{3d,,Using gnatkr}.
1634 Of course, no file shortening algorithm can guarantee uniqueness over
1635 all possible unit names; if file name krunching is used, it is your
1636 responsibility to ensure no name clashes occur. Alternatively you
1637 can specify the exact file names that you want used, as described
1638 in the next section. Finally, if your Ada programs are migrating from a
1639 compiler with a different naming convention, you can use the gnatchop
1640 utility to produce source files that follow the GNAT naming conventions.
1641 (For details see @ref{1d,,Renaming Files with gnatchop}.)
1643 Note: in the case of Windows or Mac OS operating systems, case is not
1644 significant. So for example on Windows if the canonical name is
1645 @code{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1646 However, case is significant for other operating systems, so for example,
1647 if you want to use other than canonically cased file names on a Unix system,
1648 you need to follow the procedures described in the next section.
1650 @node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1651 @anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{3e}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{1c}
1652 @subsection Using Other File Names
1655 @geindex File names
1657 In the previous section, we have described the default rules used by
1658 GNAT to determine the file name in which a given unit resides. It is
1659 often convenient to follow these default rules, and if you follow them,
1660 the compiler knows without being explicitly told where to find all
1661 the files it needs.
1663 @geindex Source_File_Name pragma
1665 However, in some cases, particularly when a program is imported from
1666 another Ada compiler environment, it may be more convenient for the
1667 programmer to specify which file names contain which units. GNAT allows
1668 arbitrary file names to be used by means of the Source_File_Name pragma.
1669 The form of this pragma is as shown in the following examples:
1671 @example
1672 pragma Source_File_Name (My_Utilities.Stacks,
1673   Spec_File_Name => "myutilst_a.ada");
1674 pragma Source_File_name (My_Utilities.Stacks,
1675   Body_File_Name => "myutilst.ada");
1676 @end example
1678 As shown in this example, the first argument for the pragma is the unit
1679 name (in this example a child unit). The second argument has the form
1680 of a named association. The identifier
1681 indicates whether the file name is for a spec or a body;
1682 the file name itself is given by a string literal.
1684 The source file name pragma is a configuration pragma, which means that
1685 normally it will be placed in the @code{gnat.adc}
1686 file used to hold configuration
1687 pragmas that apply to a complete compilation environment.
1688 For more details on how the @code{gnat.adc} file is created and used
1689 see @ref{3f,,Handling of Configuration Pragmas}.
1691 @geindex gnat.adc
1693 GNAT allows completely arbitrary file names to be specified using the
1694 source file name pragma. However, if the file name specified has an
1695 extension other than @code{.ads} or @code{.adb} it is necessary to use
1696 a special syntax when compiling the file. The name in this case must be
1697 preceded by the special sequence @code{-x} followed by a space and the name
1698 of the language, here @code{ada}, as in:
1700 @example
1701 $ gcc -c -x ada peculiar_file_name.sim
1702 @end example
1704 @code{gnatmake} handles non-standard file names in the usual manner (the
1705 non-standard file name for the main program is simply used as the
1706 argument to gnatmake). Note that if the extension is also non-standard,
1707 then it must be included in the @code{gnatmake} command, it may not
1708 be omitted.
1710 @node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
1711 @anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{41}
1712 @subsection Alternative File Naming Schemes
1715 @geindex File naming schemes
1716 @geindex alternative
1718 @geindex File names
1720 The previous section described the use of the @code{Source_File_Name}
1721 pragma to allow arbitrary names to be assigned to individual source files.
1722 However, this approach requires one pragma for each file, and especially in
1723 large systems can result in very long @code{gnat.adc} files, and also create
1724 a maintenance problem.
1726 @geindex Source_File_Name pragma
1728 GNAT also provides a facility for specifying systematic file naming schemes
1729 other than the standard default naming scheme previously described. An
1730 alternative scheme for naming is specified by the use of
1731 @code{Source_File_Name} pragmas having the following format:
1733 @example
1734 pragma Source_File_Name (
1735    Spec_File_Name  => FILE_NAME_PATTERN
1736  [ , Casing          => CASING_SPEC]
1737  [ , Dot_Replacement => STRING_LITERAL ] );
1739 pragma Source_File_Name (
1740    Body_File_Name  => FILE_NAME_PATTERN
1741  [ , Casing          => CASING_SPEC ]
1742  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1744 pragma Source_File_Name (
1745    Subunit_File_Name  => FILE_NAME_PATTERN
1746  [ , Casing          => CASING_SPEC ]
1747  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1749 FILE_NAME_PATTERN ::= STRING_LITERAL
1750 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1751 @end example
1753 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1754 It contains a single asterisk character, and the unit name is substituted
1755 systematically for this asterisk. The optional parameter
1756 @code{Casing} indicates
1757 whether the unit name is to be all upper-case letters, all lower-case letters,
1758 or mixed-case. If no
1759 @code{Casing} parameter is used, then the default is all
1760 lower-case.
1762 The optional @code{Dot_Replacement} string is used to replace any periods
1763 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1764 argument is used then separating dots appear unchanged in the resulting
1765 file name.
1766 Although the above syntax indicates that the
1767 @code{Casing} argument must appear
1768 before the @code{Dot_Replacement} argument, but it
1769 is also permissible to write these arguments in the opposite order.
1771 As indicated, it is possible to specify different naming schemes for
1772 bodies, specs, and subunits. Quite often the rule for subunits is the
1773 same as the rule for bodies, in which case, there is no need to give
1774 a separate @code{Subunit_File_Name} rule, and in this case the
1775 @code{Body_File_name} rule is used for subunits as well.
1777 The separate rule for subunits can also be used to implement the rather
1778 unusual case of a compilation environment (e.g., a single directory) which
1779 contains a subunit and a child unit with the same unit name. Although
1780 both units cannot appear in the same partition, the Ada Reference Manual
1781 allows (but does not require) the possibility of the two units coexisting
1782 in the same environment.
1784 The file name translation works in the following steps:
1787 @itemize *
1789 @item 
1790 If there is a specific @code{Source_File_Name} pragma for the given unit,
1791 then this is always used, and any general pattern rules are ignored.
1793 @item 
1794 If there is a pattern type @code{Source_File_Name} pragma that applies to
1795 the unit, then the resulting file name will be used if the file exists. If
1796 more than one pattern matches, the latest one will be tried first, and the
1797 first attempt resulting in a reference to a file that exists will be used.
1799 @item 
1800 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1801 for which the corresponding file exists, then the standard GNAT default
1802 naming rules are used.
1803 @end itemize
1805 As an example of the use of this mechanism, consider a commonly used scheme
1806 in which file names are all lower case, with separating periods copied
1807 unchanged to the resulting file name, and specs end with @code{.1.ada}, and
1808 bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
1809 two pragmas appear:
1811 @example
1812 pragma Source_File_Name
1813   (Spec_File_Name => ".1.ada");
1814 pragma Source_File_Name
1815   (Body_File_Name => ".2.ada");
1816 @end example
1818 The default GNAT scheme is actually implemented by providing the following
1819 default pragmas internally:
1821 @example
1822 pragma Source_File_Name
1823   (Spec_File_Name => ".ads", Dot_Replacement => "-");
1824 pragma Source_File_Name
1825   (Body_File_Name => ".adb", Dot_Replacement => "-");
1826 @end example
1828 Our final example implements a scheme typically used with one of the
1829 Ada 83 compilers, where the separator character for subunits was ‘__’
1830 (two underscores), specs were identified by adding @code{_.ADA}, bodies
1831 by adding @code{.ADA}, and subunits by
1832 adding @code{.SEP}. All file names were
1833 upper case. Child units were not present of course since this was an
1834 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1835 the same double underscore separator for child units.
1837 @example
1838 pragma Source_File_Name
1839   (Spec_File_Name => "_.ADA",
1840    Dot_Replacement => "__",
1841    Casing = Uppercase);
1842 pragma Source_File_Name
1843   (Body_File_Name => ".ADA",
1844    Dot_Replacement => "__",
1845    Casing = Uppercase);
1846 pragma Source_File_Name
1847   (Subunit_File_Name => ".SEP",
1848    Dot_Replacement => "__",
1849    Casing = Uppercase);
1850 @end example
1852 @geindex gnatname
1854 @node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
1855 @anchor{gnat_ugn/the_gnat_compilation_model handling-arbitrary-file-naming-conventions-with-gnatname}@anchor{42}@anchor{gnat_ugn/the_gnat_compilation_model id12}@anchor{43}
1856 @subsection Handling Arbitrary File Naming Conventions with @code{gnatname}
1859 @geindex File Naming Conventions
1861 @menu
1862 * Arbitrary File Naming Conventions:: 
1863 * Running gnatname:: 
1864 * Switches for gnatname:: 
1865 * Examples of gnatname Usage:: 
1867 @end menu
1869 @node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
1870 @anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{44}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{45}
1871 @subsubsection Arbitrary File Naming Conventions
1874 The GNAT compiler must be able to know the source file name of a compilation
1875 unit.  When using the standard GNAT default file naming conventions
1876 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
1877 does not need additional information.
1879 When the source file names do not follow the standard GNAT default file naming
1880 conventions, the GNAT compiler must be given additional information through
1881 a configuration pragmas file (@ref{25,,Configuration Pragmas})
1882 or a project file.
1883 When the non-standard file naming conventions are well-defined,
1884 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
1885 (@ref{40,,Alternative File Naming Schemes}) may be sufficient. However,
1886 if the file naming conventions are irregular or arbitrary, a number
1887 of pragma @code{Source_File_Name} for individual compilation units
1888 must be defined.
1889 To help maintain the correspondence between compilation unit names and
1890 source file names within the compiler,
1891 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
1892 set of files.
1894 @node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
1895 @anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{46}@anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{47}
1896 @subsubsection Running @code{gnatname}
1899 The usual form of the @code{gnatname} command is:
1901 @example
1902 $ gnatname [ switches ]  naming_pattern  [ naming_patterns ]
1903     [--and [ switches ]  naming_pattern  [ naming_patterns ]]
1904 @end example
1906 All of the arguments are optional. If invoked without any argument,
1907 @code{gnatname} will display its usage.
1909 When used with at least one naming pattern, @code{gnatname} will attempt to
1910 find all the compilation units in files that follow at least one of the
1911 naming patterns. To find these compilation units,
1912 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
1913 regular files.
1915 One or several Naming Patterns may be given as arguments to @code{gnatname}.
1916 Each Naming Pattern is enclosed between double quotes (or single
1917 quotes on Windows).
1918 A Naming Pattern is a regular expression similar to the wildcard patterns
1919 used in file names by the Unix shells or the DOS prompt.
1921 @code{gnatname} may be called with several sections of directories/patterns.
1922 Sections are separated by the switch @code{--and}. In each section, there must be
1923 at least one pattern. If no directory is specified in a section, the current
1924 directory (or the project directory if @code{-P} is used) is implied.
1925 The options other that the directory switches and the patterns apply globally
1926 even if they are in different sections.
1928 Examples of Naming Patterns are:
1930 @example
1931 "*.[12].ada"
1932 "*.ad[sb]*"
1933 "body_*"    "spec_*"
1934 @end example
1936 For a more complete description of the syntax of Naming Patterns,
1937 see the second kind of regular expressions described in @code{g-regexp.ads}
1938 (the ‘Glob’ regular expressions).
1940 When invoked without the switch @code{-P}, @code{gnatname} will create a
1941 configuration pragmas file @code{gnat.adc} in the current working directory,
1942 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
1943 unit.
1945 @node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
1946 @anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{48}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{49}
1947 @subsubsection Switches for @code{gnatname}
1950 Switches for @code{gnatname} must precede any specified Naming Pattern.
1952 You may specify any of the following switches to @code{gnatname}:
1954 @geindex --version (gnatname)
1957 @table @asis
1959 @item @code{--version}
1961 Display Copyright and version, then exit disregarding all other options.
1962 @end table
1964 @geindex --help (gnatname)
1967 @table @asis
1969 @item @code{--help}
1971 If @code{--version} was not used, display usage, then exit disregarding
1972 all other options.
1974 @item @code{--subdirs=`dir'}
1976 Real object, library or exec directories are subdirectories <dir> of the
1977 specified ones.
1979 @item @code{--no-backup}
1981 Do not create a backup copy of an existing project file.
1983 @item @code{--and}
1985 Start another section of directories/patterns.
1986 @end table
1988 @geindex -c (gnatname)
1991 @table @asis
1993 @item @code{-c`filename'}
1995 Create a configuration pragmas file @code{filename} (instead of the default
1996 @code{gnat.adc}).
1997 There may be zero, one or more space between @code{-c} and
1998 @code{filename}.
1999 @code{filename} may include directory information. @code{filename} must be
2000 writable. There may be only one switch @code{-c}.
2001 When a switch @code{-c} is
2002 specified, no switch @code{-P} may be specified (see below).
2003 @end table
2005 @geindex -d (gnatname)
2008 @table @asis
2010 @item @code{-d`dir'}
2012 Look for source files in directory @code{dir}. There may be zero, one or more
2013 spaces between @code{-d} and @code{dir}.
2014 @code{dir} may end with @code{/**}, that is it may be of the form
2015 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
2016 subdirectories, recursively, have to be searched for sources.
2017 When a switch @code{-d}
2018 is specified, the current working directory will not be searched for source
2019 files, unless it is explicitly specified with a @code{-d}
2020 or @code{-D} switch.
2021 Several switches @code{-d} may be specified.
2022 If @code{dir} is a relative path, it is relative to the directory of
2023 the configuration pragmas file specified with switch
2024 @code{-c},
2025 or to the directory of the project file specified with switch
2026 @code{-P} or,
2027 if neither switch @code{-c}
2028 nor switch @code{-P} are specified, it is relative to the
2029 current working directory. The directory
2030 specified with switch @code{-d} must exist and be readable.
2031 @end table
2033 @geindex -D (gnatname)
2036 @table @asis
2038 @item @code{-D`filename'}
2040 Look for source files in all directories listed in text file @code{filename}.
2041 There may be zero, one or more spaces between @code{-D}
2042 and @code{filename}.
2043 @code{filename} must be an existing, readable text file.
2044 Each nonempty line in @code{filename} must be a directory.
2045 Specifying switch @code{-D} is equivalent to specifying as many
2046 switches @code{-d} as there are nonempty lines in
2047 @code{file}.
2049 @item @code{-eL}
2051 Follow symbolic links when processing project files.
2053 @geindex -f (gnatname)
2055 @item @code{-f`pattern'}
2057 Foreign patterns. Using this switch, it is possible to add sources of languages
2058 other than Ada to the list of sources of a project file.
2059 It is only useful if a -P switch is used.
2060 For example,
2062 @example
2063 gnatname -Pprj -f"*.c" "*.ada"
2064 @end example
2066 will look for Ada units in all files with the @code{.ada} extension,
2067 and will add to the list of file for project @code{prj.gpr} the C files
2068 with extension @code{.c}.
2070 @geindex -h (gnatname)
2072 @item @code{-h}
2074 Output usage (help) information. The output is written to @code{stdout}.
2076 @geindex -P (gnatname)
2078 @item @code{-P`proj'}
2080 Create or update project file @code{proj}. There may be zero, one or more space
2081 between @code{-P} and @code{proj}. @code{proj} may include directory
2082 information. @code{proj} must be writable.
2083 There may be only one switch @code{-P}.
2084 When a switch @code{-P} is specified,
2085 no switch @code{-c} may be specified.
2086 On all platforms, except on VMS, when @code{gnatname} is invoked for an
2087 existing project file <proj>.gpr, a backup copy of the project file is created
2088 in the project directory with file name <proj>.gpr.saved_x. ‘x’ is the first
2089 non negative number that makes this backup copy a new file.
2091 @geindex -v (gnatname)
2093 @item @code{-v}
2095 Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2096 This includes name of the file written, the name of the directories to search
2097 and, for each file in those directories whose name matches at least one of
2098 the Naming Patterns, an indication of whether the file contains a unit,
2099 and if so the name of the unit.
2100 @end table
2102 @geindex -v -v (gnatname)
2105 @table @asis
2107 @item @code{-v -v}
2109 Very Verbose mode. In addition to the output produced in verbose mode,
2110 for each file in the searched directories whose name matches none of
2111 the Naming Patterns, an indication is given that there is no match.
2113 @geindex -x (gnatname)
2115 @item @code{-x`pattern'}
2117 Excluded patterns. Using this switch, it is possible to exclude some files
2118 that would match the name patterns. For example,
2120 @example
2121 gnatname -x "*_nt.ada" "*.ada"
2122 @end example
2124 will look for Ada units in all files with the @code{.ada} extension,
2125 except those whose names end with @code{_nt.ada}.
2126 @end table
2128 @node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2129 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{4a}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{4b}
2130 @subsubsection Examples of @code{gnatname} Usage
2133 @example
2134 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2135 @end example
2137 In this example, the directory @code{/home/me} must already exist
2138 and be writable. In addition, the directory
2139 @code{/home/me/sources} (specified by
2140 @code{-d sources}) must exist and be readable.
2142 Note the optional spaces after @code{-c} and @code{-d}.
2144 @example
2145 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
2146 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2147 @end example
2149 Note that several switches @code{-d} may be used,
2150 even in conjunction with one or several switches
2151 @code{-D}. Several Naming Patterns and one excluded pattern
2152 are used in this example.
2154 @node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2155 @anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{4c}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{4d}
2156 @subsection File Name Krunching with @code{gnatkr}
2159 @geindex gnatkr
2161 This section discusses the method used by the compiler to shorten
2162 the default file names chosen for Ada units so that they do not
2163 exceed the maximum length permitted. It also describes the
2164 @code{gnatkr} utility that can be used to determine the result of
2165 applying this shortening.
2167 @menu
2168 * About gnatkr:: 
2169 * Using gnatkr:: 
2170 * Krunching Method:: 
2171 * Examples of gnatkr Usage:: 
2173 @end menu
2175 @node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2176 @anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{4e}@anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{4f}
2177 @subsubsection About @code{gnatkr}
2180 The default file naming rule in GNAT
2181 is that the file name must be derived from
2182 the unit name. The exact default rule is as follows:
2185 @itemize *
2187 @item 
2188 Take the unit name and replace all dots by hyphens.
2190 @item 
2191 If such a replacement occurs in the
2192 second character position of a name, and the first character is
2193 @code{a}, @code{g}, @code{s}, or @code{i},
2194 then replace the dot by the character
2195 @code{~} (tilde)
2196 instead of a minus.
2198 The reason for this exception is to avoid clashes
2199 with the standard names for children of System, Ada, Interfaces,
2200 and GNAT, which use the prefixes
2201 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
2202 respectively.
2203 @end itemize
2205 The @code{-gnatk`nn'}
2206 switch of the compiler activates a ‘krunching’
2207 circuit that limits file names to nn characters (where nn is a decimal
2208 integer).
2210 The @code{gnatkr} utility can be used to determine the krunched name for
2211 a given file, when krunched to a specified maximum length.
2213 @node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2214 @anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{50}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{3d}
2215 @subsubsection Using @code{gnatkr}
2218 The @code{gnatkr} command has the form:
2220 @example
2221 $ gnatkr name [ length ]
2222 @end example
2224 @code{name} is the uncrunched file name, derived from the name of the unit
2225 in the standard manner described in the previous section (i.e., in particular
2226 all dots are replaced by hyphens). The file name may or may not have an
2227 extension (defined as a suffix of the form period followed by arbitrary
2228 characters other than period). If an extension is present then it will
2229 be preserved in the output. For example, when krunching @code{hellofile.ads}
2230 to eight characters, the result will be hellofil.ads.
2232 Note: for compatibility with previous versions of @code{gnatkr} dots may
2233 appear in the name instead of hyphens, but the last dot will always be
2234 taken as the start of an extension. So if @code{gnatkr} is given an argument
2235 such as @code{Hello.World.adb} it will be treated exactly as if the first
2236 period had been a hyphen, and for example krunching to eight characters
2237 gives the result @code{hellworl.adb}.
2239 Note that the result is always all lower case.
2240 Characters of the other case are folded as required.
2242 @code{length} represents the length of the krunched name. The default
2243 when no argument is given is 8 characters. A length of zero stands for
2244 unlimited, in other words do not chop except for system files where the
2245 implied crunching length is always eight characters.
2247 The output is the krunched name. The output has an extension only if the
2248 original argument was a file name with an extension.
2250 @node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2251 @anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{52}
2252 @subsubsection Krunching Method
2255 The initial file name is determined by the name of the unit that the file
2256 contains. The name is formed by taking the full expanded name of the
2257 unit and replacing the separating dots with hyphens and
2258 using lowercase
2259 for all letters, except that a hyphen in the second character position is
2260 replaced by a tilde if the first character is
2261 @code{a}, @code{i}, @code{g}, or @code{s}.
2262 The extension is @code{.ads} for a
2263 spec and @code{.adb} for a body.
2264 Krunching does not affect the extension, but the file name is shortened to
2265 the specified length by following these rules:
2268 @itemize *
2270 @item 
2271 The name is divided into segments separated by hyphens, tildes or
2272 underscores and all hyphens, tildes, and underscores are
2273 eliminated. If this leaves the name short enough, we are done.
2275 @item 
2276 If the name is too long, the longest segment is located (left-most
2277 if there are two of equal length), and shortened by dropping
2278 its last character. This is repeated until the name is short enough.
2280 As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2281 to fit the name into 8 characters as required by some operating systems:
2283 @example
2284 our-strings-wide_fixed 22
2285 our strings wide fixed 19
2286 our string  wide fixed 18
2287 our strin   wide fixed 17
2288 our stri    wide fixed 16
2289 our stri    wide fixe  15
2290 our str     wide fixe  14
2291 our str     wid  fixe  13
2292 our str     wid  fix   12
2293 ou  str     wid  fix   11
2294 ou  st      wid  fix   10
2295 ou  st      wi   fix   9
2296 ou  st      wi   fi    8
2297 Final file name: oustwifi.adb
2298 @end example
2300 @item 
2301 The file names for all predefined units are always krunched to eight
2302 characters. The krunching of these predefined units uses the following
2303 special prefix replacements:
2306 @multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
2307 @item
2309 Prefix
2311 @tab
2313 Replacement
2315 @item
2317 @code{ada-}
2319 @tab
2321 @code{a-}
2323 @item
2325 @code{gnat-}
2327 @tab
2329 @code{g-}
2331 @item
2333 @code{interfac es-}
2335 @tab
2337 @code{i-}
2339 @item
2341 @code{system-}
2343 @tab
2345 @code{s-}
2347 @end multitable
2350 These system files have a hyphen in the second character position. That
2351 is why normal user files replace such a character with a
2352 tilde, to avoid confusion with system file names.
2354 As an example of this special rule, consider
2355 @code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2357 @example
2358 ada-strings-wide_fixed 22
2359 a-  strings wide fixed 18
2360 a-  string  wide fixed 17
2361 a-  strin   wide fixed 16
2362 a-  stri    wide fixed 15
2363 a-  stri    wide fixe  14
2364 a-  str     wide fixe  13
2365 a-  str     wid  fixe  12
2366 a-  str     wid  fix   11
2367 a-  st      wid  fix   10
2368 a-  st      wi   fix   9
2369 a-  st      wi   fi    8
2370 Final file name: a-stwifi.adb
2371 @end example
2372 @end itemize
2374 Of course no file shortening algorithm can guarantee uniqueness over all
2375 possible unit names, and if file name krunching is used then it is your
2376 responsibility to ensure that no name clashes occur. The utility
2377 program @code{gnatkr} is supplied for conveniently determining the
2378 krunched name of a file.
2380 @node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2381 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{53}@anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{54}
2382 @subsubsection Examples of @code{gnatkr} Usage
2385 @example
2386 $ gnatkr very_long_unit_name.ads      --> velounna.ads
2387 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
2388 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2389 $ gnatkr grandparent-parent-child     --> grparchi
2390 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2391 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2392 @end example
2394 @node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2395 @anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{55}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{1d}
2396 @subsection Renaming Files with @code{gnatchop}
2399 @geindex gnatchop
2401 This section discusses how to handle files with multiple units by using
2402 the @code{gnatchop} utility. This utility is also useful in renaming
2403 files to meet the standard GNAT default file naming conventions.
2405 @menu
2406 * Handling Files with Multiple Units:: 
2407 * Operating gnatchop in Compilation Mode:: 
2408 * Command Line for gnatchop:: 
2409 * Switches for gnatchop:: 
2410 * Examples of gnatchop Usage:: 
2412 @end menu
2414 @node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2415 @anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{56}@anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{57}
2416 @subsubsection Handling Files with Multiple Units
2419 The basic compilation model of GNAT requires that a file submitted to the
2420 compiler have only one unit and there be a strict correspondence
2421 between the file name and the unit name.
2423 If you want to keep your files with multiple units,
2424 perhaps to maintain compatibility with some other Ada compilation system,
2425 you can use @code{gnatname} to generate or update your project files.
2426 Generated or modified project files can be processed by GNAT.
2428 See @ref{42,,Handling Arbitrary File Naming Conventions with gnatname}
2429 for more details on how to use @cite{gnatname}.
2431 Alternatively, if you want to permanently restructure a set of ‘foreign’
2432 files so that they match the GNAT rules, and do the remaining development
2433 using the GNAT structure, you can simply use @code{gnatchop} once, generate the
2434 new set of files and work with them from that point on.
2436 Note that if your file containing multiple units starts with a byte order
2437 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2438 will each start with a copy of this BOM, meaning that they can be compiled
2439 automatically in UTF-8 mode without needing to specify an explicit encoding.
2441 @node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2442 @anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{58}@anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{59}
2443 @subsubsection Operating gnatchop in Compilation Mode
2446 The basic function of @code{gnatchop} is to take a file with multiple units
2447 and split it into separate files. The boundary between files is reasonably
2448 clear, except for the issue of comments and pragmas. In default mode, the
2449 rule is that any pragmas between units belong to the previous unit, except
2450 that configuration pragmas always belong to the following unit. Any comments
2451 belong to the following unit. These rules
2452 almost always result in the right choice of
2453 the split point without needing to mark it explicitly and most users will
2454 find this default to be what they want. In this default mode it is incorrect to
2455 submit a file containing only configuration pragmas, or one that ends in
2456 configuration pragmas, to @code{gnatchop}.
2458 However, using a special option to activate ‘compilation mode’,
2459 @code{gnatchop}
2460 can perform another function, which is to provide exactly the semantics
2461 required by the RM for handling of configuration pragmas in a compilation.
2462 In the absence of configuration pragmas (at the main file level), this
2463 option has no effect, but it causes such configuration pragmas to be handled
2464 in a quite different manner.
2466 First, in compilation mode, if @code{gnatchop} is given a file that consists of
2467 only configuration pragmas, then this file is appended to the
2468 @code{gnat.adc} file in the current directory. This behavior provides
2469 the required behavior described in the RM for the actions to be taken
2470 on submitting such a file to the compiler, namely that these pragmas
2471 should apply to all subsequent compilations in the same compilation
2472 environment. Using GNAT, the current directory, possibly containing a
2473 @code{gnat.adc} file is the representation
2474 of a compilation environment. For more information on the
2475 @code{gnat.adc} file, see @ref{3f,,Handling of Configuration Pragmas}.
2477 Second, in compilation mode, if @code{gnatchop}
2478 is given a file that starts with
2479 configuration pragmas, and contains one or more units, then these
2480 configuration pragmas are prepended to each of the chopped files. This
2481 behavior provides the required behavior described in the RM for the
2482 actions to be taken on compiling such a file, namely that the pragmas
2483 apply to all units in the compilation, but not to subsequently compiled
2484 units.
2486 Finally, if configuration pragmas appear between units, they are appended
2487 to the previous unit. This results in the previous unit being illegal,
2488 since the compiler does not accept configuration pragmas that follow
2489 a unit. This provides the required RM behavior that forbids configuration
2490 pragmas other than those preceding the first compilation unit of a
2491 compilation.
2493 For most purposes, @code{gnatchop} will be used in default mode. The
2494 compilation mode described above is used only if you need exactly
2495 accurate behavior with respect to compilations, and you have files
2496 that contain multiple units and configuration pragmas. In this
2497 circumstance the use of @code{gnatchop} with the compilation mode
2498 switch provides the required behavior, and is for example the mode
2499 in which GNAT processes the ACVC tests.
2501 @node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2502 @anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{5a}@anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{5b}
2503 @subsubsection Command Line for @code{gnatchop}
2506 The @code{gnatchop} command has the form:
2508 @example
2509 $ gnatchop switches file_name [file_name ...]
2510       [directory]
2511 @end example
2513 The only required argument is the file name of the file to be chopped.
2514 There are no restrictions on the form of this file name. The file itself
2515 contains one or more Ada units, in normal GNAT format, concatenated
2516 together. As shown, more than one file may be presented to be chopped.
2518 When run in default mode, @code{gnatchop} generates one output file in
2519 the current directory for each unit in each of the files.
2521 @code{directory}, if specified, gives the name of the directory to which
2522 the output files will be written. If it is not specified, all files are
2523 written to the current directory.
2525 For example, given a
2526 file called @code{hellofiles} containing
2528 @example
2529 procedure Hello;
2531 with Ada.Text_IO; use Ada.Text_IO;
2532 procedure Hello is
2533 begin
2534    Put_Line ("Hello");
2535 end Hello;
2536 @end example
2538 the command
2540 @example
2541 $ gnatchop hellofiles
2542 @end example
2544 generates two files in the current directory, one called
2545 @code{hello.ads} containing the single line that is the procedure spec,
2546 and the other called @code{hello.adb} containing the remaining text. The
2547 original file is not affected. The generated files can be compiled in
2548 the normal manner.
2550 When gnatchop is invoked on a file that is empty or that contains only empty
2551 lines and/or comments, gnatchop will not fail, but will not produce any
2552 new sources.
2554 For example, given a
2555 file called @code{toto.txt} containing
2557 @example
2558 --  Just a comment
2559 @end example
2561 the command
2563 @example
2564 $ gnatchop toto.txt
2565 @end example
2567 will not produce any new file and will result in the following warnings:
2569 @example
2570 toto.txt:1:01: warning: empty file, contains no compilation units
2571 no compilation units found
2572 no source files written
2573 @end example
2575 @node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2576 @anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{5c}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{5d}
2577 @subsubsection Switches for @code{gnatchop}
2580 @code{gnatchop} recognizes the following switches:
2582 @geindex --version (gnatchop)
2585 @table @asis
2587 @item @code{--version}
2589 Display Copyright and version, then exit disregarding all other options.
2590 @end table
2592 @geindex --help (gnatchop)
2595 @table @asis
2597 @item @code{--help}
2599 If @code{--version} was not used, display usage, then exit disregarding
2600 all other options.
2601 @end table
2603 @geindex -c (gnatchop)
2606 @table @asis
2608 @item @code{-c}
2610 Causes @code{gnatchop} to operate in compilation mode, in which
2611 configuration pragmas are handled according to strict RM rules. See
2612 previous section for a full description of this mode.
2614 @item @code{-gnat`xxx'}
2616 This passes the given @code{-gnat`xxx'} switch to @code{gnat} which is
2617 used to parse the given file. Not all `xxx' options make sense,
2618 but for example, the use of @code{-gnati2} allows @code{gnatchop} to
2619 process a source file that uses Latin-2 coding for identifiers.
2621 @item @code{-h}
2623 Causes @code{gnatchop} to generate a brief help summary to the standard
2624 output file showing usage information.
2625 @end table
2627 @geindex -k (gnatchop)
2630 @table @asis
2632 @item @code{-k`mm'}
2634 Limit generated file names to the specified number @code{mm}
2635 of characters.
2636 This is useful if the
2637 resulting set of files is required to be interoperable with systems
2638 which limit the length of file names.
2639 No space is allowed between the @code{-k} and the numeric value. The numeric
2640 value may be omitted in which case a default of @code{-k8},
2641 suitable for use
2642 with DOS-like file systems, is used. If no @code{-k} switch
2643 is present then
2644 there is no limit on the length of file names.
2645 @end table
2647 @geindex -p (gnatchop)
2650 @table @asis
2652 @item @code{-p}
2654 Causes the file modification time stamp of the input file to be
2655 preserved and used for the time stamp of the output file(s). This may be
2656 useful for preserving coherency of time stamps in an environment where
2657 @code{gnatchop} is used as part of a standard build process.
2658 @end table
2660 @geindex -q (gnatchop)
2663 @table @asis
2665 @item @code{-q}
2667 Causes output of informational messages indicating the set of generated
2668 files to be suppressed. Warnings and error messages are unaffected.
2669 @end table
2671 @geindex -r (gnatchop)
2673 @geindex Source_Reference pragmas
2676 @table @asis
2678 @item @code{-r}
2680 Generate @code{Source_Reference} pragmas. Use this switch if the output
2681 files are regarded as temporary and development is to be done in terms
2682 of the original unchopped file. This switch causes
2683 @code{Source_Reference} pragmas to be inserted into each of the
2684 generated files to refers back to the original file name and line number.
2685 The result is that all error messages refer back to the original
2686 unchopped file.
2687 In addition, the debugging information placed into the object file (when
2688 the @code{-g} switch of @code{gcc} or @code{gnatmake} is
2689 specified)
2690 also refers back to this original file so that tools like profilers and
2691 debuggers will give information in terms of the original unchopped file.
2693 If the original file to be chopped itself contains
2694 a @code{Source_Reference}
2695 pragma referencing a third file, then gnatchop respects
2696 this pragma, and the generated @code{Source_Reference} pragmas
2697 in the chopped file refer to the original file, with appropriate
2698 line numbers. This is particularly useful when @code{gnatchop}
2699 is used in conjunction with @code{gnatprep} to compile files that
2700 contain preprocessing statements and multiple units.
2701 @end table
2703 @geindex -v (gnatchop)
2706 @table @asis
2708 @item @code{-v}
2710 Causes @code{gnatchop} to operate in verbose mode. The version
2711 number and copyright notice are output, as well as exact copies of
2712 the gnat1 commands spawned to obtain the chop control information.
2713 @end table
2715 @geindex -w (gnatchop)
2718 @table @asis
2720 @item @code{-w}
2722 Overwrite existing file names. Normally @code{gnatchop} regards it as a
2723 fatal error if there is already a file with the same name as a
2724 file it would otherwise output, in other words if the files to be
2725 chopped contain duplicated units. This switch bypasses this
2726 check, and causes all but the last instance of such duplicated
2727 units to be skipped.
2728 @end table
2730 @geindex --GCC= (gnatchop)
2733 @table @asis
2735 @item @code{--GCC=`xxxx'}
2737 Specify the path of the GNAT parser to be used. When this switch is used,
2738 no attempt is made to add the prefix to the GNAT parser executable.
2739 @end table
2741 @node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
2742 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{5e}@anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{5f}
2743 @subsubsection Examples of @code{gnatchop} Usage
2746 @example
2747 $ gnatchop -w hello_s.ada prerelease/files
2748 @end example
2750 Chops the source file @code{hello_s.ada}. The output files will be
2751 placed in the directory @code{prerelease/files},
2752 overwriting any
2753 files with matching names in that directory (no files in the current
2754 directory are modified).
2756 @example
2757 $ gnatchop archive
2758 @end example
2760 Chops the source file @code{archive}
2761 into the current directory. One
2762 useful application of @code{gnatchop} is in sending sets of sources
2763 around, for example in email messages. The required sources are simply
2764 concatenated (for example, using a Unix @code{cat}
2765 command), and then
2766 @code{gnatchop} is used at the other end to reconstitute the original
2767 file names.
2769 @example
2770 $ gnatchop file1 file2 file3 direc
2771 @end example
2773 Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
2774 the resulting files in the directory @code{direc}. Note that if any units
2775 occur more than once anywhere within this set of files, an error message
2776 is generated, and no files are written. To override this check, use the
2777 @code{-w} switch,
2778 in which case the last occurrence in the last file will
2779 be the one that is output, and earlier duplicate occurrences for a given
2780 unit will be skipped.
2782 @node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
2783 @anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{25}@anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{60}
2784 @section Configuration Pragmas
2787 @geindex Configuration pragmas
2789 @geindex Pragmas
2790 @geindex configuration
2792 Configuration pragmas include those pragmas described as
2793 such in the Ada Reference Manual, as well as
2794 implementation-dependent pragmas that are configuration pragmas.
2795 See the @code{Implementation_Defined_Pragmas} chapter in the
2796 @cite{GNAT_Reference_Manual} for details on these
2797 additional GNAT-specific configuration pragmas.
2798 Most notably, the pragma @code{Source_File_Name}, which allows
2799 specifying non-default names for source files, is a configuration
2800 pragma. The following is a complete list of configuration pragmas
2801 recognized by GNAT:
2803 @example
2804 Ada_83
2805 Ada_95
2806 Ada_05
2807 Ada_2005
2808 Ada_12
2809 Ada_2012
2810 Ada_2022
2811 Aggregate_Individually_Assign
2812 Allow_Integer_Address
2813 Annotate
2814 Assertion_Policy
2815 Assume_No_Invalid_Values
2816 C_Pass_By_Copy
2817 Check_Float_Overflow
2818 Check_Name
2819 Check_Policy
2820 Component_Alignment
2821 Convention_Identifier
2822 Debug_Policy
2823 Default_Scalar_Storage_Order
2824 Default_Storage_Pool
2825 Detect_Blocking
2826 Disable_Atomic_Synchronization
2827 Discard_Names
2828 Elaboration_Checks
2829 Eliminate
2830 Enable_Atomic_Synchronization
2831 Extend_System
2832 Extensions_Allowed
2833 External_Name_Casing
2834 Fast_Math
2835 Favor_Top_Level
2836 Ignore_Pragma
2837 Implicit_Packing
2838 Initialize_Scalars
2839 Interrupt_State
2840 License
2841 Locking_Policy
2842 No_Component_Reordering
2843 No_Heap_Finalization
2844 No_Strict_Aliasing
2845 Normalize_Scalars
2846 Optimize_Alignment
2847 Overflow_Mode
2848 Overriding_Renamings
2849 Partition_Elaboration_Policy
2850 Persistent_BSS
2851 Prefix_Exception_Messages
2852 Priority_Specific_Dispatching
2853 Profile
2854 Profile_Warnings
2855 Queuing_Policy
2856 Rename_Pragma
2857 Restrictions
2858 Restriction_Warnings
2859 Reviewable
2860 Short_Circuit_And_Or
2861 Source_File_Name
2862 Source_File_Name_Project
2863 SPARK_Mode
2864 Style_Checks
2865 Suppress
2866 Suppress_Exception_Locations
2867 Task_Dispatching_Policy
2868 Unevaluated_Use_Of_Old
2869 Unsuppress
2870 Use_VADS_Size
2871 Validity_Checks
2872 Warning_As_Error
2873 Warnings
2874 Wide_Character_Encoding
2875 @end example
2877 @menu
2878 * Handling of Configuration Pragmas:: 
2879 * The Configuration Pragmas Files:: 
2881 @end menu
2883 @node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
2884 @anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{3f}@anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{61}
2885 @subsection Handling of Configuration Pragmas
2888 Configuration pragmas may either appear at the start of a compilation
2889 unit, or they can appear in a configuration pragma file to apply to
2890 all compilations performed in a given compilation environment.
2892 GNAT also provides the @code{gnatchop} utility to provide an automatic
2893 way to handle configuration pragmas following the semantics for
2894 compilations (that is, files with multiple units), described in the RM.
2895 See @ref{59,,Operating gnatchop in Compilation Mode} for details.
2896 However, for most purposes, it will be more convenient to edit the
2897 @code{gnat.adc} file that contains configuration pragmas directly,
2898 as described in the following section.
2900 In the case of @code{Restrictions} pragmas appearing as configuration
2901 pragmas in individual compilation units, the exact handling depends on
2902 the type of restriction.
2904 Restrictions that require partition-wide consistency (like
2905 @code{No_Tasking}) are
2906 recognized wherever they appear
2907 and can be freely inherited, e.g. from a `with'ed unit to the `with'ing
2908 unit. This makes sense since the binder will in any case insist on seeing
2909 consistent use, so any unit not conforming to any restrictions that are
2910 anywhere in the partition will be rejected, and you might as well find
2911 that out at compile time rather than at bind time.
2913 For restrictions that do not require partition-wide consistency, e.g.
2914 SPARK or No_Implementation_Attributes, in general the restriction applies
2915 only to the unit in which the pragma appears, and not to any other units.
2917 The exception is No_Elaboration_Code which always applies to the entire
2918 object file from a compilation, i.e. to the body, spec, and all subunits.
2919 This restriction can be specified in a configuration pragma file, or it
2920 can be on the body and/or the spec (in either case it applies to all the
2921 relevant units). It can appear on a subunit only if it has previously
2922 appeared in the body of spec.
2924 @node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
2925 @anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{62}@anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{63}
2926 @subsection The Configuration Pragmas Files
2929 @geindex gnat.adc
2931 In GNAT a compilation environment is defined by the current
2932 directory at the time that a compile command is given. This current
2933 directory is searched for a file whose name is @code{gnat.adc}. If
2934 this file is present, it is expected to contain one or more
2935 configuration pragmas that will be applied to the current compilation.
2936 However, if the switch @code{-gnatA} is used, @code{gnat.adc} is not
2937 considered. When taken into account, @code{gnat.adc} is added to the
2938 dependencies, so that if @code{gnat.adc} is modified later, an invocation of
2939 @code{gnatmake} will recompile the source.
2941 Configuration pragmas may be entered into the @code{gnat.adc} file
2942 either by running @code{gnatchop} on a source file that consists only of
2943 configuration pragmas, or more conveniently by direct editing of the
2944 @code{gnat.adc} file, which is a standard format source file.
2946 Besides @code{gnat.adc}, additional files containing configuration
2947 pragmas may be applied to the current compilation using the switch
2948 @code{-gnatec=`path'} where @code{path} must designate an existing file that
2949 contains only configuration pragmas. These configuration pragmas are
2950 in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
2951 is present and switch @code{-gnatA} is not used).
2953 It is allowable to specify several switches @code{-gnatec=}, all of which
2954 will be taken into account.
2956 Files containing configuration pragmas specified with switches
2957 @code{-gnatec=} are added to the dependencies, unless they are
2958 temporary files. A file is considered temporary if its name ends in
2959 @code{.tmp} or @code{.TMP}. Certain tools follow this naming
2960 convention because they pass information to @code{gcc} via
2961 temporary files that are immediately deleted; it doesn’t make sense to
2962 depend on a file that no longer exists. Such tools include
2963 @code{gprbuild}, @code{gnatmake}, and @code{gnatcheck}.
2965 By default, configuration pragma files are stored by their absolute paths in
2966 ALI files. You can use the @code{-gnateb} switch in order to store them by
2967 their basename instead.
2969 If you are using project file, a separate mechanism is provided using
2970 project attributes.
2972 @c --Comment
2973 @c See :ref:`Specifying_Configuration_Pragmas` for more details.
2975 @node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
2976 @anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{26}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{64}
2977 @section Generating Object Files
2980 An Ada program consists of a set of source files, and the first step in
2981 compiling the program is to generate the corresponding object files.
2982 These are generated by compiling a subset of these source files.
2983 The files you need to compile are the following:
2986 @itemize *
2988 @item 
2989 If a package spec has no body, compile the package spec to produce the
2990 object file for the package.
2992 @item 
2993 If a package has both a spec and a body, compile the body to produce the
2994 object file for the package. The source file for the package spec need
2995 not be compiled in this case because there is only one object file, which
2996 contains the code for both the spec and body of the package.
2998 @item 
2999 For a subprogram, compile the subprogram body to produce the object file
3000 for the subprogram. The spec, if one is present, is as usual in a
3001 separate file, and need not be compiled.
3002 @end itemize
3004 @geindex Subunits
3007 @itemize *
3009 @item 
3010 In the case of subunits, only compile the parent unit. A single object
3011 file is generated for the entire subunit tree, which includes all the
3012 subunits.
3014 @item 
3015 Compile child units independently of their parent units
3016 (though, of course, the spec of all the ancestor unit must be present in order
3017 to compile a child unit).
3019 @geindex Generics
3021 @item 
3022 Compile generic units in the same manner as any other units. The object
3023 files in this case are small dummy files that contain at most the
3024 flag used for elaboration checking. This is because GNAT always handles generic
3025 instantiation by means of macro expansion. However, it is still necessary to
3026 compile generic units, for dependency checking and elaboration purposes.
3027 @end itemize
3029 The preceding rules describe the set of files that must be compiled to
3030 generate the object files for a program. Each object file has the same
3031 name as the corresponding source file, except that the extension is
3032 @code{.o} as usual.
3034 You may wish to compile other files for the purpose of checking their
3035 syntactic and semantic correctness. For example, in the case where a
3036 package has a separate spec and body, you would not normally compile the
3037 spec. However, it is convenient in practice to compile the spec to make
3038 sure it is error-free before compiling clients of this spec, because such
3039 compilations will fail if there is an error in the spec.
3041 GNAT provides an option for compiling such files purely for the
3042 purposes of checking correctness; such compilations are not required as
3043 part of the process of building a program. To compile a file in this
3044 checking mode, use the @code{-gnatc} switch.
3046 @node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3047 @anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{27}
3048 @section Source Dependencies
3051 A given object file clearly depends on the source file which is compiled
3052 to produce it. Here we are using “depends” in the sense of a typical
3053 @code{make} utility; in other words, an object file depends on a source
3054 file if changes to the source file require the object file to be
3055 recompiled.
3056 In addition to this basic dependency, a given object may depend on
3057 additional source files as follows:
3060 @itemize *
3062 @item 
3063 If a file being compiled `with's a unit @code{X}, the object file
3064 depends on the file containing the spec of unit @code{X}. This includes
3065 files that are `with'ed implicitly either because they are parents
3066 of `with'ed child units or they are run-time units required by the
3067 language constructs used in a particular unit.
3069 @item 
3070 If a file being compiled instantiates a library level generic unit, the
3071 object file depends on both the spec and body files for this generic
3072 unit.
3074 @item 
3075 If a file being compiled instantiates a generic unit defined within a
3076 package, the object file depends on the body file for the package as
3077 well as the spec file.
3078 @end itemize
3080 @geindex Inline
3082 @geindex -gnatn switch
3085 @itemize *
3087 @item 
3088 If a file being compiled contains a call to a subprogram for which
3089 pragma @code{Inline} applies and inlining is activated with the
3090 @code{-gnatn} switch, the object file depends on the file containing the
3091 body of this subprogram as well as on the file containing the spec. Note
3092 that for inlining to actually occur as a result of the use of this switch,
3093 it is necessary to compile in optimizing mode.
3095 @geindex -gnatN switch
3097 The use of @code{-gnatN} activates  inlining optimization
3098 that is performed by the front end of the compiler. This inlining does
3099 not require that the code generation be optimized. Like @code{-gnatn},
3100 the use of this switch generates additional dependencies.
3102 When using a gcc-based back end, then the use of
3103 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
3104 Historically front end inlining was more extensive than the gcc back end
3105 inlining, but that is no longer the case.
3107 @item 
3108 If an object file @code{O} depends on the proper body of a subunit through
3109 inlining or instantiation, it depends on the parent unit of the subunit.
3110 This means that any modification of the parent unit or one of its subunits
3111 affects the compilation of @code{O}.
3113 @item 
3114 The object file for a parent unit depends on all its subunit body files.
3116 @item 
3117 The previous two rules meant that for purposes of computing dependencies and
3118 recompilation, a body and all its subunits are treated as an indivisible whole.
3120 These rules are applied transitively: if unit @code{A} `with's
3121 unit @code{B}, whose elaboration calls an inlined procedure in package
3122 @code{C}, the object file for unit @code{A} will depend on the body of
3123 @code{C}, in file @code{c.adb}.
3125 The set of dependent files described by these rules includes all the
3126 files on which the unit is semantically dependent, as dictated by the
3127 Ada language standard. However, it is a superset of what the
3128 standard describes, because it includes generic, inline, and subunit
3129 dependencies.
3131 An object file must be recreated by recompiling the corresponding source
3132 file if any of the source files on which it depends are modified. For
3133 example, if the @code{make} utility is used to control compilation,
3134 the rule for an Ada object file must mention all the source files on
3135 which the object file depends, according to the above definition.
3136 The determination of the necessary
3137 recompilations is done automatically when one uses @code{gnatmake}.
3138 @end itemize
3140 @node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3141 @anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{66}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{28}
3142 @section The Ada Library Information Files
3145 @geindex Ada Library Information files
3147 @geindex ALI files
3149 Each compilation actually generates two output files. The first of these
3150 is the normal object file that has a @code{.o} extension. The second is a
3151 text file containing full dependency information. It has the same
3152 name as the source file, but an @code{.ali} extension.
3153 This file is known as the Ada Library Information (@code{ALI}) file.
3154 The following information is contained in the @code{ALI} file.
3157 @itemize *
3159 @item 
3160 Version information (indicates which version of GNAT was used to compile
3161 the unit(s) in question)
3163 @item 
3164 Main program information (including priority and time slice settings,
3165 as well as the wide character encoding used during compilation).
3167 @item 
3168 List of arguments used in the @code{gcc} command for the compilation
3170 @item 
3171 Attributes of the unit, including configuration pragmas used, an indication
3172 of whether the compilation was successful, exception model used etc.
3174 @item 
3175 A list of relevant restrictions applying to the unit (used for consistency)
3176 checking.
3178 @item 
3179 Categorization information (e.g., use of pragma @code{Pure}).
3181 @item 
3182 Information on all `with'ed units, including presence of
3183 @code{Elaborate} or @code{Elaborate_All} pragmas.
3185 @item 
3186 Information from any @code{Linker_Options} pragmas used in the unit
3188 @item 
3189 Information on the use of @code{Body_Version} or @code{Version}
3190 attributes in the unit.
3192 @item 
3193 Dependency information. This is a list of files, together with
3194 time stamp and checksum information. These are files on which
3195 the unit depends in the sense that recompilation is required
3196 if any of these units are modified.
3198 @item 
3199 Cross-reference data. Contains information on all entities referenced
3200 in the unit. Used by some tools to provide cross-reference information.
3201 @end itemize
3203 For a full detailed description of the format of the @code{ALI} file,
3204 see the source of the body of unit @code{Lib.Writ}, contained in file
3205 @code{lib-writ.adb} in the GNAT compiler sources.
3207 @node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3208 @anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{29}@anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{67}
3209 @section Binding an Ada Program
3212 When using languages such as C and C++, once the source files have been
3213 compiled the only remaining step in building an executable program
3214 is linking the object modules together. This means that it is possible to
3215 link an inconsistent version of a program, in which two units have
3216 included different versions of the same header.
3218 The rules of Ada do not permit such an inconsistent program to be built.
3219 For example, if two clients have different versions of the same package,
3220 it is illegal to build a program containing these two clients.
3221 These rules are enforced by the GNAT binder, which also determines an
3222 elaboration order consistent with the Ada rules.
3224 The GNAT binder is run after all the object files for a program have
3225 been created. It is given the name of the main program unit, and from
3226 this it determines the set of units required by the program, by reading the
3227 corresponding ALI files. It generates error messages if the program is
3228 inconsistent or if no valid order of elaboration exists.
3230 If no errors are detected, the binder produces a main program, in Ada by
3231 default, that contains calls to the elaboration procedures of those
3232 compilation unit that require them, followed by
3233 a call to the main program. This Ada program is compiled to generate the
3234 object file for the main program. The name of
3235 the Ada file is @code{b~xxx.adb} (with the corresponding spec
3236 @code{b~xxx.ads}) where @code{xxx} is the name of the
3237 main program unit.
3239 Finally, the linker is used to build the resulting executable program,
3240 using the object from the main program from the bind step as well as the
3241 object files for the Ada units of the program.
3243 @node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3244 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{2a}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{68}
3245 @section GNAT and Libraries
3248 @geindex Library building and using
3250 This section describes how to build and use libraries with GNAT, and also shows
3251 how to recompile the GNAT run-time library. You should be familiar with the
3252 Project Manager facility (see the `GNAT_Project_Manager' chapter of the
3253 `GPRbuild User’s Guide') before reading this chapter.
3255 @menu
3256 * Introduction to Libraries in GNAT:: 
3257 * General Ada Libraries:: 
3258 * Stand-alone Ada Libraries:: 
3259 * Rebuilding the GNAT Run-Time Library:: 
3261 @end menu
3263 @node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3264 @anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{69}@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{6a}
3265 @subsection Introduction to Libraries in GNAT
3268 A library is, conceptually, a collection of objects which does not have its
3269 own main thread of execution, but rather provides certain services to the
3270 applications that use it. A library can be either statically linked with the
3271 application, in which case its code is directly included in the application,
3272 or, on platforms that support it, be dynamically linked, in which case
3273 its code is shared by all applications making use of this library.
3275 GNAT supports both types of libraries.
3276 In the static case, the compiled code can be provided in different ways. The
3277 simplest approach is to provide directly the set of objects resulting from
3278 compilation of the library source files. Alternatively, you can group the
3279 objects into an archive using whatever commands are provided by the operating
3280 system. For the latter case, the objects are grouped into a shared library.
3282 In the GNAT environment, a library has three types of components:
3285 @itemize *
3287 @item 
3288 Source files,
3290 @item 
3291 @code{ALI} files (see @ref{28,,The Ada Library Information Files}), and
3293 @item 
3294 Object files, an archive or a shared library.
3295 @end itemize
3297 A GNAT library may expose all its source files, which is useful for
3298 documentation purposes. Alternatively, it may expose only the units needed by
3299 an external user to make use of the library. That is to say, the specs
3300 reflecting the library services along with all the units needed to compile
3301 those specs, which can include generic bodies or any body implementing an
3302 inlined routine. In the case of `stand-alone libraries' those exposed
3303 units are called `interface units' (@ref{6b,,Stand-alone Ada Libraries}).
3305 All compilation units comprising an application, including those in a library,
3306 need to be elaborated in an order partially defined by Ada’s semantics. GNAT
3307 computes the elaboration order from the @code{ALI} files and this is why they
3308 constitute a mandatory part of GNAT libraries.
3309 `Stand-alone libraries' are the exception to this rule because a specific
3310 library elaboration routine is produced independently of the application(s)
3311 using the library.
3313 @node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3314 @anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{6d}
3315 @subsection General Ada Libraries
3318 @menu
3319 * Building a library:: 
3320 * Installing a library:: 
3321 * Using a library:: 
3323 @end menu
3325 @node Building a library,Installing a library,,General Ada Libraries
3326 @anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{6e}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{6f}
3327 @subsubsection Building a library
3330 The easiest way to build a library is to use the Project Manager,
3331 which supports a special type of project called a `Library Project'
3332 (see the `Library Projects' section in the `GNAT Project Manager'
3333 chapter of the `GPRbuild User’s Guide').
3335 A project is considered a library project, when two project-level attributes
3336 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
3337 control different aspects of library configuration, additional optional
3338 project-level attributes can be specified:
3341 @itemize *
3343 @item 
3345 @table @asis
3347 @item @code{Library_Kind}
3349 This attribute controls whether the library is to be static or dynamic
3350 @end table
3352 @item 
3354 @table @asis
3356 @item @code{Library_Version}
3358 This attribute specifies the library version; this value is used
3359 during dynamic linking of shared libraries to determine if the currently
3360 installed versions of the binaries are compatible.
3361 @end table
3363 @item 
3364 @code{Library_Options}
3366 @item 
3368 @table @asis
3370 @item @code{Library_GCC}
3372 These attributes specify additional low-level options to be used during
3373 library generation, and redefine the actual application used to generate
3374 library.
3375 @end table
3376 @end itemize
3378 The GNAT Project Manager takes full care of the library maintenance task,
3379 including recompilation of the source files for which objects do not exist
3380 or are not up to date, assembly of the library archive, and installation of
3381 the library (i.e., copying associated source, object and @code{ALI} files
3382 to the specified location).
3384 Here is a simple library project file:
3386 @example
3387 project My_Lib is
3388   for Source_Dirs use ("src1", "src2");
3389   for Object_Dir use "obj";
3390   for Library_Name use "mylib";
3391   for Library_Dir use "lib";
3392   for Library_Kind use "dynamic";
3393 end My_lib;
3394 @end example
3396 and the compilation command to build and install the library:
3398 @example
3399 $ gnatmake -Pmy_lib
3400 @end example
3402 It is not entirely trivial to perform manually all the steps required to
3403 produce a library. We recommend that you use the GNAT Project Manager
3404 for this task. In special cases where this is not desired, the necessary
3405 steps are discussed below.
3407 There are various possibilities for compiling the units that make up the
3408 library: for example with a Makefile (@ref{70,,Using the GNU make Utility}) or
3409 with a conventional script. For simple libraries, it is also possible to create
3410 a dummy main program which depends upon all the packages that comprise the
3411 interface of the library. This dummy main program can then be given to
3412 @code{gnatmake}, which will ensure that all necessary objects are built.
3414 After this task is accomplished, you should follow the standard procedure
3415 of the underlying operating system to produce the static or shared library.
3417 Here is an example of such a dummy program:
3419 @example
3420 with My_Lib.Service1;
3421 with My_Lib.Service2;
3422 with My_Lib.Service3;
3423 procedure My_Lib_Dummy is
3424 begin
3425    null;
3426 end;
3427 @end example
3429 Here are the generic commands that will build an archive or a shared library.
3431 @example
3432 # compiling the library
3433 $ gnatmake -c my_lib_dummy.adb
3435 # we don't need the dummy object itself
3436 $ rm my_lib_dummy.o my_lib_dummy.ali
3438 # create an archive with the remaining objects
3439 $ ar rc libmy_lib.a *.o
3440 # some systems may require "ranlib" to be run as well
3442 # or create a shared library
3443 $ gcc -shared -o libmy_lib.so *.o
3444 # some systems may require the code to have been compiled with -fPIC
3446 # remove the object files that are now in the library
3447 $ rm *.o
3449 # Make the ALI files read-only so that gnatmake will not try to
3450 # regenerate the objects that are in the library
3451 $ chmod -w *.ali
3452 @end example
3454 Please note that the library must have a name of the form @code{lib`xxx'.a}
3455 or @code{lib`xxx'.so} (or @code{lib`xxx'.dll} on Windows) in order to
3456 be accessed by the directive @code{-l`xxx'} at link time.
3458 @node Installing a library,Using a library,Building a library,General Ada Libraries
3459 @anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{72}
3460 @subsubsection Installing a library
3463 @geindex ADA_PROJECT_PATH
3465 @geindex GPR_PROJECT_PATH
3467 If you use project files, library installation is part of the library build
3468 process (see the `Installing a Library with Project Files' section of the
3469 `GNAT Project Manager' chapter of the `GPRbuild User’s Guide').
3471 When project files are not an option, it is also possible, but not recommended,
3472 to install the library so that the sources needed to use the library are on the
3473 Ada source path and the ALI files & libraries be on the Ada Object path (see
3474 @ref{73,,Search Paths and the Run-Time Library (RTL)}). Alternatively, the system
3475 administrator can place general-purpose libraries in the default compiler
3476 paths, by specifying the libraries’ location in the configuration files
3477 @code{ada_source_path} and @code{ada_object_path}. These configuration files
3478 must be located in the GNAT installation tree at the same place as the gcc spec
3479 file. The location of the gcc spec file can be determined as follows:
3481 @example
3482 $ gcc -v
3483 @end example
3485 The configuration files mentioned above have a simple format: each line
3486 must contain one unique directory name.
3487 Those names are added to the corresponding path
3488 in their order of appearance in the file. The names can be either absolute
3489 or relative; in the latter case, they are relative to where theses files
3490 are located.
3492 The files @code{ada_source_path} and @code{ada_object_path} might not be
3493 present in a
3494 GNAT installation, in which case, GNAT will look for its run-time library in
3495 the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3496 objects and @code{ALI} files). When the files exist, the compiler does not
3497 look in @code{adainclude} and @code{adalib}, and thus the
3498 @code{ada_source_path} file
3499 must contain the location for the GNAT run-time sources (which can simply
3500 be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3501 contain the location for the GNAT run-time objects (which can simply
3502 be @code{adalib}).
3504 You can also specify a new default path to the run-time library at compilation
3505 time with the switch @code{--RTS=rts-path}. You can thus choose / change
3506 the run-time library you want your program to be compiled with. This switch is
3507 recognized by @code{gcc}, @code{gnatmake}, @code{gnatbind}, @code{gnatls}, and all
3508 project aware tools.
3510 It is possible to install a library before or after the standard GNAT
3511 library, by reordering the lines in the configuration files. In general, a
3512 library must be installed before the GNAT library if it redefines
3513 any part of it.
3515 @node Using a library,,Installing a library,General Ada Libraries
3516 @anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{74}@anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{75}
3517 @subsubsection Using a library
3520 Once again, the project facility greatly simplifies the use of
3521 libraries. In this context, using a library is just a matter of adding a
3522 `with' clause in the user project. For instance, to make use of the
3523 library @code{My_Lib} shown in examples in earlier sections, you can
3524 write:
3526 @example
3527 with "my_lib";
3528 project My_Proj is
3529   ...
3530 end My_Proj;
3531 @end example
3533 Even if you have a third-party, non-Ada library, you can still use GNAT’s
3534 Project Manager facility to provide a wrapper for it. For example, the
3535 following project, when `with'ed by your main project, will link with the
3536 third-party library @code{liba.a}:
3538 @example
3539 project Liba is
3540    for Externally_Built use "true";
3541    for Source_Files use ();
3542    for Library_Dir use "lib";
3543    for Library_Name use "a";
3544    for Library_Kind use "static";
3545 end Liba;
3546 @end example
3548 This is an alternative to the use of @code{pragma Linker_Options}. It is
3549 especially interesting in the context of systems with several interdependent
3550 static libraries where finding a proper linker order is not easy and best be
3551 left to the tools having visibility over project dependence information.
3553 In order to use an Ada library manually, you need to make sure that this
3554 library is on both your source and object path
3555 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}
3556 and @ref{76,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3557 in an archive or a shared library, you need to specify the desired
3558 library at link time.
3560 For example, you can use the library @code{mylib} installed in
3561 @code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3563 @example
3564 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3565   -largs -lmy_lib
3566 @end example
3568 This can be expressed more simply:
3570 @example
3571 $ gnatmake my_appl
3572 @end example
3574 when the following conditions are met:
3577 @itemize *
3579 @item 
3580 @code{/dir/my_lib_src} has been added by the user to the environment
3581 variable 
3582 @geindex ADA_INCLUDE_PATH
3583 @geindex environment variable; ADA_INCLUDE_PATH
3584 @code{ADA_INCLUDE_PATH}, or by the administrator to the file
3585 @code{ada_source_path}
3587 @item 
3588 @code{/dir/my_lib_obj} has been added by the user to the environment
3589 variable 
3590 @geindex ADA_OBJECTS_PATH
3591 @geindex environment variable; ADA_OBJECTS_PATH
3592 @code{ADA_OBJECTS_PATH}, or by the administrator to the file
3593 @code{ada_object_path}
3595 @item 
3596 a pragma @code{Linker_Options} has been added to one of the sources.
3597 For example:
3599 @example
3600 pragma Linker_Options ("-lmy_lib");
3601 @end example
3602 @end itemize
3604 Note that you may also load a library dynamically at
3605 run time given its filename, as illustrated in the GNAT @code{plugins} example
3606 in the directory @code{share/examples/gnat/plugins} within the GNAT
3607 install area.
3609 @node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3610 @anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{6b}
3611 @subsection Stand-alone Ada Libraries
3614 @geindex Stand-alone libraries
3616 @menu
3617 * Introduction to Stand-alone Libraries:: 
3618 * Building a Stand-alone Library:: 
3619 * Creating a Stand-alone Library to be used in a non-Ada context:: 
3620 * Restrictions in Stand-alone Libraries:: 
3622 @end menu
3624 @node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3625 @anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{78}@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{79}
3626 @subsubsection Introduction to Stand-alone Libraries
3629 A Stand-alone Library (abbreviated ‘SAL’) is a library that contains the
3630 necessary code to
3631 elaborate the Ada units that are included in the library. In contrast with
3632 an ordinary library, which consists of all sources, objects and @code{ALI}
3633 files of the
3634 library, a SAL may specify a restricted subset of compilation units
3635 to serve as a library interface. In this case, the fully
3636 self-sufficient set of files will normally consist of an objects
3637 archive, the sources of interface units’ specs, and the @code{ALI}
3638 files of interface units.
3639 If an interface spec contains a generic unit or an inlined subprogram,
3640 the body’s
3641 source must also be provided; if the units that must be provided in the source
3642 form depend on other units, the source and @code{ALI} files of those must
3643 also be provided.
3645 The main purpose of a SAL is to minimize the recompilation overhead of client
3646 applications when a new version of the library is installed. Specifically,
3647 if the interface sources have not changed, client applications do not need to
3648 be recompiled. If, furthermore, a SAL is provided in the shared form and its
3649 version, controlled by @code{Library_Version} attribute, is not changed,
3650 then the clients do not need to be relinked.
3652 SALs also allow the library providers to minimize the amount of library source
3653 text exposed to the clients.  Such ‘information hiding’ might be useful or
3654 necessary for various reasons.
3656 Stand-alone libraries are also well suited to be used in an executable whose
3657 main routine is not written in Ada.
3659 @node Building a Stand-alone Library,Creating a Stand-alone Library to be used in a non-Ada context,Introduction to Stand-alone Libraries,Stand-alone Ada Libraries
3660 @anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{7a}@anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{7b}
3661 @subsubsection Building a Stand-alone Library
3664 GNAT’s Project facility provides a simple way of building and installing
3665 stand-alone libraries; see the `Stand-alone Library Projects' section
3666 in the `GNAT Project Manager' chapter of the `GPRbuild User’s Guide'.
3667 To be a Stand-alone Library Project, in addition to the two attributes
3668 that make a project a Library Project (@code{Library_Name} and
3669 @code{Library_Dir}; see the `Library Projects' section in the
3670 `GNAT Project Manager' chapter of the `GPRbuild User’s Guide'),
3671 the attribute @code{Library_Interface} must be defined.  For example:
3673 @example
3674 for Library_Dir use "lib_dir";
3675 for Library_Name use "dummy";
3676 for Library_Interface use ("int1", "int1.child");
3677 @end example
3679 Attribute @code{Library_Interface} has a non-empty string list value,
3680 each string in the list designating a unit contained in an immediate source
3681 of the project file.
3683 When a Stand-alone Library is built, first the binder is invoked to build
3684 a package whose name depends on the library name
3685 (@code{b~dummy.ads/b} in the example above).
3686 This binder-generated package includes initialization and
3687 finalization procedures whose
3688 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
3689 in the example
3690 above). The object corresponding to this package is included in the library.
3692 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3693 calling of these procedures if a static SAL is built, or if a shared SAL
3694 is built
3695 with the project-level attribute @code{Library_Auto_Init} set to
3696 @code{"false"}.
3698 For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
3699 (those that are listed in attribute @code{Library_Interface}) are copied to
3700 the Library Directory. As a consequence, only the Interface Units may be
3701 imported from Ada units outside of the library. If other units are imported,
3702 the binding phase will fail.
3704 It is also possible to build an encapsulated library where not only
3705 the code to elaborate and finalize the library is embedded but also
3706 ensuring that the library is linked only against static
3707 libraries. So an encapsulated library only depends on system
3708 libraries, all other code, including the GNAT runtime, is embedded. To
3709 build an encapsulated library the attribute
3710 @code{Library_Standalone} must be set to @code{encapsulated}:
3712 @example
3713 for Library_Dir use "lib_dir";
3714 for Library_Name use "dummy";
3715 for Library_Kind use "dynamic";
3716 for Library_Interface use ("int1", "int1.child");
3717 for Library_Standalone use "encapsulated";
3718 @end example
3720 The default value for this attribute is @code{standard} in which case
3721 a stand-alone library is built.
3723 The attribute @code{Library_Src_Dir} may be specified for a
3724 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
3725 single string value. Its value must be the path (absolute or relative to the
3726 project directory) of an existing directory. This directory cannot be the
3727 object directory or one of the source directories, but it can be the same as
3728 the library directory. The sources of the Interface
3729 Units of the library that are needed by an Ada client of the library will be
3730 copied to the designated directory, called the Interface Copy directory.
3731 These sources include the specs of the Interface Units, but they may also
3732 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
3733 are used, or when there is a generic unit in the spec. Before the sources
3734 are copied to the Interface Copy directory, an attempt is made to delete all
3735 files in the Interface Copy directory.
3737 Building stand-alone libraries by hand is somewhat tedious, but for those
3738 occasions when it is necessary here are the steps that you need to perform:
3741 @itemize *
3743 @item 
3744 Compile all library sources.
3746 @item 
3747 Invoke the binder with the switch @code{-n} (No Ada main program),
3748 with all the @code{ALI} files of the interfaces, and
3749 with the switch @code{-L} to give specific names to the @code{init}
3750 and @code{final} procedures.  For example:
3752 @example
3753 $ gnatbind -n int1.ali int2.ali -Lsal1
3754 @end example
3756 @item 
3757 Compile the binder generated file:
3759 @example
3760 $ gcc -c b~int2.adb
3761 @end example
3763 @item 
3764 Link the dynamic library with all the necessary object files,
3765 indicating to the linker the names of the @code{init} (and possibly
3766 @code{final}) procedures for automatic initialization (and finalization).
3767 The built library should be placed in a directory different from
3768 the object directory.
3770 @item 
3771 Copy the @code{ALI} files of the interface to the library directory,
3772 add in this copy an indication that it is an interface to a SAL
3773 (i.e., add a word @code{SL} on the line in the @code{ALI} file that starts
3774 with letter ‘P’) and make the modified copy of the @code{ALI} file
3775 read-only.
3776 @end itemize
3778 Using SALs is not different from using other libraries
3779 (see @ref{75,,Using a library}).
3781 @node Creating a Stand-alone Library to be used in a non-Ada context,Restrictions in Stand-alone Libraries,Building a Stand-alone Library,Stand-alone Ada Libraries
3782 @anchor{gnat_ugn/the_gnat_compilation_model creating-a-stand-alone-library-to-be-used-in-a-non-ada-context}@anchor{7c}@anchor{gnat_ugn/the_gnat_compilation_model id44}@anchor{7d}
3783 @subsubsection Creating a Stand-alone Library to be used in a non-Ada context
3786 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
3787 a non-Ada context.
3789 The only extra step required is to ensure that library interface subprograms
3790 are compatible with the main program, by means of @code{pragma Export}
3791 or @code{pragma Convention}.
3793 Here is an example of simple library interface for use with C main program:
3795 @example
3796 package My_Package is
3798    procedure Do_Something;
3799    pragma Export (C, Do_Something, "do_something");
3801    procedure Do_Something_Else;
3802    pragma Export (C, Do_Something_Else, "do_something_else");
3804 end My_Package;
3805 @end example
3807 On the foreign language side, you must provide a ‘foreign’ view of the
3808 library interface; remember that it should contain elaboration routines in
3809 addition to interface subprograms.
3811 The example below shows the content of @code{mylib_interface.h} (note
3812 that there is no rule for the naming of this file, any name can be used)
3814 @example
3815 /* the library elaboration procedure */
3816 extern void mylibinit (void);
3818 /* the library finalization procedure */
3819 extern void mylibfinal (void);
3821 /* the interface exported by the library */
3822 extern void do_something (void);
3823 extern void do_something_else (void);
3824 @end example
3826 Libraries built as explained above can be used from any program, provided
3827 that the elaboration procedures (named @code{mylibinit} in the previous
3828 example) are called before the library services are used. Any number of
3829 libraries can be used simultaneously, as long as the elaboration
3830 procedure of each library is called.
3832 Below is an example of a C program that uses the @code{mylib} library.
3834 @example
3835 #include "mylib_interface.h"
3838 main (void)
3840    /* First, elaborate the library before using it */
3841    mylibinit ();
3843    /* Main program, using the library exported entities */
3844    do_something ();
3845    do_something_else ();
3847    /* Library finalization at the end of the program */
3848    mylibfinal ();
3849    return 0;
3851 @end example
3853 Note that invoking any library finalization procedure generated by
3854 @code{gnatbind} shuts down the Ada run-time environment.
3855 Consequently, the
3856 finalization of all Ada libraries must be performed at the end of the program.
3857 No call to these libraries or to the Ada run-time library should be made
3858 after the finalization phase.
3860 Information on limitations of binding Ada code in non-Ada contexts can be
3861 found under @ref{7e,,Binding with Non-Ada Main Programs}.
3863 Note also that special care must be taken with multi-tasks
3864 applications. The initialization and finalization routines are not
3865 protected against concurrent access. If such requirement is needed it
3866 must be ensured at the application level using a specific operating
3867 system services like a mutex or a critical-section.
3869 @node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
3870 @anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{7f}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{80}
3871 @subsubsection Restrictions in Stand-alone Libraries
3874 The pragmas listed below should be used with caution inside libraries,
3875 as they can create incompatibilities with other Ada libraries:
3878 @itemize *
3880 @item 
3881 pragma @code{Locking_Policy}
3883 @item 
3884 pragma @code{Partition_Elaboration_Policy}
3886 @item 
3887 pragma @code{Queuing_Policy}
3889 @item 
3890 pragma @code{Task_Dispatching_Policy}
3892 @item 
3893 pragma @code{Unreserve_All_Interrupts}
3894 @end itemize
3896 When using a library that contains such pragmas, the user must make sure
3897 that all libraries use the same pragmas with the same values. Otherwise,
3898 @code{Program_Error} will
3899 be raised during the elaboration of the conflicting
3900 libraries. The usage of these pragmas and its consequences for the user
3901 should therefore be well documented.
3903 Similarly, the traceback in the exception occurrence mechanism should be
3904 enabled or disabled in a consistent manner across all libraries.
3905 Otherwise, Program_Error will be raised during the elaboration of the
3906 conflicting libraries.
3908 If the @code{Version} or @code{Body_Version}
3909 attributes are used inside a library, then you need to
3910 perform a @code{gnatbind} step that specifies all @code{ALI} files in all
3911 libraries, so that version identifiers can be properly computed.
3912 In practice these attributes are rarely used, so this is unlikely
3913 to be a consideration.
3915 @node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
3916 @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}
3917 @subsection Rebuilding the GNAT Run-Time Library
3920 @geindex GNAT Run-Time Library
3921 @geindex rebuilding
3923 @geindex Building the GNAT Run-Time Library
3925 @geindex Rebuilding the GNAT Run-Time Library
3927 @geindex Run-Time Library
3928 @geindex rebuilding
3930 It may be useful to recompile the GNAT library in various debugging or
3931 experimentation contexts. A project file called
3932 @code{libada.gpr} is provided to that effect and can be found in
3933 the directory containing the GNAT library. The location of this
3934 directory depends on the way the GNAT environment has been installed and can
3935 be determined by means of the command:
3937 @example
3938 $ gnatls -v
3939 @end example
3941 The last entry in the source search path usually contains the
3942 gnat library (the @code{adainclude} directory). This project file contains its
3943 own documentation and in particular the set of instructions needed to rebuild a
3944 new library and to use it.
3946 Note that rebuilding the GNAT Run-Time is only recommended for temporary
3947 experiments or debugging, and is not supported.
3949 @geindex Conditional compilation
3951 @node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
3952 @anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{2b}@anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{83}
3953 @section Conditional Compilation
3956 This section presents some guidelines for modeling conditional compilation in Ada and describes the
3957 gnatprep preprocessor utility.
3959 @geindex Conditional compilation
3961 @menu
3962 * Modeling Conditional Compilation in Ada:: 
3963 * Preprocessing with gnatprep:: 
3964 * Integrated Preprocessing:: 
3966 @end menu
3968 @node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
3969 @anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{84}@anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{85}
3970 @subsection Modeling Conditional Compilation in Ada
3973 It is often necessary to arrange for a single source program
3974 to serve multiple purposes, where it is compiled in different
3975 ways to achieve these different goals. Some examples of the
3976 need for this feature are
3979 @itemize *
3981 @item 
3982 Adapting a program to a different hardware environment
3984 @item 
3985 Adapting a program to a different target architecture
3987 @item 
3988 Turning debugging features on and off
3990 @item 
3991 Arranging for a program to compile with different compilers
3992 @end itemize
3994 In C, or C++, the typical approach would be to use the preprocessor
3995 that is defined as part of the language. The Ada language does not
3996 contain such a feature. This is not an oversight, but rather a very
3997 deliberate design decision, based on the experience that overuse of
3998 the preprocessing features in C and C++ can result in programs that
3999 are extremely difficult to maintain. For example, if we have ten
4000 switches that can be on or off, this means that there are a thousand
4001 separate programs, any one of which might not even be syntactically
4002 correct, and even if syntactically correct, the resulting program
4003 might not work correctly. Testing all combinations can quickly become
4004 impossible.
4006 Nevertheless, the need to tailor programs certainly exists, and in
4007 this section we will discuss how this can
4008 be achieved using Ada in general, and GNAT in particular.
4010 @menu
4011 * Use of Boolean Constants:: 
4012 * Debugging - A Special Case:: 
4013 * Conditionalizing Declarations:: 
4014 * Use of Alternative Implementations:: 
4015 * Preprocessing:: 
4017 @end menu
4019 @node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4020 @anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{86}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{87}
4021 @subsubsection Use of Boolean Constants
4024 In the case where the difference is simply which code
4025 sequence is executed, the cleanest solution is to use Boolean
4026 constants to control which code is executed.
4028 @example
4029 FP_Initialize_Required : constant Boolean := True;
4031 if FP_Initialize_Required then
4033 end if;
4034 @end example
4036 Not only will the code inside the @code{if} statement not be executed if
4037 the constant Boolean is @code{False}, but it will also be completely
4038 deleted from the program.
4039 However, the code is only deleted after the @code{if} statement
4040 has been checked for syntactic and semantic correctness.
4041 (In contrast, with preprocessors the code is deleted before the
4042 compiler ever gets to see it, so it is not checked until the switch
4043 is turned on.)
4045 @geindex Preprocessors (contrasted with conditional compilation)
4047 Typically the Boolean constants will be in a separate package,
4048 something like:
4050 @example
4051 package Config is
4052    FP_Initialize_Required : constant Boolean := True;
4053    Reset_Available        : constant Boolean := False;
4054    ...
4055 end Config;
4056 @end example
4058 The @code{Config} package exists in multiple forms for the various targets,
4059 with an appropriate script selecting the version of @code{Config} needed.
4060 Then any other unit requiring conditional compilation can do a `with'
4061 of @code{Config} to make the constants visible.
4063 @node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4064 @anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{88}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{89}
4065 @subsubsection Debugging - A Special Case
4068 A common use of conditional code is to execute statements (for example
4069 dynamic checks, or output of intermediate results) under control of a
4070 debug switch, so that the debugging behavior can be turned on and off.
4071 This can be done using a Boolean constant to control whether the code
4072 is active:
4074 @example
4075 if Debugging then
4076    Put_Line ("got to the first stage!");
4077 end if;
4078 @end example
4082 @example
4083 if Debugging and then Temperature > 999.0 then
4084    raise Temperature_Crazy;
4085 end if;
4086 @end example
4088 @geindex pragma Assert
4090 Since this is a common case, there are special features to deal with
4091 this in a convenient manner. For the case of tests, Ada 2005 has added
4092 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
4093 on the @code{Assert} pragma that has always been available in GNAT, so this
4094 feature may be used with GNAT even if you are not using Ada 2005 features.
4095 The use of pragma @code{Assert} is described in the
4096 @cite{GNAT_Reference_Manual}, but as an
4097 example, the last test could be written:
4099 @example
4100 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4101 @end example
4103 or simply
4105 @example
4106 pragma Assert (Temperature <= 999.0);
4107 @end example
4109 In both cases, if assertions are active and the temperature is excessive,
4110 the exception @code{Assert_Failure} will be raised, with the given string in
4111 the first case or a string indicating the location of the pragma in the second
4112 case used as the exception message.
4114 @geindex pragma Assertion_Policy
4116 You can turn assertions on and off by using the @code{Assertion_Policy}
4117 pragma.
4119 @geindex -gnata switch
4121 This is an Ada 2005 pragma which is implemented in all modes by
4122 GNAT. Alternatively, you can use the @code{-gnata} switch
4123 to enable assertions from the command line, which applies to
4124 all versions of Ada.
4126 @geindex pragma Debug
4128 For the example above with the @code{Put_Line}, the GNAT-specific pragma
4129 @code{Debug} can be used:
4131 @example
4132 pragma Debug (Put_Line ("got to the first stage!"));
4133 @end example
4135 If debug pragmas are enabled, the argument, which must be of the form of
4136 a procedure call, is executed (in this case, @code{Put_Line} will be called).
4137 Only one call can be present, but of course a special debugging procedure
4138 containing any code you like can be included in the program and then
4139 called in a pragma @code{Debug} argument as needed.
4141 One advantage of pragma @code{Debug} over the @code{if Debugging then}
4142 construct is that pragma @code{Debug} can appear in declarative contexts,
4143 such as at the very beginning of a procedure, before local declarations have
4144 been elaborated.
4146 @geindex pragma Debug_Policy
4148 Debug pragmas are enabled using either the @code{-gnata} switch that also
4149 controls assertions, or with a separate Debug_Policy pragma.
4151 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4152 in Ada 95 and Ada 83 programs as well), and is analogous to
4153 pragma @code{Assertion_Policy} to control assertions.
4155 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
4156 and thus they can appear in @code{gnat.adc} if you are not using a
4157 project file, or in the file designated to contain configuration pragmas
4158 in a project file.
4159 They then apply to all subsequent compilations. In practice the use of
4160 the @code{-gnata} switch is often the most convenient method of controlling
4161 the status of these pragmas.
4163 Note that a pragma is not a statement, so in contexts where a statement
4164 sequence is required, you can’t just write a pragma on its own. You have
4165 to add a @code{null} statement.
4167 @example
4168 if ... then
4169    ... -- some statements
4170 else
4171    pragma Assert (Num_Cases < 10);
4172    null;
4173 end if;
4174 @end example
4176 @node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4177 @anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{8a}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{8b}
4178 @subsubsection Conditionalizing Declarations
4181 In some cases it may be necessary to conditionalize declarations to meet
4182 different requirements. For example we might want a bit string whose length
4183 is set to meet some hardware message requirement.
4185 This may be possible using declare blocks controlled
4186 by conditional constants:
4188 @example
4189 if Small_Machine then
4190    declare
4191       X : Bit_String (1 .. 10);
4192    begin
4193       ...
4194    end;
4195 else
4196    declare
4197       X : Large_Bit_String (1 .. 1000);
4198    begin
4199       ...
4200    end;
4201 end if;
4202 @end example
4204 Note that in this approach, both declarations are analyzed by the
4205 compiler so this can only be used where both declarations are legal,
4206 even though one of them will not be used.
4208 Another approach is to define integer constants, e.g., @code{Bits_Per_Word},
4209 or Boolean constants, e.g., @code{Little_Endian}, and then write declarations
4210 that are parameterized by these constants. For example
4212 @example
4213 for Rec use
4214   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4215 end record;
4216 @end example
4218 If @code{Bits_Per_Word} is set to 32, this generates either
4220 @example
4221 for Rec use
4222   Field1 at 0 range 0 .. 32;
4223 end record;
4224 @end example
4226 for the big endian case, or
4228 @example
4229 for Rec use record
4230     Field1 at 0 range 10 .. 32;
4231 end record;
4232 @end example
4234 for the little endian case. Since a powerful subset of Ada expression
4235 notation is usable for creating static constants, clever use of this
4236 feature can often solve quite difficult problems in conditionalizing
4237 compilation (note incidentally that in Ada 95, the little endian
4238 constant was introduced as @code{System.Default_Bit_Order}, so you do not
4239 need to define this one yourself).
4241 @node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4242 @anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{8c}@anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{8d}
4243 @subsubsection Use of Alternative Implementations
4246 In some cases, none of the approaches described above are adequate. This
4247 can occur for example if the set of declarations required is radically
4248 different for two different configurations.
4250 In this situation, the official Ada way of dealing with conditionalizing
4251 such code is to write separate units for the different cases. As long as
4252 this does not result in excessive duplication of code, this can be done
4253 without creating maintenance problems. The approach is to share common
4254 code as far as possible, and then isolate the code and declarations
4255 that are different. Subunits are often a convenient method for breaking
4256 out a piece of a unit that is to be conditionalized, with separate files
4257 for different versions of the subunit for different targets, where the
4258 build script selects the right one to give to the compiler.
4260 @geindex Subunits (and conditional compilation)
4262 As an example, consider a situation where a new feature in Ada 2005
4263 allows something to be done in a really nice way. But your code must be able
4264 to compile with an Ada 95 compiler. Conceptually you want to say:
4266 @example
4267 if Ada_2005 then
4268    ... neat Ada 2005 code
4269 else
4270    ... not quite as neat Ada 95 code
4271 end if;
4272 @end example
4274 where @code{Ada_2005} is a Boolean constant.
4276 But this won’t work when @code{Ada_2005} is set to @code{False},
4277 since the @code{then} clause will be illegal for an Ada 95 compiler.
4278 (Recall that although such unreachable code would eventually be deleted
4279 by the compiler, it still needs to be legal.  If it uses features
4280 introduced in Ada 2005, it will be illegal in Ada 95.)
4282 So instead we write
4284 @example
4285 procedure Insert is separate;
4286 @end example
4288 Then we have two files for the subunit @code{Insert}, with the two sets of
4289 code.
4290 If the package containing this is called @code{File_Queries}, then we might
4291 have two files
4294 @itemize *
4296 @item 
4297 @code{file_queries-insert-2005.adb}
4299 @item 
4300 @code{file_queries-insert-95.adb}
4301 @end itemize
4303 and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4305 This can also be done with project files’ naming schemes. For example:
4307 @example
4308 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4309 @end example
4311 Note also that with project files it is desirable to use a different extension
4312 than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4313 conflict may arise through another commonly used feature: to declare as part
4314 of the project a set of directories containing all the sources obeying the
4315 default naming scheme.
4317 The use of alternative units is certainly feasible in all situations,
4318 and for example the Ada part of the GNAT run-time is conditionalized
4319 based on the target architecture using this approach. As a specific example,
4320 consider the implementation of the AST feature in VMS. There is one
4321 spec: @code{s-asthan.ads} which is the same for all architectures, and three
4322 bodies:
4325 @itemize *
4327 @item 
4329 @table @asis
4331 @item @code{s-asthan.adb}
4333 used for all non-VMS operating systems
4334 @end table
4336 @item 
4338 @table @asis
4340 @item @code{s-asthan-vms-alpha.adb}
4342 used for VMS on the Alpha
4343 @end table
4345 @item 
4347 @table @asis
4349 @item @code{s-asthan-vms-ia64.adb}
4351 used for VMS on the ia64
4352 @end table
4353 @end itemize
4355 The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4356 this operating system feature is not available, and the two remaining
4357 versions interface with the corresponding versions of VMS to provide
4358 VMS-compatible AST handling. The GNAT build script knows the architecture
4359 and operating system, and automatically selects the right version,
4360 renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4362 Another style for arranging alternative implementations is through Ada’s
4363 access-to-subprogram facility.
4364 In case some functionality is to be conditionally included,
4365 you can declare an access-to-procedure variable @code{Ref} that is initialized
4366 to designate a ‘do nothing’ procedure, and then invoke @code{Ref.all}
4367 when appropriate.
4368 In some library package, set @code{Ref} to @code{Proc'Access} for some
4369 procedure @code{Proc} that performs the relevant processing.
4370 The initialization only occurs if the library package is included in the
4371 program.
4372 The same idea can also be implemented using tagged types and dispatching
4373 calls.
4375 @node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4376 @anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{8e}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{8f}
4377 @subsubsection Preprocessing
4380 @geindex Preprocessing
4382 Although it is quite possible to conditionalize code without the use of
4383 C-style preprocessing, as described earlier in this section, it is
4384 nevertheless convenient in some cases to use the C approach. Moreover,
4385 older Ada compilers have often provided some preprocessing capability,
4386 so legacy code may depend on this approach, even though it is not
4387 standard.
4389 To accommodate such use, GNAT provides a preprocessor (modeled to a large
4390 extent on the various preprocessors that have been used
4391 with legacy code on other compilers, to enable easier transition).
4393 @geindex gnatprep
4395 The preprocessor may be used in two separate modes. It can be used quite
4396 separately from the compiler, to generate a separate output source file
4397 that is then fed to the compiler as a separate step. This is the
4398 @code{gnatprep} utility, whose use is fully described in
4399 @ref{90,,Preprocessing with gnatprep}.
4401 The preprocessing language allows such constructs as
4403 @example
4404 #if DEBUG or else (PRIORITY > 4) then
4405    sequence of declarations
4406 #else
4407    completely different sequence of declarations
4408 #end if;
4409 @end example
4411 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
4412 defined either on the command line or in a separate file.
4414 The other way of running the preprocessor is even closer to the C style and
4415 often more convenient. In this approach the preprocessing is integrated into
4416 the compilation process. The compiler is given the preprocessor input which
4417 includes @code{#if} lines etc, and then the compiler carries out the
4418 preprocessing internally and processes the resulting output.
4419 For more details on this approach, see @ref{91,,Integrated Preprocessing}.
4421 @node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4422 @anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{92}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{90}
4423 @subsection Preprocessing with @code{gnatprep}
4426 @geindex gnatprep
4428 @geindex Preprocessing (gnatprep)
4430 This section discusses how to use GNAT’s @code{gnatprep} utility for simple
4431 preprocessing.
4432 Although designed for use with GNAT, @code{gnatprep} does not depend on any
4433 special GNAT features.
4434 For further discussion of conditional compilation in general, see
4435 @ref{2b,,Conditional Compilation}.
4437 @menu
4438 * Preprocessing Symbols:: 
4439 * Using gnatprep:: 
4440 * Switches for gnatprep:: 
4441 * Form of Definitions File:: 
4442 * Form of Input Text for gnatprep:: 
4444 @end menu
4446 @node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4447 @anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{93}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{94}
4448 @subsubsection Preprocessing Symbols
4451 Preprocessing symbols are defined in `definition files' and referenced in the
4452 sources to be preprocessed. A preprocessing symbol is an identifier, following
4453 normal Ada (case-insensitive) rules for its syntax, with the restriction that
4454 all characters need to be in the ASCII set (no accented letters).
4456 @node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4457 @anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{95}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{96}
4458 @subsubsection Using @code{gnatprep}
4461 To call @code{gnatprep} use:
4463 @example
4464 $ gnatprep [ switches ] infile outfile [ deffile ]
4465 @end example
4467 where
4470 @itemize *
4472 @item 
4474 @table @asis
4476 @item `switches'
4478 is an optional sequence of switches as described in the next section.
4479 @end table
4481 @item 
4483 @table @asis
4485 @item `infile'
4487 is the full name of the input file, which is an Ada source
4488 file containing preprocessor directives.
4489 @end table
4491 @item 
4493 @table @asis
4495 @item `outfile'
4497 is the full name of the output file, which is an Ada source
4498 in standard Ada form. When used with GNAT, this file name will
4499 normally have an @code{ads} or @code{adb} suffix.
4500 @end table
4502 @item 
4504 @table @asis
4506 @item @code{deffile}
4508 is the full name of a text file containing definitions of
4509 preprocessing symbols to be referenced by the preprocessor. This argument is
4510 optional, and can be replaced by the use of the @code{-D} switch.
4511 @end table
4512 @end itemize
4514 @node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4515 @anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{97}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{98}
4516 @subsubsection Switches for @code{gnatprep}
4519 @geindex --version (gnatprep)
4522 @table @asis
4524 @item @code{--version}
4526 Display Copyright and version, then exit disregarding all other options.
4527 @end table
4529 @geindex --help (gnatprep)
4532 @table @asis
4534 @item @code{--help}
4536 If @code{--version} was not used, display usage and then exit disregarding
4537 all other options.
4538 @end table
4540 @geindex -b (gnatprep)
4543 @table @asis
4545 @item @code{-b}
4547 Causes both preprocessor lines and the lines deleted by
4548 preprocessing to be replaced by blank lines in the output source file,
4549 preserving line numbers in the output file.
4550 @end table
4552 @geindex -c (gnatprep)
4555 @table @asis
4557 @item @code{-c}
4559 Causes both preprocessor lines and the lines deleted
4560 by preprocessing to be retained in the output source as comments marked
4561 with the special string @code{"--! "}. This option will result in line numbers
4562 being preserved in the output file.
4563 @end table
4565 @geindex -C (gnatprep)
4568 @table @asis
4570 @item @code{-C}
4572 Causes comments to be scanned. Normally comments are ignored by gnatprep.
4573 If this option is specified, then comments are scanned and any $symbol
4574 substitutions performed as in program text. This is particularly useful
4575 when structured comments are used (e.g., for programs written in a
4576 pre-2014 version of the SPARK Ada subset). Note that this switch is not
4577 available when  doing integrated preprocessing (it would be useless in
4578 this context since comments are ignored by the compiler in any case).
4579 @end table
4581 @geindex -D (gnatprep)
4584 @table @asis
4586 @item @code{-D`symbol'[=`value']}
4588 Defines a new preprocessing symbol with the specified value. If no value is given
4589 on the command line, then symbol is considered to be @code{True}. This switch
4590 can be used in place of a definition file.
4591 @end table
4593 @geindex -r (gnatprep)
4596 @table @asis
4598 @item @code{-r}
4600 Causes a @code{Source_Reference} pragma to be generated that
4601 references the original input file, so that error messages will use
4602 the file name of this original file. The use of this switch implies
4603 that preprocessor lines are not to be removed from the file, so its
4604 use will force @code{-b} mode if @code{-c}
4605 has not been specified explicitly.
4607 Note that if the file to be preprocessed contains multiple units, then
4608 it will be necessary to @code{gnatchop} the output file from
4609 @code{gnatprep}. If a @code{Source_Reference} pragma is present
4610 in the preprocessed file, it will be respected by
4611 @code{gnatchop -r}
4612 so that the final chopped files will correctly refer to the original
4613 input source file for @code{gnatprep}.
4614 @end table
4616 @geindex -s (gnatprep)
4619 @table @asis
4621 @item @code{-s}
4623 Causes a sorted list of symbol names and values to be
4624 listed on the standard output file.
4625 @end table
4627 @geindex -T (gnatprep)
4630 @table @asis
4632 @item @code{-T}
4634 Use LF as line terminators when writing files. By default the line terminator
4635 of the host (LF under unix, CR/LF under Windows) is used.
4636 @end table
4638 @geindex -u (gnatprep)
4641 @table @asis
4643 @item @code{-u}
4645 Causes undefined symbols to be treated as having the value FALSE in the context
4646 of a preprocessor test. In the absence of this option, an undefined symbol in
4647 a @code{#if} or @code{#elsif} test will be treated as an error.
4648 @end table
4650 @geindex -v (gnatprep)
4653 @table @asis
4655 @item @code{-v}
4657 Verbose mode: generates more output about work done.
4658 @end table
4660 Note: if neither @code{-b} nor @code{-c} is present,
4661 then preprocessor lines and
4662 deleted lines are completely removed from the output, unless -r is
4663 specified, in which case -b is assumed.
4665 @node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4666 @anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{99}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{9a}
4667 @subsubsection Form of Definitions File
4670 The definitions file contains lines of the form:
4672 @example
4673 symbol := value
4674 @end example
4676 where @code{symbol} is a preprocessing symbol, and @code{value} is one of the following:
4679 @itemize *
4681 @item 
4682 Empty, corresponding to a null substitution,
4684 @item 
4685 A string literal using normal Ada syntax, or
4687 @item 
4688 Any sequence of characters from the set @{letters, digits, period, underline@}.
4689 @end itemize
4691 Comment lines may also appear in the definitions file, starting with
4692 the usual @code{--},
4693 and comments may be added to the definitions lines.
4695 @node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4696 @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}
4697 @subsubsection Form of Input Text for @code{gnatprep}
4700 The input text may contain preprocessor conditional inclusion lines,
4701 as well as general symbol substitution sequences.
4703 The preprocessor conditional inclusion commands have the form:
4705 @example
4706 #if <expression> [then]
4707    lines
4708 #elsif <expression> [then]
4709    lines
4710 #elsif <expression> [then]
4711    lines
4713 #else
4714    lines
4715 #end if;
4716 @end example
4718 In this example, <expression> is defined by the following grammar:
4720 @example
4721 <expression> ::=  <symbol>
4722 <expression> ::=  <symbol> = "<value>"
4723 <expression> ::=  <symbol> = <symbol>
4724 <expression> ::=  <symbol> = <integer>
4725 <expression> ::=  <symbol> > <integer>
4726 <expression> ::=  <symbol> >= <integer>
4727 <expression> ::=  <symbol> < <integer>
4728 <expression> ::=  <symbol> <= <integer>
4729 <expression> ::=  <symbol> 'Defined
4730 <expression> ::=  not <expression>
4731 <expression> ::=  <expression> and <expression>
4732 <expression> ::=  <expression> or <expression>
4733 <expression> ::=  <expression> and then <expression>
4734 <expression> ::=  <expression> or else <expression>
4735 <expression> ::=  ( <expression> )
4736 @end example
4738 Note the following restriction: it is not allowed to have “and” or “or”
4739 following “not” in the same expression without parentheses. For example, this
4740 is not allowed:
4742 @example
4743 not X or Y
4744 @end example
4746 This can be expressed instead as one of the following forms:
4748 @example
4749 (not X) or Y
4750 not (X or Y)
4751 @end example
4753 For the first test (<expression> ::= <symbol>) the symbol must have
4754 either the value true or false, that is to say the right-hand of the
4755 symbol definition must be one of the (case-insensitive) literals
4756 @code{True} or @code{False}. If the value is true, then the
4757 corresponding lines are included, and if the value is false, they are
4758 excluded.
4760 When comparing a symbol to an integer, the integer is any non negative
4761 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
4762 2#11#. The symbol value must also be a non negative integer. Integer values
4763 in the range 0 .. 2**31-1 are supported.
4765 The test (<expression> ::= <symbol>’Defined) is true only if
4766 the symbol has been defined in the definition file or by a @code{-D}
4767 switch on the command line. Otherwise, the test is false.
4769 The equality tests are case insensitive, as are all the preprocessor lines.
4771 If the symbol referenced is not defined in the symbol definitions file,
4772 then the effect depends on whether or not switch @code{-u}
4773 is specified. If so, then the symbol is treated as if it had the value
4774 false and the test fails. If this switch is not specified, then
4775 it is an error to reference an undefined symbol. It is also an error to
4776 reference a symbol that is defined with a value other than @code{True}
4777 or @code{False}.
4779 The use of the @code{not} operator inverts the sense of this logical test.
4780 The @code{not} operator cannot be combined with the @code{or} or @code{and}
4781 operators, without parentheses. For example, “if not X or Y then” is not
4782 allowed, but “if (not X) or Y then” and “if not (X or Y) then” are.
4784 The @code{then} keyword is optional as shown
4786 The @code{#} must be the first non-blank character on a line, but
4787 otherwise the format is free form. Spaces or tabs may appear between
4788 the @code{#} and the keyword. The keywords and the symbols are case
4789 insensitive as in normal Ada code. Comments may be used on a
4790 preprocessor line, but other than that, no other tokens may appear on a
4791 preprocessor line. Any number of @code{elsif} clauses can be present,
4792 including none at all. The @code{else} is optional, as in Ada.
4794 The @code{#} marking the start of a preprocessor line must be the first
4795 non-blank character on the line, i.e., it must be preceded only by
4796 spaces or horizontal tabs.
4798 Symbol substitution outside of preprocessor lines is obtained by using
4799 the sequence:
4801 @example
4802 $symbol
4803 @end example
4805 anywhere within a source line, except in a comment or within a
4806 string literal. The identifier
4807 following the @code{$} must match one of the symbols defined in the symbol
4808 definition file, and the result is to substitute the value of the
4809 symbol in place of @code{$symbol} in the output file.
4811 Note that although the substitution of strings within a string literal
4812 is not possible, it is possible to have a symbol whose defined value is
4813 a string literal. So instead of setting XYZ to @code{hello} and writing:
4815 @example
4816 Header : String := "$XYZ";
4817 @end example
4819 you should set XYZ to @code{"hello"} and write:
4821 @example
4822 Header : String := $XYZ;
4823 @end example
4825 and then the substitution will occur as desired.
4827 @node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
4828 @anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{9d}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{91}
4829 @subsection Integrated Preprocessing
4832 As noted above, a file to be preprocessed consists of Ada source code
4833 in which preprocessing lines have been inserted. However,
4834 instead of using @code{gnatprep} to explicitly preprocess a file as a separate
4835 step before compilation, you can carry out the preprocessing implicitly
4836 as part of compilation. Such `integrated preprocessing', which is the common
4837 style with C, is performed when either or both of the following switches
4838 are passed to the compiler:
4840 @quotation
4843 @itemize *
4845 @item 
4846 @code{-gnatep}, which specifies the `preprocessor data file'.
4847 This file dictates how the source files will be preprocessed (e.g., which
4848 symbol definition files apply to which sources).
4850 @item 
4851 @code{-gnateD}, which defines values for preprocessing symbols.
4852 @end itemize
4853 @end quotation
4855 Integrated preprocessing applies only to Ada source files, it is
4856 not available for configuration pragma files.
4858 With integrated preprocessing, the output from the preprocessor is not,
4859 by default, written to any external file. Instead it is passed
4860 internally to the compiler. To preserve the result of
4861 preprocessing in a file, either run @code{gnatprep}
4862 in standalone mode or else supply the @code{-gnateG} switch
4863 (described below) to the compiler.
4865 When using project files:
4867 @quotation
4870 @itemize *
4872 @item 
4873 the builder switch @code{-x} should be used if any Ada source is
4874 compiled with @code{gnatep=}, so that the compiler finds the
4875 `preprocessor data file'.
4877 @item 
4878 the preprocessing data file and the symbol definition files should be
4879 located in the source directories of the project.
4880 @end itemize
4881 @end quotation
4883 Note that the @code{gnatmake} switch @code{-m} will almost
4884 always trigger recompilation for sources that are preprocessed,
4885 because @code{gnatmake} cannot compute the checksum of the source after
4886 preprocessing.
4888 The actual preprocessing function is described in detail in
4889 @ref{90,,Preprocessing with gnatprep}. This section explains the switches
4890 that relate to integrated preprocessing.
4892 @geindex -gnatep (gcc)
4895 @table @asis
4897 @item @code{-gnatep=`preprocessor_data_file'}
4899 This switch specifies the file name (without directory
4900 information) of the preprocessor data file. Either place this file
4901 in one of the source directories, or, when using project
4902 files, reference the project file’s directory via the
4903 @code{project_name'Project_Dir} project attribute; e.g:
4905 @quotation
4907 @example
4908 project Prj is
4909    package Compiler is
4910       for Switches ("Ada") use
4911         ("-gnatep=" & Prj'Project_Dir & "prep.def");
4912    end Compiler;
4913 end Prj;
4914 @end example
4915 @end quotation
4917 A preprocessor data file is a text file that contains `preprocessor
4918 control lines'.  A preprocessor control line directs the preprocessing of
4919 either a particular source file, or, analogous to @code{others} in Ada,
4920 all sources not specified elsewhere in  the preprocessor data file.
4921 A preprocessor control line
4922 can optionally identify a `definition file' that assigns values to
4923 preprocessor symbols, as well as a list of switches that relate to
4924 preprocessing.
4925 Empty lines and comments (using Ada syntax) are also permitted, with no
4926 semantic effect.
4928 Here’s an example of a preprocessor data file:
4930 @quotation
4932 @example
4933 "toto.adb"  "prep.def" -u
4934 --  Preprocess toto.adb, using definition file prep.def
4935 --  Undefined symbols are treated as False
4937 * -c -DVERSION=V101
4938 --  Preprocess all other sources without using a definition file
4939 --  Suppressed lined are commented
4940 --  Symbol VERSION has the value V101
4942 "tata.adb" "prep2.def" -s
4943 --  Preprocess tata.adb, using definition file prep2.def
4944 --  List all symbols with their values
4945 @end example
4946 @end quotation
4948 A preprocessor control line has the following syntax:
4950 @quotation
4952 @example
4953 <preprocessor_control_line> ::=
4954    <preprocessor_input> [ <definition_file_name> ] @{ <switch> @}
4956 <preprocessor_input> ::= <source_file_name> | '*'
4958 <definition_file_name> ::= <string_literal>
4960 <source_file_name> := <string_literal>
4962 <switch> := (See below for list)
4963 @end example
4964 @end quotation
4966 Thus  each preprocessor control line starts with either a literal string or
4967 the character ‘*’:
4970 @itemize *
4972 @item 
4973 A literal string is the file name (without directory information) of the source
4974 file that will be input to the preprocessor.
4976 @item 
4977 The character ‘*’ is a wild-card indicator; the additional parameters on the line
4978 indicate the preprocessing for all the sources
4979 that are not specified explicitly on other lines (the order of the lines is not
4980 significant).
4981 @end itemize
4983 It is an error to have two lines with the same file name or two
4984 lines starting with the character ‘*’.
4986 After the file name or ‘*’, an optional literal string specifies the name of
4987 the definition file to be used for preprocessing
4988 (@ref{99,,Form of Definitions File}). The definition files are found by the
4989 compiler in one of the source directories. In some cases, when compiling
4990 a source in a directory other than the current directory, if the definition
4991 file is in the current directory, it may be necessary to add the current
4992 directory as a source directory through the @code{-I} switch; otherwise
4993 the compiler would not find the definition file.
4995 Finally, switches similar to those of @code{gnatprep} may optionally appear:
4998 @table @asis
5000 @item @code{-b}
5002 Causes both preprocessor lines and the lines deleted by
5003 preprocessing to be replaced by blank lines, preserving the line number.
5004 This switch is always implied; however, if specified after @code{-c}
5005 it cancels the effect of @code{-c}.
5007 @item @code{-c}
5009 Causes both preprocessor lines and the lines deleted
5010 by preprocessing to be retained as comments marked
5011 with the special string ‘@cite{–!}’.
5013 @item @code{-D`symbol'=`new_value'}
5015 Define or redefine @code{symbol} to have @code{new_value} as its value.
5016 The permitted form for @code{symbol} is either an Ada identifier, or any Ada reserved word
5017 aside from @code{if},
5018 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5019 The permitted form for @code{new_value} is a literal string, an Ada identifier or any Ada reserved
5020 word. A symbol declared with this switch replaces a symbol with the
5021 same name defined in a definition file.
5023 @item @code{-s}
5025 Causes a sorted list of symbol names and values to be
5026 listed on the standard output file.
5028 @item @code{-u}
5030 Causes undefined symbols to be treated as having the value @code{FALSE}
5031 in the context
5032 of a preprocessor test. In the absence of this option, an undefined symbol in
5033 a @code{#if} or @code{#elsif} test will be treated as an error.
5034 @end table
5035 @end table
5037 @geindex -gnateD (gcc)
5040 @table @asis
5042 @item @code{-gnateD`symbol'[=`new_value']}
5044 Define or redefine @code{symbol} to have @code{new_value} as its value. If no value
5045 is supplied, then the value of @code{symbol} is @code{True}.
5046 The form of @code{symbol} is an identifier, following normal Ada (case-insensitive)
5047 rules for its syntax, and @code{new_value} is either an arbitrary string between double
5048 quotes or any sequence (including an empty sequence) of characters from the
5049 set (letters, digits, period, underline).
5050 Ada reserved words may be used as symbols, with the exceptions of @code{if},
5051 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5053 Examples:
5055 @quotation
5057 @example
5058 -gnateDToto=Tata
5059 -gnateDFoo
5060 -gnateDFoo=\"Foo-Bar\"
5061 @end example
5062 @end quotation
5064 A symbol declared with this switch on the command line replaces a
5065 symbol with the same name either in a definition file or specified with a
5066 switch @code{-D} in the preprocessor data file.
5068 This switch is similar to switch @code{-D} of @code{gnatprep}.
5070 @item @code{-gnateG}
5072 When integrated preprocessing is performed on source file @code{filename.extension},
5073 create or overwrite @code{filename.extension.prep} to contain
5074 the result of the preprocessing.
5075 For example if the source file is @code{foo.adb} then
5076 the output file will be @code{foo.adb.prep}.
5077 @end table
5079 @node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5080 @anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{9e}@anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{2c}
5081 @section Mixed Language Programming
5084 @geindex Mixed Language Programming
5086 This section describes how to develop a mixed-language program,
5087 with a focus on combining Ada with C or C++.
5089 @menu
5090 * Interfacing to C:: 
5091 * Calling Conventions:: 
5092 * Building Mixed Ada and C++ Programs:: 
5093 * Partition-Wide Settings:: 
5094 * Generating Ada Bindings for C and C++ headers:: 
5095 * Generating C Headers for Ada Specifications:: 
5097 @end menu
5099 @node Interfacing to C,Calling Conventions,,Mixed Language Programming
5100 @anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{a0}
5101 @subsection Interfacing to C
5104 Interfacing Ada with a foreign language such as C involves using
5105 compiler directives to import and/or export entity definitions in each
5106 language – using @code{extern} statements in C, for instance, and the
5107 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
5108 A full treatment of these topics is provided in Appendix B, section 1
5109 of the Ada Reference Manual.
5111 There are two ways to build a program using GNAT that contains some Ada
5112 sources and some foreign language sources, depending on whether or not
5113 the main subprogram is written in Ada.  Here is a source example with
5114 the main subprogram in Ada:
5116 @example
5117 /* file1.c */
5118 #include <stdio.h>
5120 void print_num (int num)
5122   printf ("num is %d.\\n", num);
5123   return;
5125 @end example
5127 @example
5128 /* file2.c */
5130 /* num_from_Ada is declared in my_main.adb */
5131 extern int num_from_Ada;
5133 int get_num (void)
5135   return num_from_Ada;
5137 @end example
5139 @example
5140 --  my_main.adb
5141 procedure My_Main is
5143    --  Declare then export an Integer entity called num_from_Ada
5144    My_Num : Integer := 10;
5145    pragma Export (C, My_Num, "num_from_Ada");
5147    --  Declare an Ada function spec for Get_Num, then use
5148    --  C function get_num for the implementation.
5149    function Get_Num return Integer;
5150    pragma Import (C, Get_Num, "get_num");
5152    --  Declare an Ada procedure spec for Print_Num, then use
5153    --  C function print_num for the implementation.
5154    procedure Print_Num (Num : Integer);
5155    pragma Import (C, Print_Num, "print_num");
5157 begin
5158    Print_Num (Get_Num);
5159 end My_Main;
5160 @end example
5162 To build this example:
5165 @itemize *
5167 @item 
5168 First compile the foreign language files to
5169 generate object files:
5171 @example
5172 $ gcc -c file1.c
5173 $ gcc -c file2.c
5174 @end example
5176 @item 
5177 Then, compile the Ada units to produce a set of object files and ALI
5178 files:
5180 @example
5181 $ gnatmake -c my_main.adb
5182 @end example
5184 @item 
5185 Run the Ada binder on the Ada main program:
5187 @example
5188 $ gnatbind my_main.ali
5189 @end example
5191 @item 
5192 Link the Ada main program, the Ada objects and the other language
5193 objects:
5195 @example
5196 $ gnatlink my_main.ali file1.o file2.o
5197 @end example
5198 @end itemize
5200 The last three steps can be grouped in a single command:
5202 @example
5203 $ gnatmake my_main.adb -largs file1.o file2.o
5204 @end example
5206 @geindex Binder output file
5208 If the main program is in a language other than Ada, then you may have
5209 more than one entry point into the Ada subsystem. You must use a special
5210 binder option to generate callable routines that initialize and
5211 finalize the Ada units (@ref{7e,,Binding with Non-Ada Main Programs}).
5212 Calls to the initialization and finalization routines must be inserted
5213 in the main program, or some other appropriate point in the code. The
5214 call to initialize the Ada units must occur before the first Ada
5215 subprogram is called, and the call to finalize the Ada units must occur
5216 after the last Ada subprogram returns. The binder will place the
5217 initialization and finalization subprograms into the
5218 @code{b~xxx.adb} file where they can be accessed by your C
5219 sources.  To illustrate, we have the following example:
5221 @example
5222 /* main.c */
5223 extern void adainit (void);
5224 extern void adafinal (void);
5225 extern int add (int, int);
5226 extern int sub (int, int);
5228 int main (int argc, char *argv[])
5230    int a = 21, b = 7;
5232    adainit();
5234    /* Should print "21 + 7 = 28" */
5235    printf ("%d + %d = %d\\n", a, b, add (a, b));
5237    /* Should print "21 - 7 = 14" */
5238    printf ("%d - %d = %d\\n", a, b, sub (a, b));
5240    adafinal();
5242 @end example
5244 @example
5245 --  unit1.ads
5246 package Unit1 is
5247    function Add (A, B : Integer) return Integer;
5248    pragma Export (C, Add, "add");
5249 end Unit1;
5250 @end example
5252 @example
5253 --  unit1.adb
5254 package body Unit1 is
5255    function Add (A, B : Integer) return Integer is
5256    begin
5257       return A + B;
5258    end Add;
5259 end Unit1;
5260 @end example
5262 @example
5263 --  unit2.ads
5264 package Unit2 is
5265    function Sub (A, B : Integer) return Integer;
5266    pragma Export (C, Sub, "sub");
5267 end Unit2;
5268 @end example
5270 @example
5271 --  unit2.adb
5272 package body Unit2 is
5273    function Sub (A, B : Integer) return Integer is
5274    begin
5275       return A - B;
5276    end Sub;
5277 end Unit2;
5278 @end example
5280 The build procedure for this application is similar to the last
5281 example’s:
5284 @itemize *
5286 @item 
5287 First, compile the foreign language files to generate object files:
5289 @example
5290 $ gcc -c main.c
5291 @end example
5293 @item 
5294 Next, compile the Ada units to produce a set of object files and ALI
5295 files:
5297 @example
5298 $ gnatmake -c unit1.adb
5299 $ gnatmake -c unit2.adb
5300 @end example
5302 @item 
5303 Run the Ada binder on every generated ALI file.  Make sure to use the
5304 @code{-n} option to specify a foreign main program:
5306 @example
5307 $ gnatbind -n unit1.ali unit2.ali
5308 @end example
5310 @item 
5311 Link the Ada main program, the Ada objects and the foreign language
5312 objects. You need only list the last ALI file here:
5314 @example
5315 $ gnatlink unit2.ali main.o -o exec_file
5316 @end example
5318 This procedure yields a binary executable called @code{exec_file}.
5319 @end itemize
5321 Depending on the circumstances (for example when your non-Ada main object
5322 does not provide symbol @code{main}), you may also need to instruct the
5323 GNAT linker not to include the standard startup objects by passing the
5324 @code{-nostartfiles} switch to @code{gnatlink}.
5326 @node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5327 @anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{a2}
5328 @subsection Calling Conventions
5331 @geindex Foreign Languages
5333 @geindex Calling Conventions
5335 GNAT follows standard calling sequence conventions and will thus interface
5336 to any other language that also follows these conventions. The following
5337 Convention identifiers are recognized by GNAT:
5339 @geindex Interfacing to Ada
5341 @geindex Other Ada compilers
5343 @geindex Convention Ada
5346 @table @asis
5348 @item @code{Ada}
5350 This indicates that the standard Ada calling sequence will be
5351 used and all Ada data items may be passed without any limitations in the
5352 case where GNAT is used to generate both the caller and callee. It is also
5353 possible to mix GNAT generated code and code generated by another Ada
5354 compiler. In this case, the data types should be restricted to simple
5355 cases, including primitive types. Whether complex data types can be passed
5356 depends on the situation. Probably it is safe to pass simple arrays, such
5357 as arrays of integers or floats. Records may or may not work, depending
5358 on whether both compilers lay them out identically. Complex structures
5359 involving variant records, access parameters, tasks, or protected types,
5360 are unlikely to be able to be passed.
5362 Note that in the case of GNAT running
5363 on a platform that supports HP Ada 83, a higher degree of compatibility
5364 can be guaranteed, and in particular records are laid out in an identical
5365 manner in the two compilers. Note also that if output from two different
5366 compilers is mixed, the program is responsible for dealing with elaboration
5367 issues. Probably the safest approach is to write the main program in the
5368 version of Ada other than GNAT, so that it takes care of its own elaboration
5369 requirements, and then call the GNAT-generated adainit procedure to ensure
5370 elaboration of the GNAT components. Consult the documentation of the other
5371 Ada compiler for further details on elaboration.
5373 However, it is not possible to mix the tasking run time of GNAT and
5374 HP Ada 83, all the tasking operations must either be entirely within
5375 GNAT compiled sections of the program, or entirely within HP Ada 83
5376 compiled sections of the program.
5377 @end table
5379 @geindex Interfacing to Assembly
5381 @geindex Convention Assembler
5384 @table @asis
5386 @item @code{Assembler}
5388 Specifies assembler as the convention. In practice this has the
5389 same effect as convention Ada (but is not equivalent in the sense of being
5390 considered the same convention).
5391 @end table
5393 @geindex Convention Asm
5395 @geindex Asm
5398 @table @asis
5400 @item @code{Asm}
5402 Equivalent to Assembler.
5404 @geindex Interfacing to COBOL
5406 @geindex Convention COBOL
5407 @end table
5409 @geindex COBOL
5412 @table @asis
5414 @item @code{COBOL}
5416 Data will be passed according to the conventions described
5417 in section B.4 of the Ada Reference Manual.
5418 @end table
5420 @geindex C
5422 @geindex Interfacing to C
5424 @geindex Convention C
5427 @table @asis
5429 @item @code{C}
5431 Data will be passed according to the conventions described
5432 in section B.3 of the Ada Reference Manual.
5434 A note on interfacing to a C ‘varargs’ function:
5436 @quotation
5438 @geindex C varargs function
5440 @geindex Interfacing to C varargs function
5442 @geindex varargs function interfaces
5444 In C, @code{varargs} allows a function to take a variable number of
5445 arguments. There is no direct equivalent in this to Ada. One
5446 approach that can be used is to create a C wrapper for each
5447 different profile and then interface to this C wrapper. For
5448 example, to print an @code{int} value using @code{printf},
5449 create a C function @code{printfi} that takes two arguments, a
5450 pointer to a string and an int, and calls @code{printf}.
5451 Then in the Ada program, use pragma @code{Import} to
5452 interface to @code{printfi}.
5454 It may work on some platforms to directly interface to
5455 a @code{varargs} function by providing a specific Ada profile
5456 for a particular call. However, this does not work on
5457 all platforms, since there is no guarantee that the
5458 calling sequence for a two argument normal C function
5459 is the same as for calling a @code{varargs} C function with
5460 the same two arguments.
5461 @end quotation
5462 @end table
5464 @geindex Convention Default
5466 @geindex Default
5469 @table @asis
5471 @item @code{Default}
5473 Equivalent to C.
5474 @end table
5476 @geindex Convention External
5478 @geindex External
5481 @table @asis
5483 @item @code{External}
5485 Equivalent to C.
5486 @end table
5488 @geindex C++
5490 @geindex Interfacing to C++
5492 @geindex Convention C++
5495 @table @asis
5497 @item @code{C_Plus_Plus} (or @code{CPP})
5499 This stands for C++. For most purposes this is identical to C.
5500 See the separate description of the specialized GNAT pragmas relating to
5501 C++ interfacing for further details.
5502 @end table
5504 @geindex Fortran
5506 @geindex Interfacing to Fortran
5508 @geindex Convention Fortran
5511 @table @asis
5513 @item @code{Fortran}
5515 Data will be passed according to the conventions described
5516 in section B.5 of the Ada Reference Manual.
5518 @item @code{Intrinsic}
5520 This applies to an intrinsic operation, as defined in the Ada
5521 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5522 this means that the body of the subprogram is provided by the compiler itself,
5523 usually by means of an efficient code sequence, and that the user does not
5524 supply an explicit body for it. In an application program, the pragma may
5525 be applied to the following sets of names:
5528 @itemize *
5530 @item 
5531 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5532 The corresponding subprogram declaration must have
5533 two formal parameters. The
5534 first one must be a signed integer type or a modular type with a binary
5535 modulus, and the second parameter must be of type Natural.
5536 The return type must be the same as the type of the first argument. The size
5537 of this type can only be 8, 16, 32, or 64.
5539 @item 
5540 Binary arithmetic operators: ‘+’, ‘-’, ‘*’, ‘/’.
5541 The corresponding operator declaration must have parameters and result type
5542 that have the same root numeric type (for example, all three are long_float
5543 types). This simplifies the definition of operations that use type checking
5544 to perform dimensional checks:
5546 @example
5547 type Distance is new Long_Float;
5548 type Time     is new Long_Float;
5549 type Velocity is new Long_Float;
5550 function "/" (D : Distance; T : Time)
5551   return Velocity;
5552 pragma Import (Intrinsic, "/");
5553 @end example
5555 This common idiom is often programmed with a generic definition and an
5556 explicit body. The pragma makes it simpler to introduce such declarations.
5557 It incurs no overhead in compilation time or code size, because it is
5558 implemented as a single machine instruction.
5560 @item 
5561 General subprogram entities. This is used  to bind an Ada subprogram
5562 declaration to
5563 a compiler builtin by name with back-ends where such interfaces are
5564 available. A typical example is the set of @code{__builtin} functions
5565 exposed by the GCC back-end, as in the following example:
5567 @example
5568 function builtin_sqrt (F : Float) return Float;
5569 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5570 @end example
5572 Most of the GCC builtins are accessible this way, and as for other
5573 import conventions (e.g. C), it is the user’s responsibility to ensure
5574 that the Ada subprogram profile matches the underlying builtin
5575 expectations.
5576 @end itemize
5577 @end table
5579 @geindex Stdcall
5581 @geindex Convention Stdcall
5584 @table @asis
5586 @item @code{Stdcall}
5588 This is relevant only to Windows implementations of GNAT,
5589 and specifies that the @code{Stdcall} calling sequence will be used,
5590 as defined by the NT API. Nevertheless, to ease building
5591 cross-platform bindings this convention will be handled as a @code{C} calling
5592 convention on non-Windows platforms.
5593 @end table
5595 @geindex DLL
5597 @geindex Convention DLL
5600 @table @asis
5602 @item @code{DLL}
5604 This is equivalent to @code{Stdcall}.
5605 @end table
5607 @geindex Win32
5609 @geindex Convention Win32
5612 @table @asis
5614 @item @code{Win32}
5616 This is equivalent to @code{Stdcall}.
5617 @end table
5619 @geindex Stubbed
5621 @geindex Convention Stubbed
5624 @table @asis
5626 @item @code{Stubbed}
5628 This is a special convention that indicates that the compiler
5629 should provide a stub body that raises @code{Program_Error}.
5630 @end table
5632 GNAT additionally provides a useful pragma @code{Convention_Identifier}
5633 that can be used to parameterize conventions and allow additional synonyms
5634 to be specified. For example if you have legacy code in which the convention
5635 identifier Fortran77 was used for Fortran, you can use the configuration
5636 pragma:
5638 @example
5639 pragma Convention_Identifier (Fortran77, Fortran);
5640 @end example
5642 And from now on the identifier Fortran77 may be used as a convention
5643 identifier (for example in an @code{Import} pragma) with the same
5644 meaning as Fortran.
5646 @node Building Mixed Ada and C++ Programs,Partition-Wide Settings,Calling Conventions,Mixed Language Programming
5647 @anchor{gnat_ugn/the_gnat_compilation_model building-mixed-ada-and-c-programs}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id64}@anchor{a4}
5648 @subsection Building Mixed Ada and C++ Programs
5651 A programmer inexperienced with mixed-language development may find that
5652 building an application containing both Ada and C++ code can be a
5653 challenge.  This section gives a few hints that should make this task easier.
5655 @menu
5656 * Interfacing to C++:: 
5657 * Linking a Mixed C++ & Ada Program:: 
5658 * A Simple Example:: 
5659 * Interfacing with C++ constructors:: 
5660 * Interfacing with C++ at the Class Level:: 
5662 @end menu
5664 @node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5665 @anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{a6}
5666 @subsubsection Interfacing to C++
5669 GNAT supports interfacing with the G++ compiler (or any C++ compiler
5670 generating code that is compatible with the G++ Application Binary
5671 Interface —see @indicateurl{http://itanium-cxx-abi.github.io/cxx-abi/abi.html}).
5673 Interfacing can be done at 3 levels: simple data, subprograms, and
5674 classes. In the first two cases, GNAT offers a specific @code{Convention C_Plus_Plus}
5675 (or @code{CPP}) that behaves exactly like @code{Convention C}.
5676 Usually, C++ mangles the names of subprograms. To generate proper mangled
5677 names automatically, see @ref{a7,,Generating Ada Bindings for C and C++ headers}).
5678 This problem can also be addressed manually in two ways:
5681 @itemize *
5683 @item 
5684 by modifying the C++ code in order to force a C convention using
5685 the @code{extern "C"} syntax.
5687 @item 
5688 by figuring out the mangled name (using e.g. @code{nm}) and using it as the
5689 Link_Name argument of the pragma import.
5690 @end itemize
5692 Interfacing at the class level can be achieved by using the GNAT specific
5693 pragmas such as @code{CPP_Constructor}.  See the @cite{GNAT_Reference_Manual} for additional information.
5695 @node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5696 @anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-ada-program}@anchor{a8}@anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-and-ada-program}@anchor{a9}
5697 @subsubsection Linking a Mixed C++ & Ada Program
5700 Usually the linker of the C++ development system must be used to link
5701 mixed applications because most C++ systems will resolve elaboration
5702 issues (such as calling constructors on global class instances)
5703 transparently during the link phase. GNAT has been adapted to ease the
5704 use of a foreign linker for the last phase. Three cases can be
5705 considered:
5708 @itemize *
5710 @item 
5711 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5712 The C++ linker can simply be called by using the C++ specific driver
5713 called @code{g++}.
5715 Note that if the C++ code uses inline functions, you will need to
5716 compile your C++ code with the @code{-fkeep-inline-functions} switch in
5717 order to provide an existing function implementation that the Ada code can
5718 link with.
5720 @example
5721 $ g++ -c -fkeep-inline-functions file1.C
5722 $ g++ -c -fkeep-inline-functions file2.C
5723 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5724 @end example
5726 @item 
5727 Using GNAT and G++ from two different GCC installations: If both
5728 compilers are on the 
5729 @geindex PATH
5730 @geindex environment variable; PATH
5731 @code{PATH}, the previous method may be used. It is
5732 important to note that environment variables such as
5733 @geindex C_INCLUDE_PATH
5734 @geindex environment variable; C_INCLUDE_PATH
5735 @code{C_INCLUDE_PATH}, 
5736 @geindex GCC_EXEC_PREFIX
5737 @geindex environment variable; GCC_EXEC_PREFIX
5738 @code{GCC_EXEC_PREFIX},
5739 @geindex BINUTILS_ROOT
5740 @geindex environment variable; BINUTILS_ROOT
5741 @code{BINUTILS_ROOT}, and
5742 @geindex GCC_ROOT
5743 @geindex environment variable; GCC_ROOT
5744 @code{GCC_ROOT} will affect both compilers
5745 at the same time and may make one of the two compilers operate
5746 improperly if set during invocation of the wrong compiler.  It is also
5747 very important that the linker uses the proper @code{libgcc.a} GCC
5748 library – that is, the one from the C++ compiler installation. The
5749 implicit link command as suggested in the @code{gnatmake} command
5750 from the former example can be replaced by an explicit link command with
5751 the full-verbosity option in order to verify which library is used:
5753 @example
5754 $ gnatbind ada_unit
5755 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5756 @end example
5758 If there is a problem due to interfering environment variables, it can
5759 be worked around by using an intermediate script. The following example
5760 shows the proper script to use when GNAT has not been installed at its
5761 default location and g++ has been installed at its default location:
5763 @example
5764 $ cat ./my_script
5765 #!/bin/sh
5766 unset BINUTILS_ROOT
5767 unset GCC_ROOT
5768 c++ $*
5769 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5770 @end example
5772 @item 
5773 Using a non-GNU C++ compiler: The commands previously described can be
5774 used to insure that the C++ linker is used. Nonetheless, you need to add
5775 a few more parameters to the link command line, depending on the exception
5776 mechanism used.
5778 If the @code{setjmp} / @code{longjmp} exception mechanism is used, only the paths
5779 to the @code{libgcc} libraries are required:
5781 @example
5782 $ cat ./my_script
5783 #!/bin/sh
5784 CC $* gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a
5785 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5786 @end example
5788 where CC is the name of the non-GNU C++ compiler.
5790 If the “zero cost” exception mechanism is used, and the platform
5791 supports automatic registration of exception tables (e.g., Solaris),
5792 paths to more objects are required:
5794 @example
5795 $ cat ./my_script
5796 #!/bin/sh
5797 CC gcc -print-file-name=crtbegin.o $* \\
5798 gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a \\
5799 gcc -print-file-name=crtend.o
5800 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5801 @end example
5803 If the “zero cost exception” mechanism is used, and the platform
5804 doesn’t support automatic registration of exception tables (e.g., HP-UX
5805 or AIX), the simple approach described above will not work and
5806 a pre-linking phase using GNAT will be necessary.
5807 @end itemize
5809 Another alternative is to use the @code{gprbuild} multi-language builder
5810 which has a large knowledge base and knows how to link Ada and C++ code
5811 together automatically in most cases.
5813 @node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
5814 @anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{aa}@anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{ab}
5815 @subsubsection A Simple Example
5818 The following example, provided as part of the GNAT examples, shows how
5819 to achieve procedural interfacing between Ada and C++ in both
5820 directions. The C++ class A has two methods. The first method is exported
5821 to Ada by the means of an extern C wrapper function. The second method
5822 calls an Ada subprogram. On the Ada side, the C++ calls are modelled by
5823 a limited record with a layout comparable to the C++ class. The Ada
5824 subprogram, in turn, calls the C++ method. So, starting from the C++
5825 main program, the process passes back and forth between the two
5826 languages.
5828 Here are the compilation commands:
5830 @example
5831 $ gnatmake -c simple_cpp_interface
5832 $ g++ -c cpp_main.C
5833 $ g++ -c ex7.C
5834 $ gnatbind -n simple_cpp_interface
5835 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
5836 @end example
5838 Here are the corresponding sources:
5840 @example
5841 //cpp_main.C
5843 #include "ex7.h"
5845 extern "C" @{
5846   void adainit (void);
5847   void adafinal (void);
5848   void method1 (A *t);
5851 void method1 (A *t)
5853   t->method1 ();
5856 int main ()
5858   A obj;
5859   adainit ();
5860   obj.method2 (3030);
5861   adafinal ();
5863 @end example
5865 @example
5866 //ex7.h
5868 class Origin @{
5869  public:
5870   int o_value;
5872 class A : public Origin @{
5873  public:
5874   void method1 (void);
5875   void method2 (int v);
5876   A();
5877   int   a_value;
5879 @end example
5881 @example
5882 //ex7.C
5884 #include "ex7.h"
5885 #include <stdio.h>
5887 extern "C" @{ void ada_method2 (A *t, int v);@}
5889 void A::method1 (void)
5891   a_value = 2020;
5892   printf ("in A::method1, a_value = %d \\n",a_value);
5895 void A::method2 (int v)
5897    ada_method2 (this, v);
5898    printf ("in A::method2, a_value = %d \\n",a_value);
5901 A::A(void)
5903    a_value = 1010;
5904   printf ("in A::A, a_value = %d \\n",a_value);
5906 @end example
5908 @example
5909 -- simple_cpp_interface.ads
5910 with System;
5911 package Simple_Cpp_Interface is
5912    type A is limited
5913       record
5914          Vptr    : System.Address;
5915          O_Value : Integer;
5916          A_Value : Integer;
5917       end record;
5918    pragma Convention (C, A);
5920    procedure Method1 (This : in out A);
5921    pragma Import (C, Method1);
5923    procedure Ada_Method2 (This : in out A; V : Integer);
5924    pragma Export (C, Ada_Method2);
5926 end Simple_Cpp_Interface;
5927 @end example
5929 @example
5930 -- simple_cpp_interface.adb
5931 package body Simple_Cpp_Interface is
5933    procedure Ada_Method2 (This : in out A; V : Integer) is
5934    begin
5935       Method1 (This);
5936       This.A_Value := V;
5937    end Ada_Method2;
5939 end Simple_Cpp_Interface;
5940 @end example
5942 @node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
5943 @anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{ad}
5944 @subsubsection Interfacing with C++ constructors
5947 In order to interface with C++ constructors GNAT provides the
5948 @code{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
5949 for additional information).
5950 In this section we present some common uses of C++ constructors
5951 in mixed-languages programs in GNAT.
5953 Let us assume that we need to interface with the following
5954 C++ class:
5956 @example
5957 class Root @{
5958 public:
5959   int  a_value;
5960   int  b_value;
5961   virtual int Get_Value ();
5962   Root();              // Default constructor
5963   Root(int v);         // 1st non-default constructor
5964   Root(int v, int w);  // 2nd non-default constructor
5966 @end example
5968 For this purpose we can write the following package spec (further
5969 information on how to build this spec is available in
5970 @ref{ae,,Interfacing with C++ at the Class Level} and
5971 @ref{a7,,Generating Ada Bindings for C and C++ headers}).
5973 @example
5974 with Interfaces.C; use Interfaces.C;
5975 package Pkg_Root is
5976   type Root is tagged limited record
5977      A_Value : int;
5978      B_Value : int;
5979   end record;
5980   pragma Import (CPP, Root);
5982   function Get_Value (Obj : Root) return int;
5983   pragma Import (CPP, Get_Value);
5985   function Constructor return Root;
5986   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
5988   function Constructor (v : Integer) return Root;
5989   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
5991   function Constructor (v, w : Integer) return Root;
5992   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
5993 end Pkg_Root;
5994 @end example
5996 On the Ada side the constructor is represented by a function (whose
5997 name is arbitrary) that returns the classwide type corresponding to
5998 the imported C++ class. Although the constructor is described as a
5999 function, it is typically a procedure with an extra implicit argument
6000 (the object being initialized) at the implementation level. GNAT
6001 issues the appropriate call, whatever it is, to get the object
6002 properly initialized.
6004 Constructors can only appear in the following contexts:
6007 @itemize *
6009 @item 
6010 On the right side of an initialization of an object of type @code{T}.
6012 @item 
6013 On the right side of an initialization of a record component of type @code{T}.
6015 @item 
6016 In an Ada 2005 limited aggregate.
6018 @item 
6019 In an Ada 2005 nested limited aggregate.
6021 @item 
6022 In an Ada 2005 limited aggregate that initializes an object built in
6023 place by an extended return statement.
6024 @end itemize
6026 In a declaration of an object whose type is a class imported from C++,
6027 either the default C++ constructor is implicitly called by GNAT, or
6028 else the required C++ constructor must be explicitly called in the
6029 expression that initializes the object. For example:
6031 @example
6032 Obj1 : Root;
6033 Obj2 : Root := Constructor;
6034 Obj3 : Root := Constructor (v => 10);
6035 Obj4 : Root := Constructor (30, 40);
6036 @end example
6038 The first two declarations are equivalent: in both cases the default C++
6039 constructor is invoked (in the former case the call to the constructor is
6040 implicit, and in the latter case the call is explicit in the object
6041 declaration). @code{Obj3} is initialized by the C++ non-default constructor
6042 that takes an integer argument, and @code{Obj4} is initialized by the
6043 non-default C++ constructor that takes two integers.
6045 Let us derive the imported C++ class in the Ada side. For example:
6047 @example
6048 type DT is new Root with record
6049    C_Value : Natural := 2009;
6050 end record;
6051 @end example
6053 In this case the components DT inherited from the C++ side must be
6054 initialized by a C++ constructor, and the additional Ada components
6055 of type DT are initialized by GNAT. The initialization of such an
6056 object is done either by default, or by means of a function returning
6057 an aggregate of type DT, or by means of an extension aggregate.
6059 @example
6060 Obj5 : DT;
6061 Obj6 : DT := Function_Returning_DT (50);
6062 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6063 @end example
6065 The declaration of @code{Obj5} invokes the default constructors: the
6066 C++ default constructor of the parent type takes care of the initialization
6067 of the components inherited from Root, and GNAT takes care of the default
6068 initialization of the additional Ada components of type DT (that is,
6069 @code{C_Value} is initialized to value 2009). The order of invocation of
6070 the constructors is consistent with the order of elaboration required by
6071 Ada and C++. That is, the constructor of the parent type is always called
6072 before the constructor of the derived type.
6074 Let us now consider a record that has components whose type is imported
6075 from C++. For example:
6077 @example
6078 type Rec1 is limited record
6079    Data1 : Root := Constructor (10);
6080    Value : Natural := 1000;
6081 end record;
6083 type Rec2 (D : Integer := 20) is limited record
6084    Rec   : Rec1;
6085    Data2 : Root := Constructor (D, 30);
6086 end record;
6087 @end example
6089 The initialization of an object of type @code{Rec2} will call the
6090 non-default C++ constructors specified for the imported components.
6091 For example:
6093 @example
6094 Obj8 : Rec2 (40);
6095 @end example
6097 Using Ada 2005 we can use limited aggregates to initialize an object
6098 invoking C++ constructors that differ from those specified in the type
6099 declarations. For example:
6101 @example
6102 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6103                         others => <>),
6104                 others => <>);
6105 @end example
6107 The above declaration uses an Ada 2005 limited aggregate to
6108 initialize @code{Obj9}, and the C++ constructor that has two integer
6109 arguments is invoked to initialize the @code{Data1} component instead
6110 of the constructor specified in the declaration of type @code{Rec1}. In
6111 Ada 2005 the box in the aggregate indicates that unspecified components
6112 are initialized using the expression (if any) available in the component
6113 declaration. That is, in this case discriminant @code{D} is initialized
6114 to value @code{20}, @code{Value} is initialized to value 1000, and the
6115 non-default C++ constructor that handles two integers takes care of
6116 initializing component @code{Data2} with values @code{20,30}.
6118 In Ada 2005 we can use the extended return statement to build the Ada
6119 equivalent to C++ non-default constructors. For example:
6121 @example
6122 function Constructor (V : Integer) return Rec2 is
6123 begin
6124    return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
6125                                  others => <>),
6126                          others => <>) do
6127       --  Further actions required for construction of
6128       --  objects of type Rec2
6129       ...
6130    end record;
6131 end Constructor;
6132 @end example
6134 In this example the extended return statement construct is used to
6135 build in place the returned object whose components are initialized
6136 by means of a limited aggregate. Any further action associated with
6137 the constructor can be placed inside the construct.
6139 @node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6140 @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}
6141 @subsubsection Interfacing with C++ at the Class Level
6144 In this section we demonstrate the GNAT features for interfacing with
6145 C++ by means of an example making use of Ada 2005 abstract interface
6146 types. This example consists of a classification of animals; classes
6147 have been used to model our main classification of animals, and
6148 interfaces provide support for the management of secondary
6149 classifications. We first demonstrate a case in which the types and
6150 constructors are defined on the C++ side and imported from the Ada
6151 side, and latter the reverse case.
6153 The root of our derivation will be the @code{Animal} class, with a
6154 single private attribute (the @code{Age} of the animal), a constructor,
6155 and two public primitives to set and get the value of this attribute.
6157 @example
6158 class Animal @{
6159  public:
6160    virtual void Set_Age (int New_Age);
6161    virtual int Age ();
6162    Animal() @{Age_Count = 0;@};
6163  private:
6164    int Age_Count;
6166 @end example
6168 Abstract interface types are defined in C++ by means of classes with pure
6169 virtual functions and no data members. In our example we will use two
6170 interfaces that provide support for the common management of @code{Carnivore}
6171 and @code{Domestic} animals:
6173 @example
6174 class Carnivore @{
6175 public:
6176    virtual int Number_Of_Teeth () = 0;
6179 class Domestic @{
6180 public:
6181    virtual void Set_Owner (char* Name) = 0;
6183 @end example
6185 Using these declarations, we can now say that a @code{Dog} is an animal that is
6186 both Carnivore and Domestic, that is:
6188 @example
6189 class Dog : Animal, Carnivore, Domestic @{
6190  public:
6191    virtual int  Number_Of_Teeth ();
6192    virtual void Set_Owner (char* Name);
6194    Dog(); // Constructor
6195  private:
6196    int  Tooth_Count;
6197    char *Owner;
6199 @end example
6201 In the following examples we will assume that the previous declarations are
6202 located in a file named @code{animals.h}. The following package demonstrates
6203 how to import these C++ declarations from the Ada side:
6205 @example
6206 with Interfaces.C.Strings; use Interfaces.C.Strings;
6207 package Animals is
6208   type Carnivore is limited interface;
6209   pragma Convention (C_Plus_Plus, Carnivore);
6210   function Number_Of_Teeth (X : Carnivore)
6211      return Natural is abstract;
6213   type Domestic is limited interface;
6214   pragma Convention (C_Plus_Plus, Domestic);
6215   procedure Set_Owner
6216     (X    : in out Domestic;
6217      Name : Chars_Ptr) is abstract;
6219   type Animal is tagged limited record
6220     Age : Natural;
6221   end record;
6222   pragma Import (C_Plus_Plus, Animal);
6224   procedure Set_Age (X : in out Animal; Age : Integer);
6225   pragma Import (C_Plus_Plus, Set_Age);
6227   function Age (X : Animal) return Integer;
6228   pragma Import (C_Plus_Plus, Age);
6230   function New_Animal return Animal;
6231   pragma CPP_Constructor (New_Animal);
6232   pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6234   type Dog is new Animal and Carnivore and Domestic with record
6235     Tooth_Count : Natural;
6236     Owner       : Chars_Ptr;
6237   end record;
6238   pragma Import (C_Plus_Plus, Dog);
6240   function Number_Of_Teeth (A : Dog) return Natural;
6241   pragma Import (C_Plus_Plus, Number_Of_Teeth);
6243   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6244   pragma Import (C_Plus_Plus, Set_Owner);
6246   function New_Dog return Dog;
6247   pragma CPP_Constructor (New_Dog);
6248   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6249 end Animals;
6250 @end example
6252 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6253 interfacing with these C++ classes is easy. The only requirement is that all
6254 the primitives and components must be declared exactly in the same order in
6255 the two languages.
6257 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6258 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
6259 the arguments to the called primitives will be the same as for C++. For the
6260 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
6261 to indicate that they have been defined on the C++ side; this is required
6262 because the dispatch table associated with these tagged types will be built
6263 in the C++ side and therefore will not contain the predefined Ada primitives
6264 which Ada would otherwise expect.
6266 As the reader can see there is no need to indicate the C++ mangled names
6267 associated with each subprogram because it is assumed that all the calls to
6268 these primitives will be dispatching calls. The only exception is the
6269 constructor, which must be registered with the compiler by means of
6270 @code{pragma CPP_Constructor} and needs to provide its associated C++
6271 mangled name because the Ada compiler generates direct calls to it.
6273 With the above packages we can now declare objects of type Dog on the Ada side
6274 and dispatch calls to the corresponding subprograms on the C++ side. We can
6275 also extend the tagged type Dog with further fields and primitives, and
6276 override some of its C++ primitives on the Ada side. For example, here we have
6277 a type derivation defined on the Ada side that inherits all the dispatching
6278 primitives of the ancestor from the C++ side.
6280 @example
6281 with Animals; use Animals;
6282 package Vaccinated_Animals is
6283   type Vaccinated_Dog is new Dog with null record;
6284   function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6285 end Vaccinated_Animals;
6286 @end example
6288 It is important to note that, because of the ABI compatibility, the programmer
6289 does not need to add any further information to indicate either the object
6290 layout or the dispatch table entry associated with each dispatching operation.
6292 Now let us define all the types and constructors on the Ada side and export
6293 them to C++, using the same hierarchy of our previous example:
6295 @example
6296 with Interfaces.C.Strings;
6297 use Interfaces.C.Strings;
6298 package Animals is
6299   type Carnivore is limited interface;
6300   pragma Convention (C_Plus_Plus, Carnivore);
6301   function Number_Of_Teeth (X : Carnivore)
6302      return Natural is abstract;
6304   type Domestic is limited interface;
6305   pragma Convention (C_Plus_Plus, Domestic);
6306   procedure Set_Owner
6307     (X    : in out Domestic;
6308      Name : Chars_Ptr) is abstract;
6310   type Animal is tagged record
6311     Age : Natural;
6312   end record;
6313   pragma Convention (C_Plus_Plus, Animal);
6315   procedure Set_Age (X : in out Animal; Age : Integer);
6316   pragma Export (C_Plus_Plus, Set_Age);
6318   function Age (X : Animal) return Integer;
6319   pragma Export (C_Plus_Plus, Age);
6321   function New_Animal return Animal'Class;
6322   pragma Export (C_Plus_Plus, New_Animal);
6324   type Dog is new Animal and Carnivore and Domestic with record
6325     Tooth_Count : Natural;
6326     Owner       : String (1 .. 30);
6327   end record;
6328   pragma Convention (C_Plus_Plus, Dog);
6330   function Number_Of_Teeth (A : Dog) return Natural;
6331   pragma Export (C_Plus_Plus, Number_Of_Teeth);
6333   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6334   pragma Export (C_Plus_Plus, Set_Owner);
6336   function New_Dog return Dog'Class;
6337   pragma Export (C_Plus_Plus, New_Dog);
6338 end Animals;
6339 @end example
6341 Compared with our previous example the only differences are the use of
6342 @code{pragma Convention} (instead of @code{pragma Import}), and the use of
6343 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
6344 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6345 nothing else to be done; as explained above, the only requirement is that all
6346 the primitives and components are declared in exactly the same order.
6348 For completeness, let us see a brief C++ main program that uses the
6349 declarations available in @code{animals.h} (presented in our first example) to
6350 import and use the declarations from the Ada side, properly initializing and
6351 finalizing the Ada run-time system along the way:
6353 @example
6354 #include "animals.h"
6355 #include <iostream>
6356 using namespace std;
6358 void Check_Carnivore (Carnivore *obj) @{...@}
6359 void Check_Domestic (Domestic *obj)   @{...@}
6360 void Check_Animal (Animal *obj)       @{...@}
6361 void Check_Dog (Dog *obj)             @{...@}
6363 extern "C" @{
6364   void adainit (void);
6365   void adafinal (void);
6366   Dog* new_dog ();
6369 void test ()
6371   Dog *obj = new_dog();  // Ada constructor
6372   Check_Carnivore (obj); // Check secondary DT
6373   Check_Domestic (obj);  // Check secondary DT
6374   Check_Animal (obj);    // Check primary DT
6375   Check_Dog (obj);       // Check primary DT
6378 int main ()
6380   adainit ();  test();  adafinal ();
6381   return 0;
6383 @end example
6385 @node Partition-Wide Settings,Generating Ada Bindings for C and C++ headers,Building Mixed Ada and C++ Programs,Mixed Language Programming
6386 @anchor{gnat_ugn/the_gnat_compilation_model id70}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model partition-wide-settings}@anchor{b1}
6387 @subsection Partition-Wide Settings
6390 When building a mixed-language application it is important to be aware that
6391 Ada enforces some partition-wide settings that may implicitly impact the
6392 behavior of the other languages.
6394 This is the case of certain signals that are reserved to the
6395 implementation to implement proper Ada semantics (such as the behavior
6396 of @code{abort} statements).
6398 It means that the Ada part of the application may override signal handlers
6399 that were previously installed by either the system or by other user code.
6401 If your application requires that either system or user signals be preserved
6402 then you need to instruct the Ada part not to install its own signal handler.
6403 This is done using @code{pragma Interrupt_State} that provides a general
6404 mechanism for overriding such uses of interrupts.
6406 The set of interrupts for which the Ada run-time library sets a specific signal
6407 handler is the following:
6410 @itemize *
6412 @item 
6413 Ada.Interrupts.Names.SIGSEGV
6415 @item 
6416 Ada.Interrupts.Names.SIGBUS
6418 @item 
6419 Ada.Interrupts.Names.SIGFPE
6421 @item 
6422 Ada.Interrupts.Names.SIGILL
6424 @item 
6425 Ada.Interrupts.Names.SIGABRT
6426 @end itemize
6428 The run-time library can be instructed not to install its signal handler for a
6429 particular signal by using the configuration pragma @code{Interrupt_State} in the
6430 Ada code. For example:
6432 @example
6433 pragma Interrupt_State (Ada.Interrupts.Names.SIGSEGV, System);
6434 pragma Interrupt_State (Ada.Interrupts.Names.SIGBUS,  System);
6435 pragma Interrupt_State (Ada.Interrupts.Names.SIGFPE,  System);
6436 pragma Interrupt_State (Ada.Interrupts.Names.SIGILL,  System);
6437 pragma Interrupt_State (Ada.Interrupts.Names.SIGABRT, System);
6438 @end example
6440 Obviously, if the Ada run-time system cannot set these handlers it comes with the
6441 drawback of not fully preserving Ada semantics. @code{SIGSEGV}, @code{SIGBUS}, @code{SIGFPE}
6442 and @code{SIGILL} are used to raise corresponding Ada exceptions in the application,
6443 while @code{SIGABRT} is used to asynchronously abort an action or a task.
6445 @node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Partition-Wide Settings,Mixed Language Programming
6446 @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}
6447 @subsection Generating Ada Bindings for C and C++ headers
6450 @geindex Binding generation (for C and C++ headers)
6452 @geindex C headers (binding generation)
6454 @geindex C++ headers (binding generation)
6456 GNAT includes a binding generator for C and C++ headers which is
6457 intended to do 95% of the tedious work of generating Ada specs from C
6458 or C++ header files.
6460 Note that this capability is not intended to generate 100% correct Ada specs,
6461 and will is some cases require manual adjustments, although it can often
6462 be used out of the box in practice.
6464 Some of the known limitations include:
6467 @itemize *
6469 @item 
6470 only very simple character constant macros are translated into Ada
6471 constants. Function macros (macros with arguments) are partially translated
6472 as comments, to be completed manually if needed.
6474 @item 
6475 some extensions (e.g. vector types) are not supported
6477 @item 
6478 pointers to pointers are mapped to System.Address
6480 @item 
6481 identifiers with identical name (except casing) may generate compilation
6482 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
6483 @end itemize
6485 The code is generated using Ada 2012 syntax, which makes it easier to interface
6486 with other languages. In most cases you can still use the generated binding
6487 even if your code is compiled using earlier versions of Ada (e.g. @code{-gnat95}).
6489 @menu
6490 * Running the Binding Generator:: 
6491 * Generating Bindings for C++ Headers:: 
6492 * Switches:: 
6494 @end menu
6496 @node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6497 @anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{b3}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{b4}
6498 @subsubsection Running the Binding Generator
6501 The binding generator is part of the @code{gcc} compiler and can be
6502 invoked via the @code{-fdump-ada-spec} switch, which will generate Ada
6503 spec files for the header files specified on the command line, and all
6504 header files needed by these files transitively. For example:
6506 @example
6507 $ gcc -c -fdump-ada-spec -C /usr/include/time.h
6508 $ gcc -c *.ads
6509 @end example
6511 will generate, under GNU/Linux, the following files: @code{time_h.ads},
6512 @code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6513 correspond to the files @code{/usr/include/time.h},
6514 @code{/usr/include/bits/time.h}, etc…, and then compile these Ada specs.
6515 That is to say, the name of the Ada specs is in keeping with the relative path
6516 under @code{/usr/include/} of the header files. This behavior is specific to
6517 paths ending with @code{/include/}; in all the other cases, the name of the
6518 Ada specs is derived from the simple name of the header files instead.
6520 The @code{-C} switch tells @code{gcc} to extract comments from headers,
6521 and will attempt to generate corresponding Ada comments.
6523 If you want to generate a single Ada file and not the transitive closure, you
6524 can use instead the @code{-fdump-ada-spec-slim} switch.
6526 You can optionally specify a parent unit, of which all generated units will
6527 be children, using @code{-fada-spec-parent=`unit'}.
6529 The simple @code{gcc}-based command works only for C headers. For C++ headers
6530 you need to use either the @code{g++} command or the combination @code{gcc -x c++}.
6532 In some cases, the generated bindings will be more complete or more meaningful
6533 when defining some macros, which you can do via the @code{-D} switch. This
6534 is for example the case with @code{Xlib.h} under GNU/Linux:
6536 @example
6537 $ gcc -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6538 @end example
6540 The above will generate more complete bindings than a straight call without
6541 the @code{-DXLIB_ILLEGAL_ACCESS} switch.
6543 In other cases, it is not possible to parse a header file in a stand-alone
6544 manner, because other include files need to be included first. In this
6545 case, the solution is to create a small header file including the needed
6546 @code{#include} and possible @code{#define} directives. For example, to
6547 generate Ada bindings for @code{readline/readline.h}, you need to first
6548 include @code{stdio.h}, so you can create a file with the following two
6549 lines in e.g. @code{readline1.h}:
6551 @example
6552 #include <stdio.h>
6553 #include <readline/readline.h>
6554 @end example
6556 and then generate Ada bindings from this file:
6558 @example
6559 $ gcc -c -fdump-ada-spec readline1.h
6560 @end example
6562 @node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6563 @anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{b5}@anchor{gnat_ugn/the_gnat_compilation_model id73}@anchor{b6}
6564 @subsubsection Generating Bindings for C++ Headers
6567 Generating bindings for C++ headers is done using the same options, always
6568 with the `g++' compiler. Note that generating Ada spec from C++ headers is a
6569 much more complex job and support for C++ headers is much more limited that
6570 support for C headers. As a result, you will need to modify the resulting
6571 bindings by hand more extensively when using C++ headers.
6573 In this mode, C++ classes will be mapped to Ada tagged types, constructors
6574 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
6575 multiple inheritance of abstract classes will be mapped to Ada interfaces
6576 (see the `Interfacing to C++' section in the @cite{GNAT Reference Manual}
6577 for additional information on interfacing to C++).
6579 For example, given the following C++ header file:
6581 @example
6582 class Carnivore @{
6583 public:
6584    virtual int Number_Of_Teeth () = 0;
6587 class Domestic @{
6588 public:
6589    virtual void Set_Owner (char* Name) = 0;
6592 class Animal @{
6593 public:
6594   int Age_Count;
6595   virtual void Set_Age (int New_Age);
6598 class Dog : Animal, Carnivore, Domestic @{
6599  public:
6600   int  Tooth_Count;
6601   char *Owner;
6603   virtual int  Number_Of_Teeth ();
6604   virtual void Set_Owner (char* Name);
6606   Dog();
6608 @end example
6610 The corresponding Ada code is generated:
6612 @example
6613 package Class_Carnivore is
6614   type Carnivore is limited interface;
6615   pragma Import (CPP, Carnivore);
6617   function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6618 end;
6619 use Class_Carnivore;
6621 package Class_Domestic is
6622   type Domestic is limited interface;
6623   pragma Import (CPP, Domestic);
6625   procedure Set_Owner
6626     (this : access Domestic;
6627      Name : Interfaces.C.Strings.chars_ptr) is abstract;
6628 end;
6629 use Class_Domestic;
6631 package Class_Animal is
6632   type Animal is tagged limited record
6633     Age_Count : aliased int;
6634   end record;
6635   pragma Import (CPP, Animal);
6637   procedure Set_Age (this : access Animal; New_Age : int);
6638   pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6639 end;
6640 use Class_Animal;
6642 package Class_Dog is
6643   type Dog is new Animal and Carnivore and Domestic with record
6644     Tooth_Count : aliased int;
6645     Owner : Interfaces.C.Strings.chars_ptr;
6646   end record;
6647   pragma Import (CPP, Dog);
6649   function Number_Of_Teeth (this : access Dog) return int;
6650   pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6652   procedure Set_Owner
6653     (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6654   pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6656   function New_Dog return Dog;
6657   pragma CPP_Constructor (New_Dog);
6658   pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6659 end;
6660 use Class_Dog;
6661 @end example
6663 @node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6664 @anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{b7}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{b8}
6665 @subsubsection Switches
6668 @geindex -fdump-ada-spec (gcc)
6671 @table @asis
6673 @item @code{-fdump-ada-spec}
6675 Generate Ada spec files for the given header files transitively (including
6676 all header files that these headers depend upon).
6677 @end table
6679 @geindex -fdump-ada-spec-slim (gcc)
6682 @table @asis
6684 @item @code{-fdump-ada-spec-slim}
6686 Generate Ada spec files for the header files specified on the command line
6687 only.
6688 @end table
6690 @geindex -fada-spec-parent (gcc)
6693 @table @asis
6695 @item @code{-fada-spec-parent=`unit'}
6697 Specifies that all files generated by @code{-fdump-ada-spec} are
6698 to be child units of the specified parent unit.
6699 @end table
6701 @geindex -C (gcc)
6704 @table @asis
6706 @item @code{-C}
6708 Extract comments from headers and generate Ada comments in the Ada spec files.
6709 @end table
6711 @node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6712 @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}
6713 @subsection Generating C Headers for Ada Specifications
6716 @geindex Binding generation (for Ada specs)
6718 @geindex C headers (binding generation)
6720 GNAT includes a C header generator for Ada specifications which supports
6721 Ada types that have a direct mapping to C types. This includes in particular
6722 support for:
6725 @itemize *
6727 @item 
6728 Scalar types
6730 @item 
6731 Constrained arrays
6733 @item 
6734 Records (untagged)
6736 @item 
6737 Composition of the above types
6739 @item 
6740 Constant declarations
6742 @item 
6743 Object declarations
6745 @item 
6746 Subprogram declarations
6747 @end itemize
6749 @menu
6750 * Running the C Header Generator:: 
6752 @end menu
6754 @node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6755 @anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{bb}
6756 @subsubsection Running the C Header Generator
6759 The C header generator is part of the GNAT compiler and can be invoked via
6760 the @code{-gnatceg} combination of switches, which will generate a @code{.h}
6761 file corresponding to the given input file (Ada spec or body). Note that
6762 only spec files are processed in any case, so giving a spec or a body file
6763 as input is equivalent. For example:
6765 @example
6766 $ gcc -c -gnatceg pack1.ads
6767 @end example
6769 will generate a self-contained file called @code{pack1.h} including
6770 common definitions from the Ada Standard package, followed by the
6771 definitions included in @code{pack1.ads}, as well as all the other units
6772 withed by this file.
6774 For instance, given the following Ada files:
6776 @example
6777 package Pack2 is
6778    type Int is range 1 .. 10;
6779 end Pack2;
6780 @end example
6782 @example
6783 with Pack2;
6785 package Pack1 is
6786    type Rec is record
6787       Field1, Field2 : Pack2.Int;
6788    end record;
6790    Global : Rec := (1, 2);
6792    procedure Proc1 (R : Rec);
6793    procedure Proc2 (R : in out Rec);
6794 end Pack1;
6795 @end example
6797 The above @code{gcc} command will generate the following @code{pack1.h} file:
6799 @example
6800 /* Standard definitions skipped */
6801 #ifndef PACK2_ADS
6802 #define PACK2_ADS
6803 typedef short_short_integer pack2__TintB;
6804 typedef pack2__TintB pack2__int;
6805 #endif /* PACK2_ADS */
6807 #ifndef PACK1_ADS
6808 #define PACK1_ADS
6809 typedef struct _pack1__rec @{
6810   pack2__int field1;
6811   pack2__int field2;
6812 @} pack1__rec;
6813 extern pack1__rec pack1__global;
6814 extern void pack1__proc1(const pack1__rec r);
6815 extern void pack1__proc2(pack1__rec *r);
6816 #endif /* PACK1_ADS */
6817 @end example
6819 You can then @code{include} @code{pack1.h} from a C source file and use the types,
6820 call subprograms, reference objects, and constants.
6822 @node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
6823 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{2d}@anchor{gnat_ugn/the_gnat_compilation_model id75}@anchor{bc}
6824 @section GNAT and Other Compilation Models
6827 This section compares the GNAT model with the approaches taken in
6828 other environments, first the C/C++ model and then the mechanism that
6829 has been used in other Ada systems, in particular those traditionally
6830 used for Ada 83.
6832 @menu
6833 * Comparison between GNAT and C/C++ Compilation Models:: 
6834 * Comparison between GNAT and Conventional Ada Library Models:: 
6836 @end menu
6838 @node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
6839 @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}
6840 @subsection Comparison between GNAT and C/C++ Compilation Models
6843 The GNAT model of compilation is close to the C and C++ models. You can
6844 think of Ada specs as corresponding to header files in C. As in C, you
6845 don’t need to compile specs; they are compiled when they are used. The
6846 Ada `with' is similar in effect to the @code{#include} of a C
6847 header.
6849 One notable difference is that, in Ada, you may compile specs separately
6850 to check them for semantic and syntactic accuracy. This is not always
6851 possible with C headers because they are fragments of programs that have
6852 less specific syntactic or semantic rules.
6854 The other major difference is the requirement for running the binder,
6855 which performs two important functions. First, it checks for
6856 consistency. In C or C++, the only defense against assembling
6857 inconsistent programs lies outside the compiler, in a makefile, for
6858 example. The binder satisfies the Ada requirement that it be impossible
6859 to construct an inconsistent program when the compiler is used in normal
6860 mode.
6862 @geindex Elaboration order control
6864 The other important function of the binder is to deal with elaboration
6865 issues. There are also elaboration issues in C++ that are handled
6866 automatically. This automatic handling has the advantage of being
6867 simpler to use, but the C++ programmer has no control over elaboration.
6868 Where @code{gnatbind} might complain there was no valid order of
6869 elaboration, a C++ compiler would simply construct a program that
6870 malfunctioned at run time.
6872 @node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
6873 @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}
6874 @subsection Comparison between GNAT and Conventional Ada Library Models
6877 This section is intended for Ada programmers who have
6878 used an Ada compiler implementing the traditional Ada library
6879 model, as described in the Ada Reference Manual.
6881 @geindex GNAT library
6883 In GNAT, there is no ‘library’ in the normal sense. Instead, the set of
6884 source files themselves acts as the library. Compiling Ada programs does
6885 not generate any centralized information, but rather an object file and
6886 a ALI file, which are of interest only to the binder and linker.
6887 In a traditional system, the compiler reads information not only from
6888 the source file being compiled, but also from the centralized library.
6889 This means that the effect of a compilation depends on what has been
6890 previously compiled. In particular:
6893 @itemize *
6895 @item 
6896 When a unit is `with'ed, the unit seen by the compiler corresponds
6897 to the version of the unit most recently compiled into the library.
6899 @item 
6900 Inlining is effective only if the necessary body has already been
6901 compiled into the library.
6903 @item 
6904 Compiling a unit may obsolete other units in the library.
6905 @end itemize
6907 In GNAT, compiling one unit never affects the compilation of any other
6908 units because the compiler reads only source files. Only changes to source
6909 files can affect the results of a compilation. In particular:
6912 @itemize *
6914 @item 
6915 When a unit is `with'ed, the unit seen by the compiler corresponds
6916 to the source version of the unit that is currently accessible to the
6917 compiler.
6919 @geindex Inlining
6921 @item 
6922 Inlining requires the appropriate source files for the package or
6923 subprogram bodies to be available to the compiler. Inlining is always
6924 effective, independent of the order in which units are compiled.
6926 @item 
6927 Compiling a unit never affects any other compilations. The editing of
6928 sources may cause previous compilations to be out of date if they
6929 depended on the source file being modified.
6930 @end itemize
6932 The most important result of these differences is that order of compilation
6933 is never significant in GNAT. There is no situation in which one is
6934 required to do one compilation before another. What shows up as order of
6935 compilation requirements in the traditional Ada library becomes, in
6936 GNAT, simple source dependencies; in other words, there is only a set
6937 of rules saying what source files must be present when a file is
6938 compiled.
6940 @node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
6941 @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}
6942 @section Using GNAT Files with External Tools
6945 This section explains how files that are produced by GNAT may be
6946 used with tools designed for other languages.
6948 @menu
6949 * Using Other Utility Programs with GNAT:: 
6950 * The External Symbol Naming Scheme of GNAT:: 
6952 @end menu
6954 @node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
6955 @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}
6956 @subsection Using Other Utility Programs with GNAT
6959 The object files generated by GNAT are in standard system format and in
6960 particular the debugging information uses this format. This means
6961 programs generated by GNAT can be used with existing utilities that
6962 depend on these formats.
6964 In general, any utility program that works with C will also often work with
6965 Ada programs generated by GNAT. This includes software utilities such as
6966 gprof (a profiling program), gdb (the FSF debugger), and utilities such
6967 as Purify.
6969 @node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
6970 @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}
6971 @subsection The External Symbol Naming Scheme of GNAT
6974 In order to interpret the output from GNAT, when using tools that are
6975 originally intended for use with other languages, it is useful to
6976 understand the conventions used to generate link names from the Ada
6977 entity names.
6979 All link names are in all lowercase letters. With the exception of library
6980 procedure names, the mechanism used is simply to use the full expanded
6981 Ada name with dots replaced by double underscores. For example, suppose
6982 we have the following package spec:
6984 @example
6985 package QRS is
6986    MN : Integer;
6987 end QRS;
6988 @end example
6990 @geindex pragma Export
6992 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
6993 the corresponding link name is @code{qrs__mn}.
6994 Of course if a @code{pragma Export} is used this may be overridden:
6996 @example
6997 package Exports is
6998    Var1 : Integer;
6999    pragma Export (Var1, C, External_Name => "var1_name");
7000    Var2 : Integer;
7001    pragma Export (Var2, C, Link_Name => "var2_link_name");
7002 end Exports;
7003 @end example
7005 In this case, the link name for @code{Var1} is whatever link name the
7006 C compiler would assign for the C function @code{var1_name}. This typically
7007 would be either @code{var1_name} or @code{_var1_name}, depending on operating
7008 system conventions, but other possibilities exist. The link name for
7009 @code{Var2} is @code{var2_link_name}, and this is not operating system
7010 dependent.
7012 One exception occurs for library level procedures. A potential ambiguity
7013 arises between the required name @code{_main} for the C main program,
7014 and the name we would otherwise assign to an Ada library level procedure
7015 called @code{Main} (which might well not be the main program).
7017 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
7018 names. So if we have a library level procedure such as:
7020 @example
7021 procedure Hello (S : String);
7022 @end example
7024 the external name of this procedure will be @code{_ada_hello}.
7026 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7028 @node Building Executable Programs with GNAT,GNAT Utility Programs,The GNAT Compilation Model,Top
7029 @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}
7030 @chapter Building Executable Programs with GNAT
7033 This chapter describes first the gnatmake tool
7034 (@ref{c8,,Building with gnatmake}),
7035 which automatically determines the set of sources
7036 needed by an Ada compilation unit and executes the necessary
7037 (re)compilations, binding and linking.
7038 It also explains how to use each tool individually: the
7039 compiler (gcc, see @ref{c9,,Compiling with gcc}),
7040 binder (gnatbind, see @ref{ca,,Binding with gnatbind}),
7041 and linker (gnatlink, see @ref{cb,,Linking with gnatlink})
7042 to build executable programs.
7043 Finally, this chapter provides examples of
7044 how to make use of the general GNU make mechanism
7045 in a GNAT context (see @ref{70,,Using the GNU make Utility}).
7048 @menu
7049 * Building with gnatmake:: 
7050 * Compiling with gcc:: 
7051 * Compiler Switches:: 
7052 * Linker Switches:: 
7053 * Binding with gnatbind:: 
7054 * Linking with gnatlink:: 
7055 * Using the GNU make Utility:: 
7057 @end menu
7059 @node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7060 @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}
7061 @section Building with @code{gnatmake}
7064 @geindex gnatmake
7066 A typical development cycle when working on an Ada program consists of
7067 the following steps:
7070 @enumerate 
7072 @item 
7073 Edit some sources to fix bugs;
7075 @item 
7076 Add enhancements;
7078 @item 
7079 Compile all sources affected;
7081 @item 
7082 Rebind and relink; and
7084 @item 
7085 Test.
7086 @end enumerate
7088 @geindex Dependency rules (compilation)
7090 The third step in particular can be tricky, because not only do the modified
7091 files have to be compiled, but any files depending on these files must also be
7092 recompiled. The dependency rules in Ada can be quite complex, especially
7093 in the presence of overloading, @code{use} clauses, generics and inlined
7094 subprograms.
7096 @code{gnatmake} automatically takes care of the third and fourth steps
7097 of this process. It determines which sources need to be compiled,
7098 compiles them, and binds and links the resulting object files.
7100 Unlike some other Ada make programs, the dependencies are always
7101 accurately recomputed from the new sources. The source based approach of
7102 the GNAT compilation model makes this possible. This means that if
7103 changes to the source program cause corresponding changes in
7104 dependencies, they will always be tracked exactly correctly by
7105 @code{gnatmake}.
7107 Note that for advanced forms of project structure, we recommend creating
7108 a project file as explained in the `GNAT_Project_Manager' chapter in the
7109 `GPRbuild User’s Guide', and using the
7110 @code{gprbuild} tool which supports building with project files and works similarly
7111 to @code{gnatmake}.
7113 @menu
7114 * Running gnatmake:: 
7115 * Switches for gnatmake:: 
7116 * Mode Switches for gnatmake:: 
7117 * Notes on the Command Line:: 
7118 * How gnatmake Works:: 
7119 * Examples of gnatmake Usage:: 
7121 @end menu
7123 @node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7124 @anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{cd}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{ce}
7125 @subsection Running @code{gnatmake}
7128 The usual form of the @code{gnatmake} command is
7130 @example
7131 $ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7132 @end example
7134 The only required argument is one @code{file_name}, which specifies
7135 a compilation unit that is a main program. Several @code{file_names} can be
7136 specified: this will result in several executables being built.
7137 If @code{switches} are present, they can be placed before the first
7138 @code{file_name}, between @code{file_names} or after the last @code{file_name}.
7139 If @code{mode_switches} are present, they must always be placed after
7140 the last @code{file_name} and all @code{switches}.
7142 If you are using standard file extensions (@code{.adb} and
7143 @code{.ads}), then the
7144 extension may be omitted from the @code{file_name} arguments. However, if
7145 you are using non-standard extensions, then it is required that the
7146 extension be given. A relative or absolute directory path can be
7147 specified in a @code{file_name}, in which case, the input source file will
7148 be searched for in the specified directory only. Otherwise, the input
7149 source file will first be searched in the directory where
7150 @code{gnatmake} was invoked and if it is not found, it will be search on
7151 the source path of the compiler as described in
7152 @ref{73,,Search Paths and the Run-Time Library (RTL)}.
7154 All @code{gnatmake} output (except when you specify @code{-M}) is sent to
7155 @code{stderr}. The output produced by the
7156 @code{-M} switch is sent to @code{stdout}.
7158 @node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7159 @anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{cf}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{d0}
7160 @subsection Switches for @code{gnatmake}
7163 You may specify any of the following switches to @code{gnatmake}:
7165 @geindex --version (gnatmake)
7168 @table @asis
7170 @item @code{--version}
7172 Display Copyright and version, then exit disregarding all other options.
7173 @end table
7175 @geindex --help (gnatmake)
7178 @table @asis
7180 @item @code{--help}
7182 If @code{--version} was not used, display usage, then exit disregarding
7183 all other options.
7184 @end table
7186 @geindex -P (gnatmake)
7189 @table @asis
7191 @item @code{-P`project'}
7193 Build GNAT project file @code{project} using GPRbuild. When this switch is
7194 present, all other command-line switches are treated as GPRbuild switches
7195 and not @code{gnatmake} switches.
7196 @end table
7198 @c -- Comment:
7199 @c :ref:`gnatmake_and_Project_Files`.
7201 @geindex --GCC=compiler_name (gnatmake)
7204 @table @asis
7206 @item @code{--GCC=`compiler_name'}
7208 Program used for compiling. The default is @code{gcc}. You need to use
7209 quotes around @code{compiler_name} if @code{compiler_name} contains
7210 spaces or other separator characters.
7211 As an example @code{--GCC="foo -x  -y"}
7212 will instruct @code{gnatmake} to use @code{foo -x -y} as your
7213 compiler. A limitation of this syntax is that the name and path name of
7214 the executable itself must not include any embedded spaces. Note that
7215 switch @code{-c} is always inserted after your command name. Thus in the
7216 above example the compiler command that will be used by @code{gnatmake}
7217 will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7218 used, only the last @code{compiler_name} is taken into account. However,
7219 all the additional switches are also taken into account. Thus,
7220 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7221 @code{--GCC="bar -x -y -z -t"}.
7222 @end table
7224 @geindex --GNATBIND=binder_name (gnatmake)
7227 @table @asis
7229 @item @code{--GNATBIND=`binder_name'}
7231 Program used for binding. The default is @code{gnatbind}. You need to
7232 use quotes around @code{binder_name} if @code{binder_name} contains spaces
7233 or other separator characters.
7234 As an example @code{--GNATBIND="bar -x  -y"}
7235 will instruct @code{gnatmake} to use @code{bar -x -y} as your
7236 binder. Binder switches that are normally appended by @code{gnatmake}
7237 to @code{gnatbind} are now appended to the end of @code{bar -x -y}.
7238 A limitation of this syntax is that the name and path name of the executable
7239 itself must not include any embedded spaces.
7240 @end table
7242 @geindex --GNATLINK=linker_name (gnatmake)
7245 @table @asis
7247 @item @code{--GNATLINK=`linker_name'}
7249 Program used for linking. The default is @code{gnatlink}. You need to
7250 use quotes around @code{linker_name} if @code{linker_name} contains spaces
7251 or other separator characters.
7252 As an example @code{--GNATLINK="lan -x  -y"}
7253 will instruct @code{gnatmake} to use @code{lan -x -y} as your
7254 linker. Linker switches that are normally appended by @code{gnatmake} to
7255 @code{gnatlink} are now appended to the end of @code{lan -x -y}.
7256 A limitation of this syntax is that the name and path name of the executable
7257 itself must not include any embedded spaces.
7259 @item @code{--create-map-file}
7261 When linking an executable, create a map file. The name of the map file
7262 has the same name as the executable with extension “.map”.
7264 @item @code{--create-map-file=`mapfile'}
7266 When linking an executable, create a map file with the specified name.
7267 @end table
7269 @geindex --create-missing-dirs (gnatmake)
7272 @table @asis
7274 @item @code{--create-missing-dirs}
7276 When using project files (@code{-P`project'}), automatically create
7277 missing object directories, library directories and exec
7278 directories.
7280 @item @code{--single-compile-per-obj-dir}
7282 Disallow simultaneous compilations in the same object directory when
7283 project files are used.
7285 @item @code{--subdirs=`subdir'}
7287 Actual object directory of each project file is the subdirectory subdir of the
7288 object directory specified or defaulted in the project file.
7290 @item @code{--unchecked-shared-lib-imports}
7292 By default, shared library projects are not allowed to import static library
7293 projects. When this switch is used on the command line, this restriction is
7294 relaxed.
7296 @item @code{--source-info=`source info file'}
7298 Specify a source info file. This switch is active only when project files
7299 are used. If the source info file is specified as a relative path, then it is
7300 relative to the object directory of the main project. If the source info file
7301 does not exist, then after the Project Manager has successfully parsed and
7302 processed the project files and found the sources, it creates the source info
7303 file. If the source info file already exists and can be read successfully,
7304 then the Project Manager will get all the needed information about the sources
7305 from the source info file and will not look for them. This reduces the time
7306 to process the project files, especially when looking for sources that take a
7307 long time. If the source info file exists but cannot be parsed successfully,
7308 the Project Manager will attempt to recreate it. If the Project Manager fails
7309 to create the source info file, a message is issued, but gnatmake does not
7310 fail. @code{gnatmake} “trusts” the source info file. This means that
7311 if the source files have changed (addition, deletion, moving to a different
7312 source directory), then the source info file need to be deleted and recreated.
7313 @end table
7315 @geindex -a (gnatmake)
7318 @table @asis
7320 @item @code{-a}
7322 Consider all files in the make process, even the GNAT internal system
7323 files (for example, the predefined Ada library files), as well as any
7324 locked files. Locked files are files whose ALI file is write-protected.
7325 By default,
7326 @code{gnatmake} does not check these files,
7327 because the assumption is that the GNAT internal files are properly up
7328 to date, and also that any write protected ALI files have been properly
7329 installed. Note that if there is an installation problem, such that one
7330 of these files is not up to date, it will be properly caught by the
7331 binder.
7332 You may have to specify this switch if you are working on GNAT
7333 itself. The switch @code{-a} is also useful
7334 in conjunction with @code{-f}
7335 if you need to recompile an entire application,
7336 including run-time files, using special configuration pragmas,
7337 such as a @code{Normalize_Scalars} pragma.
7339 By default
7340 @code{gnatmake -a} compiles all GNAT
7341 internal files with
7342 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7343 @end table
7345 @geindex -b (gnatmake)
7348 @table @asis
7350 @item @code{-b}
7352 Bind only. Can be combined with @code{-c} to do
7353 compilation and binding, but no link.
7354 Can be combined with @code{-l}
7355 to do binding and linking. When not combined with
7356 @code{-c}
7357 all the units in the closure of the main program must have been previously
7358 compiled and must be up to date. The root unit specified by @code{file_name}
7359 may be given without extension, with the source extension or, if no GNAT
7360 Project File is specified, with the ALI file extension.
7361 @end table
7363 @geindex -c (gnatmake)
7366 @table @asis
7368 @item @code{-c}
7370 Compile only. Do not perform binding, except when @code{-b}
7371 is also specified. Do not perform linking, except if both
7372 @code{-b} and
7373 @code{-l} are also specified.
7374 If the root unit specified by @code{file_name} is not a main unit, this is the
7375 default. Otherwise @code{gnatmake} will attempt binding and linking
7376 unless all objects are up to date and the executable is more recent than
7377 the objects.
7378 @end table
7380 @geindex -C (gnatmake)
7383 @table @asis
7385 @item @code{-C}
7387 Use a temporary mapping file. A mapping file is a way to communicate
7388 to the compiler two mappings: from unit names to file names (without
7389 any directory information) and from file names to path names (with
7390 full directory information). A mapping file can make the compiler’s
7391 file searches faster, especially if there are many source directories,
7392 or the sources are read over a slow network connection. If
7393 @code{-P} is used, a mapping file is always used, so
7394 @code{-C} is unnecessary; in this case the mapping file
7395 is initially populated based on the project file. If
7396 @code{-C} is used without
7397 @code{-P},
7398 the mapping file is initially empty. Each invocation of the compiler
7399 will add any newly accessed sources to the mapping file.
7400 @end table
7402 @geindex -C= (gnatmake)
7405 @table @asis
7407 @item @code{-C=`file'}
7409 Use a specific mapping file. The file, specified as a path name (absolute or
7410 relative) by this switch, should already exist, otherwise the switch is
7411 ineffective. The specified mapping file will be communicated to the compiler.
7412 This switch is not compatible with a project file
7413 (-P`file`) or with multiple compiling processes
7414 (-jnnn, when nnn is greater than 1).
7415 @end table
7417 @geindex -d (gnatmake)
7420 @table @asis
7422 @item @code{-d}
7424 Display progress for each source, up to date or not, as a single line:
7426 @example
7427 completed x out of y (zz%)
7428 @end example
7430 If the file needs to be compiled this is displayed after the invocation of
7431 the compiler. These lines are displayed even in quiet output mode.
7432 @end table
7434 @geindex -D (gnatmake)
7437 @table @asis
7439 @item @code{-D `dir'}
7441 Put all object files and ALI file in directory @code{dir}.
7442 If the @code{-D} switch is not used, all object files
7443 and ALI files go in the current working directory.
7445 This switch cannot be used when using a project file.
7446 @end table
7448 @geindex -eI (gnatmake)
7451 @table @asis
7453 @item @code{-eI`nnn'}
7455 Indicates that the main source is a multi-unit source and the rank of the unit
7456 in the source file is nnn. nnn needs to be a positive number and a valid
7457 index in the source. This switch cannot be used when @code{gnatmake} is
7458 invoked for several mains.
7459 @end table
7461 @geindex -eL (gnatmake)
7463 @geindex symbolic links
7466 @table @asis
7468 @item @code{-eL}
7470 Follow all symbolic links when processing project files.
7471 This should be used if your project uses symbolic links for files or
7472 directories, but is not needed in other cases.
7474 @geindex naming scheme
7476 This also assumes that no directory matches the naming scheme for files (for
7477 instance that you do not have a directory called “sources.ads” when using the
7478 default GNAT naming scheme).
7480 When you do not have to use this switch (i.e., by default), gnatmake is able to
7481 save a lot of system calls (several per source file and object file), which
7482 can result in a significant speed up to load and manipulate a project file,
7483 especially when using source files from a remote system.
7484 @end table
7486 @geindex -eS (gnatmake)
7489 @table @asis
7491 @item @code{-eS}
7493 Output the commands for the compiler, the binder and the linker
7494 on standard output,
7495 instead of standard error.
7496 @end table
7498 @geindex -f (gnatmake)
7501 @table @asis
7503 @item @code{-f}
7505 Force recompilations. Recompile all sources, even though some object
7506 files may be up to date, but don’t recompile predefined or GNAT internal
7507 files or locked files (files with a write-protected ALI file),
7508 unless the @code{-a} switch is also specified.
7509 @end table
7511 @geindex -F (gnatmake)
7514 @table @asis
7516 @item @code{-F}
7518 When using project files, if some errors or warnings are detected during
7519 parsing and verbose mode is not in effect (no use of switch
7520 -v), then error lines start with the full path name of the project
7521 file, rather than its simple file name.
7522 @end table
7524 @geindex -g (gnatmake)
7527 @table @asis
7529 @item @code{-g}
7531 Enable debugging. This switch is simply passed to the compiler and to the
7532 linker.
7533 @end table
7535 @geindex -i (gnatmake)
7538 @table @asis
7540 @item @code{-i}
7542 In normal mode, @code{gnatmake} compiles all object files and ALI files
7543 into the current directory. If the @code{-i} switch is used,
7544 then instead object files and ALI files that already exist are overwritten
7545 in place. This means that once a large project is organized into separate
7546 directories in the desired manner, then @code{gnatmake} will automatically
7547 maintain and update this organization. If no ALI files are found on the
7548 Ada object path (see @ref{73,,Search Paths and the Run-Time Library (RTL)}),
7549 the new object and ALI files are created in the
7550 directory containing the source being compiled. If another organization
7551 is desired, where objects and sources are kept in different directories,
7552 a useful technique is to create dummy ALI files in the desired directories.
7553 When detecting such a dummy file, @code{gnatmake} will be forced to
7554 recompile the corresponding source file, and it will be put the resulting
7555 object and ALI files in the directory where it found the dummy file.
7556 @end table
7558 @geindex -j (gnatmake)
7560 @geindex Parallel make
7563 @table @asis
7565 @item @code{-j`n'}
7567 Use @code{n} processes to carry out the (re)compilations. On a multiprocessor
7568 machine compilations will occur in parallel. If @code{n} is 0, then the
7569 maximum number of parallel compilations is the number of core processors
7570 on the platform. In the event of compilation errors, messages from various
7571 compilations might get interspersed (but @code{gnatmake} will give you the
7572 full ordered list of failing compiles at the end). If this is problematic,
7573 rerun the make process with n set to 1 to get a clean list of messages.
7574 @end table
7576 @geindex -k (gnatmake)
7579 @table @asis
7581 @item @code{-k}
7583 Keep going. Continue as much as possible after a compilation error. To
7584 ease the programmer’s task in case of compilation errors, the list of
7585 sources for which the compile fails is given when @code{gnatmake}
7586 terminates.
7588 If @code{gnatmake} is invoked with several @code{file_names} and with this
7589 switch, if there are compilation errors when building an executable,
7590 @code{gnatmake} will not attempt to build the following executables.
7591 @end table
7593 @geindex -l (gnatmake)
7596 @table @asis
7598 @item @code{-l}
7600 Link only. Can be combined with @code{-b} to binding
7601 and linking. Linking will not be performed if combined with
7602 @code{-c}
7603 but not with @code{-b}.
7604 When not combined with @code{-b}
7605 all the units in the closure of the main program must have been previously
7606 compiled and must be up to date, and the main program needs to have been bound.
7607 The root unit specified by @code{file_name}
7608 may be given without extension, with the source extension or, if no GNAT
7609 Project File is specified, with the ALI file extension.
7610 @end table
7612 @geindex -m (gnatmake)
7615 @table @asis
7617 @item @code{-m}
7619 Specify that the minimum necessary amount of recompilations
7620 be performed. In this mode @code{gnatmake} ignores time
7621 stamp differences when the only
7622 modifications to a source file consist in adding/removing comments,
7623 empty lines, spaces or tabs. This means that if you have changed the
7624 comments in a source file or have simply reformatted it, using this
7625 switch will tell @code{gnatmake} not to recompile files that depend on it
7626 (provided other sources on which these files depend have undergone no
7627 semantic modifications). Note that the debugging information may be
7628 out of date with respect to the sources if the @code{-m} switch causes
7629 a compilation to be switched, so the use of this switch represents a
7630 trade-off between compilation time and accurate debugging information.
7631 @end table
7633 @geindex Dependencies
7634 @geindex producing list
7636 @geindex -M (gnatmake)
7639 @table @asis
7641 @item @code{-M}
7643 Check if all objects are up to date. If they are, output the object
7644 dependences to @code{stdout} in a form that can be directly exploited in
7645 a @code{Makefile}. By default, each source file is prefixed with its
7646 (relative or absolute) directory name. This name is whatever you
7647 specified in the various @code{-aI}
7648 and @code{-I} switches. If you use
7649 @code{gnatmake -M}  @code{-q}
7650 (see below), only the source file names,
7651 without relative paths, are output. If you just specify the  @code{-M}
7652 switch, dependencies of the GNAT internal system files are omitted. This
7653 is typically what you want. If you also specify
7654 the @code{-a} switch,
7655 dependencies of the GNAT internal files are also listed. Note that
7656 dependencies of the objects in external Ada libraries (see
7657 switch  @code{-aL`dir'} in the following list)
7658 are never reported.
7659 @end table
7661 @geindex -n (gnatmake)
7664 @table @asis
7666 @item @code{-n}
7668 Don’t compile, bind, or link. Checks if all objects are up to date.
7669 If they are not, the full name of the first file that needs to be
7670 recompiled is printed.
7671 Repeated use of this option, followed by compiling the indicated source
7672 file, will eventually result in recompiling all required units.
7673 @end table
7675 @geindex -o (gnatmake)
7678 @table @asis
7680 @item @code{-o `exec_name'}
7682 Output executable name. The name of the final executable program will be
7683 @code{exec_name}. If the @code{-o} switch is omitted the default
7684 name for the executable will be the name of the input file in appropriate form
7685 for an executable file on the host system.
7687 This switch cannot be used when invoking @code{gnatmake} with several
7688 @code{file_names}.
7689 @end table
7691 @geindex -p (gnatmake)
7694 @table @asis
7696 @item @code{-p}
7698 Same as @code{--create-missing-dirs}
7699 @end table
7701 @geindex -q (gnatmake)
7704 @table @asis
7706 @item @code{-q}
7708 Quiet. When this flag is not set, the commands carried out by
7709 @code{gnatmake} are displayed.
7710 @end table
7712 @geindex -s (gnatmake)
7715 @table @asis
7717 @item @code{-s}
7719 Recompile if compiler switches have changed since last compilation.
7720 All compiler switches but -I and -o are taken into account in the
7721 following way:
7722 orders between different ‘first letter’ switches are ignored, but
7723 orders between same switches are taken into account. For example,
7724 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O}
7725 is equivalent to @code{-O -g}.
7727 This switch is recommended when Integrated Preprocessing is used.
7728 @end table
7730 @geindex -u (gnatmake)
7733 @table @asis
7735 @item @code{-u}
7737 Unique. Recompile at most the main files. It implies -c. Combined with
7738 -f, it is equivalent to calling the compiler directly. Note that using
7739 -u with a project file and no main has a special meaning.
7740 @end table
7742 @c --Comment
7743 @c (See :ref:`Project_Files_and_Main_Subprograms`.)
7745 @geindex -U (gnatmake)
7748 @table @asis
7750 @item @code{-U}
7752 When used without a project file or with one or several mains on the command
7753 line, is equivalent to -u. When used with a project file and no main
7754 on the command line, all sources of all project files are checked and compiled
7755 if not up to date, and libraries are rebuilt, if necessary.
7756 @end table
7758 @geindex -v (gnatmake)
7761 @table @asis
7763 @item @code{-v}
7765 Verbose. Display the reason for all recompilations @code{gnatmake}
7766 decides are necessary, with the highest verbosity level.
7767 @end table
7769 @geindex -vl (gnatmake)
7772 @table @asis
7774 @item @code{-vl}
7776 Verbosity level Low. Display fewer lines than in verbosity Medium.
7777 @end table
7779 @geindex -vm (gnatmake)
7782 @table @asis
7784 @item @code{-vm}
7786 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7787 @end table
7789 @geindex -vm (gnatmake)
7792 @table @asis
7794 @item @code{-vh}
7796 Verbosity level High. Equivalent to -v.
7798 @item @code{-vP`x'}
7800 Indicate the verbosity of the parsing of GNAT project files.
7801 See @ref{d1,,Switches Related to Project Files}.
7802 @end table
7804 @geindex -x (gnatmake)
7807 @table @asis
7809 @item @code{-x}
7811 Indicate that sources that are not part of any Project File may be compiled.
7812 Normally, when using Project Files, only sources that are part of a Project
7813 File may be compile. When this switch is used, a source outside of all Project
7814 Files may be compiled. The ALI file and the object file will be put in the
7815 object directory of the main Project. The compilation switches used will only
7816 be those specified on the command line. Even when
7817 @code{-x} is used, mains specified on the
7818 command line need to be sources of a project file.
7820 @item @code{-X`name'=`value'}
7822 Indicate that external variable @code{name} has the value @code{value}.
7823 The Project Manager will use this value for occurrences of
7824 @code{external(name)} when parsing the project file.
7825 @ref{d1,,Switches Related to Project Files}.
7826 @end table
7828 @geindex -z (gnatmake)
7831 @table @asis
7833 @item @code{-z}
7835 No main subprogram. Bind and link the program even if the unit name
7836 given on the command line is a package name. The resulting executable
7837 will execute the elaboration routines of the package and its closure,
7838 then the finalization routines.
7839 @end table
7841 @subsubheading GCC switches
7844 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
7845 is passed to @code{gcc} (e.g., @code{-O}, @code{-gnato,} etc.)
7847 @subsubheading Source and library search path switches
7850 @geindex -aI (gnatmake)
7853 @table @asis
7855 @item @code{-aI`dir'}
7857 When looking for source files also look in directory @code{dir}.
7858 The order in which source files search is undertaken is
7859 described in @ref{73,,Search Paths and the Run-Time Library (RTL)}.
7860 @end table
7862 @geindex -aL (gnatmake)
7865 @table @asis
7867 @item @code{-aL`dir'}
7869 Consider @code{dir} as being an externally provided Ada library.
7870 Instructs @code{gnatmake} to skip compilation units whose @code{.ALI}
7871 files have been located in directory @code{dir}. This allows you to have
7872 missing bodies for the units in @code{dir} and to ignore out of date bodies
7873 for the same units. You still need to specify
7874 the location of the specs for these units by using the switches
7875 @code{-aI`dir'}  or @code{-I`dir'}.
7876 Note: this switch is provided for compatibility with previous versions
7877 of @code{gnatmake}. The easier method of causing standard libraries
7878 to be excluded from consideration is to write-protect the corresponding
7879 ALI files.
7880 @end table
7882 @geindex -aO (gnatmake)
7885 @table @asis
7887 @item @code{-aO`dir'}
7889 When searching for library and object files, look in directory
7890 @code{dir}. The order in which library files are searched is described in
7891 @ref{76,,Search Paths for gnatbind}.
7892 @end table
7894 @geindex Search paths
7895 @geindex for gnatmake
7897 @geindex -A (gnatmake)
7900 @table @asis
7902 @item @code{-A`dir'}
7904 Equivalent to @code{-aL`dir'} @code{-aI`dir'}.
7906 @geindex -I (gnatmake)
7908 @item @code{-I`dir'}
7910 Equivalent to @code{-aO`dir' -aI`dir'}.
7911 @end table
7913 @geindex -I- (gnatmake)
7915 @geindex Source files
7916 @geindex suppressing search
7919 @table @asis
7921 @item @code{-I-}
7923 Do not look for source files in the directory containing the source
7924 file named in the command line.
7925 Do not look for ALI or object files in the directory
7926 where @code{gnatmake} was invoked.
7927 @end table
7929 @geindex -L (gnatmake)
7931 @geindex Linker libraries
7934 @table @asis
7936 @item @code{-L`dir'}
7938 Add directory @code{dir} to the list of directories in which the linker
7939 will search for libraries. This is equivalent to
7940 @code{-largs} @code{-L`dir'}.
7941 Furthermore, under Windows, the sources pointed to by the libraries path
7942 set in the registry are not searched for.
7943 @end table
7945 @geindex -nostdinc (gnatmake)
7948 @table @asis
7950 @item @code{-nostdinc}
7952 Do not look for source files in the system default directory.
7953 @end table
7955 @geindex -nostdlib (gnatmake)
7958 @table @asis
7960 @item @code{-nostdlib}
7962 Do not look for library files in the system default directory.
7963 @end table
7965 @geindex --RTS (gnatmake)
7968 @table @asis
7970 @item @code{--RTS=`rts-path'}
7972 Specifies the default location of the run-time library. GNAT looks for the
7973 run-time
7974 in the following directories, and stops as soon as a valid run-time is found
7975 (@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
7976 @code{ada_object_path} present):
7979 @itemize *
7981 @item 
7982 `<current directory>/$rts_path'
7984 @item 
7985 `<default-search-dir>/$rts_path'
7987 @item 
7988 `<default-search-dir>/rts-$rts_path'
7990 @item 
7991 The selected path is handled like a normal RTS path.
7992 @end itemize
7993 @end table
7995 @node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
7996 @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}
7997 @subsection Mode Switches for @code{gnatmake}
8000 The mode switches (referred to as @code{mode_switches}) allow the
8001 inclusion of switches that are to be passed to the compiler itself, the
8002 binder or the linker. The effect of a mode switch is to cause all
8003 subsequent switches up to the end of the switch list, or up to the next
8004 mode switch, to be interpreted as switches to be passed on to the
8005 designated component of GNAT.
8007 @geindex -cargs (gnatmake)
8010 @table @asis
8012 @item @code{-cargs `switches'}
8014 Compiler switches. Here @code{switches} is a list of switches
8015 that are valid switches for @code{gcc}. They will be passed on to
8016 all compile steps performed by @code{gnatmake}.
8017 @end table
8019 @geindex -bargs (gnatmake)
8022 @table @asis
8024 @item @code{-bargs `switches'}
8026 Binder switches. Here @code{switches} is a list of switches
8027 that are valid switches for @code{gnatbind}. They will be passed on to
8028 all bind steps performed by @code{gnatmake}.
8029 @end table
8031 @geindex -largs (gnatmake)
8034 @table @asis
8036 @item @code{-largs `switches'}
8038 Linker switches. Here @code{switches} is a list of switches
8039 that are valid switches for @code{gnatlink}. They will be passed on to
8040 all link steps performed by @code{gnatmake}.
8041 @end table
8043 @geindex -margs (gnatmake)
8046 @table @asis
8048 @item @code{-margs `switches'}
8050 Make switches. The switches are directly interpreted by @code{gnatmake},
8051 regardless of any previous occurrence of @code{-cargs}, @code{-bargs}
8052 or @code{-largs}.
8053 @end table
8055 @node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8056 @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}
8057 @subsection Notes on the Command Line
8060 This section contains some additional useful notes on the operation
8061 of the @code{gnatmake} command.
8063 @geindex Recompilation (by gnatmake)
8066 @itemize *
8068 @item 
8069 If @code{gnatmake} finds no ALI files, it recompiles the main program
8070 and all other units required by the main program.
8071 This means that @code{gnatmake}
8072 can be used for the initial compile, as well as during subsequent steps of
8073 the development cycle.
8075 @item 
8076 If you enter @code{gnatmake foo.adb}, where @code{foo}
8077 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8078 @code{foo.adb} (because it finds no ALI) and stops, issuing a
8079 warning.
8081 @item 
8082 In @code{gnatmake} the switch @code{-I}
8083 is used to specify both source and
8084 library file paths. Use @code{-aI}
8085 instead if you just want to specify
8086 source paths only and @code{-aO}
8087 if you want to specify library paths
8088 only.
8090 @item 
8091 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8092 This may conveniently be used to exclude standard libraries from
8093 consideration and in particular it means that the use of the
8094 @code{-f} switch will not recompile these files
8095 unless @code{-a} is also specified.
8097 @item 
8098 @code{gnatmake} has been designed to make the use of Ada libraries
8099 particularly convenient. Assume you have an Ada library organized
8100 as follows: `obj-dir' contains the objects and ALI files for
8101 of your Ada compilation units,
8102 whereas `include-dir' contains the
8103 specs of these units, but no bodies. Then to compile a unit
8104 stored in @code{main.adb}, which uses this Ada library you would just type:
8106 @example
8107 $ gnatmake -aI`include-dir`  -aL`obj-dir`  main
8108 @end example
8110 @item 
8111 Using @code{gnatmake} along with the @code{-m (minimal recompilation)}
8112 switch provides a mechanism for avoiding unnecessary recompilations. Using
8113 this switch,
8114 you can update the comments/format of your
8115 source files without having to recompile everything. Note, however, that
8116 adding or deleting lines in a source files may render its debugging
8117 info obsolete. If the file in question is a spec, the impact is rather
8118 limited, as that debugging info will only be useful during the
8119 elaboration phase of your program. For bodies the impact can be more
8120 significant. In all events, your debugger will warn you if a source file
8121 is more recent than the corresponding object, and alert you to the fact
8122 that the debugging information may be out of date.
8123 @end itemize
8125 @node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8126 @anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{d6}@anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{d7}
8127 @subsection How @code{gnatmake} Works
8130 Generally @code{gnatmake} automatically performs all necessary
8131 recompilations and you don’t need to worry about how it works. However,
8132 it may be useful to have some basic understanding of the @code{gnatmake}
8133 approach and in particular to understand how it uses the results of
8134 previous compilations without incorrectly depending on them.
8136 First a definition: an object file is considered `up to date' if the
8137 corresponding ALI file exists and if all the source files listed in the
8138 dependency section of this ALI file have time stamps matching those in
8139 the ALI file. This means that neither the source file itself nor any
8140 files that it depends on have been modified, and hence there is no need
8141 to recompile this file.
8143 @code{gnatmake} works by first checking if the specified main unit is up
8144 to date. If so, no compilations are required for the main unit. If not,
8145 @code{gnatmake} compiles the main program to build a new ALI file that
8146 reflects the latest sources. Then the ALI file of the main unit is
8147 examined to find all the source files on which the main program depends,
8148 and @code{gnatmake} recursively applies the above procedure on all these
8149 files.
8151 This process ensures that @code{gnatmake} only trusts the dependencies
8152 in an existing ALI file if they are known to be correct. Otherwise it
8153 always recompiles to determine a new, guaranteed accurate set of
8154 dependencies. As a result the program is compiled ‘upside down’ from what may
8155 be more familiar as the required order of compilation in some other Ada
8156 systems. In particular, clients are compiled before the units on which
8157 they depend. The ability of GNAT to compile in any order is critical in
8158 allowing an order of compilation to be chosen that guarantees that
8159 @code{gnatmake} will recompute a correct set of new dependencies if
8160 necessary.
8162 When invoking @code{gnatmake} with several @code{file_names}, if a unit is
8163 imported by several of the executables, it will be recompiled at most once.
8165 Note: when using non-standard naming conventions
8166 (@ref{1c,,Using Other File Names}), changing through a configuration pragmas
8167 file the version of a source and invoking @code{gnatmake} to recompile may
8168 have no effect, if the previous version of the source is still accessible
8169 by @code{gnatmake}. It may be necessary to use the switch
8172 @node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8173 @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}
8174 @subsection Examples of @code{gnatmake} Usage
8178 @table @asis
8180 @item @code{gnatmake hello.adb}
8182 Compile all files necessary to bind and link the main program
8183 @code{hello.adb} (containing unit @code{Hello}) and bind and link the
8184 resulting object files to generate an executable file @code{hello}.
8186 @item @code{gnatmake main1 main2 main3}
8188 Compile all files necessary to bind and link the main programs
8189 @code{main1.adb} (containing unit @code{Main1}), @code{main2.adb}
8190 (containing unit @code{Main2}) and @code{main3.adb}
8191 (containing unit @code{Main3}) and bind and link the resulting object files
8192 to generate three executable files @code{main1},
8193 @code{main2}  and @code{main3}.
8195 @item @code{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8197 Compile all files necessary to bind and link the main program unit
8198 @code{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8199 be done with optimization level 2 and the order of elaboration will be
8200 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8201 displaying commands it is executing.
8202 @end table
8204 @node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8205 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{c9}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{da}
8206 @section Compiling with @code{gcc}
8209 This section discusses how to compile Ada programs using the @code{gcc}
8210 command. It also describes the set of switches
8211 that can be used to control the behavior of the compiler.
8213 @menu
8214 * Compiling Programs:: 
8215 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
8216 * Order of Compilation Issues:: 
8217 * Examples:: 
8219 @end menu
8221 @node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8222 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{db}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{dc}
8223 @subsection Compiling Programs
8226 The first step in creating an executable program is to compile the units
8227 of the program using the @code{gcc} command. You must compile the
8228 following files:
8231 @itemize *
8233 @item 
8234 the body file (@code{.adb}) for a library level subprogram or generic
8235 subprogram
8237 @item 
8238 the spec file (@code{.ads}) for a library level package or generic
8239 package that has no body
8241 @item 
8242 the body file (@code{.adb}) for a library level package
8243 or generic package that has a body
8244 @end itemize
8246 You need `not' compile the following files
8249 @itemize *
8251 @item 
8252 the spec of a library unit which has a body
8254 @item 
8255 subunits
8256 @end itemize
8258 because they are compiled as part of compiling related units. GNAT compiles
8259 package specs
8260 when the corresponding body is compiled, and subunits when the parent is
8261 compiled.
8263 @geindex cannot generate code
8265 If you attempt to compile any of these files, you will get one of the
8266 following error messages (where @code{fff} is the name of the file you
8267 compiled):
8269 @quotation
8271 @example
8272 cannot generate code for file `@w{`}fff`@w{`} (package spec)
8273 to check package spec, use -gnatc
8275 cannot generate code for file `@w{`}fff`@w{`} (missing subunits)
8276 to check parent unit, use -gnatc
8278 cannot generate code for file `@w{`}fff`@w{`} (subprogram spec)
8279 to check subprogram spec, use -gnatc
8281 cannot generate code for file `@w{`}fff`@w{`} (subunit)
8282 to check subunit, use -gnatc
8283 @end example
8284 @end quotation
8286 As indicated by the above error messages, if you want to submit
8287 one of these files to the compiler to check for correct semantics
8288 without generating code, then use the @code{-gnatc} switch.
8290 The basic command for compiling a file containing an Ada unit is:
8292 @example
8293 $ gcc -c [switches] <file name>
8294 @end example
8296 where @code{file name} is the name of the Ada file (usually
8297 having an extension @code{.ads} for a spec or @code{.adb} for a body).
8298 You specify the
8299 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
8300 The result of a successful compilation is an object file, which has the
8301 same name as the source file but an extension of @code{.o} and an Ada
8302 Library Information (ALI) file, which also has the same name as the
8303 source file, but with @code{.ali} as the extension. GNAT creates these
8304 two output files in the current directory, but you may specify a source
8305 file in any directory using an absolute or relative path specification
8306 containing the directory information.
8308 @geindex gnat1
8310 @code{gcc} is actually a driver program that looks at the extensions of
8311 the file arguments and loads the appropriate compiler. For example, the
8312 GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8313 These programs are in directories known to the driver program (in some
8314 configurations via environment variables you set), but need not be in
8315 your path. The @code{gcc} driver also calls the assembler and any other
8316 utilities needed to complete the generation of the required object
8317 files.
8319 It is possible to supply several file names on the same @code{gcc}
8320 command. This causes @code{gcc} to call the appropriate compiler for
8321 each file. For example, the following command lists two separate
8322 files to be compiled:
8324 @example
8325 $ gcc -c x.adb y.adb
8326 @end example
8328 calls @code{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8329 @code{y.adb}.
8330 The compiler generates two object files @code{x.o} and @code{y.o}
8331 and the two ALI files @code{x.ali} and @code{y.ali}.
8333 Any switches apply to all the files listed, see @ref{dd,,Compiler Switches} for a
8334 list of available @code{gcc} switches.
8336 @node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8337 @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}
8338 @subsection Search Paths and the Run-Time Library (RTL)
8341 With the GNAT source-based library system, the compiler must be able to
8342 find source files for units that are needed by the unit being compiled.
8343 Search paths are used to guide this process.
8345 The compiler compiles one source file whose name must be given
8346 explicitly on the command line. In other words, no searching is done
8347 for this file. To find all other source files that are needed (the most
8348 common being the specs of units), the compiler examines the following
8349 directories, in the following order:
8352 @itemize *
8354 @item 
8355 The directory containing the source file of the main unit being compiled
8356 (the file name on the command line).
8358 @item 
8359 Each directory named by an @code{-I} switch given on the @code{gcc}
8360 command line, in the order given.
8362 @geindex ADA_PRJ_INCLUDE_FILE
8364 @item 
8365 Each of the directories listed in the text file whose name is given
8366 by the 
8367 @geindex ADA_PRJ_INCLUDE_FILE
8368 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8369 @code{ADA_PRJ_INCLUDE_FILE} environment variable.
8370 @geindex ADA_PRJ_INCLUDE_FILE
8371 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8372 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8373 driver when project files are used. It should not normally be set
8374 by other means.
8376 @geindex ADA_INCLUDE_PATH
8378 @item 
8379 Each of the directories listed in the value of the
8380 @geindex ADA_INCLUDE_PATH
8381 @geindex environment variable; ADA_INCLUDE_PATH
8382 @code{ADA_INCLUDE_PATH} environment variable.
8383 Construct this value
8384 exactly as the 
8385 @geindex PATH
8386 @geindex environment variable; PATH
8387 @code{PATH} environment variable: a list of directory
8388 names separated by colons (semicolons when working with the NT version).
8390 @item 
8391 The content of the @code{ada_source_path} file which is part of the GNAT
8392 installation tree and is used to store standard libraries such as the
8393 GNAT Run Time Library (RTL) source files.
8394 See also @ref{72,,Installing a library}.
8395 @end itemize
8397 Specifying the switch @code{-I-}
8398 inhibits the use of the directory
8399 containing the source file named in the command line. You can still
8400 have this directory on your search path, but in this case it must be
8401 explicitly requested with a @code{-I} switch.
8403 Specifying the switch @code{-nostdinc}
8404 inhibits the search of the default location for the GNAT Run Time
8405 Library (RTL) source files.
8407 The compiler outputs its object files and ALI files in the current
8408 working directory.
8409 Caution: The object file can be redirected with the @code{-o} switch;
8410 however, @code{gcc} and @code{gnat1} have not been coordinated on this
8411 so the @code{ALI} file will not go to the right place. Therefore, you should
8412 avoid using the @code{-o} switch.
8414 @geindex System.IO
8416 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8417 children make up the GNAT RTL, together with the simple @code{System.IO}
8418 package used in the @code{"Hello World"} example. The sources for these units
8419 are needed by the compiler and are kept together in one directory. Not
8420 all of the bodies are needed, but all of the sources are kept together
8421 anyway. In a normal installation, you need not specify these directory
8422 names when compiling or binding. Either the environment variables or
8423 the built-in defaults cause these files to be found.
8425 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8426 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8427 consisting of child units of @code{GNAT}. This is a collection of generally
8428 useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8429 for further details.
8431 Besides simplifying access to the RTL, a major use of search paths is
8432 in compiling sources from multiple directories. This can make
8433 development environments much more flexible.
8435 @node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8436 @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}
8437 @subsection Order of Compilation Issues
8440 If, in our earlier example, there was a spec for the @code{hello}
8441 procedure, it would be contained in the file @code{hello.ads}; yet this
8442 file would not have to be explicitly compiled. This is the result of the
8443 model we chose to implement library management. Some of the consequences
8444 of this model are as follows:
8447 @itemize *
8449 @item 
8450 There is no point in compiling specs (except for package
8451 specs with no bodies) because these are compiled as needed by clients. If
8452 you attempt a useless compilation, you will receive an error message.
8453 It is also useless to compile subunits because they are compiled as needed
8454 by the parent.
8456 @item 
8457 There are no order of compilation requirements: performing a
8458 compilation never obsoletes anything. The only way you can obsolete
8459 something and require recompilations is to modify one of the
8460 source files on which it depends.
8462 @item 
8463 There is no library as such, apart from the ALI files
8464 (@ref{28,,The Ada Library Information Files}, for information on the format
8465 of these files). For now we find it convenient to create separate ALI files,
8466 but eventually the information therein may be incorporated into the object
8467 file directly.
8469 @item 
8470 When you compile a unit, the source files for the specs of all units
8471 that it `with's, all its subunits, and the bodies of any generics it
8472 instantiates must be available (reachable by the search-paths mechanism
8473 described above), or you will receive a fatal error message.
8474 @end itemize
8476 @node Examples,,Order of Compilation Issues,Compiling with gcc
8477 @anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{e1}@anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{e2}
8478 @subsection Examples
8481 The following are some typical Ada compilation command line examples:
8483 @example
8484 $ gcc -c xyz.adb
8485 @end example
8487 Compile body in file @code{xyz.adb} with all default options.
8489 @example
8490 $ gcc -c -O2 -gnata xyz-def.adb
8491 @end example
8493 Compile the child unit package in file @code{xyz-def.adb} with extensive
8494 optimizations, and pragma @code{Assert}/@code{Debug} statements
8495 enabled.
8497 @example
8498 $ gcc -c -gnatc abc-def.adb
8499 @end example
8501 Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8502 mode.
8504 @node Compiler Switches,Linker Switches,Compiling with gcc,Building Executable Programs with GNAT
8505 @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}
8506 @section Compiler Switches
8509 The @code{gcc} command accepts switches that control the
8510 compilation process. These switches are fully described in this section:
8511 first an alphabetical listing of all switches with a brief description,
8512 and then functionally grouped sets of switches with more detailed
8513 information.
8515 More switches exist for GCC than those documented here, especially
8516 for specific targets. However, their use is not recommended as
8517 they may change code generation in ways that are incompatible with
8518 the Ada run-time library, or can cause inconsistencies between
8519 compilation units.
8521 @menu
8522 * Alphabetical List of All Switches:: 
8523 * Output and Error Message Control:: 
8524 * Warning Message Control:: 
8525 * Debugging and Assertion Control:: 
8526 * Validity Checking:: 
8527 * Style Checking:: 
8528 * Run-Time Checks:: 
8529 * Using gcc for Syntax Checking:: 
8530 * Using gcc for Semantic Checking:: 
8531 * Compiling Different Versions of Ada:: 
8532 * Character Set Control:: 
8533 * File Naming Control:: 
8534 * Subprogram Inlining Control:: 
8535 * Auxiliary Output Control:: 
8536 * Debugging Control:: 
8537 * Exception Handling Control:: 
8538 * Units to Sources Mapping Files:: 
8539 * Code Generation Control:: 
8541 @end menu
8543 @node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8544 @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}
8545 @subsection Alphabetical List of All Switches
8548 @geindex -b (gcc)
8551 @table @asis
8553 @item @code{-b `target'}
8555 Compile your program to run on @code{target}, which is the name of a
8556 system configuration. You must have a GNAT cross-compiler built if
8557 @code{target} is not the same as your host system.
8558 @end table
8560 @geindex -B (gcc)
8563 @table @asis
8565 @item @code{-B`dir'}
8567 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8568 from @code{dir} instead of the default location. Only use this switch
8569 when multiple versions of the GNAT compiler are available.
8570 See the “Options for Directory Search” section in the
8571 @cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8572 You would normally use the @code{-b} or @code{-V} switch instead.
8573 @end table
8575 @geindex -c (gcc)
8578 @table @asis
8580 @item @code{-c}
8582 Compile. Always use this switch when compiling Ada programs.
8584 Note: for some other languages when using @code{gcc}, notably in
8585 the case of C and C++, it is possible to use
8586 use @code{gcc} without a @code{-c} switch to
8587 compile and link in one step. In the case of GNAT, you
8588 cannot use this approach, because the binder must be run
8589 and @code{gcc} cannot be used to run the GNAT binder.
8590 @end table
8592 @geindex -fcallgraph-info (gcc)
8595 @table @asis
8597 @item @code{-fcallgraph-info[=su,da]}
8599 Makes the compiler output callgraph information for the program, on a
8600 per-file basis. The information is generated in the VCG format.  It can
8601 be decorated with additional, per-node and/or per-edge information, if a
8602 list of comma-separated markers is additionally specified. When the
8603 @code{su} marker is specified, the callgraph is decorated with stack usage
8604 information; it is equivalent to @code{-fstack-usage}. When the @code{da}
8605 marker is specified, the callgraph is decorated with information about
8606 dynamically allocated objects.
8607 @end table
8609 @geindex -fdiagnostics-format (gcc)
8612 @table @asis
8614 @item @code{-fdiagnostics-format=json}
8616 Makes GNAT emit warning and error messages as JSON. Inhibits printing of
8617 text warning and errors messages except if @code{-gnatv} or
8618 @code{-gnatl} are present. Uses absolute file paths when used along
8619 @code{-gnatef}.
8620 @end table
8622 @geindex -fdump-scos (gcc)
8625 @table @asis
8627 @item @code{-fdump-scos}
8629 Generates SCO (Source Coverage Obligation) information in the ALI file.
8630 This information is used by advanced coverage tools. See unit @code{SCOs}
8631 in the compiler sources for details in files @code{scos.ads} and
8632 @code{scos.adb}.
8633 @end table
8635 @geindex -fgnat-encodings (gcc)
8638 @table @asis
8640 @item @code{-fgnat-encodings=[all|gdb|minimal]}
8642 This switch controls the balance between GNAT encodings and standard DWARF
8643 emitted in the debug information.
8644 @end table
8646 @geindex -flto (gcc)
8649 @table @asis
8651 @item @code{-flto[=`n']}
8653 Enables Link Time Optimization. This switch must be used in conjunction
8654 with the @code{-Ox} switches (but not with the @code{-gnatn} switch
8655 since it is a full replacement for the latter) and instructs the compiler
8656 to defer most optimizations until the link stage. The advantage of this
8657 approach is that the compiler can do a whole-program analysis and choose
8658 the best interprocedural optimization strategy based on a complete view
8659 of the program, instead of a fragmentary view with the usual approach.
8660 This can also speed up the compilation of big programs and reduce the
8661 size of the executable, compared with a traditional per-unit compilation
8662 with inlining across units enabled by the @code{-gnatn} switch.
8663 The drawback of this approach is that it may require more memory and that
8664 the debugging information generated by @code{-g} with it might be hardly usable.
8665 The switch, as well as the accompanying @code{-Ox} switches, must be
8666 specified both for the compilation and the link phases.
8667 If the @code{n} parameter is specified, the optimization and final code
8668 generation at link time are executed using @code{n} parallel jobs by
8669 means of an installed @code{make} program.
8670 @end table
8672 @geindex -fno-inline (gcc)
8675 @table @asis
8677 @item @code{-fno-inline}
8679 Suppresses all inlining, unless requested with pragma @code{Inline_Always}. The
8680 effect is enforced regardless of other optimization or inlining switches.
8681 Note that inlining can also be suppressed on a finer-grained basis with
8682 pragma @code{No_Inline}.
8683 @end table
8685 @geindex -fno-inline-functions (gcc)
8688 @table @asis
8690 @item @code{-fno-inline-functions}
8692 Suppresses automatic inlining of subprograms, which is enabled
8693 if @code{-O3} is used.
8694 @end table
8696 @geindex -fno-inline-small-functions (gcc)
8699 @table @asis
8701 @item @code{-fno-inline-small-functions}
8703 Suppresses automatic inlining of small subprograms, which is enabled
8704 if @code{-O2} is used.
8705 @end table
8707 @geindex -fno-inline-functions-called-once (gcc)
8710 @table @asis
8712 @item @code{-fno-inline-functions-called-once}
8714 Suppresses inlining of subprograms local to the unit and called once
8715 from within it, which is enabled if @code{-O1} is used.
8716 @end table
8718 @geindex -fno-ivopts (gcc)
8721 @table @asis
8723 @item @code{-fno-ivopts}
8725 Suppresses high-level loop induction variable optimizations, which are
8726 enabled if @code{-O1} is used. These optimizations are generally
8727 profitable but, for some specific cases of loops with numerous uses
8728 of the iteration variable that follow a common pattern, they may end
8729 up destroying the regularity that could be exploited at a lower level
8730 and thus producing inferior code.
8731 @end table
8733 @geindex -fno-strict-aliasing (gcc)
8736 @table @asis
8738 @item @code{-fno-strict-aliasing}
8740 Causes the compiler to avoid assumptions regarding non-aliasing
8741 of objects of different types. See
8742 @ref{e6,,Optimization and Strict Aliasing} for details.
8743 @end table
8745 @geindex -fno-strict-overflow (gcc)
8748 @table @asis
8750 @item @code{-fno-strict-overflow}
8752 Causes the compiler to avoid assumptions regarding the rules of signed
8753 integer overflow. These rules specify that signed integer overflow will
8754 result in a Constraint_Error exception at run time and are enforced in
8755 default mode by the compiler, so this switch should not be necessary in
8756 normal operating mode. It might be useful in conjunction with @code{-gnato0}
8757 for very peculiar cases of low-level programming.
8758 @end table
8760 @geindex -fstack-check (gcc)
8763 @table @asis
8765 @item @code{-fstack-check}
8767 Activates stack checking.
8768 See @ref{e7,,Stack Overflow Checking} for details.
8769 @end table
8771 @geindex -fstack-usage (gcc)
8774 @table @asis
8776 @item @code{-fstack-usage}
8778 Makes the compiler output stack usage information for the program, on a
8779 per-subprogram basis. See @ref{e8,,Static Stack Usage Analysis} for details.
8780 @end table
8782 @geindex -g (gcc)
8785 @table @asis
8787 @item @code{-g}
8789 Generate debugging information. This information is stored in the object
8790 file and copied from there to the final executable file by the linker,
8791 where it can be read by the debugger. You must use the
8792 @code{-g} switch if you plan on using the debugger.
8793 @end table
8795 @geindex -gnat05 (gcc)
8798 @table @asis
8800 @item @code{-gnat05}
8802 Allow full Ada 2005 features.
8803 @end table
8805 @geindex -gnat12 (gcc)
8808 @table @asis
8810 @item @code{-gnat12}
8812 Allow full Ada 2012 features.
8813 @end table
8815 @geindex -gnat83 (gcc)
8817 @geindex -gnat2005 (gcc)
8820 @table @asis
8822 @item @code{-gnat2005}
8824 Allow full Ada 2005 features (same as @code{-gnat05})
8825 @end table
8827 @geindex -gnat2012 (gcc)
8830 @table @asis
8832 @item @code{-gnat2012}
8834 Allow full Ada 2012 features (same as @code{-gnat12})
8835 @end table
8837 @geindex -gnat2022 (gcc)
8840 @table @asis
8842 @item @code{-gnat2022}
8844 Allow full Ada 2022 features
8846 @item @code{-gnat83}
8848 Enforce Ada 83 restrictions.
8849 @end table
8851 @geindex -gnat95 (gcc)
8854 @table @asis
8856 @item @code{-gnat95}
8858 Enforce Ada 95 restrictions.
8860 Note: for compatibility with some Ada 95 compilers which support only
8861 the @code{overriding} keyword of Ada 2005, the @code{-gnatd.D} switch can
8862 be used along with @code{-gnat95} to achieve a similar effect with GNAT.
8864 @code{-gnatd.D} instructs GNAT to consider @code{overriding} as a keyword
8865 and handle its associated semantic checks, even in Ada 95 mode.
8866 @end table
8868 @geindex -gnata (gcc)
8871 @table @asis
8873 @item @code{-gnata}
8875 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
8876 activated. Note that these pragmas can also be controlled using the
8877 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
8878 It also activates pragmas @code{Check}, @code{Precondition}, and
8879 @code{Postcondition}. Note that these pragmas can also be controlled
8880 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
8881 also activates all assertions defined in the RM as aspects: preconditions,
8882 postconditions, type invariants and (sub)type predicates. In all Ada modes,
8883 corresponding pragmas for type invariants and (sub)type predicates are
8884 also activated. The default is that all these assertions are disabled,
8885 and have no effect, other than being checked for syntactic validity, and
8886 in the case of subtype predicates, constructions such as membership tests
8887 still test predicates even if assertions are turned off.
8888 @end table
8890 @geindex -gnatA (gcc)
8893 @table @asis
8895 @item @code{-gnatA}
8897 Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
8898 it will be ignored.
8899 @end table
8901 @geindex -gnatb (gcc)
8904 @table @asis
8906 @item @code{-gnatb}
8908 Generate brief messages to @code{stderr} even if verbose mode set.
8909 @end table
8911 @geindex -gnatB (gcc)
8914 @table @asis
8916 @item @code{-gnatB}
8918 Assume no invalid (bad) values except for ‘Valid attribute use
8919 (@ref{e9,,Validity Checking}).
8920 @end table
8922 @geindex -gnatc (gcc)
8925 @table @asis
8927 @item @code{-gnatc}
8929 Check syntax and semantics only (no code generation attempted). When the
8930 compiler is invoked by @code{gnatmake}, if the switch @code{-gnatc} is
8931 only given to the compiler (after @code{-cargs} or in package Compiler of
8932 the project file), @code{gnatmake} will fail because it will not find the
8933 object file after compilation. If @code{gnatmake} is called with
8934 @code{-gnatc} as a builder switch (before @code{-cargs} or in package
8935 Builder of the project file) then @code{gnatmake} will not fail because
8936 it will not look for the object files after compilation, and it will not try
8937 to build and link.
8938 @end table
8940 @geindex -gnatC (gcc)
8943 @table @asis
8945 @item @code{-gnatC}
8947 Generate CodePeer intermediate format (no code generation attempted).
8948 This switch will generate an intermediate representation suitable for
8949 use by CodePeer (@code{.scil} files). This switch is not compatible with
8950 code generation (it will, among other things, disable some switches such
8951 as @code{-gnatn}, and enable others such as @code{-gnata}).
8952 @end table
8954 @geindex -gnatd (gcc)
8957 @table @asis
8959 @item @code{-gnatd}
8961 Specify debug options for the compiler. The string of characters after
8962 the @code{-gnatd} specifies the specific debug options. The possible
8963 characters are 0-9, a-z, A-Z, optionally preceded by a dot or underscore.
8964 See compiler source file @code{debug.adb} for details of the implemented
8965 debug options. Certain debug options are relevant to application
8966 programmers, and these are documented at appropriate points in this
8967 user’s guide.
8968 @end table
8970 @geindex -gnatD[nn] (gcc)
8973 @table @asis
8975 @item @code{-gnatD}
8977 Create expanded source files for source level debugging. This switch
8978 also suppresses generation of cross-reference information
8979 (see @code{-gnatx}). Note that this switch is not allowed if a previous
8980 @code{-gnatR} switch has been given, since these two switches are not compatible.
8981 @end table
8983 @geindex -gnateA (gcc)
8986 @table @asis
8988 @item @code{-gnateA}
8990 Check that the actual parameters of a subprogram call are not aliases of one
8991 another. To qualify as aliasing, their memory locations must be identical or
8992 overlapping, at least one of the corresponding formal parameters must be of
8993 mode OUT or IN OUT, and at least one of the corresponding formal parameters
8994 must have its parameter passing mechanism not specified.
8996 @example
8997 type Rec_Typ is record
8998    Data : Integer := 0;
8999 end record;
9001 function Self (Val : Rec_Typ) return Rec_Typ is
9002 begin
9003    return Val;
9004 end Self;
9006 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
9007 begin
9008    null;
9009 end Detect_Aliasing;
9011 Obj : Rec_Typ;
9013 Detect_Aliasing (Obj, Obj);
9014 Detect_Aliasing (Obj, Self (Obj));
9015 @end example
9017 In the example above, the first call to @code{Detect_Aliasing} fails with a
9018 @code{Program_Error} at run time because the actuals for @code{Val_1} and
9019 @code{Val_2} denote the same object. The second call executes without raising
9020 an exception because @code{Self(Obj)} produces an anonymous object which does
9021 not share the memory location of @code{Obj}.
9022 @end table
9024 @geindex -gnateb (gcc)
9027 @table @asis
9029 @item @code{-gnateb}
9031 Store configuration files by their basename in ALI files. This switch is
9032 used for instance by gprbuild for distributed builds in order to prevent
9033 issues where machine-specific absolute paths could end up being stored in
9034 ALI files.
9035 @end table
9037 @geindex -gnatec (gcc)
9040 @table @asis
9042 @item @code{-gnatec=`path'}
9044 Specify a configuration pragma file
9045 (the equal sign is optional)
9046 (@ref{63,,The Configuration Pragmas Files}).
9047 @end table
9049 @geindex -gnateC (gcc)
9052 @table @asis
9054 @item @code{-gnateC}
9056 Generate CodePeer messages in a compiler-like format. This switch is only
9057 effective if @code{-gnatcC} is also specified and requires an installation
9058 of CodePeer.
9059 @end table
9061 @geindex -gnated (gcc)
9064 @table @asis
9066 @item @code{-gnated}
9068 Disable atomic synchronization
9069 @end table
9071 @geindex -gnateD (gcc)
9074 @table @asis
9076 @item @code{-gnateDsymbol[=`value']}
9078 Defines a symbol, associated with @code{value}, for preprocessing.
9079 (@ref{91,,Integrated Preprocessing}).
9080 @end table
9082 @geindex -gnateE (gcc)
9085 @table @asis
9087 @item @code{-gnateE}
9089 Generate extra information in exception messages. In particular, display
9090 extra column information and the value and range associated with index and
9091 range check failures, and extra column information for access checks.
9092 In cases where the compiler is able to determine at compile time that
9093 a check will fail, it gives a warning, and the extra information is not
9094 produced at run time.
9095 @end table
9097 @geindex -gnatef (gcc)
9100 @table @asis
9102 @item @code{-gnatef}
9104 Display full source path name in brief error messages and absolute paths in
9105 @code{-fdiagnostics-format=json}’s output.
9106 @end table
9108 @geindex -gnateF (gcc)
9111 @table @asis
9113 @item @code{-gnateF}
9115 Check for overflow on all floating-point operations, including those
9116 for unconstrained predefined types. See description of pragma
9117 @code{Check_Float_Overflow} in GNAT RM.
9118 @end table
9120 @geindex -gnateg (gcc)
9122 @code{-gnateg}
9123 @code{-gnatceg}
9125 @quotation
9127 The @code{-gnatc} switch must always be specified before this switch, e.g.
9128 @code{-gnatceg}. Generate a C header from the Ada input file. See
9129 @ref{b9,,Generating C Headers for Ada Specifications} for more
9130 information.
9131 @end quotation
9133 @geindex -gnateG (gcc)
9136 @table @asis
9138 @item @code{-gnateG}
9140 Save result of preprocessing in a text file.
9141 @end table
9143 @geindex -gnateH (gcc)
9146 @table @asis
9148 @item @code{-gnateH}
9150 Set the threshold from which the RM 13.5.1(13.3/2) clause applies to 64.
9151 This is useful only on 64-bit plaforms where this threshold is 128, but
9152 used to be 64 in earlier versions of the compiler.
9153 @end table
9155 @geindex -gnatei (gcc)
9158 @table @asis
9160 @item @code{-gnatei`nnn'}
9162 Set maximum number of instantiations during compilation of a single unit to
9163 @code{nnn}. This may be useful in increasing the default maximum of 8000 for
9164 the rare case when a single unit legitimately exceeds this limit.
9165 @end table
9167 @geindex -gnateI (gcc)
9170 @table @asis
9172 @item @code{-gnateI`nnn'}
9174 Indicates that the source is a multi-unit source and that the index of the
9175 unit to compile is @code{nnn}. @code{nnn} needs to be a positive number and need
9176 to be a valid index in the multi-unit source.
9177 @end table
9179 @geindex -gnatel (gcc)
9182 @table @asis
9184 @item @code{-gnatel}
9186 This switch can be used with the static elaboration model to issue info
9187 messages showing
9188 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
9189 are generated. This is useful in diagnosing elaboration circularities
9190 caused by these implicit pragmas when using the static elaboration
9191 model. See the section in this guide on elaboration checking for
9192 further details. These messages are not generated by default, and are
9193 intended only for temporary use when debugging circularity problems.
9194 @end table
9196 @geindex -gnatel (gcc)
9199 @table @asis
9201 @item @code{-gnateL}
9203 This switch turns off the info messages about implicit elaboration pragmas.
9204 @end table
9206 @geindex -gnatem (gcc)
9209 @table @asis
9211 @item @code{-gnatem=`path'}
9213 Specify a mapping file
9214 (the equal sign is optional)
9215 (@ref{ea,,Units to Sources Mapping Files}).
9216 @end table
9218 @geindex -gnatep (gcc)
9221 @table @asis
9223 @item @code{-gnatep=`file'}
9225 Specify a preprocessing data file
9226 (the equal sign is optional)
9227 (@ref{91,,Integrated Preprocessing}).
9228 @end table
9230 @geindex -gnateP (gcc)
9233 @table @asis
9235 @item @code{-gnateP}
9237 Turn categorization dependency errors into warnings.
9238 Ada requires that units that WITH one another have compatible categories, for
9239 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9240 these errors become warnings (which can be ignored, or suppressed in the usual
9241 manner). This can be useful in some specialized circumstances such as the
9242 temporary use of special test software.
9243 @end table
9245 @geindex -gnateS (gcc)
9248 @table @asis
9250 @item @code{-gnateS}
9252 Synonym of @code{-fdump-scos}, kept for backwards compatibility.
9253 @end table
9255 @geindex -gnatet=file (gcc)
9258 @table @asis
9260 @item @code{-gnatet=`path'}
9262 Generate target dependent information. The format of the output file is
9263 described in the section about switch @code{-gnateT}.
9264 @end table
9266 @geindex -gnateT (gcc)
9269 @table @asis
9271 @item @code{-gnateT=`path'}
9273 Read target dependent information, such as endianness or sizes and alignments
9274 of base type. If this switch is passed, the default target dependent
9275 information of the compiler is replaced by the one read from the input file.
9276 This is used by tools other than the compiler, e.g. to do
9277 semantic analysis of programs that will run on some other target than
9278 the machine on which the tool is run.
9280 The following target dependent values should be defined,
9281 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
9282 positive integer value, and fields marked with a question mark are
9283 boolean fields, where a value of 0 is False, and a value of 1 is True:
9285 @example
9286 Bits_BE                    : Nat; -- Bits stored big-endian?
9287 Bits_Per_Unit              : Pos; -- Bits in a storage unit
9288 Bits_Per_Word              : Pos; -- Bits in a word
9289 Bytes_BE                   : Nat; -- Bytes stored big-endian?
9290 Char_Size                  : Pos; -- Standard.Character'Size
9291 Double_Float_Alignment     : Nat; -- Alignment of double float
9292 Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
9293 Double_Size                : Pos; -- Standard.Long_Float'Size
9294 Float_Size                 : Pos; -- Standard.Float'Size
9295 Float_Words_BE             : Nat; -- Float words stored big-endian?
9296 Int_Size                   : Pos; -- Standard.Integer'Size
9297 Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
9298 Long_Long_Long_Size        : Pos; -- Standard.Long_Long_Long_Integer'Size
9299 Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
9300 Long_Size                  : Pos; -- Standard.Long_Integer'Size
9301 Maximum_Alignment          : Pos; -- Maximum permitted alignment
9302 Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
9303 Pointer_Size               : Pos; -- System.Address'Size
9304 Short_Enums                : Nat; -- Foreign enums use short size?
9305 Short_Size                 : Pos; -- Standard.Short_Integer'Size
9306 Strict_Alignment           : Nat; -- Strict alignment?
9307 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9308 Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
9309 Words_BE                   : Nat; -- Words stored big-endian?
9310 @end example
9312 @code{Bits_Per_Unit} is the number of bits in a storage unit, the equivalent of
9313 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.}
9315 @code{Bits_Per_Word} is the number of bits in a machine word, the equivalent of
9316 GCC macro @code{BITS_PER_WORD} documented as follows: @cite{Number of bits in a word; normally 32.}
9318 @code{Double_Float_Alignment}, if not zero, is the maximum alignment that the
9319 compiler can choose by default for a 64-bit floating-point type or object.
9321 @code{Double_Scalar_Alignment}, if not zero, is the maximum alignment that the
9322 compiler can choose by default for a 64-bit or larger scalar type or object.
9324 @code{Maximum_Alignment} is the maximum alignment that the compiler can choose
9325 by default for a type or object, which is also the maximum alignment that can
9326 be specified in GNAT. It is computed for GCC backends as @code{BIGGEST_ALIGNMENT
9327 / BITS_PER_UNIT} where GCC macro @code{BIGGEST_ALIGNMENT} is documented as
9328 follows: @cite{Biggest alignment that any data type can require on this machine@comma{} in bits.}
9330 @code{Max_Unaligned_Field} is the maximum size for unaligned bit field, which is
9331 64 for the majority of GCC targets (but can be different on some targets).
9333 @code{Strict_Alignment} is the equivalent of GCC macro @code{STRICT_ALIGNMENT}
9334 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.}
9336 @code{System_Allocator_Alignment} is the guaranteed alignment of data returned
9337 by calls to @code{malloc}.
9339 The format of the input file is as follows. First come the values of
9340 the variables defined above, with one line per value:
9342 @example
9343 name  value
9344 @end example
9346 where @code{name} is the name of the parameter, spelled out in full,
9347 and cased as in the above list, and @code{value} is an unsigned decimal
9348 integer. Two or more blanks separates the name from the value.
9350 All the variables must be present, in alphabetical order (i.e. the
9351 same order as the list above).
9353 Then there is a blank line to separate the two parts of the file. Then
9354 come the lines showing the floating-point types to be registered, with
9355 one line per registered mode:
9357 @example
9358 name  digs float_rep size alignment
9359 @end example
9361 where @code{name} is the string name of the type (which can have
9362 single spaces embedded in the name, e.g. long double), @code{digs} is
9363 the number of digits for the floating-point type, @code{float_rep} is
9364 the float representation (I for IEEE-754-Binary, which is
9365 the only one supported at this time),
9366 @code{size} is the size in bits, @code{alignment} is the
9367 alignment in bits. The name is followed by at least two blanks, fields
9368 are separated by at least one blank, and a LF character immediately
9369 follows the alignment field.
9371 Here is an example of a target parameterization file:
9373 @example
9374 Bits_BE                       0
9375 Bits_Per_Unit                 8
9376 Bits_Per_Word                64
9377 Bytes_BE                      0
9378 Char_Size                     8
9379 Double_Float_Alignment        0
9380 Double_Scalar_Alignment       0
9381 Double_Size                  64
9382 Float_Size                   32
9383 Float_Words_BE                0
9384 Int_Size                     64
9385 Long_Double_Size            128
9386 Long_Long_Long_Size         128
9387 Long_Long_Size               64
9388 Long_Size                    64
9389 Maximum_Alignment            16
9390 Max_Unaligned_Field          64
9391 Pointer_Size                 64
9392 Short_Size                   16
9393 Strict_Alignment              0
9394 System_Allocator_Alignment   16
9395 Wchar_T_Size                 32
9396 Words_BE                      0
9398 float         15  I  64  64
9399 double        15  I  64  64
9400 long double   18  I  80 128
9401 TF            33  I 128 128
9402 @end example
9403 @end table
9405 @geindex -gnateu (gcc)
9408 @table @asis
9410 @item @code{-gnateu}
9412 Ignore unrecognized validity, warning, and style switches that
9413 appear after this switch is given. This may be useful when
9414 compiling sources developed on a later version of the compiler
9415 with an earlier version. Of course the earlier version must
9416 support this switch.
9417 @end table
9419 @geindex -gnateV (gcc)
9422 @table @asis
9424 @item @code{-gnateV}
9426 Check that all actual parameters of a subprogram call are valid according to
9427 the rules of validity checking (@ref{e9,,Validity Checking}).
9428 @end table
9430 @geindex -gnateY (gcc)
9433 @table @asis
9435 @item @code{-gnateY}
9437 Ignore all STYLE_CHECKS pragmas. Full legality checks
9438 are still carried out, but the pragmas have no effect
9439 on what style checks are active. This allows all style
9440 checking options to be controlled from the command line.
9441 @end table
9443 @geindex -gnatE (gcc)
9446 @table @asis
9448 @item @code{-gnatE}
9450 Dynamic elaboration checking mode enabled. For further details see
9451 @ref{f,,Elaboration Order Handling in GNAT}.
9452 @end table
9454 @geindex -gnatf (gcc)
9457 @table @asis
9459 @item @code{-gnatf}
9461 Full errors. Multiple errors per line, all undefined references, do not
9462 attempt to suppress cascaded errors.
9463 @end table
9465 @geindex -gnatF (gcc)
9468 @table @asis
9470 @item @code{-gnatF}
9472 Externals names are folded to all uppercase.
9473 @end table
9475 @geindex -gnatg (gcc)
9478 @table @asis
9480 @item @code{-gnatg}
9482 Internal GNAT implementation mode. This should not be used for applications
9483 programs, it is intended only for use by the compiler and its run-time
9484 library. For documentation, see the GNAT sources. Note that @code{-gnatg}
9485 implies @code{-gnatw.ge} and @code{-gnatyg} so that all standard
9486 warnings and all standard style options are turned on. All warnings and style
9487 messages are treated as errors.
9488 @end table
9490 @geindex -gnatG[nn] (gcc)
9493 @table @asis
9495 @item @code{-gnatG=nn}
9497 List generated expanded code in source form.
9498 @end table
9500 @geindex -gnath (gcc)
9503 @table @asis
9505 @item @code{-gnath}
9507 Output usage information. The output is written to @code{stdout}.
9508 @end table
9510 @geindex -gnatH (gcc)
9513 @table @asis
9515 @item @code{-gnatH}
9517 Legacy elaboration-checking mode enabled. When this switch is in effect,
9518 the pre-18.x access-before-elaboration model becomes the de facto model.
9519 For further details see @ref{f,,Elaboration Order Handling in GNAT}.
9520 @end table
9522 @geindex -gnati (gcc)
9525 @table @asis
9527 @item @code{-gnati`c'}
9529 Identifier character set (@code{c} = 1/2/3/4/5/9/p/8/f/n/w).
9530 For details of the possible selections for @code{c},
9531 see @ref{31,,Character Set Control}.
9532 @end table
9534 @geindex -gnatI (gcc)
9537 @table @asis
9539 @item @code{-gnatI}
9541 Ignore representation clauses. When this switch is used,
9542 representation clauses are treated as comments. This is useful
9543 when initially porting code where you want to ignore rep clause
9544 problems, and also for compiling foreign code (particularly
9545 for use with ASIS). The representation clauses that are ignored
9546 are: enumeration_representation_clause, record_representation_clause,
9547 and attribute_definition_clause for the following attributes:
9548 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9549 Object_Size, Scalar_Storage_Order, Size, Small, Stream_Size,
9550 and Value_Size. Pragma Default_Scalar_Storage_Order is also ignored.
9551 Note that this option should be used only for compiling – the
9552 code is likely to malfunction at run time.
9553 @end table
9555 @geindex -gnatjnn (gcc)
9558 @table @asis
9560 @item @code{-gnatj`nn'}
9562 Reformat error messages to fit on @code{nn} character lines
9563 @end table
9565 @geindex -gnatJ (gcc)
9568 @table @asis
9570 @item @code{-gnatJ}
9572 Permissive elaboration-checking mode enabled. When this switch is in effect,
9573 the post-18.x access-before-elaboration model ignores potential issues with:
9576 @itemize -
9578 @item 
9579 Accept statements
9581 @item 
9582 Activations of tasks defined in instances
9584 @item 
9585 Assertion pragmas
9587 @item 
9588 Calls from within an instance to its enclosing context
9590 @item 
9591 Calls through generic formal parameters
9593 @item 
9594 Calls to subprograms defined in instances
9596 @item 
9597 Entry calls
9599 @item 
9600 Indirect calls using ‘Access
9602 @item 
9603 Requeue statements
9605 @item 
9606 Select statements
9608 @item 
9609 Synchronous task suspension
9610 @end itemize
9612 and does not emit compile-time diagnostics or run-time checks. For further
9613 details see @ref{f,,Elaboration Order Handling in GNAT}.
9614 @end table
9616 @geindex -gnatk (gcc)
9619 @table @asis
9621 @item @code{-gnatk=`n'}
9623 Limit file names to @code{n} (1-999) characters (@code{k} = krunch).
9624 @end table
9626 @geindex -gnatl (gcc)
9629 @table @asis
9631 @item @code{-gnatl}
9633 Output full source listing with embedded error messages.
9634 @end table
9636 @geindex -gnatL (gcc)
9639 @table @asis
9641 @item @code{-gnatL}
9643 Used in conjunction with -gnatG or -gnatD to intersperse original
9644 source lines (as comment lines with line numbers) in the expanded
9645 source output.
9646 @end table
9648 @geindex -gnatm (gcc)
9651 @table @asis
9653 @item @code{-gnatm=`n'}
9655 Limit number of detected error or warning messages to @code{n}
9656 where @code{n} is in the range 1..999999. The default setting if
9657 no switch is given is 9999. If the number of warnings reaches this
9658 limit, then a message is output and further warnings are suppressed,
9659 but the compilation is continued. If the number of error messages
9660 reaches this limit, then a message is output and the compilation
9661 is abandoned. The equal sign here is optional. A value of zero
9662 means that no limit applies.
9663 @end table
9665 @geindex -gnatn (gcc)
9668 @table @asis
9670 @item @code{-gnatn[12]}
9672 Activate inlining across units for subprograms for which pragma @code{Inline}
9673 is specified. This inlining is performed by the GCC back-end. An optional
9674 digit sets the inlining level: 1 for moderate inlining across units
9675 or 2 for full inlining across units. If no inlining level is specified,
9676 the compiler will pick it based on the optimization level.
9677 @end table
9679 @geindex -gnatN (gcc)
9682 @table @asis
9684 @item @code{-gnatN}
9686 Activate front end inlining for subprograms for which
9687 pragma @code{Inline} is specified. This inlining is performed
9688 by the front end and will be visible in the
9689 @code{-gnatG} output.
9691 When using a gcc-based back end, then the use of
9692 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
9693 Historically front end inlining was more extensive than the gcc back end
9694 inlining, but that is no longer the case.
9695 @end table
9697 @geindex -gnato0 (gcc)
9700 @table @asis
9702 @item @code{-gnato0}
9704 Suppresses overflow checking. This causes the behavior of the compiler to
9705 match the default for older versions where overflow checking was suppressed
9706 by default. This is equivalent to having
9707 @code{pragma Suppress (Overflow_Check)} in a configuration pragma file.
9708 @end table
9710 @geindex -gnato?? (gcc)
9713 @table @asis
9715 @item @code{-gnato??}
9717 Set default mode for handling generation of code to avoid intermediate
9718 arithmetic overflow. Here @code{??} is two digits, a
9719 single digit, or nothing. Each digit is one of the digits @code{1}
9720 through @code{3}:
9723 @multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
9724 @item
9726 Digit
9728 @tab
9730 Interpretation
9732 @item
9736 @tab
9738 All intermediate overflows checked against base type (@code{STRICT})
9740 @item
9744 @tab
9746 Minimize intermediate overflows (@code{MINIMIZED})
9748 @item
9752 @tab
9754 Eliminate intermediate overflows (@code{ELIMINATED})
9756 @end multitable
9759 If only one digit appears, then it applies to all
9760 cases; if two digits are given, then the first applies outside
9761 assertions, pre/postconditions, and type invariants, and the second
9762 applies within assertions, pre/postconditions, and type invariants.
9764 If no digits follow the @code{-gnato}, then it is equivalent to
9765 @code{-gnato11},
9766 causing all intermediate overflows to be handled in strict
9767 mode.
9769 This switch also causes arithmetic overflow checking to be performed
9770 (as though @code{pragma Unsuppress (Overflow_Check)} had been specified).
9772 The default if no option @code{-gnato} is given is that overflow handling
9773 is in @code{STRICT} mode (computations done using the base type), and that
9774 overflow checking is enabled.
9776 Note that division by zero is a separate check that is not
9777 controlled by this switch (divide-by-zero checking is on by default).
9779 See also @ref{eb,,Specifying the Desired Mode}.
9780 @end table
9782 @geindex -gnatp (gcc)
9785 @table @asis
9787 @item @code{-gnatp}
9789 Suppress all checks. See @ref{ec,,Run-Time Checks} for details. This switch
9790 has no effect if cancelled by a subsequent @code{-gnat-p} switch.
9791 @end table
9793 @geindex -gnat-p (gcc)
9796 @table @asis
9798 @item @code{-gnat-p}
9800 Cancel effect of previous @code{-gnatp} switch.
9801 @end table
9803 @geindex -gnatq (gcc)
9806 @table @asis
9808 @item @code{-gnatq}
9810 Don’t quit. Try semantics, even if parse errors.
9811 @end table
9813 @geindex -gnatQ (gcc)
9816 @table @asis
9818 @item @code{-gnatQ}
9820 Don’t quit. Generate @code{ALI} and tree files even if illegalities.
9821 Note that code generation is still suppressed in the presence of any
9822 errors, so even with @code{-gnatQ} no object file is generated.
9823 @end table
9825 @geindex -gnatr (gcc)
9828 @table @asis
9830 @item @code{-gnatr}
9832 Treat pragma Restrictions as Restriction_Warnings.
9833 @end table
9835 @geindex -gnatR (gcc)
9838 @table @asis
9840 @item @code{-gnatR[0|1|2|3|4][e][j][m][s]}
9842 Output representation information for declared types, objects and
9843 subprograms. Note that this switch is not allowed if a previous
9844 @code{-gnatD} switch has been given, since these two switches
9845 are not compatible.
9846 @end table
9848 @geindex -gnats (gcc)
9851 @table @asis
9853 @item @code{-gnats}
9855 Syntax check only.
9856 @end table
9858 @geindex -gnatS (gcc)
9861 @table @asis
9863 @item @code{-gnatS}
9865 Print package Standard.
9866 @end table
9868 @geindex -gnatT (gcc)
9871 @table @asis
9873 @item @code{-gnatT`nnn'}
9875 All compiler tables start at @code{nnn} times usual starting size.
9876 @end table
9878 @geindex -gnatu (gcc)
9881 @table @asis
9883 @item @code{-gnatu}
9885 List units for this compilation.
9886 @end table
9888 @geindex -gnatU (gcc)
9891 @table @asis
9893 @item @code{-gnatU}
9895 Tag all error messages with the unique string ‘error:’
9896 @end table
9898 @geindex -gnatv (gcc)
9901 @table @asis
9903 @item @code{-gnatv}
9905 Verbose mode. Full error output with source lines to @code{stdout}.
9906 @end table
9908 @geindex -gnatV (gcc)
9911 @table @asis
9913 @item @code{-gnatV}
9915 Control level of validity checking (@ref{e9,,Validity Checking}).
9916 @end table
9918 @geindex -gnatw (gcc)
9921 @table @asis
9923 @item @code{-gnatw`xxx'}
9925 Warning mode where
9926 @code{xxx} is a string of option letters that denotes
9927 the exact warnings that
9928 are enabled or disabled (@ref{ed,,Warning Message Control}).
9929 @end table
9931 @geindex -gnatW (gcc)
9934 @table @asis
9936 @item @code{-gnatW`e'}
9938 Wide character encoding method
9939 (@code{e}=n/h/u/s/e/8).
9940 @end table
9942 @geindex -gnatx (gcc)
9945 @table @asis
9947 @item @code{-gnatx}
9949 Suppress generation of cross-reference information.
9950 @end table
9952 @geindex -gnatX (gcc)
9955 @table @asis
9957 @item @code{-gnatX}
9959 Enable core GNAT implementation extensions and latest Ada version.
9960 @end table
9962 @geindex -gnatX0 (gcc)
9965 @table @asis
9967 @item @code{-gnatX0}
9969 Enable all GNAT implementation extensions and latest Ada version.
9970 @end table
9972 @geindex -gnaty (gcc)
9975 @table @asis
9977 @item @code{-gnaty}
9979 Enable built-in style checks (@ref{ee,,Style Checking}).
9980 @end table
9982 @geindex -gnatz (gcc)
9985 @table @asis
9987 @item @code{-gnatz`m'}
9989 Distribution stub generation and compilation
9990 (@code{m}=r/c for receiver/caller stubs).
9991 @end table
9993 @geindex -I (gcc)
9996 @table @asis
9998 @item @code{-I`dir'}
10000 @geindex RTL
10002 Direct GNAT to search the @code{dir} directory for source files needed by
10003 the current compilation
10004 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
10005 @end table
10007 @geindex -I- (gcc)
10010 @table @asis
10012 @item @code{-I-}
10014 @geindex RTL
10016 Except for the source file named in the command line, do not look for source
10017 files in the directory containing the source file named in the command line
10018 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
10019 @end table
10021 @geindex -o (gcc)
10024 @table @asis
10026 @item @code{-o `file'}
10028 This switch is used in @code{gcc} to redirect the generated object file
10029 and its associated ALI file. Beware of this switch with GNAT, because it may
10030 cause the object file and ALI file to have different names which in turn
10031 may confuse the binder and the linker.
10032 @end table
10034 @geindex -nostdinc (gcc)
10037 @table @asis
10039 @item @code{-nostdinc}
10041 Inhibit the search of the default location for the GNAT Run Time
10042 Library (RTL) source files.
10043 @end table
10045 @geindex -nostdlib (gcc)
10048 @table @asis
10050 @item @code{-nostdlib}
10052 Inhibit the search of the default location for the GNAT Run Time
10053 Library (RTL) ALI files.
10054 @end table
10056 @geindex -O (gcc)
10059 @table @asis
10061 @item @code{-O[`n']}
10063 @code{n} controls the optimization level:
10066 @multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
10067 @item
10071 @tab
10073 Effect
10075 @item
10079 @tab
10081 No optimization, the default setting if no @code{-O} appears
10083 @item
10087 @tab
10089 Normal optimization, the default if you specify @code{-O} without an
10090 operand. A good compromise between code quality and compilation
10091 time.
10093 @item
10097 @tab
10099 Extensive optimization, may improve execution time, possibly at
10100 the cost of substantially increased compilation time.
10102 @item
10106 @tab
10108 Same as @code{-O2}, and also includes inline expansion for small
10109 subprograms in the same unit.
10111 @item
10115 @tab
10117 Optimize space usage
10119 @end multitable
10122 See also @ref{ef,,Optimization Levels}.
10123 @end table
10125 @geindex -pass-exit-codes (gcc)
10128 @table @asis
10130 @item @code{-pass-exit-codes}
10132 Catch exit codes from the compiler and use the most meaningful as
10133 exit status.
10134 @end table
10136 @geindex --RTS (gcc)
10139 @table @asis
10141 @item @code{--RTS=`rts-path'}
10143 Specifies the default location of the run-time library. Same meaning as the
10144 equivalent @code{gnatmake} flag (@ref{d0,,Switches for gnatmake}).
10145 @end table
10147 @geindex -S (gcc)
10150 @table @asis
10152 @item @code{-S}
10154 Used in place of @code{-c} to
10155 cause the assembler source file to be
10156 generated, using @code{.s} as the extension,
10157 instead of the object file.
10158 This may be useful if you need to examine the generated assembly code.
10159 @end table
10161 @geindex -fverbose-asm (gcc)
10164 @table @asis
10166 @item @code{-fverbose-asm}
10168 Used in conjunction with @code{-S}
10169 to cause the generated assembly code file to be annotated with variable
10170 names, making it significantly easier to follow.
10171 @end table
10173 @geindex -v (gcc)
10176 @table @asis
10178 @item @code{-v}
10180 Show commands generated by the @code{gcc} driver. Normally used only for
10181 debugging purposes or if you need to be sure what version of the
10182 compiler you are executing.
10183 @end table
10185 @geindex -V (gcc)
10188 @table @asis
10190 @item @code{-V `ver'}
10192 Execute @code{ver} version of the compiler. This is the @code{gcc}
10193 version, not the GNAT version.
10194 @end table
10196 @geindex -w (gcc)
10199 @table @asis
10201 @item @code{-w}
10203 Turn off warnings generated by the back end of the compiler. Use of
10204 this switch also causes the default for front end warnings to be set
10205 to suppress (as though @code{-gnatws} had appeared at the start of
10206 the options).
10207 @end table
10209 @geindex Combining GNAT switches
10211 You may combine a sequence of GNAT switches into a single switch. For
10212 example, the combined switch
10214 @quotation
10216 @example
10217 -gnatofi3
10218 @end example
10219 @end quotation
10221 is equivalent to specifying the following sequence of switches:
10223 @quotation
10225 @example
10226 -gnato -gnatf -gnati3
10227 @end example
10228 @end quotation
10230 The following restrictions apply to the combination of switches
10231 in this manner:
10234 @itemize *
10236 @item 
10237 The switch @code{-gnatc} if combined with other switches must come
10238 first in the string.
10240 @item 
10241 The switch @code{-gnats} if combined with other switches must come
10242 first in the string.
10244 @item 
10245 The switches
10246 @code{-gnatzc} and @code{-gnatzr} may not be combined with any other
10247 switches, and only one of them may appear in the command line.
10249 @item 
10250 The switch @code{-gnat-p} may not be combined with any other switch.
10252 @item 
10253 Once a ‘y’ appears in the string (that is a use of the @code{-gnaty}
10254 switch), then all further characters in the switch are interpreted
10255 as style modifiers (see description of @code{-gnaty}).
10257 @item 
10258 Once a ‘d’ appears in the string (that is a use of the @code{-gnatd}
10259 switch), then all further characters in the switch are interpreted
10260 as debug flags (see description of @code{-gnatd}).
10262 @item 
10263 Once a ‘w’ appears in the string (that is a use of the @code{-gnatw}
10264 switch), then all further characters in the switch are interpreted
10265 as warning mode modifiers (see description of @code{-gnatw}).
10267 @item 
10268 Once a ‘V’ appears in the string (that is a use of the @code{-gnatV}
10269 switch), then all further characters in the switch are interpreted
10270 as validity checking options (@ref{e9,,Validity Checking}).
10272 @item 
10273 Option ‘em’, ‘ec’, ‘ep’, ‘l=’ and ‘R’ must be the last options in
10274 a combined list of options.
10275 @end itemize
10277 @node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10278 @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}
10279 @subsection Output and Error Message Control
10282 @geindex stderr
10284 The standard default format for error messages is called ‘brief format’.
10285 Brief format messages are written to @code{stderr} (the standard error
10286 file) and have the following form:
10288 @example
10289 e.adb:3:04: Incorrect spelling of keyword "function"
10290 e.adb:4:20: ";" should be "is"
10291 @end example
10293 The first integer after the file name is the line number in the file,
10294 and the second integer is the column number within the line.
10295 @code{GNAT Studio} can parse the error messages
10296 and point to the referenced character.
10297 The following switches provide control over the error message
10298 format:
10300 @geindex -gnatv (gcc)
10303 @table @asis
10305 @item @code{-gnatv}
10307 The @code{v} stands for verbose.
10308 The effect of this setting is to write long-format error
10309 messages to @code{stdout} (the standard output file).
10310 The same program compiled with the
10311 @code{-gnatv} switch would generate:
10313 @example
10314 3. funcion X (Q : Integer)
10315    |
10316 >>> Incorrect spelling of keyword "function"
10317 4. return Integer;
10318                  |
10319 >>> ";" should be "is"
10320 @end example
10322 The vertical bar indicates the location of the error, and the @code{>>>}
10323 prefix can be used to search for error messages. When this switch is
10324 used the only source lines output are those with errors.
10325 @end table
10327 @geindex -gnatl (gcc)
10330 @table @asis
10332 @item @code{-gnatl}
10334 The @code{l} stands for list.
10335 This switch causes a full listing of
10336 the file to be generated. In the case where a body is
10337 compiled, the corresponding spec is also listed, along
10338 with any subunits. Typical output from compiling a package
10339 body @code{p.adb} might look like:
10341 @example
10342 Compiling: p.adb
10344      1. package body p is
10345      2.    procedure a;
10346      3.    procedure a is separate;
10347      4. begin
10348      5.    null
10349                |
10350         >>> missing ";"
10352      6. end;
10354 Compiling: p.ads
10356      1. package p is
10357      2.    pragma Elaborate_Body
10358                                 |
10359         >>> missing ";"
10361      3. end p;
10363 Compiling: p-a.adb
10365      1. separate p
10366                 |
10367         >>> missing "("
10369      2. procedure a is
10370      3. begin
10371      4.    null
10372                |
10373         >>> missing ";"
10375      5. end;
10376 @end example
10378 When you specify the @code{-gnatv} or @code{-gnatl} switches and
10379 standard output is redirected, a brief summary is written to
10380 @code{stderr} (standard error) giving the number of error messages and
10381 warning messages generated.
10382 @end table
10384 @geindex -gnatl=fname (gcc)
10387 @table @asis
10389 @item @code{-gnatl=`fname'}
10391 This has the same effect as @code{-gnatl} except that the output is
10392 written to a file instead of to standard output. If the given name
10393 @code{fname} does not start with a period, then it is the full name
10394 of the file to be written. If @code{fname} is an extension, it is
10395 appended to the name of the file being compiled. For example, if
10396 file @code{xyz.adb} is compiled with @code{-gnatl=.lst},
10397 then the output is written to file xyz.adb.lst.
10398 @end table
10400 @geindex -gnatU (gcc)
10403 @table @asis
10405 @item @code{-gnatU}
10407 This switch forces all error messages to be preceded by the unique
10408 string ‘error:’. This means that error messages take a few more
10409 characters in space, but allows easy searching for and identification
10410 of error messages.
10411 @end table
10413 @geindex -gnatb (gcc)
10416 @table @asis
10418 @item @code{-gnatb}
10420 The @code{b} stands for brief.
10421 This switch causes GNAT to generate the
10422 brief format error messages to @code{stderr} (the standard error
10423 file) as well as the verbose
10424 format message or full listing (which as usual is written to
10425 @code{stdout}, the standard output file).
10426 @end table
10428 @geindex -gnatm (gcc)
10431 @table @asis
10433 @item @code{-gnatm=`n'}
10435 The @code{m} stands for maximum.
10436 @code{n} is a decimal integer in the
10437 range of 1 to 999999 and limits the number of error or warning
10438 messages to be generated. For example, using
10439 @code{-gnatm2} might yield
10441 @example
10442 e.adb:3:04: Incorrect spelling of keyword "function"
10443 e.adb:5:35: missing ".."
10444 fatal error: maximum number of errors detected
10445 compilation abandoned
10446 @end example
10448 The default setting if
10449 no switch is given is 9999. If the number of warnings reaches this
10450 limit, then a message is output and further warnings are suppressed,
10451 but the compilation is continued. If the number of error messages
10452 reaches this limit, then a message is output and the compilation
10453 is abandoned. A value of zero means that no limit applies.
10455 Note that the equal sign is optional, so the switches
10456 @code{-gnatm2} and @code{-gnatm=2} are equivalent.
10457 @end table
10459 @geindex -gnatf (gcc)
10462 @table @asis
10464 @item @code{-gnatf}
10466 @geindex Error messages
10467 @geindex suppressing
10469 The @code{f} stands for full.
10470 Normally, the compiler suppresses error messages that are likely to be
10471 redundant. This switch causes all error
10472 messages to be generated. In particular, in the case of
10473 references to undefined variables. If a given variable is referenced
10474 several times, the normal format of messages is
10476 @example
10477 e.adb:7:07: "V" is undefined (more references follow)
10478 @end example
10480 where the parenthetical comment warns that there are additional
10481 references to the variable @code{V}. Compiling the same program with the
10482 @code{-gnatf} switch yields
10484 @example
10485 e.adb:7:07: "V" is undefined
10486 e.adb:8:07: "V" is undefined
10487 e.adb:8:12: "V" is undefined
10488 e.adb:8:16: "V" is undefined
10489 e.adb:9:07: "V" is undefined
10490 e.adb:9:12: "V" is undefined
10491 @end example
10493 The @code{-gnatf} switch also generates additional information for
10494 some error messages.  Some examples are:
10497 @itemize *
10499 @item 
10500 Details on possibly non-portable unchecked conversion
10502 @item 
10503 List possible interpretations for ambiguous calls
10505 @item 
10506 Additional details on incorrect parameters
10507 @end itemize
10508 @end table
10510 @geindex -gnatjnn (gcc)
10513 @table @asis
10515 @item @code{-gnatjnn}
10517 In normal operation mode (or if @code{-gnatj0} is used), then error messages
10518 with continuation lines are treated as though the continuation lines were
10519 separate messages (and so a warning with two continuation lines counts as
10520 three warnings, and is listed as three separate messages).
10522 If the @code{-gnatjnn} switch is used with a positive value for nn, then
10523 messages are output in a different manner. A message and all its continuation
10524 lines are treated as a unit, and count as only one warning or message in the
10525 statistics totals. Furthermore, the message is reformatted so that no line
10526 is longer than nn characters.
10527 @end table
10529 @geindex -gnatq (gcc)
10532 @table @asis
10534 @item @code{-gnatq}
10536 The @code{q} stands for quit (really ‘don’t quit’).
10537 In normal operation mode, the compiler first parses the program and
10538 determines if there are any syntax errors. If there are, appropriate
10539 error messages are generated and compilation is immediately terminated.
10540 This switch tells
10541 GNAT to continue with semantic analysis even if syntax errors have been
10542 found. This may enable the detection of more errors in a single run. On
10543 the other hand, the semantic analyzer is more likely to encounter some
10544 internal fatal error when given a syntactically invalid tree.
10545 @end table
10547 @geindex -gnatQ (gcc)
10550 @table @asis
10552 @item @code{-gnatQ}
10554 In normal operation mode, the @code{ALI} file is not generated if any
10555 illegalities are detected in the program. The use of @code{-gnatQ} forces
10556 generation of the @code{ALI} file. This file is marked as being in
10557 error, so it cannot be used for binding purposes, but it does contain
10558 reasonably complete cross-reference information, and thus may be useful
10559 for use by tools (e.g., semantic browsing tools or integrated development
10560 environments) that are driven from the @code{ALI} file. This switch
10561 implies @code{-gnatq}, since the semantic phase must be run to get a
10562 meaningful ALI file.
10564 When @code{-gnatQ} is used and the generated @code{ALI} file is marked as
10565 being in error, @code{gnatmake} will attempt to recompile the source when it
10566 finds such an @code{ALI} file, including with switch @code{-gnatc}.
10568 Note that @code{-gnatQ} has no effect if @code{-gnats} is specified,
10569 since ALI files are never generated if @code{-gnats} is set.
10570 @end table
10572 @node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10573 @anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{f2}@anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{ed}
10574 @subsection Warning Message Control
10577 @geindex Warning messages
10579 In addition to error messages, which correspond to illegalities as defined
10580 in the Ada Reference Manual, the compiler detects two kinds of warning
10581 situations.
10583 First, the compiler considers some constructs suspicious and generates a
10584 warning message to alert you to a possible error. Second, if the
10585 compiler detects a situation that is sure to raise an exception at
10586 run time, it generates a warning message. The following shows an example
10587 of warning messages:
10589 @example
10590 e.adb:4:24: warning: creation of object may raise Storage_Error
10591 e.adb:10:17: warning: static value out of range
10592 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10593 @end example
10595 GNAT considers a large number of situations as appropriate
10596 for the generation of warning messages. As always, warnings are not
10597 definite indications of errors. For example, if you do an out-of-range
10598 assignment with the deliberate intention of raising a
10599 @code{Constraint_Error} exception, then the warning that may be
10600 issued does not indicate an error. Some of the situations for which GNAT
10601 issues warnings (at least some of the time) are given in the following
10602 list. This list is not complete, and new warnings are often added to
10603 subsequent versions of GNAT. The list is intended to give a general idea
10604 of the kinds of warnings that are generated.
10607 @itemize *
10609 @item 
10610 Possible infinitely recursive calls
10612 @item 
10613 Out-of-range values being assigned
10615 @item 
10616 Possible order of elaboration problems
10618 @item 
10619 Size not a multiple of alignment for a record type
10621 @item 
10622 Assertions (pragma Assert) that are sure to fail
10624 @item 
10625 Unreachable code
10627 @item 
10628 Address clauses with possibly unaligned values, or where an attempt is
10629 made to overlay a smaller variable with a larger one.
10631 @item 
10632 Fixed-point type declarations with a null range
10634 @item 
10635 Direct_IO or Sequential_IO instantiated with a type that has access values
10637 @item 
10638 Variables that are never assigned a value
10640 @item 
10641 Variables that are referenced before being initialized
10643 @item 
10644 Task entries with no corresponding @code{accept} statement
10646 @item 
10647 Duplicate accepts for the same task entry in a @code{select}
10649 @item 
10650 Objects that take too much storage
10652 @item 
10653 Unchecked conversion between types of differing sizes
10655 @item 
10656 Missing @code{return} statement along some execution path in a function
10658 @item 
10659 Incorrect (unrecognized) pragmas
10661 @item 
10662 Incorrect external names
10664 @item 
10665 Allocation from empty storage pool
10667 @item 
10668 Potentially blocking operation in protected type
10670 @item 
10671 Suspicious parenthesization of expressions
10673 @item 
10674 Mismatching bounds in an aggregate
10676 @item 
10677 Attempt to return local value by reference
10679 @item 
10680 Premature instantiation of a generic body
10682 @item 
10683 Attempt to pack aliased components
10685 @item 
10686 Out of bounds array subscripts
10688 @item 
10689 Wrong length on string assignment
10691 @item 
10692 Violations of style rules if style checking is enabled
10694 @item 
10695 Unused `with' clauses
10697 @item 
10698 @code{Bit_Order} usage that does not have any effect
10700 @item 
10701 @code{Standard.Duration} used to resolve universal fixed expression
10703 @item 
10704 Dereference of possibly null value
10706 @item 
10707 Declaration that is likely to cause storage error
10709 @item 
10710 Internal GNAT unit `with'ed by application unit
10712 @item 
10713 Values known to be out of range at compile time
10715 @item 
10716 Unreferenced or unmodified variables. Note that a special
10717 exemption applies to variables which contain any of the substrings
10718 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
10719 are considered likely to be intentionally used in a situation where
10720 otherwise a warning would be given, so warnings of this kind are
10721 always suppressed for such variables.
10723 @item 
10724 Address overlays that could clobber memory
10726 @item 
10727 Unexpected initialization when address clause present
10729 @item 
10730 Bad alignment for address clause
10732 @item 
10733 Useless type conversions
10735 @item 
10736 Redundant assignment statements and other redundant constructs
10738 @item 
10739 Useless exception handlers
10741 @item 
10742 Accidental hiding of name by child unit
10744 @item 
10745 Access before elaboration detected at compile time
10747 @item 
10748 A range in a @code{for} loop that is known to be null or might be null
10749 @end itemize
10751 The following section lists compiler switches that are available
10752 to control the handling of warning messages. It is also possible
10753 to exercise much finer control over what warnings are issued and
10754 suppressed using the GNAT pragma Warnings (see the description
10755 of the pragma in the @cite{GNAT_Reference_manual}).
10757 @geindex -gnatwa (gcc)
10760 @table @asis
10762 @item @code{-gnatwa}
10764 `Activate most optional warnings.'
10766 This switch activates most optional warning messages. See the remaining list
10767 in this section for details on optional warning messages that can be
10768 individually controlled.  The warnings that are not turned on by this
10769 switch are:
10772 @itemize *
10774 @item 
10775 @code{-gnatwd} (implicit dereferencing)
10777 @item 
10778 @code{-gnatw.d} (tag warnings with -gnatw switch)
10780 @item 
10781 @code{-gnatwh} (hiding)
10783 @item 
10784 @code{-gnatw.h} (holes in record layouts)
10786 @item 
10787 @code{-gnatw.j} (late primitives of tagged types)
10789 @item 
10790 @code{-gnatw.k} (redefinition of names in standard)
10792 @item 
10793 @code{-gnatwl} (elaboration warnings)
10795 @item 
10796 @code{-gnatw.l} (inherited aspects)
10798 @item 
10799 @code{-gnatw.n} (atomic synchronization)
10801 @item 
10802 @code{-gnatwo} (address clause overlay)
10804 @item 
10805 @code{-gnatw.o} (values set by out parameters ignored)
10807 @item 
10808 @code{-gnatw.q} (questionable layout of record types)
10810 @item 
10811 @code{-gnatw_q} (ignored equality)
10813 @item 
10814 @code{-gnatw_r} (out-of-order record representation clauses)
10816 @item 
10817 @code{-gnatw.s} (overridden size clause)
10819 @item 
10820 @code{-gnatw_s} (ineffective predicate test)
10822 @item 
10823 @code{-gnatwt} (tracking of deleted conditional code)
10825 @item 
10826 @code{-gnatw.u} (unordered enumeration)
10828 @item 
10829 @code{-gnatw.w} (use of Warnings Off)
10831 @item 
10832 @code{-gnatw.y} (reasons for package needing body)
10833 @end itemize
10835 All other optional warnings are turned on.
10836 @end table
10838 @geindex -gnatwA (gcc)
10841 @table @asis
10843 @item @code{-gnatwA}
10845 `Suppress all optional errors.'
10847 This switch suppresses all optional warning messages, see remaining list
10848 in this section for details on optional warning messages that can be
10849 individually controlled. Note that unlike switch @code{-gnatws}, the
10850 use of switch @code{-gnatwA} does not suppress warnings that are
10851 normally given unconditionally and cannot be individually controlled
10852 (for example, the warning about a missing exit path in a function).
10853 Also, again unlike switch @code{-gnatws}, warnings suppressed by
10854 the use of switch @code{-gnatwA} can be individually turned back
10855 on. For example the use of switch @code{-gnatwA} followed by
10856 switch @code{-gnatwd} will suppress all optional warnings except
10857 the warnings for implicit dereferencing.
10858 @end table
10860 @geindex -gnatw.a (gcc)
10863 @table @asis
10865 @item @code{-gnatw.a}
10867 `Activate warnings on failing assertions.'
10869 @geindex Assert failures
10871 This switch activates warnings for assertions where the compiler can tell at
10872 compile time that the assertion will fail. Note that this warning is given
10873 even if assertions are disabled. The default is that such warnings are
10874 generated.
10875 @end table
10877 @geindex -gnatw.A (gcc)
10880 @table @asis
10882 @item @code{-gnatw.A}
10884 `Suppress warnings on failing assertions.'
10886 @geindex Assert failures
10888 This switch suppresses warnings for assertions where the compiler can tell at
10889 compile time that the assertion will fail.
10890 @end table
10892 @geindex -gnatw_a
10895 @table @asis
10897 @item @code{-gnatw_a}
10899 `Activate warnings on anonymous allocators.'
10901 @geindex Anonymous allocators
10903 This switch activates warnings for allocators of anonymous access types,
10904 which can involve run-time accessibility checks and lead to unexpected
10905 accessibility violations. For more details on the rules involved, see
10906 RM 3.10.2 (14).
10907 @end table
10909 @geindex -gnatw_A
10912 @table @asis
10914 @item @code{-gnatw_A}
10916 `Suppress warnings on anonymous allocators.'
10918 @geindex Anonymous allocators
10920 This switch suppresses warnings for anonymous access type allocators.
10921 @end table
10923 @geindex -gnatwb (gcc)
10926 @table @asis
10928 @item @code{-gnatwb}
10930 `Activate warnings on bad fixed values.'
10932 @geindex Bad fixed values
10934 @geindex Fixed-point Small value
10936 @geindex Small value
10938 This switch activates warnings for static fixed-point expressions whose
10939 value is not an exact multiple of Small. Such values are implementation
10940 dependent, since an implementation is free to choose either of the multiples
10941 that surround the value. GNAT always chooses the closer one, but this is not
10942 required behavior, and it is better to specify a value that is an exact
10943 multiple, ensuring predictable execution. The default is that such warnings
10944 are not generated.
10945 @end table
10947 @geindex -gnatwB (gcc)
10950 @table @asis
10952 @item @code{-gnatwB}
10954 `Suppress warnings on bad fixed values.'
10956 This switch suppresses warnings for static fixed-point expressions whose
10957 value is not an exact multiple of Small.
10958 @end table
10960 @geindex -gnatw.b (gcc)
10963 @table @asis
10965 @item @code{-gnatw.b}
10967 `Activate warnings on biased representation.'
10969 @geindex Biased representation
10971 This switch activates warnings when a size clause, value size clause, component
10972 clause, or component size clause forces the use of biased representation for an
10973 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
10974 to represent 10/11). The default is that such warnings are generated.
10975 @end table
10977 @geindex -gnatwB (gcc)
10980 @table @asis
10982 @item @code{-gnatw.B}
10984 `Suppress warnings on biased representation.'
10986 This switch suppresses warnings for representation clauses that force the use
10987 of biased representation.
10988 @end table
10990 @geindex -gnatwc (gcc)
10993 @table @asis
10995 @item @code{-gnatwc}
10997 `Activate warnings on conditionals.'
10999 @geindex Conditionals
11000 @geindex constant
11002 This switch activates warnings for conditional expressions used in
11003 tests that are known to be True or False at compile time. The default
11004 is that such warnings are not generated.
11005 Note that this warning does
11006 not get issued for the use of boolean constants whose
11007 values are known at compile time, since this is a standard technique
11008 for conditional compilation in Ada, and this would generate too many
11009 false positive warnings.
11011 This warning option also activates a special test for comparisons using
11012 the operators ‘>=’ and’ <=’.
11013 If the compiler can tell that only the equality condition is possible,
11014 then it will warn that the ‘>’ or ‘<’ part of the test
11015 is useless and that the operator could be replaced by ‘=’.
11016 An example would be comparing a @code{Natural} variable <= 0.
11018 This warning option also generates warnings if
11019 one or both tests is optimized away in a membership test for integer
11020 values if the result can be determined at compile time. Range tests on
11021 enumeration types are not included, since it is common for such tests
11022 to include an end point.
11024 This warning can also be turned on using @code{-gnatwa}.
11025 @end table
11027 @geindex -gnatwC (gcc)
11030 @table @asis
11032 @item @code{-gnatwC}
11034 `Suppress warnings on conditionals.'
11036 This switch suppresses warnings for conditional expressions used in
11037 tests that are known to be True or False at compile time.
11038 @end table
11040 @geindex -gnatw.c (gcc)
11043 @table @asis
11045 @item @code{-gnatw.c}
11047 `Activate warnings on missing component clauses.'
11049 @geindex Component clause
11050 @geindex missing
11052 This switch activates warnings for record components where a record
11053 representation clause is present and has component clauses for the
11054 majority, but not all, of the components. A warning is given for each
11055 component for which no component clause is present.
11056 @end table
11058 @geindex -gnatw.C (gcc)
11061 @table @asis
11063 @item @code{-gnatw.C}
11065 `Suppress warnings on missing component clauses.'
11067 This switch suppresses warnings for record components that are
11068 missing a component clause in the situation described above.
11069 @end table
11071 @geindex -gnatw_c (gcc)
11074 @table @asis
11076 @item @code{-gnatw_c}
11078 `Activate warnings on unknown condition in Compile_Time_Warning.'
11080 @geindex Compile_Time_Warning
11082 @geindex Compile_Time_Error
11084 This switch activates warnings on a pragma Compile_Time_Warning
11085 or Compile_Time_Error whose condition has a value that is not
11086 known at compile time.
11087 The default is that such warnings are generated.
11088 @end table
11090 @geindex -gnatw_C (gcc)
11093 @table @asis
11095 @item @code{-gnatw_C}
11097 `Suppress warnings on unknown condition in Compile_Time_Warning.'
11099 This switch suppresses warnings on a pragma Compile_Time_Warning
11100 or Compile_Time_Error whose condition has a value that is not
11101 known at compile time.
11102 @end table
11104 @geindex -gnatwd (gcc)
11107 @table @asis
11109 @item @code{-gnatwd}
11111 `Activate warnings on implicit dereferencing.'
11113 If this switch is set, then the use of a prefix of an access type
11114 in an indexed component, slice, or selected component without an
11115 explicit @code{.all} will generate a warning. With this warning
11116 enabled, access checks occur only at points where an explicit
11117 @code{.all} appears in the source code (assuming no warnings are
11118 generated as a result of this switch). The default is that such
11119 warnings are not generated.
11120 @end table
11122 @geindex -gnatwD (gcc)
11125 @table @asis
11127 @item @code{-gnatwD}
11129 `Suppress warnings on implicit dereferencing.'
11131 @geindex Implicit dereferencing
11133 @geindex Dereferencing
11134 @geindex implicit
11136 This switch suppresses warnings for implicit dereferences in
11137 indexed components, slices, and selected components.
11138 @end table
11140 @geindex -gnatw.d (gcc)
11143 @table @asis
11145 @item @code{-gnatw.d}
11147 `Activate tagging of warning and info messages.'
11149 If this switch is set, then warning messages are tagged, with one of the
11150 following strings:
11152 @quotation
11155 @itemize -
11157 @item 
11158 `[-gnatw?]'
11159 Used to tag warnings controlled by the switch @code{-gnatwx} where x
11160 is a letter a-z.
11162 @item 
11163 `[-gnatw.?]'
11164 Used to tag warnings controlled by the switch @code{-gnatw.x} where x
11165 is a letter a-z.
11167 @item 
11168 `[-gnatel]'
11169 Used to tag elaboration information (info) messages generated when the
11170 static model of elaboration is used and the @code{-gnatel} switch is set.
11172 @item 
11173 `[restriction warning]'
11174 Used to tag warning messages for restriction violations, activated by use
11175 of the pragma @code{Restriction_Warnings}.
11177 @item 
11178 `[warning-as-error]'
11179 Used to tag warning messages that have been converted to error messages by
11180 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11181 the string “error: ” rather than “warning: “.
11183 @item 
11184 `[enabled by default]'
11185 Used to tag all other warnings that are always given by default, unless
11186 warnings are completely suppressed using pragma `Warnings(Off)' or
11187 the switch @code{-gnatws}.
11188 @end itemize
11189 @end quotation
11190 @end table
11192 @geindex -gnatw.d (gcc)
11195 @table @asis
11197 @item @code{-gnatw.D}
11199 `Deactivate tagging of warning and info messages messages.'
11201 If this switch is set, then warning messages return to the default
11202 mode in which warnings and info messages are not tagged as described above for
11203 @code{-gnatw.d}.
11204 @end table
11206 @geindex -gnatwe (gcc)
11208 @geindex Warnings
11209 @geindex treat as error
11212 @table @asis
11214 @item @code{-gnatwe}
11216 `Treat warnings and style checks as errors.'
11218 This switch causes warning messages and style check messages to be
11219 treated as errors.
11220 The warning string still appears, but the warning messages are counted
11221 as errors, and prevent the generation of an object file. Note that this
11222 is the only -gnatw switch that affects the handling of style check messages.
11223 Note also that this switch has no effect on info (information) messages, which
11224 are not treated as errors if this switch is present.
11225 @end table
11227 @geindex -gnatw.e (gcc)
11230 @table @asis
11232 @item @code{-gnatw.e}
11234 `Activate every optional warning.'
11236 @geindex Warnings
11237 @geindex activate every optional warning
11239 This switch activates all optional warnings, including those which
11240 are not activated by @code{-gnatwa}. The use of this switch is not
11241 recommended for normal use. If you turn this switch on, it is almost
11242 certain that you will get large numbers of useless warnings. The
11243 warnings that are excluded from @code{-gnatwa} are typically highly
11244 specialized warnings that are suitable for use only in code that has
11245 been specifically designed according to specialized coding rules.
11246 @end table
11248 @geindex -gnatwE (gcc)
11250 @geindex Warnings
11251 @geindex treat as error
11254 @table @asis
11256 @item @code{-gnatwE}
11258 `Treat all run-time exception warnings as errors.'
11260 This switch causes warning messages regarding errors that will be raised
11261 during run-time execution to be treated as errors.
11262 @end table
11264 @geindex -gnatwf (gcc)
11267 @table @asis
11269 @item @code{-gnatwf}
11271 `Activate warnings on unreferenced formals.'
11273 @geindex Formals
11274 @geindex unreferenced
11276 This switch causes a warning to be generated if a formal parameter
11277 is not referenced in the body of the subprogram. This warning can
11278 also be turned on using @code{-gnatwu}. The
11279 default is that these warnings are not generated.
11280 @end table
11282 @geindex -gnatwF (gcc)
11285 @table @asis
11287 @item @code{-gnatwF}
11289 `Suppress warnings on unreferenced formals.'
11291 This switch suppresses warnings for unreferenced formal
11292 parameters. Note that the
11293 combination @code{-gnatwu} followed by @code{-gnatwF} has the
11294 effect of warning on unreferenced entities other than subprogram
11295 formals.
11296 @end table
11298 @geindex -gnatwg (gcc)
11301 @table @asis
11303 @item @code{-gnatwg}
11305 `Activate warnings on unrecognized pragmas.'
11307 @geindex Pragmas
11308 @geindex unrecognized
11310 This switch causes a warning to be generated if an unrecognized
11311 pragma is encountered. Apart from issuing this warning, the
11312 pragma is ignored and has no effect. The default
11313 is that such warnings are issued (satisfying the Ada Reference
11314 Manual requirement that such warnings appear).
11315 @end table
11317 @geindex -gnatwG (gcc)
11320 @table @asis
11322 @item @code{-gnatwG}
11324 `Suppress warnings on unrecognized pragmas.'
11326 This switch suppresses warnings for unrecognized pragmas.
11327 @end table
11329 @geindex -gnatw.g (gcc)
11332 @table @asis
11334 @item @code{-gnatw.g}
11336 `Warnings used for GNAT sources.'
11338 This switch sets the warning categories that are used by the standard
11339 GNAT style. Currently this is equivalent to
11340 @code{-gnatwAao.q.s.CI.V.X.Z}
11341 but more warnings may be added in the future without advanced notice.
11342 @end table
11344 @geindex -gnatwh (gcc)
11347 @table @asis
11349 @item @code{-gnatwh}
11351 `Activate warnings on hiding.'
11353 @geindex Hiding of Declarations
11355 This switch activates warnings on hiding declarations that are considered
11356 potentially confusing. Not all cases of hiding cause warnings; for example an
11357 overriding declaration hides an implicit declaration, which is just normal
11358 code. The default is that warnings on hiding are not generated.
11359 @end table
11361 @geindex -gnatwH (gcc)
11364 @table @asis
11366 @item @code{-gnatwH}
11368 `Suppress warnings on hiding.'
11370 This switch suppresses warnings on hiding declarations.
11371 @end table
11373 @geindex -gnatw.h (gcc)
11376 @table @asis
11378 @item @code{-gnatw.h}
11380 `Activate warnings on holes/gaps in records.'
11382 @geindex Record Representation (gaps)
11384 This switch activates warnings on component clauses in record
11385 representation clauses that leave holes (gaps) in the record layout.
11386 If a record representation clause does not specify a location for
11387 every component of the record type, then the warnings generated (or not
11388 generated) are unspecified. For example, there may be gaps for which
11389 either no warning is generated or a warning is generated that
11390 incorrectly describes the location of the gap. This undesirable situation
11391 can sometimes be avoided by adding (and specifying the location for) unused
11392 fill fields.
11393 @end table
11395 @geindex -gnatw.H (gcc)
11398 @table @asis
11400 @item @code{-gnatw.H}
11402 `Suppress warnings on holes/gaps in records.'
11404 This switch suppresses warnings on component clauses in record
11405 representation clauses that leave holes (haps) in the record layout.
11406 @end table
11408 @geindex -gnatwi (gcc)
11411 @table @asis
11413 @item @code{-gnatwi}
11415 `Activate warnings on implementation units.'
11417 This switch activates warnings for a `with' of an internal GNAT
11418 implementation unit, defined as any unit from the @code{Ada},
11419 @code{Interfaces}, @code{GNAT},
11420 or @code{System}
11421 hierarchies that is not
11422 documented in either the Ada Reference Manual or the GNAT
11423 Programmer’s Reference Manual. Such units are intended only
11424 for internal implementation purposes and should not be `with'ed
11425 by user programs. The default is that such warnings are generated
11426 @end table
11428 @geindex -gnatwI (gcc)
11431 @table @asis
11433 @item @code{-gnatwI}
11435 `Disable warnings on implementation units.'
11437 This switch disables warnings for a `with' of an internal GNAT
11438 implementation unit.
11439 @end table
11441 @geindex -gnatw.i (gcc)
11444 @table @asis
11446 @item @code{-gnatw.i}
11448 `Activate warnings on overlapping actuals.'
11450 This switch enables a warning on statically detectable overlapping actuals in
11451 a subprogram call, when one of the actuals is an in-out parameter, and the
11452 types of the actuals are not by-copy types. This warning is off by default.
11453 @end table
11455 @geindex -gnatw.I (gcc)
11458 @table @asis
11460 @item @code{-gnatw.I}
11462 `Disable warnings on overlapping actuals.'
11464 This switch disables warnings on overlapping actuals in a call.
11465 @end table
11467 @geindex -gnatwj (gcc)
11470 @table @asis
11472 @item @code{-gnatwj}
11474 `Activate warnings on obsolescent features (Annex J).'
11476 @geindex Features
11477 @geindex obsolescent
11479 @geindex Obsolescent features
11481 If this warning option is activated, then warnings are generated for
11482 calls to subprograms marked with @code{pragma Obsolescent} and
11483 for use of features in Annex J of the Ada Reference Manual. In the
11484 case of Annex J, not all features are flagged. In particular, uses of package
11485 @code{ASCII} are not flagged, since these are very common and
11486 would generate many annoying positive warnings. The default is that
11487 such warnings are not generated.
11489 In addition to the above cases, warnings are also generated for
11490 GNAT features that have been provided in past versions but which
11491 have been superseded (typically by features in the new Ada standard).
11492 For example, @code{pragma Ravenscar} will be flagged since its
11493 function is replaced by @code{pragma Profile(Ravenscar)}, and
11494 @code{pragma Interface_Name} will be flagged since its function
11495 is replaced by @code{pragma Import}.
11497 Note that this warning option functions differently from the
11498 restriction @code{No_Obsolescent_Features} in two respects.
11499 First, the restriction applies only to annex J features.
11500 Second, the restriction does flag uses of package @code{ASCII}.
11501 @end table
11503 @geindex -gnatwJ (gcc)
11506 @table @asis
11508 @item @code{-gnatwJ}
11510 `Suppress warnings on obsolescent features (Annex J).'
11512 This switch disables warnings on use of obsolescent features.
11513 @end table
11515 @geindex -gnatw.j (gcc)
11518 @table @asis
11520 @item @code{-gnatw.j}
11522 `Activate warnings on late declarations of tagged type primitives.'
11524 This switch activates warnings on visible primitives added to a
11525 tagged type after deriving a private extension from it.
11526 @end table
11528 @geindex -gnatw.J (gcc)
11531 @table @asis
11533 @item @code{-gnatw.J}
11535 `Suppress warnings on late declarations of tagged type primitives.'
11537 This switch suppresses warnings on visible primitives added to a
11538 tagged type after deriving a private extension from it.
11539 @end table
11541 @geindex -gnatwk (gcc)
11544 @table @asis
11546 @item @code{-gnatwk}
11548 `Activate warnings on variables that could be constants.'
11550 This switch activates warnings for variables that are initialized but
11551 never modified, and then could be declared constants. The default is that
11552 such warnings are not given.
11553 @end table
11555 @geindex -gnatwK (gcc)
11558 @table @asis
11560 @item @code{-gnatwK}
11562 `Suppress warnings on variables that could be constants.'
11564 This switch disables warnings on variables that could be declared constants.
11565 @end table
11567 @geindex -gnatw.k (gcc)
11570 @table @asis
11572 @item @code{-gnatw.k}
11574 `Activate warnings on redefinition of names in standard.'
11576 This switch activates warnings for declarations that declare a name that
11577 is defined in package Standard. Such declarations can be confusing,
11578 especially since the names in package Standard continue to be directly
11579 visible, meaning that use visibility on such redeclared names does not
11580 work as expected. Names of discriminants and components in records are
11581 not included in this check.
11582 @end table
11584 @geindex -gnatwK (gcc)
11587 @table @asis
11589 @item @code{-gnatw.K}
11591 `Suppress warnings on redefinition of names in standard.'
11593 This switch disables warnings for declarations that declare a name that
11594 is defined in package Standard.
11595 @end table
11597 @geindex -gnatwl (gcc)
11600 @table @asis
11602 @item @code{-gnatwl}
11604 `Activate warnings for elaboration pragmas.'
11606 @geindex Elaboration
11607 @geindex warnings
11609 This switch activates warnings for possible elaboration problems,
11610 including suspicious use
11611 of @code{Elaborate} pragmas, when using the static elaboration model, and
11612 possible situations that may raise @code{Program_Error} when using the
11613 dynamic elaboration model.
11614 See the section in this guide on elaboration checking for further details.
11615 The default is that such warnings
11616 are not generated.
11617 @end table
11619 @geindex -gnatwL (gcc)
11622 @table @asis
11624 @item @code{-gnatwL}
11626 `Suppress warnings for elaboration pragmas.'
11628 This switch suppresses warnings for possible elaboration problems.
11629 @end table
11631 @geindex -gnatw.l (gcc)
11634 @table @asis
11636 @item @code{-gnatw.l}
11638 `List inherited aspects.'
11640 This switch causes the compiler to list inherited invariants,
11641 preconditions, and postconditions from Type_Invariant’Class, Invariant’Class,
11642 Pre’Class, and Post’Class aspects. Also list inherited subtype predicates.
11643 @end table
11645 @geindex -gnatw.L (gcc)
11648 @table @asis
11650 @item @code{-gnatw.L}
11652 `Suppress listing of inherited aspects.'
11654 This switch suppresses listing of inherited aspects.
11655 @end table
11657 @geindex -gnatwm (gcc)
11660 @table @asis
11662 @item @code{-gnatwm}
11664 `Activate warnings on modified but unreferenced variables.'
11666 This switch activates warnings for variables that are assigned (using
11667 an initialization value or with one or more assignment statements) but
11668 whose value is never read. The warning is suppressed for volatile
11669 variables and also for variables that are renamings of other variables
11670 or for which an address clause is given.
11671 The default is that these warnings are not given.
11672 @end table
11674 @geindex -gnatwM (gcc)
11677 @table @asis
11679 @item @code{-gnatwM}
11681 `Disable warnings on modified but unreferenced variables.'
11683 This switch disables warnings for variables that are assigned or
11684 initialized, but never read.
11685 @end table
11687 @geindex -gnatw.m (gcc)
11690 @table @asis
11692 @item @code{-gnatw.m}
11694 `Activate warnings on suspicious modulus values.'
11696 This switch activates warnings for modulus values that seem suspicious.
11697 The cases caught are where the size is the same as the modulus (e.g.
11698 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11699 with no size clause. The guess in both cases is that 2**x was intended
11700 rather than x. In addition expressions of the form 2*x for small x
11701 generate a warning (the almost certainly accurate guess being that
11702 2**x was intended). This switch also activates warnings for negative
11703 literal values of a modular type, which are interpreted as large positive
11704 integers after wrap-around. The default is that these warnings are given.
11705 @end table
11707 @geindex -gnatw.M (gcc)
11710 @table @asis
11712 @item @code{-gnatw.M}
11714 `Disable warnings on suspicious modulus values.'
11716 This switch disables warnings for suspicious modulus values.
11717 @end table
11719 @geindex -gnatwn (gcc)
11722 @table @asis
11724 @item @code{-gnatwn}
11726 `Set normal warnings mode.'
11728 This switch sets normal warning mode, in which enabled warnings are
11729 issued and treated as warnings rather than errors. This is the default
11730 mode. the switch @code{-gnatwn} can be used to cancel the effect of
11731 an explicit @code{-gnatws} or
11732 @code{-gnatwe}. It also cancels the effect of the
11733 implicit @code{-gnatwe} that is activated by the
11734 use of @code{-gnatg}.
11735 @end table
11737 @geindex -gnatw.n (gcc)
11739 @geindex Atomic Synchronization
11740 @geindex warnings
11743 @table @asis
11745 @item @code{-gnatw.n}
11747 `Activate warnings on atomic synchronization.'
11749 This switch actives warnings when an access to an atomic variable
11750 requires the generation of atomic synchronization code. These
11751 warnings are off by default.
11752 @end table
11754 @geindex -gnatw.N (gcc)
11757 @table @asis
11759 @item @code{-gnatw.N}
11761 `Suppress warnings on atomic synchronization.'
11763 @geindex Atomic Synchronization
11764 @geindex warnings
11766 This switch suppresses warnings when an access to an atomic variable
11767 requires the generation of atomic synchronization code.
11768 @end table
11770 @geindex -gnatwo (gcc)
11772 @geindex Address Clauses
11773 @geindex warnings
11776 @table @asis
11778 @item @code{-gnatwo}
11780 `Activate warnings on address clause overlays.'
11782 This switch activates warnings for possibly unintended initialization
11783 effects of defining address clauses that cause one variable to overlap
11784 another. The default is that such warnings are generated.
11785 @end table
11787 @geindex -gnatwO (gcc)
11790 @table @asis
11792 @item @code{-gnatwO}
11794 `Suppress warnings on address clause overlays.'
11796 This switch suppresses warnings on possibly unintended initialization
11797 effects of defining address clauses that cause one variable to overlap
11798 another.
11799 @end table
11801 @geindex -gnatw.o (gcc)
11804 @table @asis
11806 @item @code{-gnatw.o}
11808 `Activate warnings on modified but unreferenced out parameters.'
11810 This switch activates warnings for variables that are modified by using
11811 them as actuals for a call to a procedure with an out mode formal, where
11812 the resulting assigned value is never read. It is applicable in the case
11813 where there is more than one out mode formal. If there is only one out
11814 mode formal, the warning is issued by default (controlled by -gnatwu).
11815 The warning is suppressed for volatile
11816 variables and also for variables that are renamings of other variables
11817 or for which an address clause is given.
11818 The default is that these warnings are not given.
11819 @end table
11821 @geindex -gnatw.O (gcc)
11824 @table @asis
11826 @item @code{-gnatw.O}
11828 `Disable warnings on modified but unreferenced out parameters.'
11830 This switch suppresses warnings for variables that are modified by using
11831 them as actuals for a call to a procedure with an out mode formal, where
11832 the resulting assigned value is never read.
11833 @end table
11835 @geindex -gnatwp (gcc)
11837 @geindex Inlining
11838 @geindex warnings
11841 @table @asis
11843 @item @code{-gnatwp}
11845 `Activate warnings on ineffective pragma Inlines.'
11847 This switch activates warnings for failure of front end inlining
11848 (activated by @code{-gnatN}) to inline a particular call. There are
11849 many reasons for not being able to inline a call, including most
11850 commonly that the call is too complex to inline. The default is
11851 that such warnings are not given.
11852 Warnings on ineffective inlining by the gcc back-end can be activated
11853 separately, using the gcc switch -Winline.
11854 @end table
11856 @geindex -gnatwP (gcc)
11859 @table @asis
11861 @item @code{-gnatwP}
11863 `Suppress warnings on ineffective pragma Inlines.'
11865 This switch suppresses warnings on ineffective pragma Inlines. If the
11866 inlining mechanism cannot inline a call, it will simply ignore the
11867 request silently.
11868 @end table
11870 @geindex -gnatw.p (gcc)
11872 @geindex Parameter order
11873 @geindex warnings
11876 @table @asis
11878 @item @code{-gnatw.p}
11880 `Activate warnings on parameter ordering.'
11882 This switch activates warnings for cases of suspicious parameter
11883 ordering when the list of arguments are all simple identifiers that
11884 match the names of the formals, but are in a different order. The
11885 warning is suppressed if any use of named parameter notation is used,
11886 so this is the appropriate way to suppress a false positive (and
11887 serves to emphasize that the “misordering” is deliberate). The
11888 default is that such warnings are not given.
11889 @end table
11891 @geindex -gnatw.P (gcc)
11894 @table @asis
11896 @item @code{-gnatw.P}
11898 `Suppress warnings on parameter ordering.'
11900 This switch suppresses warnings on cases of suspicious parameter
11901 ordering.
11902 @end table
11904 @geindex -gnatw_p (gcc)
11907 @table @asis
11909 @item @code{-gnatw_p}
11911 `Activate warnings for pedantic checks.'
11913 This switch activates warnings for the failure of certain pedantic checks.
11914 The only case currently supported is a check that the subtype_marks given
11915 for corresponding formal parameter and function results in a subprogram
11916 declaration and its body denote the same subtype declaration. The default
11917 is that such warnings are not given.
11918 @end table
11920 @geindex -gnatw_P (gcc)
11923 @table @asis
11925 @item @code{-gnatw_P}
11927 `Suppress warnings for pedantic checks.'
11929 This switch suppresses warnings on violations of pedantic checks.
11930 @end table
11932 @geindex -gnatwq (gcc)
11934 @geindex Parentheses
11935 @geindex warnings
11938 @table @asis
11940 @item @code{-gnatwq}
11942 `Activate warnings on questionable missing parentheses.'
11944 This switch activates warnings for cases where parentheses are not used and
11945 the result is potential ambiguity from a readers point of view. For example
11946 (not a > b) when a and b are modular means ((not a) > b) and very likely the
11947 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11948 quite likely ((-x) mod 5) was intended. In such situations it seems best to
11949 follow the rule of always parenthesizing to make the association clear, and
11950 this warning switch warns if such parentheses are not present. The default
11951 is that these warnings are given.
11952 @end table
11954 @geindex -gnatwQ (gcc)
11957 @table @asis
11959 @item @code{-gnatwQ}
11961 `Suppress warnings on questionable missing parentheses.'
11963 This switch suppresses warnings for cases where the association is not
11964 clear and the use of parentheses is preferred.
11965 @end table
11967 @geindex -gnatw.q (gcc)
11969 @geindex Layout
11970 @geindex warnings
11973 @table @asis
11975 @item @code{-gnatw.q}
11977 `Activate warnings on questionable layout of record types.'
11979 This switch activates warnings for cases where the default layout of
11980 a record type, that is to say the layout of its components in textual
11981 order of the source code, would very likely cause inefficiencies in
11982 the code generated by the compiler, both in terms of space and speed
11983 during execution. One warning is issued for each problematic component
11984 without representation clause in the nonvariant part and then in each
11985 variant recursively, if any.
11987 The purpose of these warnings is neither to prescribe an optimal layout
11988 nor to force the use of representation clauses, but rather to get rid of
11989 the most blatant inefficiencies in the layout. Therefore, the default
11990 layout is matched against the following synthetic ordered layout and
11991 the deviations are flagged on a component-by-component basis:
11994 @itemize *
11996 @item 
11997 first all components or groups of components whose length is fixed
11998 and a multiple of the storage unit,
12000 @item 
12001 then the remaining components whose length is fixed and not a multiple
12002 of the storage unit,
12004 @item 
12005 then the remaining components whose length doesn’t depend on discriminants
12006 (that is to say, with variable but uniform length for all objects),
12008 @item 
12009 then all components whose length depends on discriminants,
12011 @item 
12012 finally the variant part (if any),
12013 @end itemize
12015 for the nonvariant part and for each variant recursively, if any.
12017 The exact wording of the warning depends on whether the compiler is allowed
12018 to reorder the components in the record type or precluded from doing it by
12019 means of pragma @code{No_Component_Reordering}.
12021 The default is that these warnings are not given.
12022 @end table
12024 @geindex -gnatw.Q (gcc)
12027 @table @asis
12029 @item @code{-gnatw.Q}
12031 `Suppress warnings on questionable layout of record types.'
12033 This switch suppresses warnings for cases where the default layout of
12034 a record type would very likely cause inefficiencies.
12035 @end table
12037 @geindex -gnatw_q (gcc)
12040 @table @asis
12042 @item @code{-gnatw_q}
12044 `Activate warnings for ignored equality operators.'
12046 This switch activates warnings for a user-defined “=” function that does
12047 not compose (i.e. is ignored for a predefined “=” for a composite type
12048 containing a component whose type has the user-defined “=” as
12049 primitive). Note that the user-defined “=” must be a primitive operator
12050 in order to trigger the warning.
12051 See RM-4.5.2(14/3-15/5, 21, 24/3, 32.1/1)
12052 for the exact Ada rules on composability of “=”.
12054 The default is that these warnings are not given.
12055 @end table
12057 @geindex -gnatw_Q (gcc)
12060 @table @asis
12062 @item @code{-gnatw_Q}
12064 `Suppress warnings for ignored equality operators.'
12065 @end table
12067 @geindex -gnatwr (gcc)
12070 @table @asis
12072 @item @code{-gnatwr}
12074 `Activate warnings on redundant constructs.'
12076 This switch activates warnings for redundant constructs. The following
12077 is the current list of constructs regarded as redundant:
12080 @itemize *
12082 @item 
12083 Assignment of an item to itself.
12085 @item 
12086 Type conversion that converts an expression to its own type.
12088 @item 
12089 Use of the attribute @code{Base} where @code{typ'Base} is the same
12090 as @code{typ}.
12092 @item 
12093 Use of pragma @code{Pack} when all components are placed by a record
12094 representation clause.
12096 @item 
12097 Exception handler containing only a reraise statement (raise with no
12098 operand) which has no effect.
12100 @item 
12101 Use of the operator abs on an operand that is known at compile time
12102 to be non-negative
12104 @item 
12105 Comparison of an object or (unary or binary) operation of boolean type to
12106 an explicit True value.
12108 @item 
12109 Import of parent package.
12110 @end itemize
12112 The default is that warnings for redundant constructs are not given.
12113 @end table
12115 @geindex -gnatwR (gcc)
12118 @table @asis
12120 @item @code{-gnatwR}
12122 `Suppress warnings on redundant constructs.'
12124 This switch suppresses warnings for redundant constructs.
12125 @end table
12127 @geindex -gnatw.r (gcc)
12130 @table @asis
12132 @item @code{-gnatw.r}
12134 `Activate warnings for object renaming function.'
12136 This switch activates warnings for an object renaming that renames a
12137 function call, which is equivalent to a constant declaration (as
12138 opposed to renaming the function itself).  The default is that these
12139 warnings are given.
12140 @end table
12142 @geindex -gnatw.R (gcc)
12145 @table @asis
12147 @item @code{-gnatw.R}
12149 `Suppress warnings for object renaming function.'
12151 This switch suppresses warnings for object renaming function.
12152 @end table
12154 @geindex -gnatw_r (gcc)
12157 @table @asis
12159 @item @code{-gnatw_r}
12161 `Activate warnings for out-of-order record representation clauses.'
12163 This switch activates warnings for record representation clauses,
12164 if the order of component declarations, component clauses,
12165 and bit-level layout do not all agree.
12166 The default is that these warnings are not given.
12167 @end table
12169 @geindex -gnatw_R (gcc)
12172 @table @asis
12174 @item @code{-gnatw_R}
12176 `Suppress warnings for out-of-order record representation clauses.'
12177 @end table
12179 @geindex -gnatws (gcc)
12182 @table @asis
12184 @item @code{-gnatws}
12186 `Suppress all warnings.'
12188 This switch completely suppresses the
12189 output of all warning messages from the GNAT front end, including
12190 both warnings that can be controlled by switches described in this
12191 section, and those that are normally given unconditionally. The
12192 effect of this suppress action can only be cancelled by a subsequent
12193 use of the switch @code{-gnatwn}.
12195 Note that switch @code{-gnatws} does not suppress
12196 warnings from the @code{gcc} back end.
12197 To suppress these back end warnings as well, use the switch @code{-w}
12198 in addition to @code{-gnatws}. Also this switch has no effect on the
12199 handling of style check messages.
12200 @end table
12202 @geindex -gnatw.s (gcc)
12204 @geindex Record Representation (component sizes)
12207 @table @asis
12209 @item @code{-gnatw.s}
12211 `Activate warnings on overridden size clauses.'
12213 This switch activates warnings on component clauses in record
12214 representation clauses where the length given overrides that
12215 specified by an explicit size clause for the component type. A
12216 warning is similarly given in the array case if a specified
12217 component size overrides an explicit size clause for the array
12218 component type.
12219 @end table
12221 @geindex -gnatw.S (gcc)
12224 @table @asis
12226 @item @code{-gnatw.S}
12228 `Suppress warnings on overridden size clauses.'
12230 This switch suppresses warnings on component clauses in record
12231 representation clauses that override size clauses, and similar
12232 warnings when an array component size overrides a size clause.
12233 @end table
12235 @geindex -gnatw_s (gcc)
12237 @geindex Warnings
12240 @table @asis
12242 @item @code{-gnatw_s}
12244 `Activate warnings on ineffective predicate tests.'
12246 This switch activates warnings on Static_Predicate aspect
12247 specifications that test for values that do not belong to
12248 the parent subtype. Not all such ineffective tests are detected.
12249 @end table
12251 @geindex -gnatw_S (gcc)
12254 @table @asis
12256 @item @code{-gnatw_S}
12258 `Suppress warnings on ineffective predicate tests.'
12260 This switch suppresses warnings on Static_Predicate aspect
12261 specifications that test for values that do not belong to
12262 the parent subtype.
12263 @end table
12265 @geindex -gnatwt (gcc)
12267 @geindex Deactivated code
12268 @geindex warnings
12270 @geindex Deleted code
12271 @geindex warnings
12274 @table @asis
12276 @item @code{-gnatwt}
12278 `Activate warnings for tracking of deleted conditional code.'
12280 This switch activates warnings for tracking of code in conditionals (IF and
12281 CASE statements) that is detected to be dead code which cannot be executed, and
12282 which is removed by the front end. This warning is off by default. This may be
12283 useful for detecting deactivated code in certified applications.
12284 @end table
12286 @geindex -gnatwT (gcc)
12289 @table @asis
12291 @item @code{-gnatwT}
12293 `Suppress warnings for tracking of deleted conditional code.'
12295 This switch suppresses warnings for tracking of deleted conditional code.
12296 @end table
12298 @geindex -gnatw.t (gcc)
12301 @table @asis
12303 @item @code{-gnatw.t}
12305 `Activate warnings on suspicious contracts.'
12307 This switch activates warnings on suspicious contracts. This includes
12308 warnings on suspicious postconditions (whether a pragma @code{Postcondition} or a
12309 @code{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
12310 @code{Contract_Cases}). A function postcondition or contract case is suspicious
12311 when no postcondition or contract case for this function mentions the result
12312 of the function.  A procedure postcondition or contract case is suspicious
12313 when it only refers to the pre-state of the procedure, because in that case
12314 it should rather be expressed as a precondition. This switch also controls
12315 warnings on suspicious cases of expressions typically found in contracts like
12316 quantified expressions and uses of Update attribute. The default is that such
12317 warnings are generated.
12318 @end table
12320 @geindex -gnatw.T (gcc)
12323 @table @asis
12325 @item @code{-gnatw.T}
12327 `Suppress warnings on suspicious contracts.'
12329 This switch suppresses warnings on suspicious contracts.
12330 @end table
12332 @geindex -gnatwu (gcc)
12335 @table @asis
12337 @item @code{-gnatwu}
12339 `Activate warnings on unused entities.'
12341 This switch activates warnings to be generated for entities that
12342 are declared but not referenced, and for units that are `with'ed
12343 and not
12344 referenced. In the case of packages, a warning is also generated if
12345 no entities in the package are referenced. This means that if a with’ed
12346 package is referenced but the only references are in @code{use}
12347 clauses or @code{renames}
12348 declarations, a warning is still generated. A warning is also generated
12349 for a generic package that is `with'ed but never instantiated.
12350 In the case where a package or subprogram body is compiled, and there
12351 is a `with' on the corresponding spec
12352 that is only referenced in the body,
12353 a warning is also generated, noting that the
12354 `with' can be moved to the body. The default is that
12355 such warnings are not generated.
12356 This switch also activates warnings on unreferenced formals
12357 (it includes the effect of @code{-gnatwf}).
12358 @end table
12360 @geindex -gnatwU (gcc)
12363 @table @asis
12365 @item @code{-gnatwU}
12367 `Suppress warnings on unused entities.'
12369 This switch suppresses warnings for unused entities and packages.
12370 It also turns off warnings on unreferenced formals (and thus includes
12371 the effect of @code{-gnatwF}).
12372 @end table
12374 @geindex -gnatw.u (gcc)
12377 @table @asis
12379 @item @code{-gnatw.u}
12381 `Activate warnings on unordered enumeration types.'
12383 This switch causes enumeration types to be considered as conceptually
12384 unordered, unless an explicit pragma @code{Ordered} is given for the type.
12385 The effect is to generate warnings in clients that use explicit comparisons
12386 or subranges, since these constructs both treat objects of the type as
12387 ordered. (A `client' is defined as a unit that is other than the unit in
12388 which the type is declared, or its body or subunits.) Please refer to
12389 the description of pragma @code{Ordered} in the
12390 @cite{GNAT Reference Manual} for further details.
12391 The default is that such warnings are not generated.
12392 @end table
12394 @geindex -gnatw.U (gcc)
12397 @table @asis
12399 @item @code{-gnatw.U}
12401 `Deactivate warnings on unordered enumeration types.'
12403 This switch causes all enumeration types to be considered as ordered, so
12404 that no warnings are given for comparisons or subranges for any type.
12405 @end table
12407 @geindex -gnatwv (gcc)
12409 @geindex Unassigned variable warnings
12412 @table @asis
12414 @item @code{-gnatwv}
12416 `Activate warnings on unassigned variables.'
12418 This switch activates warnings for access to variables which
12419 may not be properly initialized. The default is that
12420 such warnings are generated. This switch will also be emitted when
12421 initializing an array or record object via the following aggregate:
12423 @example
12424 Array_Or_Record : XXX := (others => <>);
12425 @end example
12427 unless the relevant type fully initializes all components.
12428 @end table
12430 @geindex -gnatwV (gcc)
12433 @table @asis
12435 @item @code{-gnatwV}
12437 `Suppress warnings on unassigned variables.'
12439 This switch suppresses warnings for access to variables which
12440 may not be properly initialized.
12441 @end table
12443 @geindex -gnatw.v (gcc)
12445 @geindex bit order warnings
12448 @table @asis
12450 @item @code{-gnatw.v}
12452 `Activate info messages for non-default bit order.'
12454 This switch activates messages (labeled “info”, they are not warnings,
12455 just informational messages) about the effects of non-default bit-order
12456 on records to which a component clause is applied. The effect of specifying
12457 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12458 these messages, which are given by default, are useful in understanding the
12459 exact consequences of using this feature.
12460 @end table
12462 @geindex -gnatw.V (gcc)
12465 @table @asis
12467 @item @code{-gnatw.V}
12469 `Suppress info messages for non-default bit order.'
12471 This switch suppresses information messages for the effects of specifying
12472 non-default bit order on record components with component clauses.
12473 @end table
12475 @geindex -gnatww (gcc)
12477 @geindex String indexing warnings
12480 @table @asis
12482 @item @code{-gnatww}
12484 `Activate warnings on wrong low bound assumption.'
12486 This switch activates warnings for indexing an unconstrained string parameter
12487 with a literal or S’Length. This is a case where the code is assuming that the
12488 low bound is one, which is in general not true (for example when a slice is
12489 passed). The default is that such warnings are generated.
12490 @end table
12492 @geindex -gnatwW (gcc)
12495 @table @asis
12497 @item @code{-gnatwW}
12499 `Suppress warnings on wrong low bound assumption.'
12501 This switch suppresses warnings for indexing an unconstrained string parameter
12502 with a literal or S’Length. Note that this warning can also be suppressed
12503 in a particular case by adding an assertion that the lower bound is 1,
12504 as shown in the following example:
12506 @example
12507 procedure K (S : String) is
12508    pragma Assert (S'First = 1);
12509    ...
12510 @end example
12511 @end table
12513 @geindex -gnatw.w (gcc)
12515 @geindex Warnings Off control
12518 @table @asis
12520 @item @code{-gnatw.w}
12522 `Activate warnings on Warnings Off pragmas.'
12524 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
12525 where either the pragma is entirely useless (because it suppresses no
12526 warnings), or it could be replaced by @code{pragma Unreferenced} or
12527 @code{pragma Unmodified}.
12528 Also activates warnings for the case of
12529 Warnings (Off, String), where either there is no matching
12530 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12531 The default is that these warnings are not given.
12532 @end table
12534 @geindex -gnatw.W (gcc)
12537 @table @asis
12539 @item @code{-gnatw.W}
12541 `Suppress warnings on unnecessary Warnings Off pragmas.'
12543 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
12544 @end table
12546 @geindex -gnatwx (gcc)
12548 @geindex Export/Import pragma warnings
12551 @table @asis
12553 @item @code{-gnatwx}
12555 `Activate warnings on Export/Import pragmas.'
12557 This switch activates warnings on Export/Import pragmas when
12558 the compiler detects a possible conflict between the Ada and
12559 foreign language calling sequences. For example, the use of
12560 default parameters in a convention C procedure is dubious
12561 because the C compiler cannot supply the proper default, so
12562 a warning is issued. The default is that such warnings are
12563 generated.
12564 @end table
12566 @geindex -gnatwX (gcc)
12569 @table @asis
12571 @item @code{-gnatwX}
12573 `Suppress warnings on Export/Import pragmas.'
12575 This switch suppresses warnings on Export/Import pragmas.
12576 The sense of this is that you are telling the compiler that
12577 you know what you are doing in writing the pragma, and it
12578 should not complain at you.
12579 @end table
12581 @geindex -gnatwm (gcc)
12584 @table @asis
12586 @item @code{-gnatw.x}
12588 `Activate warnings for No_Exception_Propagation mode.'
12590 This switch activates warnings for exception usage when pragma Restrictions
12591 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
12592 explicit exception raises which are not covered by a local handler, and for
12593 exception handlers which do not cover a local raise. The default is that
12594 these warnings are given for units that contain exception handlers.
12596 @item @code{-gnatw.X}
12598 `Disable warnings for No_Exception_Propagation mode.'
12600 This switch disables warnings for exception usage when pragma Restrictions
12601 (No_Exception_Propagation) is in effect.
12602 @end table
12604 @geindex -gnatwy (gcc)
12606 @geindex Ada compatibility issues warnings
12609 @table @asis
12611 @item @code{-gnatwy}
12613 `Activate warnings for Ada compatibility issues.'
12615 For the most part, newer versions of Ada are upwards compatible
12616 with older versions. For example, Ada 2005 programs will almost
12617 always work when compiled as Ada 2012.
12618 However there are some exceptions (for example the fact that
12619 @code{some} is now a reserved word in Ada 2012). This
12620 switch activates several warnings to help in identifying
12621 and correcting such incompatibilities. The default is that
12622 these warnings are generated. Note that at one point Ada 2005
12623 was called Ada 0Y, hence the choice of character.
12624 @end table
12626 @geindex -gnatwY (gcc)
12628 @geindex Ada compatibility issues warnings
12631 @table @asis
12633 @item @code{-gnatwY}
12635 `Disable warnings for Ada compatibility issues.'
12637 This switch suppresses the warnings intended to help in identifying
12638 incompatibilities between Ada language versions.
12639 @end table
12641 @geindex -gnatw.y (gcc)
12643 @geindex Package spec needing body
12646 @table @asis
12648 @item @code{-gnatw.y}
12650 `Activate information messages for why package spec needs body.'
12652 There are a number of cases in which a package spec needs a body.
12653 For example, the use of pragma Elaborate_Body, or the declaration
12654 of a procedure specification requiring a completion. This switch
12655 causes information messages to be output showing why a package
12656 specification requires a body. This can be useful in the case of
12657 a large package specification which is unexpectedly requiring a
12658 body. The default is that such information messages are not output.
12659 @end table
12661 @geindex -gnatw.Y (gcc)
12663 @geindex No information messages for why package spec needs body
12666 @table @asis
12668 @item @code{-gnatw.Y}
12670 `Disable information messages for why package spec needs body.'
12672 This switch suppresses the output of information messages showing why
12673 a package specification needs a body.
12674 @end table
12676 @geindex -gnatwz (gcc)
12678 @geindex Unchecked_Conversion warnings
12681 @table @asis
12683 @item @code{-gnatwz}
12685 `Activate warnings on unchecked conversions.'
12687 This switch activates warnings for unchecked conversions
12688 where the types are known at compile time to have different
12689 sizes. The default is that such warnings are generated. Warnings are also
12690 generated for subprogram pointers with different conventions.
12691 @end table
12693 @geindex -gnatwZ (gcc)
12696 @table @asis
12698 @item @code{-gnatwZ}
12700 `Suppress warnings on unchecked conversions.'
12702 This switch suppresses warnings for unchecked conversions
12703 where the types are known at compile time to have different
12704 sizes or conventions.
12705 @end table
12707 @geindex -gnatw.z (gcc)
12709 @geindex Size/Alignment warnings
12712 @table @asis
12714 @item @code{-gnatw.z}
12716 `Activate warnings for size not a multiple of alignment.'
12718 This switch activates warnings for cases of array and record types
12719 with specified @code{Size} and @code{Alignment} attributes where the
12720 size is not a multiple of the alignment, resulting in an object
12721 size that is greater than the specified size. The default
12722 is that such warnings are generated.
12723 @end table
12725 @geindex -gnatw.Z (gcc)
12727 @geindex Size/Alignment warnings
12730 @table @asis
12732 @item @code{-gnatw.Z}
12734 `Suppress warnings for size not a multiple of alignment.'
12736 This switch suppresses warnings for cases of array and record types
12737 with specified @code{Size} and @code{Alignment} attributes where the
12738 size is not a multiple of the alignment, resulting in an object
12739 size that is greater than the specified size. The warning can also
12740 be suppressed by giving an explicit @code{Object_Size} value.
12741 @end table
12743 @geindex -Wunused (gcc)
12746 @table @asis
12748 @item @code{-Wunused}
12750 The warnings controlled by the @code{-gnatw} switch are generated by
12751 the front end of the compiler. The GCC back end can provide
12752 additional warnings and they are controlled by the @code{-W} switch.
12753 For example, @code{-Wunused} activates back end
12754 warnings for entities that are declared but not referenced.
12755 @end table
12757 @geindex -Wuninitialized (gcc)
12760 @table @asis
12762 @item @code{-Wuninitialized}
12764 Similarly, @code{-Wuninitialized} activates
12765 the back end warning for uninitialized variables. This switch must be
12766 used in conjunction with an optimization level greater than zero.
12767 @end table
12769 @geindex -Wstack-usage (gcc)
12772 @table @asis
12774 @item @code{-Wstack-usage=`len'}
12776 Warn if the stack usage of a subprogram might be larger than @code{len} bytes.
12777 See @ref{e8,,Static Stack Usage Analysis} for details.
12778 @end table
12780 @geindex -Wall (gcc)
12783 @table @asis
12785 @item @code{-Wall}
12787 This switch enables most warnings from the GCC back end.
12788 The code generator detects a number of warning situations that are missed
12789 by the GNAT front end, and this switch can be used to activate them.
12790 The use of this switch also sets the default front-end warning mode to
12791 @code{-gnatwa}, that is, most front-end warnings are activated as well.
12792 @end table
12794 @geindex -w (gcc)
12797 @table @asis
12799 @item @code{-w}
12801 Conversely, this switch suppresses warnings from the GCC back end.
12802 The use of this switch also sets the default front-end warning mode to
12803 @code{-gnatws}, that is, front-end warnings are suppressed as well.
12804 @end table
12806 @geindex -Werror (gcc)
12809 @table @asis
12811 @item @code{-Werror}
12813 This switch causes warnings from the GCC back end to be treated as
12814 errors.  The warning string still appears, but the warning messages are
12815 counted as errors, and prevent the generation of an object file.
12816 The use of this switch also sets the default front-end warning mode to
12817 @code{-gnatwe}, that is, front-end warning messages and style check
12818 messages are treated as errors as well.
12819 @end table
12821 A string of warning parameters can be used in the same parameter. For example:
12823 @example
12824 -gnatwaGe
12825 @end example
12827 will turn on all optional warnings except for unrecognized pragma warnings,
12828 and also specify that warnings should be treated as errors.
12830 When no switch @code{-gnatw} is used, this is equivalent to:
12832 @quotation
12835 @itemize *
12837 @item 
12838 @code{-gnatw.a}
12840 @item 
12841 @code{-gnatwB}
12843 @item 
12844 @code{-gnatw.b}
12846 @item 
12847 @code{-gnatwC}
12849 @item 
12850 @code{-gnatw.C}
12852 @item 
12853 @code{-gnatwD}
12855 @item 
12856 @code{-gnatw.D}
12858 @item 
12859 @code{-gnatwF}
12861 @item 
12862 @code{-gnatw.F}
12864 @item 
12865 @code{-gnatwg}
12867 @item 
12868 @code{-gnatwH}
12870 @item 
12871 @code{-gnatw.H}
12873 @item 
12874 @code{-gnatwi}
12876 @item 
12877 @code{-gnatwJ}
12879 @item 
12880 @code{-gnatw.J}
12882 @item 
12883 @code{-gnatwK}
12885 @item 
12886 @code{-gnatw.K}
12888 @item 
12889 @code{-gnatwL}
12891 @item 
12892 @code{-gnatw.L}
12894 @item 
12895 @code{-gnatwM}
12897 @item 
12898 @code{-gnatw.m}
12900 @item 
12901 @code{-gnatwn}
12903 @item 
12904 @code{-gnatw.N}
12906 @item 
12907 @code{-gnatwo}
12909 @item 
12910 @code{-gnatw.O}
12912 @item 
12913 @code{-gnatwP}
12915 @item 
12916 @code{-gnatw.P}
12918 @item 
12919 @code{-gnatwq}
12921 @item 
12922 @code{-gnatw.Q}
12924 @item 
12925 @code{-gnatwR}
12927 @item 
12928 @code{-gnatw.R}
12930 @item 
12931 @code{-gnatw.S}
12933 @item 
12934 @code{-gnatwT}
12936 @item 
12937 @code{-gnatw.t}
12939 @item 
12940 @code{-gnatwU}
12942 @item 
12943 @code{-gnatw.U}
12945 @item 
12946 @code{-gnatwv}
12948 @item 
12949 @code{-gnatw.v}
12951 @item 
12952 @code{-gnatww}
12954 @item 
12955 @code{-gnatw.W}
12957 @item 
12958 @code{-gnatwx}
12960 @item 
12961 @code{-gnatw.X}
12963 @item 
12964 @code{-gnatwy}
12966 @item 
12967 @code{-gnatw.Y}
12969 @item 
12970 @code{-gnatwz}
12972 @item 
12973 @code{-gnatw.z}
12974 @end itemize
12975 @end quotation
12977 @node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12978 @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}
12979 @subsection Debugging and Assertion Control
12982 @geindex -gnata (gcc)
12985 @table @asis
12987 @item @code{-gnata}
12989 @geindex Assert
12991 @geindex Debug
12993 @geindex Assertions
12995 @geindex Precondition
12997 @geindex Postcondition
12999 @geindex Type invariants
13001 @geindex Subtype predicates
13003 The @code{-gnata} option is equivalent to the following @code{Assertion_Policy} pragma:
13005 @example
13006 pragma Assertion_Policy (Check);
13007 @end example
13009 Which is a shorthand for:
13011 @example
13012 pragma Assertion_Policy
13013 --  Ada RM assertion pragmas
13014   (Assert                    => Check,
13015    Static_Predicate          => Check,
13016    Dynamic_Predicate         => Check,
13017    Pre                       => Check,
13018    Pre'Class                 => Check,
13019    Post                      => Check,
13020    Post'Class                => Check,
13021    Type_Invariant            => Check,
13022    Type_Invariant'Class      => Check,
13023    Default_Initial_Condition => Check,
13024 --  GNAT specific assertion pragmas
13025    Assert_And_Cut            => Check,
13026    Assume                    => Check,
13027    Contract_Cases            => Check,
13028    Debug                     => Check,
13029    Ghost                     => Check,
13030    Initial_Condition         => Check,
13031    Loop_Invariant            => Check,
13032    Loop_Variant              => Check,
13033    Postcondition             => Check,
13034    Precondition              => Check,
13035    Predicate                 => Check,
13036    Refined_Post              => Check,
13037    Subprogram_Variant        => Check);
13038 @end example
13040 The pragmas @code{Assert} and @code{Debug} normally have no effect and
13041 are ignored. This switch, where @code{a} stands for ‘assert’, causes
13042 pragmas @code{Assert} and @code{Debug} to be activated. This switch also
13043 causes preconditions, postconditions, subtype predicates, and
13044 type invariants to be activated.
13046 The pragmas have the form:
13048 @example
13049 pragma Assert (<Boolean-expression> [, <static-string-expression>])
13050 pragma Debug (<procedure call>)
13051 pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
13052 pragma Predicate (<type-local-name>, <Boolean-expression>)
13053 pragma Precondition (<Boolean-expression>, <string-expression>)
13054 pragma Postcondition (<Boolean-expression>, <string-expression>)
13055 @end example
13057 The aspects have the form:
13059 @example
13060 with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
13061   => <Boolean-expression>;
13062 @end example
13064 The @code{Assert} pragma causes @code{Boolean-expression} to be tested.
13065 If the result is @code{True}, the pragma has no effect (other than
13066 possible side effects from evaluating the expression). If the result is
13067 @code{False}, the exception @code{Assert_Failure} declared in the package
13068 @code{System.Assertions} is raised (passing @code{static-string-expression}, if
13069 present, as the message associated with the exception). If no string
13070 expression is given, the default is a string containing the file name and
13071 line number of the pragma.
13073 The @code{Debug} pragma causes @code{procedure} to be called. Note that
13074 @code{pragma Debug} may appear within a declaration sequence, allowing
13075 debugging procedures to be called between declarations.
13077 For the aspect specification, the @code{Boolean-expression} is evaluated.
13078 If the result is @code{True}, the aspect has no effect. If the result
13079 is @code{False}, the exception @code{Assert_Failure} is raised.
13080 @end table
13082 @node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
13083 @anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{f5}@anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{e9}
13084 @subsection Validity Checking
13087 @geindex Validity Checking
13089 The Ada Reference Manual defines the concept of invalid values (see
13090 RM 13.9.1). The primary source of invalid values is uninitialized
13091 variables. A scalar variable that is left uninitialized may contain
13092 an invalid value; the concept of invalid does not apply to access or
13093 composite types.
13095 It is an error to read an invalid value, but the RM does not require
13096 run-time checks to detect such errors, except for some minimal
13097 checking to prevent erroneous execution (i.e. unpredictable
13098 behavior). This corresponds to the @code{-gnatVd} switch below,
13099 which is the default. For example, by default, if the expression of a
13100 case statement is invalid, it will raise Constraint_Error rather than
13101 causing a wild jump, and if an array index on the left-hand side of an
13102 assignment is invalid, it will raise Constraint_Error rather than
13103 overwriting an arbitrary memory location.
13105 The @code{-gnatVa} may be used to enable additional validity checks,
13106 which are not required by the RM. These checks are often very
13107 expensive (which is why the RM does not require them). These checks
13108 are useful in tracking down uninitialized variables, but they are
13109 not usually recommended for production builds, and in particular
13110 we do not recommend using these extra validity checking options in
13111 combination with optimization, since this can confuse the optimizer.
13112 If performance is a consideration, leading to the need to optimize,
13113 then the validity checking options should not be used.
13115 The other @code{-gnatV`x'} switches below allow finer-grained
13116 control; you can enable whichever validity checks you desire. However,
13117 for most debugging purposes, @code{-gnatVa} is sufficient, and the
13118 default @code{-gnatVd} (i.e. standard Ada behavior) is usually
13119 sufficient for non-debugging use.
13121 The @code{-gnatB} switch tells the compiler to assume that all
13122 values are valid (that is, within their declared subtype range)
13123 except in the context of a use of the Valid attribute. This means
13124 the compiler can generate more efficient code, since the range
13125 of values is better known at compile time. However, an uninitialized
13126 variable can cause wild jumps and memory corruption in this mode.
13128 The @code{-gnatV`x'} switch allows control over the validity
13129 checking mode as described below.
13130 The @code{x} argument is a string of letters that
13131 indicate validity checks that are performed or not performed in addition
13132 to the default checks required by Ada as described above.
13134 @geindex -gnatVa (gcc)
13137 @table @asis
13139 @item @code{-gnatVa}
13141 `All validity checks.'
13143 All validity checks are turned on.
13144 That is, @code{-gnatVa} is
13145 equivalent to @code{gnatVcdefimoprst}.
13146 @end table
13148 @geindex -gnatVc (gcc)
13151 @table @asis
13153 @item @code{-gnatVc}
13155 `Validity checks for copies.'
13157 The right-hand side of assignments, and the (explicit) initializing values
13158 of object declarations are validity checked.
13159 @end table
13161 @geindex -gnatVd (gcc)
13164 @table @asis
13166 @item @code{-gnatVd}
13168 `Default (RM) validity checks.'
13170 Some validity checks are required by Ada (see RM 13.9.1 (9-11)); these
13171 (and only these) validity checks are enabled by default.
13172 For case statements (and case expressions) that lack a “when others =>”
13173 choice, a check is made that the value of the selector expression
13174 belongs to its nominal subtype. If it does not, Constraint_Error is raised.
13175 For assignments to array components (and for indexed components in some
13176 other contexts), a check is made that each index expression belongs to the
13177 corresponding index subtype. If it does not, Constraint_Error is raised.
13178 Both these validity checks may be turned off using switch @code{-gnatVD}.
13179 They are turned on by default. If @code{-gnatVD} is specified, a subsequent
13180 switch @code{-gnatVd} will leave the checks turned on.
13181 Switch @code{-gnatVD} should be used only if you are sure that all such
13182 expressions have valid values. If you use this switch and invalid values
13183 are present, then the program is erroneous, and wild jumps or memory
13184 overwriting may occur.
13185 @end table
13187 @geindex -gnatVe (gcc)
13190 @table @asis
13192 @item @code{-gnatVe}
13194 `Validity checks for scalar components.'
13196 In the absence of this switch, assignments to scalar components of
13197 enclosing record or array objects are not validity checked, even if
13198 validity checks for assignments generally (@code{-gnatVc}) are turned on.
13199 Specifying this switch enables such checks.
13200 This switch has no effect if the @code{-gnatVc} switch is not specified.
13201 @end table
13203 @geindex -gnatVf (gcc)
13206 @table @asis
13208 @item @code{-gnatVf}
13210 `Validity checks for floating-point values.'
13212 Specifying this switch enables validity checking for floating-point
13213 values in the same contexts where validity checking is enabled for
13214 other scalar values.
13215 In the absence of this switch, validity checking is not performed for
13216 floating-point values. This takes precedence over other statements about
13217 performing validity checking for scalar objects in various scenarios.
13218 One way to look at it is that if this switch is not set, then whenever
13219 any of the other rules in this section use the word “scalar” they
13220 really mean “scalar and not floating-point”.
13221 If @code{-gnatVf} is specified, then validity checking also applies
13222 for floating-point values, and NaNs and infinities are considered invalid,
13223 as well as out-of-range values for constrained types. The exact contexts
13224 in which floating-point values are checked depends on the setting of other
13225 options. For example, @code{-gnatVif} or @code{-gnatVfi}
13226 (the order does not matter) specifies that floating-point parameters of mode
13227 @code{in} should be validity checked.
13228 @end table
13230 @geindex -gnatVi (gcc)
13233 @table @asis
13235 @item @code{-gnatVi}
13237 `Validity checks for `@w{`}in`@w{`} mode parameters.'
13239 Arguments for parameters of mode @code{in} are validity checked in function
13240 and procedure calls at the point of call.
13241 @end table
13243 @geindex -gnatVm (gcc)
13246 @table @asis
13248 @item @code{-gnatVm}
13250 `Validity checks for `@w{`}in out`@w{`} mode parameters.'
13252 Arguments for parameters of mode @code{in out} are validity checked in
13253 procedure calls at the point of call. The @code{'m'} here stands for
13254 modify, since this concerns parameters that can be modified by the call.
13255 Note that there is no specific option to test @code{out} parameters,
13256 but any reference within the subprogram will be tested in the usual
13257 manner, and if an invalid value is copied back, any reference to it
13258 will be subject to validity checking.
13259 @end table
13261 @geindex -gnatVn (gcc)
13264 @table @asis
13266 @item @code{-gnatVn}
13268 `No validity checks.'
13270 This switch turns off all validity checking, including the default checking
13271 for case statements and left hand side subscripts. Note that the use of
13272 the switch @code{-gnatp} suppresses all run-time checks, including
13273 validity checks, and thus implies @code{-gnatVn}. When this switch
13274 is used, it cancels any other @code{-gnatV} previously issued.
13275 @end table
13277 @geindex -gnatVo (gcc)
13280 @table @asis
13282 @item @code{-gnatVo}
13284 `Validity checks for operator and attribute operands.'
13286 Scalar arguments for predefined operators and for attributes are
13287 validity checked.
13288 This includes all operators in package @code{Standard},
13289 the shift operators defined as intrinsic in package @code{Interfaces}
13290 and operands for attributes such as @code{Pos}. Checks are also made
13291 on individual component values for composite comparisons, and on the
13292 expressions in type conversions and qualified expressions. Checks are
13293 also made on explicit ranges using @code{..} (e.g., slices, loops etc).
13294 @end table
13296 @geindex -gnatVp (gcc)
13299 @table @asis
13301 @item @code{-gnatVp}
13303 `Validity checks for parameters.'
13305 This controls the treatment of formal parameters within a subprogram (as
13306 opposed to @code{-gnatVi} and @code{-gnatVm}, which control validity
13307 testing of actual parameters of a call). If either of these call options is
13308 specified, then normally an assumption is made within a subprogram that
13309 the validity of any incoming formal parameters of the corresponding mode(s)
13310 has already been checked at the point of call and does not need rechecking.
13311 If @code{-gnatVp} is set, then this assumption is not made and so their
13312 validity may be checked (or rechecked) within the subprogram. If neither of
13313 the two call-related options is specified, then this switch has no effect.
13314 @end table
13316 @geindex -gnatVr (gcc)
13319 @table @asis
13321 @item @code{-gnatVr}
13323 `Validity checks for function returns.'
13325 The expression in simple @code{return} statements in functions is validity
13326 checked.
13327 @end table
13329 @geindex -gnatVs (gcc)
13332 @table @asis
13334 @item @code{-gnatVs}
13336 `Validity checks for subscripts.'
13338 All subscript expressions are checked for validity, whatever context
13339 they occur in (in default mode some subscripts are not validity checked;
13340 for example, validity checking may be omitted in some cases involving
13341 a read of a component of an array).
13342 @end table
13344 @geindex -gnatVt (gcc)
13347 @table @asis
13349 @item @code{-gnatVt}
13351 `Validity checks for tests.'
13353 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
13354 statements are checked, as well as guard expressions in entry calls.
13355 @end table
13357 The @code{-gnatV} switch may be followed by a string of letters
13358 to turn on a series of validity checking options.
13359 For example, @code{-gnatVcr}
13360 specifies that in addition to the default validity checking, copies and
13361 function return expressions are to be validity checked.
13362 In order to make it easier to specify the desired combination of effects,
13363 the upper case letters @code{CDFIMORST} may
13364 be used to turn off the corresponding lower case option.
13365 Thus @code{-gnatVaM} turns on all validity checking options except for
13366 checking of @code{in out} parameters.
13368 The specification of additional validity checking generates extra code (and
13369 in the case of @code{-gnatVa} the code expansion can be substantial).
13370 However, these additional checks can be very useful in detecting
13371 uninitialized variables, incorrect use of unchecked conversion, and other
13372 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
13373 is useful in conjunction with the extra validity checking, since this
13374 ensures that wherever possible uninitialized variables have invalid values.
13376 See also the pragma @code{Validity_Checks} which allows modification of
13377 the validity checking mode at the program source level, and also allows for
13378 temporary disabling of validity checks.
13380 @node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
13381 @anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{ee}
13382 @subsection Style Checking
13385 @geindex Style checking
13387 @geindex -gnaty (gcc)
13389 The @code{-gnaty} switch causes the compiler to
13390 enforce specified style rules. A limited set of style rules has been used
13391 in writing the GNAT sources themselves. This switch allows user programs
13392 to activate all or some of these checks. If the source program fails a
13393 specified style check, an appropriate message is given, preceded by
13394 the character sequence ‘(style)’. This message does not prevent
13395 successful compilation (unless the @code{-gnatwe} switch is used).
13397 Note that this is by no means intended to be a general facility for
13398 checking arbitrary coding standards. It is simply an embedding of the
13399 style rules we have chosen for the GNAT sources. If you are starting
13400 a project which does not have established style standards, you may
13401 find it useful to adopt the entire set of GNAT coding standards, or
13402 some subset of them.
13405 The string @code{x} is a sequence of letters or digits
13406 indicating the particular style
13407 checks to be performed. The following checks are defined:
13409 @geindex -gnaty[0-9] (gcc)
13412 @table @asis
13414 @item @code{-gnaty0}
13416 `Specify indentation level.'
13418 If a digit from 1-9 appears
13419 in the string after @code{-gnaty}
13420 then proper indentation is checked, with the digit indicating the
13421 indentation level required. A value of zero turns off this style check.
13422 The rule checks that the following constructs start on a column that is
13423 a multiple of the alignment level:
13426 @itemize *
13428 @item 
13429 beginnings of declarations (except record component declarations)
13430 and statements;
13432 @item 
13433 beginnings of the structural components of compound statements;
13435 @item 
13436 @code{end} keyword that completes the declaration of a program unit declaration
13437 or body or that completes a compound statement.
13438 @end itemize
13440 Full line comments must be
13441 aligned with the @code{--} starting on a column that is a multiple of
13442 the alignment level, or they may be aligned the same way as the following
13443 non-blank line (this is useful when full line comments appear in the middle
13444 of a statement, or they may be aligned with the source line on the previous
13445 non-blank line.
13446 @end table
13448 @geindex -gnatya (gcc)
13451 @table @asis
13453 @item @code{-gnatya}
13455 `Check attribute casing.'
13457 Attribute names, including the case of keywords such as @code{digits}
13458 used as attributes names, must be written in mixed case, that is, the
13459 initial letter and any letter following an underscore must be uppercase.
13460 All other letters must be lowercase.
13461 @end table
13463 @geindex -gnatyA (gcc)
13466 @table @asis
13468 @item @code{-gnatyA}
13470 `Use of array index numbers in array attributes.'
13472 When using the array attributes First, Last, Range,
13473 or Length, the index number must be omitted for one-dimensional arrays
13474 and is required for multi-dimensional arrays.
13475 @end table
13477 @geindex -gnatyb (gcc)
13480 @table @asis
13482 @item @code{-gnatyb}
13484 `Blanks not allowed at statement end.'
13486 Trailing blanks are not allowed at the end of statements. The purpose of this
13487 rule, together with h (no horizontal tabs), is to enforce a canonical format
13488 for the use of blanks to separate source tokens.
13489 @end table
13491 @geindex -gnatyB (gcc)
13494 @table @asis
13496 @item @code{-gnatyB}
13498 `Check Boolean operators.'
13500 The use of AND/OR operators is not permitted except in the cases of modular
13501 operands, array operands, and simple stand-alone boolean variables or
13502 boolean constants. In all other cases @code{and then}/@cite{or else} are
13503 required.
13504 @end table
13506 @geindex -gnatyc (gcc)
13509 @table @asis
13511 @item @code{-gnatyc}
13513 `Check comments, double space.'
13515 Comments must meet the following set of rules:
13518 @itemize *
13520 @item 
13521 The @code{--} that starts the column must either start in column one,
13522 or else at least one blank must precede this sequence.
13524 @item 
13525 Comments that follow other tokens on a line must have at least one blank
13526 following the @code{--} at the start of the comment.
13528 @item 
13529 Full line comments must have at least two blanks following the
13530 @code{--} that starts the comment, with the following exceptions.
13532 @item 
13533 A line consisting only of the @code{--} characters, possibly preceded
13534 by blanks is permitted.
13536 @item 
13537 A comment starting with @code{--x} where @code{x} is a special character
13538 is permitted.
13539 This allows proper processing of the output from specialized tools
13540 such as @code{gnatprep} (where @code{--!} is used) and in earlier versions of the SPARK
13541 annotation
13542 language (where @code{--#} is used). For the purposes of this rule, a
13543 special character is defined as being in one of the ASCII ranges
13544 @code{16#21#...16#2F#} or @code{16#3A#...16#3F#}.
13545 Note that this usage is not permitted
13546 in GNAT implementation units (i.e., when @code{-gnatg} is used).
13548 @item 
13549 A line consisting entirely of minus signs, possibly preceded by blanks, is
13550 permitted. This allows the construction of box comments where lines of minus
13551 signs are used to form the top and bottom of the box.
13553 @item 
13554 A comment that starts and ends with @code{--} is permitted as long as at
13555 least one blank follows the initial @code{--}. Together with the preceding
13556 rule, this allows the construction of box comments, as shown in the following
13557 example:
13559 @example
13560 ---------------------------
13561 -- This is a box comment --
13562 -- with two text lines.  --
13563 ---------------------------
13564 @end example
13565 @end itemize
13566 @end table
13568 @geindex -gnatyC (gcc)
13571 @table @asis
13573 @item @code{-gnatyC}
13575 `Check comments, single space.'
13577 This is identical to @code{c} except that only one space
13578 is required following the @code{--} of a comment instead of two.
13579 @end table
13581 @geindex -gnatyd (gcc)
13584 @table @asis
13586 @item @code{-gnatyd}
13588 `Check no DOS line terminators present.'
13590 All lines must be terminated by a single ASCII.LF
13591 character (in particular the DOS line terminator sequence CR/LF is not
13592 allowed).
13593 @end table
13595 @geindex -gnatyD (gcc)
13598 @table @asis
13600 @item @code{-gnatyD}
13602 `Check declared identifiers in mixed case.'
13604 Declared identifiers must be in mixed case, as in
13605 This_Is_An_Identifier. Use -gnatyr in addition to ensure
13606 that references match declarations.
13607 @end table
13609 @geindex -gnatye (gcc)
13612 @table @asis
13614 @item @code{-gnatye}
13616 `Check end/exit labels.'
13618 Optional labels on @code{end} statements ending subprograms and on
13619 @code{exit} statements exiting named loops, are required to be present.
13620 @end table
13622 @geindex -gnatyf (gcc)
13625 @table @asis
13627 @item @code{-gnatyf}
13629 `No form feeds or vertical tabs.'
13631 Neither form feeds nor vertical tab characters are permitted
13632 in the source text.
13633 @end table
13635 @geindex -gnatyg (gcc)
13638 @table @asis
13640 @item @code{-gnatyg}
13642 `GNAT style mode.'
13644 The set of style check switches is set to match that used by the GNAT sources.
13645 This may be useful when developing code that is eventually intended to be
13646 incorporated into GNAT. Currently this is equivalent to
13647 @code{-gnatyydISuxz}) but additional style switches may be added to this
13648 set in the future without advance notice.
13649 @end table
13651 @geindex -gnatyh (gcc)
13654 @table @asis
13656 @item @code{-gnatyh}
13658 `No horizontal tabs.'
13660 Horizontal tab characters are not permitted in the source text.
13661 Together with the b (no blanks at end of line) check, this
13662 enforces a canonical form for the use of blanks to separate
13663 source tokens.
13664 @end table
13666 @geindex -gnatyi (gcc)
13669 @table @asis
13671 @item @code{-gnatyi}
13673 `Check if-then layout.'
13675 The keyword @code{then} must appear either on the same
13676 line as corresponding @code{if}, or on a line on its own, lined
13677 up under the @code{if}.
13678 @end table
13680 @geindex -gnatyI (gcc)
13683 @table @asis
13685 @item @code{-gnatyI}
13687 `check mode IN keywords.'
13689 Mode @code{in} (the default mode) is not
13690 allowed to be given explicitly. @code{in out} is fine,
13691 but not @code{in} on its own.
13692 @end table
13694 @geindex -gnatyk (gcc)
13697 @table @asis
13699 @item @code{-gnatyk}
13701 `Check keyword casing.'
13703 All keywords must be in lower case (with the exception of keywords
13704 such as @code{digits} used as attribute names to which this check
13705 does not apply). A single error is reported for each line breaking
13706 this rule even if multiple casing issues exist on a same line.
13707 @end table
13709 @geindex -gnatyl (gcc)
13712 @table @asis
13714 @item @code{-gnatyl}
13716 `Check layout.'
13718 Layout of statement and declaration constructs must follow the
13719 recommendations in the Ada Reference Manual, as indicated by the
13720 form of the syntax rules. For example an @code{else} keyword must
13721 be lined up with the corresponding @code{if} keyword.
13723 There are two respects in which the style rule enforced by this check
13724 option are more liberal than those in the Ada Reference Manual. First
13725 in the case of record declarations, it is permissible to put the
13726 @code{record} keyword on the same line as the @code{type} keyword, and
13727 then the @code{end} in @code{end record} must line up under @code{type}.
13728 This is also permitted when the type declaration is split on two lines.
13729 For example, any of the following three layouts is acceptable:
13731 @example
13732 type q is record
13733    a : integer;
13734    b : integer;
13735 end record;
13737 type q is
13738    record
13739       a : integer;
13740       b : integer;
13741    end record;
13743 type q is
13744    record
13745       a : integer;
13746       b : integer;
13747 end record;
13748 @end example
13750 Second, in the case of a block statement, a permitted alternative
13751 is to put the block label on the same line as the @code{declare} or
13752 @code{begin} keyword, and then line the @code{end} keyword up under
13753 the block label. For example both the following are permitted:
13755 @example
13756 Block : declare
13757    A : Integer := 3;
13758 begin
13759    Proc (A, A);
13760 end Block;
13762 Block :
13763    declare
13764       A : Integer := 3;
13765    begin
13766       Proc (A, A);
13767    end Block;
13768 @end example
13770 The same alternative format is allowed for loops. For example, both of
13771 the following are permitted:
13773 @example
13774 Clear : while J < 10 loop
13775    A (J) := 0;
13776 end loop Clear;
13778 Clear :
13779    while J < 10 loop
13780       A (J) := 0;
13781    end loop Clear;
13782 @end example
13783 @end table
13785 @geindex -gnatyLnnn (gcc)
13788 @table @asis
13790 @item @code{-gnatyL}
13792 `Set maximum nesting level.'
13794 The maximum level of nesting of constructs (including subprograms, loops,
13795 blocks, packages, and conditionals) may not exceed the given value
13796 `nnn'. A value of zero disconnects this style check.
13797 @end table
13799 @geindex -gnatym (gcc)
13802 @table @asis
13804 @item @code{-gnatym}
13806 `Check maximum line length.'
13808 The length of source lines must not exceed 79 characters, including
13809 any trailing blanks. The value of 79 allows convenient display on an
13810 80 character wide device or window, allowing for possible special
13811 treatment of 80 character lines. Note that this count is of
13812 characters in the source text. This means that a tab character counts
13813 as one character in this count and a wide character sequence counts as
13814 a single character (however many bytes are needed in the encoding).
13815 @end table
13817 @geindex -gnatyMnnn (gcc)
13820 @table @asis
13822 @item @code{-gnatyM}
13824 `Set maximum line length.'
13826 The length of lines must not exceed the
13827 given value `nnn'. The maximum value that can be specified is 32767.
13828 If neither style option for setting the line length is used, then the
13829 default is 255. This also controls the maximum length of lexical elements,
13830 where the only restriction is that they must fit on a single line.
13831 @end table
13833 @geindex -gnatyn (gcc)
13836 @table @asis
13838 @item @code{-gnatyn}
13840 `Check casing of entities in Standard.'
13842 Any identifier from Standard must be cased
13843 to match the presentation in the Ada Reference Manual (for example,
13844 @code{Integer} and @code{ASCII.NUL}).
13845 @end table
13847 @geindex -gnatyN (gcc)
13850 @table @asis
13852 @item @code{-gnatyN}
13854 `Turn off all style checks.'
13856 All style check options are turned off.
13857 @end table
13859 @geindex -gnatyo (gcc)
13862 @table @asis
13864 @item @code{-gnatyo}
13866 `Check order of subprogram bodies.'
13868 All subprogram bodies in a given scope
13869 (e.g., a package body) must be in alphabetical order. The ordering
13870 rule uses normal Ada rules for comparing strings, ignoring casing
13871 of letters, except that if there is a trailing numeric suffix, then
13872 the value of this suffix is used in the ordering (e.g., Junk2 comes
13873 before Junk10).
13874 @end table
13876 @geindex -gnatyO (gcc)
13879 @table @asis
13881 @item @code{-gnatyO}
13883 `Check that overriding subprograms are explicitly marked as such.'
13885 This applies to all subprograms of a derived type that override a primitive
13886 operation of the type, for both tagged and untagged types. In particular,
13887 the declaration of a primitive operation of a type extension that overrides
13888 an inherited operation must carry an overriding indicator. Another case is
13889 the declaration of a function that overrides a predefined operator (such
13890 as an equality operator).
13891 @end table
13893 @geindex -gnatyp (gcc)
13896 @table @asis
13898 @item @code{-gnatyp}
13900 `Check pragma casing.'
13902 Pragma names must be written in mixed case, that is, the
13903 initial letter and any letter following an underscore must be uppercase.
13904 All other letters must be lowercase. An exception is that SPARK_Mode is
13905 allowed as an alternative for Spark_Mode.
13906 @end table
13908 @geindex -gnatyr (gcc)
13911 @table @asis
13913 @item @code{-gnatyr}
13915 `Check references.'
13917 All identifier references must be cased in the same way as the
13918 corresponding declaration. No specific casing style is imposed on
13919 identifiers. The only requirement is for consistency of references
13920 with declarations.
13921 @end table
13923 @geindex -gnatys (gcc)
13926 @table @asis
13928 @item @code{-gnatys}
13930 `Check separate specs.'
13932 Separate declarations (‘specs’) are required for subprograms (a
13933 body is not allowed to serve as its own declaration). The only
13934 exception is that parameterless library level procedures are
13935 not required to have a separate declaration. This exception covers
13936 the most frequent form of main program procedures.
13937 @end table
13939 @geindex -gnatyS (gcc)
13942 @table @asis
13944 @item @code{-gnatyS}
13946 `Check no statements after then/else.'
13948 No statements are allowed
13949 on the same line as a @code{then} or @code{else} keyword following the
13950 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
13951 affected, and a special exception allows a pragma to appear after @code{else}.
13952 @end table
13954 @geindex -gnatyt (gcc)
13957 @table @asis
13959 @item @code{-gnatyt}
13961 `Check token spacing.'
13963 The following token spacing rules are enforced:
13966 @itemize *
13968 @item 
13969 The keywords @code{abs} and @code{not} must be followed by a space.
13971 @item 
13972 The token @code{=>} must be surrounded by spaces.
13974 @item 
13975 The token @code{<>} must be preceded by a space or a left parenthesis.
13977 @item 
13978 Binary operators other than @code{**} must be surrounded by spaces.
13979 There is no restriction on the layout of the @code{**} binary operator.
13981 @item 
13982 Colon must be surrounded by spaces.
13984 @item 
13985 Colon-equal (assignment, initialization) must be surrounded by spaces.
13987 @item 
13988 Comma must be the first non-blank character on the line, or be
13989 immediately preceded by a non-blank character, and must be followed
13990 by a space.
13992 @item 
13993 If the token preceding a left parenthesis ends with a letter or digit, then
13994 a space must separate the two tokens.
13996 @item 
13997 If the token following a right parenthesis starts with a letter or digit, then
13998 a space must separate the two tokens.
14000 @item 
14001 A right parenthesis must either be the first non-blank character on
14002 a line, or it must be preceded by a non-blank character.
14004 @item 
14005 A semicolon must not be preceded by a space, and must not be followed by
14006 a non-blank character.
14008 @item 
14009 A unary plus or minus may not be followed by a space.
14011 @item 
14012 A vertical bar must be surrounded by spaces.
14013 @end itemize
14015 Exactly one blank (and no other white space) must appear between
14016 a @code{not} token and a following @code{in} token.
14017 @end table
14019 @geindex -gnatyu (gcc)
14022 @table @asis
14024 @item @code{-gnatyu}
14026 `Check unnecessary blank lines.'
14028 Unnecessary blank lines are not allowed. A blank line is considered
14029 unnecessary if it appears at the end of the file, or if more than
14030 one blank line occurs in sequence.
14031 @end table
14033 @geindex -gnatyx (gcc)
14036 @table @asis
14038 @item @code{-gnatyx}
14040 `Check extra parentheses.'
14042 Unnecessary extra levels of parentheses (C-style) are not allowed
14043 around conditions (or selection expressions) in @code{if}, @code{while},
14044 @code{case}, and @code{exit} statements, as well as part of ranges.
14045 @end table
14047 @geindex -gnatyy (gcc)
14050 @table @asis
14052 @item @code{-gnatyy}
14054 `Set all standard style check options.'
14056 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
14057 options enabled with the exception of @code{-gnatyB}, @code{-gnatyd},
14058 @code{-gnatyI}, @code{-gnatyLnnn}, @code{-gnatyo}, @code{-gnatyO},
14059 @code{-gnatyS}, @code{-gnatyu}, and @code{-gnatyx}.
14060 @end table
14062 @geindex -gnatyz (gcc)
14065 @table @asis
14067 @item @code{-gnatyz}
14069 `Check extra parentheses (operator precedence).'
14071 Extra levels of parentheses that are not required by operator precedence
14072 rules are flagged. See also @code{-gnatyx}.
14073 @end table
14075 @geindex -gnaty- (gcc)
14078 @table @asis
14080 @item @code{-gnaty-}
14082 `Remove style check options.'
14084 This causes any subsequent options in the string to act as canceling the
14085 corresponding style check option. To cancel maximum nesting level control,
14086 use the @code{L} parameter without any integer value after that, because any
14087 digit following `-' in the parameter string of the @code{-gnaty}
14088 option will be treated as canceling the indentation check. The same is true
14089 for the @code{M} parameter. @code{y} and @code{N} parameters are not
14090 allowed after `-'.
14091 @end table
14093 @geindex -gnaty+ (gcc)
14096 @table @asis
14098 @item @code{-gnaty+}
14100 `Enable style check options.'
14102 This causes any subsequent options in the string to enable the corresponding
14103 style check option. That is, it cancels the effect of a previous -,
14104 if any.
14105 @end table
14107 @c end of switch description (leave this comment to ease automatic parsing for
14109 @c GNAT Studio)
14111 In the above rules, appearing in column one is always permitted, that is,
14112 counts as meeting either a requirement for a required preceding space,
14113 or as meeting a requirement for no preceding space.
14115 Appearing at the end of a line is also always permitted, that is, counts
14116 as meeting either a requirement for a following space, or as meeting
14117 a requirement for no following space.
14119 If any of these style rules is violated, a message is generated giving
14120 details on the violation. The initial characters of such messages are
14121 always ‘@cite{(style)}’. Note that these messages are treated as warning
14122 messages, so they normally do not prevent the generation of an object
14123 file. The @code{-gnatwe} switch can be used to treat warning messages,
14124 including style messages, as fatal errors.
14126 The switch @code{-gnaty} on its own (that is not
14127 followed by any letters or digits) is equivalent
14128 to the use of @code{-gnatyy} as described above, that is all
14129 built-in standard style check options are enabled.
14131 The switch @code{-gnatyN} clears any previously set style checks.
14133 @node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
14134 @anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{f7}@anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{ec}
14135 @subsection Run-Time Checks
14138 @geindex Division by zero
14140 @geindex Access before elaboration
14142 @geindex Checks
14143 @geindex division by zero
14145 @geindex Checks
14146 @geindex access before elaboration
14148 @geindex Checks
14149 @geindex stack overflow checking
14151 By default, the following checks are suppressed: stack overflow
14152 checks, and checks for access before elaboration on subprogram
14153 calls. All other checks, including overflow checks, range checks and
14154 array bounds checks, are turned on by default. The following @code{gcc}
14155 switches refine this default behavior.
14157 @geindex -gnatp (gcc)
14160 @table @asis
14162 @item @code{-gnatp}
14164 @geindex Suppressing checks
14166 @geindex Checks
14167 @geindex suppressing
14169 This switch causes the unit to be compiled
14170 as though @code{pragma Suppress (All_checks)}
14171 had been present in the source. Validity checks are also eliminated (in
14172 other words @code{-gnatp} also implies @code{-gnatVn}.
14173 Use this switch to improve the performance
14174 of the code at the expense of safety in the presence of invalid data or
14175 program bugs.
14177 Note that when checks are suppressed, the compiler is allowed, but not
14178 required, to omit the checking code. If the run-time cost of the
14179 checking code is zero or near-zero, the compiler will generate it even
14180 if checks are suppressed. In particular, if the compiler can prove
14181 that a certain check will necessarily fail, it will generate code to
14182 do an unconditional ‘raise’, even if checks are suppressed. The
14183 compiler warns in this case. Another case in which checks may not be
14184 eliminated is when they are embedded in certain run-time routines such
14185 as math library routines.
14187 Of course, run-time checks are omitted whenever the compiler can prove
14188 that they will not fail, whether or not checks are suppressed.
14190 Note that if you suppress a check that would have failed, program
14191 execution is erroneous, which means the behavior is totally
14192 unpredictable. The program might crash, or print wrong answers, or
14193 do anything else. It might even do exactly what you wanted it to do
14194 (and then it might start failing mysteriously next week or next
14195 year). The compiler will generate code based on the assumption that
14196 the condition being checked is true, which can result in erroneous
14197 execution if that assumption is wrong.
14199 The checks subject to suppression include all the checks defined by the Ada
14200 standard, the additional implementation defined checks @code{Alignment_Check},
14201 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, @code{Container_Checks}, @code{Tampering_Check},
14202 and @code{Validity_Check}, as well as any checks introduced using @code{pragma Check_Name}.
14203 Note that @code{Atomic_Synchronization} is not automatically suppressed by use of this option.
14205 If the code depends on certain checks being active, you can use
14206 pragma @code{Unsuppress} either as a configuration pragma or as
14207 a local pragma to make sure that a specified check is performed
14208 even if @code{gnatp} is specified.
14210 The @code{-gnatp} switch has no effect if a subsequent
14211 @code{-gnat-p} switch appears.
14212 @end table
14214 @geindex -gnat-p (gcc)
14216 @geindex Suppressing checks
14218 @geindex Checks
14219 @geindex suppressing
14221 @geindex Suppress
14224 @table @asis
14226 @item @code{-gnat-p}
14228 This switch cancels the effect of a previous @code{gnatp} switch.
14229 @end table
14231 @geindex -gnato?? (gcc)
14233 @geindex Overflow checks
14235 @geindex Overflow mode
14237 @geindex Check
14238 @geindex overflow
14241 @table @asis
14243 @item @code{-gnato??}
14245 This switch controls the mode used for computing intermediate
14246 arithmetic integer operations, and also enables overflow checking.
14247 For a full description of overflow mode and checking control, see
14248 the ‘Overflow Check Handling in GNAT’ appendix in this
14249 User’s Guide.
14251 Overflow checks are always enabled by this switch. The argument
14252 controls the mode, using the codes
14255 @table @asis
14257 @item `1 = STRICT'
14259 In STRICT mode, intermediate operations are always done using the
14260 base type, and overflow checking ensures that the result is within
14261 the base type range.
14263 @item `2 = MINIMIZED'
14265 In MINIMIZED mode, overflows in intermediate operations are avoided
14266 where possible by using a larger integer type for the computation
14267 (typically @code{Long_Long_Integer}). Overflow checking ensures that
14268 the result fits in this larger integer type.
14270 @item `3 = ELIMINATED'
14272 In ELIMINATED mode, overflows in intermediate operations are avoided
14273 by using multi-precision arithmetic. In this case, overflow checking
14274 has no effect on intermediate operations (since overflow is impossible).
14275 @end table
14277 If two digits are present after @code{-gnato} then the first digit
14278 sets the mode for expressions outside assertions, and the second digit
14279 sets the mode for expressions within assertions. Here assertions is used
14280 in the technical sense (which includes for example precondition and
14281 postcondition expressions).
14283 If one digit is present, the corresponding mode is applicable to both
14284 expressions within and outside assertion expressions.
14286 If no digits are present, the default is to enable overflow checks
14287 and set STRICT mode for both kinds of expressions. This is compatible
14288 with the use of @code{-gnato} in previous versions of GNAT.
14290 @geindex Machine_Overflows
14292 Note that the @code{-gnato??} switch does not affect the code generated
14293 for any floating-point operations; it applies only to integer semantics.
14294 For floating-point, GNAT has the @code{Machine_Overflows}
14295 attribute set to @code{False} and the normal mode of operation is to
14296 generate IEEE NaN and infinite values on overflow or invalid operations
14297 (such as dividing 0.0 by 0.0).
14299 The reason that we distinguish overflow checking from other kinds of
14300 range constraint checking is that a failure of an overflow check, unlike
14301 for example the failure of a range check, can result in an incorrect
14302 value, but cannot cause random memory destruction (like an out of range
14303 subscript), or a wild jump (from an out of range case value). Overflow
14304 checking is also quite expensive in time and space, since in general it
14305 requires the use of double length arithmetic.
14307 Note again that the default is @code{-gnato11} (equivalent to @code{-gnato1}),
14308 so overflow checking is performed in STRICT mode by default.
14309 @end table
14311 @geindex -gnatE (gcc)
14313 @geindex Elaboration checks
14315 @geindex Check
14316 @geindex elaboration
14319 @table @asis
14321 @item @code{-gnatE}
14323 Enables dynamic checks for access-before-elaboration
14324 on subprogram calls and generic instantiations.
14325 Note that @code{-gnatE} is not necessary for safety, because in the
14326 default mode, GNAT ensures statically that the checks would not fail.
14327 For full details of the effect and use of this switch,
14328 @ref{c9,,Compiling with gcc}.
14329 @end table
14331 @geindex -fstack-check (gcc)
14333 @geindex Stack Overflow Checking
14335 @geindex Checks
14336 @geindex stack overflow checking
14339 @table @asis
14341 @item @code{-fstack-check}
14343 Activates stack overflow checking. For full details of the effect and use of
14344 this switch see @ref{e7,,Stack Overflow Checking}.
14345 @end table
14347 @geindex Unsuppress
14349 The setting of these switches only controls the default setting of the
14350 checks. You may modify them using either @code{Suppress} (to remove
14351 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
14352 the program source.
14354 @node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
14355 @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}
14356 @subsection Using @code{gcc} for Syntax Checking
14359 @geindex -gnats (gcc)
14362 @table @asis
14364 @item @code{-gnats}
14366 The @code{s} stands for ‘syntax’.
14368 Run GNAT in syntax checking only mode. For
14369 example, the command
14371 @example
14372 $ gcc -c -gnats x.adb
14373 @end example
14375 compiles file @code{x.adb} in syntax-check-only mode. You can check a
14376 series of files in a single command
14377 , and can use wildcards to specify such a group of files.
14378 Note that you must specify the @code{-c} (compile
14379 only) flag in addition to the @code{-gnats} flag.
14381 You may use other switches in conjunction with @code{-gnats}. In
14382 particular, @code{-gnatl} and @code{-gnatv} are useful to control the
14383 format of any generated error messages.
14385 When the source file is empty or contains only empty lines and/or comments,
14386 the output is a warning:
14388 @example
14389 $ gcc -c -gnats -x ada toto.txt
14390 toto.txt:1:01: warning: empty file, contains no compilation units
14392 @end example
14394 Otherwise, the output is simply the error messages, if any. No object file or
14395 ALI file is generated by a syntax-only compilation. Also, no units other
14396 than the one specified are accessed. For example, if a unit @code{X}
14397 `with's a unit @code{Y}, compiling unit @code{X} in syntax
14398 check only mode does not access the source file containing unit
14399 @code{Y}.
14401 @geindex Multiple units
14402 @geindex syntax checking
14404 Normally, GNAT allows only a single unit in a source file. However, this
14405 restriction does not apply in syntax-check-only mode, and it is possible
14406 to check a file containing multiple compilation units concatenated
14407 together. This is primarily used by the @code{gnatchop} utility
14408 (@ref{1d,,Renaming Files with gnatchop}).
14409 @end table
14411 @node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
14412 @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}
14413 @subsection Using @code{gcc} for Semantic Checking
14416 @geindex -gnatc (gcc)
14419 @table @asis
14421 @item @code{-gnatc}
14423 The @code{c} stands for ‘check’.
14424 Causes the compiler to operate in semantic check mode,
14425 with full checking for all illegalities specified in the
14426 Ada Reference Manual, but without generation of any object code
14427 (no object file is generated).
14429 Because dependent files must be accessed, you must follow the GNAT
14430 semantic restrictions on file structuring to operate in this mode:
14433 @itemize *
14435 @item 
14436 The needed source files must be accessible
14437 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
14439 @item 
14440 Each file must contain only one compilation unit.
14442 @item 
14443 The file name and unit name must match (@ref{3b,,File Naming Rules}).
14444 @end itemize
14446 The output consists of error messages as appropriate. No object file is
14447 generated. An @code{ALI} file is generated for use in the context of
14448 cross-reference tools, but this file is marked as not being suitable
14449 for binding (since no object file is generated).
14450 The checking corresponds exactly to the notion of
14451 legality in the Ada Reference Manual.
14453 Any unit can be compiled in semantics-checking-only mode, including
14454 units that would not normally be compiled (subunits,
14455 and specifications where a separate body is present).
14456 @end table
14458 @node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14459 @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}
14460 @subsection Compiling Different Versions of Ada
14463 The switches described in this section allow you to explicitly specify
14464 the version of the Ada language that your programs are written in.
14465 The default mode is Ada 2012,
14466 but you can also specify Ada 95, Ada 2005 mode, or
14467 indicate Ada 83 compatibility mode.
14469 @geindex Compatibility with Ada 83
14471 @geindex -gnat83 (gcc)
14473 @geindex ACVC
14474 @geindex Ada 83 tests
14476 @geindex Ada 83 mode
14479 @table @asis
14481 @item @code{-gnat83} (Ada 83 Compatibility Mode)
14483 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14484 specifies that the program is to be compiled in Ada 83 mode. With
14485 @code{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14486 semantics where this can be done easily.
14487 It is not possible to guarantee this switch does a perfect
14488 job; some subtle tests, such as are
14489 found in earlier ACVC tests (and that have been removed from the ACATS suite
14490 for Ada 95), might not compile correctly.
14491 Nevertheless, this switch may be useful in some circumstances, for example
14492 where, due to contractual reasons, existing code needs to be maintained
14493 using only Ada 83 features.
14495 With few exceptions (most notably the need to use @code{<>} on
14496 unconstrained 
14497 @geindex Generic formal parameters
14498 generic formal parameters,
14499 the use of the new Ada 95 / Ada 2005
14500 reserved words, and the use of packages
14501 with optional bodies), it is not necessary to specify the
14502 @code{-gnat83} switch when compiling Ada 83 programs, because, with rare
14503 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14504 a correct Ada 83 program is usually also a correct program
14505 in these later versions of the language standard. For further information
14506 please refer to the `Compatibility and Porting Guide' chapter in the
14507 @cite{GNAT Reference Manual}.
14508 @end table
14510 @geindex -gnat95 (gcc)
14512 @geindex Ada 95 mode
14515 @table @asis
14517 @item @code{-gnat95} (Ada 95 mode)
14519 This switch directs the compiler to implement the Ada 95 version of the
14520 language.
14521 Since Ada 95 is almost completely upwards
14522 compatible with Ada 83, Ada 83 programs may generally be compiled using
14523 this switch (see the description of the @code{-gnat83} switch for further
14524 information about Ada 83 mode).
14525 If an Ada 2005 program is compiled in Ada 95 mode,
14526 uses of the new Ada 2005 features will cause error
14527 messages or warnings.
14529 This switch also can be used to cancel the effect of a previous
14530 @code{-gnat83}, @code{-gnat05/2005}, or @code{-gnat12/2012}
14531 switch earlier in the command line.
14532 @end table
14534 @geindex -gnat05 (gcc)
14536 @geindex -gnat2005 (gcc)
14538 @geindex Ada 2005 mode
14541 @table @asis
14543 @item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14545 This switch directs the compiler to implement the Ada 2005 version of the
14546 language, as documented in the official Ada standards document.
14547 Since Ada 2005 is almost completely upwards
14548 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14549 may generally be compiled using this switch (see the description of the
14550 @code{-gnat83} and @code{-gnat95} switches for further
14551 information).
14552 @end table
14554 @geindex -gnat12 (gcc)
14556 @geindex -gnat2012 (gcc)
14558 @geindex Ada 2012 mode
14561 @table @asis
14563 @item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14565 This switch directs the compiler to implement the Ada 2012 version of the
14566 language (also the default).
14567 Since Ada 2012 is almost completely upwards
14568 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14569 Ada 83 and Ada 95 programs
14570 may generally be compiled using this switch (see the description of the
14571 @code{-gnat83}, @code{-gnat95}, and @code{-gnat05/2005} switches
14572 for further information).
14573 @end table
14575 @geindex -gnat2022 (gcc)
14577 @geindex Ada 2022 mode
14580 @table @asis
14582 @item @code{-gnat2022} (Ada 2022 mode)
14584 This switch directs the compiler to implement the Ada 2022 version of the
14585 language.
14586 @end table
14588 @geindex -gnatX0 (gcc)
14590 @geindex Ada language extensions
14592 @geindex GNAT extensions
14595 @table @asis
14597 @item @code{-gnatX0} (Enable GNAT Extensions)
14599 This switch directs the compiler to implement the latest version of the
14600 language (currently Ada 2022) and also to enable certain GNAT implementation
14601 extensions that are not part of any Ada standard. For a full list of these
14602 extensions, see the GNAT reference manual, @code{Pragma Extensions_Allowed}.
14603 @end table
14605 @geindex -gnatX (gcc)
14607 @geindex Ada language extensions
14609 @geindex GNAT extensions
14612 @table @asis
14614 @item @code{-gnatX} (Enable core GNAT Extensions)
14616 This switch is similar to -gnatX0 except that only some, not all, of the
14617 GNAT-defined language extensions are enabled. For a list of the
14618 extensions enabled by this switch, see the GNAT reference manual
14619 @code{Pragma Extensions_Allowed} and the description of that pragma’s
14620 “On” (as opposed to “All”) argument.
14621 @end table
14623 @node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14624 @anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{31}@anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{fd}
14625 @subsection Character Set Control
14628 @geindex -gnati (gcc)
14631 @table @asis
14633 @item @code{-gnati`c'}
14635 Normally GNAT recognizes the Latin-1 character set in source program
14636 identifiers, as described in the Ada Reference Manual.
14637 This switch causes
14638 GNAT to recognize alternate character sets in identifiers. @code{c} is a
14639 single character  indicating the character set, as follows:
14642 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14643 @item
14647 @tab
14649 ISO 8859-1 (Latin-1) identifiers
14651 @item
14655 @tab
14657 ISO 8859-2 (Latin-2) letters allowed in identifiers
14659 @item
14663 @tab
14665 ISO 8859-3 (Latin-3) letters allowed in identifiers
14667 @item
14671 @tab
14673 ISO 8859-4 (Latin-4) letters allowed in identifiers
14675 @item
14679 @tab
14681 ISO 8859-5 (Cyrillic) letters allowed in identifiers
14683 @item
14687 @tab
14689 ISO 8859-15 (Latin-9) letters allowed in identifiers
14691 @item
14695 @tab
14697 IBM PC letters (code page 437) allowed in identifiers
14699 @item
14703 @tab
14705 IBM PC letters (code page 850) allowed in identifiers
14707 @item
14711 @tab
14713 Full upper-half codes allowed in identifiers
14715 @item
14719 @tab
14721 No upper-half codes allowed in identifiers
14723 @item
14727 @tab
14729 Wide-character codes (that is, codes greater than 255)
14730 allowed in identifiers
14732 @end multitable
14735 See @ref{23,,Foreign Language Representation} for full details on the
14736 implementation of these character sets.
14737 @end table
14739 @geindex -gnatW (gcc)
14742 @table @asis
14744 @item @code{-gnatW`e'}
14746 Specify the method of encoding for wide characters.
14747 @code{e} is one of the following:
14750 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14751 @item
14755 @tab
14757 Hex encoding (brackets coding also recognized)
14759 @item
14763 @tab
14765 Upper half encoding (brackets encoding also recognized)
14767 @item
14771 @tab
14773 Shift/JIS encoding (brackets encoding also recognized)
14775 @item
14779 @tab
14781 EUC encoding (brackets encoding also recognized)
14783 @item
14787 @tab
14789 UTF-8 encoding (brackets encoding also recognized)
14791 @item
14795 @tab
14797 Brackets encoding only (default value)
14799 @end multitable
14802 For full details on these encoding
14803 methods see @ref{37,,Wide_Character Encodings}.
14804 Note that brackets coding is always accepted, even if one of the other
14805 options is specified, so for example @code{-gnatW8} specifies that both
14806 brackets and UTF-8 encodings will be recognized. The units that are
14807 with’ed directly or indirectly will be scanned using the specified
14808 representation scheme, and so if one of the non-brackets scheme is
14809 used, it must be used consistently throughout the program. However,
14810 since brackets encoding is always recognized, it may be conveniently
14811 used in standard libraries, allowing these libraries to be used with
14812 any of the available coding schemes.
14814 Note that brackets encoding only applies to program text. Within comments,
14815 brackets are considered to be normal graphic characters, and bracket sequences
14816 are never recognized as wide characters.
14818 If no @code{-gnatW?} parameter is present, then the default
14819 representation is normally Brackets encoding only. However, if the
14820 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14821 byte order mark or BOM for UTF-8), then these three characters are
14822 skipped and the default representation for the file is set to UTF-8.
14824 Note that the wide character representation that is specified (explicitly
14825 or by default) for the main program also acts as the default encoding used
14826 for Wide_Text_IO files if not specifically overridden by a WCEM form
14827 parameter.
14828 @end table
14830 When no @code{-gnatW?} is specified, then characters (other than wide
14831 characters represented using brackets notation) are treated as 8-bit
14832 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14833 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14834 characters in the range 16#00#..16#1F# are not accepted in program text
14835 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14836 in program text, but allowed and ignored in comments. Note in particular
14837 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14838 as an end of line in this default mode. If your source program contains
14839 instances of the NEL character used as a line terminator,
14840 you must use UTF-8 encoding for the whole
14841 source program. In default mode, all lines must be ended by a standard
14842 end of line sequence (CR, CR/LF, or LF).
14844 Note that the convention of simply accepting all upper half characters in
14845 comments means that programs that use standard ASCII for program text, but
14846 UTF-8 encoding for comments are accepted in default mode, providing that the
14847 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14848 This is a common mode for many programs with foreign language comments.
14850 @node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14851 @anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{fe}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{ff}
14852 @subsection File Naming Control
14855 @geindex -gnatk (gcc)
14858 @table @asis
14860 @item @code{-gnatk`n'}
14862 Activates file name ‘krunching’. @code{n}, a decimal integer in the range
14863 1-999, indicates the maximum allowable length of a file name (not
14864 including the @code{.ads} or @code{.adb} extension). The default is not
14865 to enable file name krunching.
14867 For the source file naming rules, @ref{3b,,File Naming Rules}.
14868 @end table
14870 @node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14871 @anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{100}@anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{101}
14872 @subsection Subprogram Inlining Control
14875 @geindex -gnatn (gcc)
14878 @table @asis
14880 @item @code{-gnatn[12]}
14882 The @code{n} here is intended to suggest the first syllable of the word ‘inline’.
14883 GNAT recognizes and processes @code{Inline} pragmas. However, for inlining to
14884 actually occur, optimization must be enabled and, by default, inlining of
14885 subprograms across units is not performed. If you want to additionally
14886 enable inlining of subprograms specified by pragma @code{Inline} across units,
14887 you must also specify this switch.
14889 In the absence of this switch, GNAT does not attempt inlining across units
14890 and does not access the bodies of subprograms for which @code{pragma Inline} is
14891 specified if they are not in the current unit.
14893 You can optionally specify the inlining level: 1 for moderate inlining across
14894 units, which is a good compromise between compilation times and performances
14895 at run time, or 2 for full inlining across units, which may bring about
14896 longer compilation times. If no inlining level is specified, the compiler will
14897 pick it based on the optimization level: 1 for @code{-O1}, @code{-O2} or
14898 @code{-Os} and 2 for @code{-O3}.
14900 If you specify this switch the compiler will access these bodies,
14901 creating an extra source dependency for the resulting object file, and
14902 where possible, the call will be inlined.
14903 For further details on when inlining is possible
14904 see @ref{102,,Inlining of Subprograms}.
14905 @end table
14907 @geindex -gnatN (gcc)
14910 @table @asis
14912 @item @code{-gnatN}
14914 This switch activates front-end inlining which also
14915 generates additional dependencies.
14917 When using a gcc-based back end, then the use of
14918 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
14919 Historically front end inlining was more extensive than the gcc back end
14920 inlining, but that is no longer the case.
14921 @end table
14923 @node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14924 @anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{103}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{104}
14925 @subsection Auxiliary Output Control
14928 @geindex -gnatu (gcc)
14931 @table @asis
14933 @item @code{-gnatu}
14935 Print a list of units required by this compilation on @code{stdout}.
14936 The listing includes all units on which the unit being compiled depends
14937 either directly or indirectly.
14938 @end table
14940 @geindex -pass-exit-codes (gcc)
14943 @table @asis
14945 @item @code{-pass-exit-codes}
14947 If this switch is not used, the exit code returned by @code{gcc} when
14948 compiling multiple files indicates whether all source files have
14949 been successfully used to generate object files or not.
14951 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
14952 exit status and allows an integrated development environment to better
14953 react to a compilation failure. Those exit status are:
14956 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14957 @item
14961 @tab
14963 There was an error in at least one source file.
14965 @item
14969 @tab
14971 At least one source file did not generate an object file.
14973 @item
14977 @tab
14979 The compiler died unexpectedly (internal error for example).
14981 @item
14985 @tab
14987 An object file has been generated for every source file.
14989 @end multitable
14991 @end table
14993 @node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
14994 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{105}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{106}
14995 @subsection Debugging Control
14998 @quotation
15000 @geindex Debugging options
15001 @end quotation
15003 @geindex -gnatd (gcc)
15006 @table @asis
15008 @item @code{-gnatd`x'}
15010 Activate internal debugging switches. @code{x} is a letter or digit, or
15011 string of letters or digits, which specifies the type of debugging
15012 outputs desired. Normally these are used only for internal development
15013 or system debugging purposes. You can find full documentation for these
15014 switches in the body of the @code{Debug} unit in the compiler source
15015 file @code{debug.adb}.
15016 @end table
15018 @geindex -gnatG (gcc)
15021 @table @asis
15023 @item @code{-gnatG[=`nn']}
15025 This switch causes the compiler to generate auxiliary output containing
15026 a pseudo-source listing of the generated expanded code. Like most Ada
15027 compilers, GNAT works by first transforming the high level Ada code into
15028 lower level constructs. For example, tasking operations are transformed
15029 into calls to the tasking run-time routines. A unique capability of GNAT
15030 is to list this expanded code in a form very close to normal Ada source.
15031 This is very useful in understanding the implications of various Ada
15032 usage on the efficiency of the generated code. There are many cases in
15033 Ada (e.g., the use of controlled types), where simple Ada statements can
15034 generate a lot of run-time code. By using @code{-gnatG} you can identify
15035 these cases, and consider whether it may be desirable to modify the coding
15036 approach to improve efficiency.
15038 The optional parameter @code{nn} if present after -gnatG specifies an
15039 alternative maximum line length that overrides the normal default of 72.
15040 This value is in the range 40-999999, values less than 40 being silently
15041 reset to 40. The equal sign is optional.
15043 The format of the output is very similar to standard Ada source, and is
15044 easily understood by an Ada programmer. The following special syntactic
15045 additions correspond to low level features used in the generated code that
15046 do not have any exact analogies in pure Ada source form. The following
15047 is a partial list of these special constructions. See the spec
15048 of package @code{Sprint} in file @code{sprint.ads} for a full list.
15050 @geindex -gnatL (gcc)
15052 If the switch @code{-gnatL} is used in conjunction with
15053 @code{-gnatG}, then the original source lines are interspersed
15054 in the expanded source (as comment lines with the original line number).
15057 @table @asis
15059 @item @code{new @var{xxx} [storage_pool = @var{yyy}]}
15061 Shows the storage pool being used for an allocator.
15063 @item @code{at end @var{procedure-name};}
15065 Shows the finalization (cleanup) procedure for a scope.
15067 @item @code{(if @var{expr} then @var{expr} else @var{expr})}
15069 Conditional expression equivalent to the @code{x?y:z} construction in C.
15071 @item @code{@var{target}^(@var{source})}
15073 A conversion with floating-point truncation instead of rounding.
15075 @item @code{@var{target}?(@var{source})}
15077 A conversion that bypasses normal Ada semantic checking. In particular
15078 enumeration types and fixed-point types are treated simply as integers.
15080 @item @code{@var{target}?^(@var{source})}
15082 Combines the above two cases.
15083 @end table
15085 @code{@var{x} #/ @var{y}}
15087 @code{@var{x} #mod @var{y}}
15089 @code{@var{x} # @var{y}}
15092 @table @asis
15094 @item @code{@var{x} #rem @var{y}}
15096 A division or multiplication of fixed-point values which are treated as
15097 integers without any kind of scaling.
15099 @item @code{free @var{expr} [storage_pool = @var{xxx}]}
15101 Shows the storage pool associated with a @code{free} statement.
15103 @item @code{[subtype or type declaration]}
15105 Used to list an equivalent declaration for an internally generated
15106 type that is referenced elsewhere in the listing.
15108 @item @code{freeze @var{type-name} [@var{actions}]}
15110 Shows the point at which @code{type-name} is frozen, with possible
15111 associated actions to be performed at the freeze point.
15113 @item @code{reference @var{itype}}
15115 Reference (and hence definition) to internal type @code{itype}.
15117 @item @code{@var{function-name}! (@var{arg}, @var{arg}, @var{arg})}
15119 Intrinsic function call.
15121 @item @code{@var{label-name} : label}
15123 Declaration of label @code{labelname}.
15125 @item @code{#$ @var{subprogram-name}}
15127 An implicit call to a run-time support routine
15128 (to meet the requirement of H.3.1(9) in a
15129 convenient manner).
15131 @item @code{@var{expr} && @var{expr} && @var{expr} ... && @var{expr}}
15133 A multiple concatenation (same effect as @code{expr} & @code{expr} &
15134 @code{expr}, but handled more efficiently).
15136 @item @code{[constraint_error]}
15138 Raise the @code{Constraint_Error} exception.
15140 @item @code{@var{expression}'reference}
15142 A pointer to the result of evaluating @{expression@}.
15144 @item @code{@var{target-type}!(@var{source-expression})}
15146 An unchecked conversion of @code{source-expression} to @code{target-type}.
15148 @item @code{[@var{numerator}/@var{denominator}]}
15150 Used to represent internal real literals (that) have no exact
15151 representation in base 2-16 (for example, the result of compile time
15152 evaluation of the expression 1.0/27.0).
15153 @end table
15154 @end table
15156 @geindex -gnatD (gcc)
15159 @table @asis
15161 @item @code{-gnatD[=nn]}
15163 When used in conjunction with @code{-gnatG}, this switch causes
15164 the expanded source, as described above for
15165 @code{-gnatG} to be written to files with names
15166 @code{xxx.dg}, where @code{xxx} is the normal file name,
15167 instead of to the standard output file. For
15168 example, if the source file name is @code{hello.adb}, then a file
15169 @code{hello.adb.dg} will be written.  The debugging
15170 information generated by the @code{gcc} @code{-g} switch
15171 will refer to the generated @code{xxx.dg} file. This allows
15172 you to do source level debugging using the generated code which is
15173 sometimes useful for complex code, for example to find out exactly
15174 which part of a complex construction raised an exception. This switch
15175 also suppresses generation of cross-reference information (see
15176 @code{-gnatx}) since otherwise the cross-reference information
15177 would refer to the @code{.dg} file, which would cause
15178 confusion since this is not the original source file.
15180 Note that @code{-gnatD} actually implies @code{-gnatG}
15181 automatically, so it is not necessary to give both options.
15182 In other words @code{-gnatD} is equivalent to @code{-gnatDG}).
15184 @geindex -gnatL (gcc)
15186 If the switch @code{-gnatL} is used in conjunction with
15187 @code{-gnatDG}, then the original source lines are interspersed
15188 in the expanded source (as comment lines with the original line number).
15190 The optional parameter @code{nn} if present after -gnatD specifies an
15191 alternative maximum line length that overrides the normal default of 72.
15192 This value is in the range 40-999999, values less than 40 being silently
15193 reset to 40. The equal sign is optional.
15194 @end table
15196 @geindex -gnatr (gcc)
15198 @geindex pragma Restrictions
15201 @table @asis
15203 @item @code{-gnatr}
15205 This switch causes pragma Restrictions to be treated as Restriction_Warnings
15206 so that violation of restrictions causes warnings rather than illegalities.
15207 This is useful during the development process when new restrictions are added
15208 or investigated. The switch also causes pragma Profile to be treated as
15209 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
15210 restriction warnings rather than restrictions.
15211 @end table
15213 @geindex -gnatR (gcc)
15216 @table @asis
15218 @item @code{-gnatR[0|1|2|3|4][e][j][m][s]}
15220 This switch controls output from the compiler of a listing showing
15221 representation information for declared types, objects and subprograms.
15222 For @code{-gnatR0}, no information is output (equivalent to omitting
15223 the @code{-gnatR} switch). For @code{-gnatR1} (which is the default,
15224 so @code{-gnatR} with no parameter has the same effect), size and
15225 alignment information is listed for declared array and record types.
15227 For @code{-gnatR2}, size and alignment information is listed for all
15228 declared types and objects. The @code{Linker_Section} is also listed for any
15229 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
15230 latter case occurs for objects of a type for which a @code{Linker_Section}
15231 is set).
15233 For @code{-gnatR3}, symbolic expressions for values that are computed
15234 at run time for records are included. These symbolic expressions have
15235 a mostly obvious format with #n being used to represent the value of the
15236 n’th discriminant. See source files @code{repinfo.ads/adb} in the
15237 GNAT sources for full details on the format of @code{-gnatR3} output.
15239 For @code{-gnatR4}, information for relevant compiler-generated types
15240 is also listed, i.e. when they are structurally part of other declared
15241 types and objects.
15243 If the switch is followed by an @code{e} (e.g. @code{-gnatR2e}), then
15244 extended representation information for record sub-components of records
15245 is included.
15247 If the switch is followed by an @code{m} (e.g. @code{-gnatRm}), then
15248 subprogram conventions and parameter passing mechanisms for all the
15249 subprograms are included.
15251 If the switch is followed by a @code{j} (e.g., @code{-gnatRj}), then
15252 the output is in the JSON data interchange format specified by the
15253 ECMA-404 standard. The semantic description of this JSON output is
15254 available in the specification of the Repinfo unit present in the
15255 compiler sources.
15257 If the switch is followed by an @code{s} (e.g., @code{-gnatR3s}), then
15258 the output is to a file with the name @code{file.rep} where @code{file} is
15259 the name of the corresponding source file, except if @code{j} is also
15260 specified, in which case the file name is @code{file.json}.
15262 Note that it is possible for record components to have zero size. In
15263 this case, the component clause uses an obvious extension of permitted
15264 Ada syntax, for example @code{at 0 range 0 .. -1}.
15265 @end table
15267 @geindex -gnatS (gcc)
15270 @table @asis
15272 @item @code{-gnatS}
15274 The use of the switch @code{-gnatS} for an
15275 Ada compilation will cause the compiler to output a
15276 representation of package Standard in a form very
15277 close to standard Ada. It is not quite possible to
15278 do this entirely in standard Ada (since new
15279 numeric base types cannot be created in standard
15280 Ada), but the output is easily
15281 readable to any Ada programmer, and is useful to
15282 determine the characteristics of target dependent
15283 types in package Standard.
15284 @end table
15286 @geindex -gnatx (gcc)
15289 @table @asis
15291 @item @code{-gnatx}
15293 Normally the compiler generates full cross-referencing information in
15294 the @code{ALI} file. This information is used by a number of tools.
15295 The @code{-gnatx} switch suppresses this information. This saves some space
15296 and may slightly speed up compilation, but means that tools depending
15297 on this information cannot be used.
15298 @end table
15300 @geindex -fgnat-encodings (gcc)
15303 @table @asis
15305 @item @code{-fgnat-encodings=[all|gdb|minimal]}
15307 This switch controls the balance between GNAT encodings and standard DWARF
15308 emitted in the debug information.
15310 Historically, old debug formats like stabs were not powerful enough to
15311 express some Ada types (for instance, variant records or fixed-point types).
15312 To work around this, GNAT introduced proprietary encodings that embed the
15313 missing information (“GNAT encodings”).
15315 Recent versions of the DWARF debug information format are now able to
15316 correctly describe most of these Ada constructs (“standard DWARF”). As
15317 third-party tools started to use this format, GNAT has been enhanced to
15318 generate it. However, most tools (including GDB) are still relying on GNAT
15319 encodings.
15321 To support all tools, GNAT needs to be versatile about the balance between
15322 generation of GNAT encodings and standard DWARF. This is what
15323 @code{-fgnat-encodings} is about.
15326 @itemize *
15328 @item 
15329 @code{=all}: Emit all GNAT encodings, and then emit as much standard DWARF as
15330 possible so it does not conflict with GNAT encodings.
15332 @item 
15333 @code{=gdb}: Emit as much standard DWARF as possible as long as the current
15334 GDB handles it. Emit GNAT encodings for the rest.
15336 @item 
15337 @code{=minimal}: Emit as much standard DWARF as possible and emit GNAT
15338 encodings for the rest.
15339 @end itemize
15340 @end table
15342 @node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
15343 @anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{107}@anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{108}
15344 @subsection Exception Handling Control
15347 GNAT uses two methods for handling exceptions at run time. The
15348 @code{setjmp/longjmp} method saves the context when entering
15349 a frame with an exception handler. Then when an exception is
15350 raised, the context can be restored immediately, without the
15351 need for tracing stack frames. This method provides very fast
15352 exception propagation, but introduces significant overhead for
15353 the use of exception handlers, even if no exception is raised.
15355 The other approach is called ‘zero cost’ exception handling.
15356 With this method, the compiler builds static tables to describe
15357 the exception ranges. No dynamic code is required when entering
15358 a frame containing an exception handler. When an exception is
15359 raised, the tables are used to control a back trace of the
15360 subprogram invocation stack to locate the required exception
15361 handler. This method has considerably poorer performance for
15362 the propagation of exceptions, but there is no overhead for
15363 exception handlers if no exception is raised. Note that in this
15364 mode and in the context of mixed Ada and C/C++ programming,
15365 to propagate an exception through a C/C++ code, the C/C++ code
15366 must be compiled with the @code{-funwind-tables} GCC’s
15367 option.
15369 The following switches may be used to control which of the
15370 two exception handling methods is used.
15372 @geindex --RTS=sjlj (gnatmake)
15375 @table @asis
15377 @item @code{--RTS=sjlj}
15379 This switch causes the setjmp/longjmp run-time (when available) to be used
15380 for exception handling. If the default
15381 mechanism for the target is zero cost exceptions, then
15382 this switch can be used to modify this default, and must be
15383 used for all units in the partition.
15384 This option is rarely used. One case in which it may be
15385 advantageous is if you have an application where exception
15386 raising is common and the overall performance of the
15387 application is improved by favoring exception propagation.
15388 @end table
15390 @geindex --RTS=zcx (gnatmake)
15392 @geindex Zero Cost Exceptions
15395 @table @asis
15397 @item @code{--RTS=zcx}
15399 This switch causes the zero cost approach to be used
15400 for exception handling. If this is the default mechanism for the
15401 target (see below), then this switch is unneeded. If the default
15402 mechanism for the target is setjmp/longjmp exceptions, then
15403 this switch can be used to modify this default, and must be
15404 used for all units in the partition.
15405 This option can only be used if the zero cost approach
15406 is available for the target in use, otherwise it will generate an error.
15407 @end table
15409 The same option @code{--RTS} must be used both for @code{gcc}
15410 and @code{gnatbind}. Passing this option to @code{gnatmake}
15411 (@ref{d0,,Switches for gnatmake}) will ensure the required consistency
15412 through the compilation and binding steps.
15414 @node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
15415 @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}
15416 @subsection Units to Sources Mapping Files
15419 @geindex -gnatem (gcc)
15422 @table @asis
15424 @item @code{-gnatem=`path'}
15426 A mapping file is a way to communicate to the compiler two mappings:
15427 from unit names to file names (without any directory information) and from
15428 file names to path names (with full directory information). These mappings
15429 are used by the compiler to short-circuit the path search.
15431 The use of mapping files is not required for correct operation of the
15432 compiler, but mapping files can improve efficiency, particularly when
15433 sources are read over a slow network connection. In normal operation,
15434 you need not be concerned with the format or use of mapping files,
15435 and the @code{-gnatem} switch is not a switch that you would use
15436 explicitly. It is intended primarily for use by automatic tools such as
15437 @code{gnatmake} running under the project file facility. The
15438 description here of the format of mapping files is provided
15439 for completeness and for possible use by other tools.
15441 A mapping file is a sequence of sets of three lines. In each set, the
15442 first line is the unit name, in lower case, with @code{%s} appended
15443 for specs and @code{%b} appended for bodies; the second line is the
15444 file name; and the third line is the path name.
15446 Example:
15448 @example
15449 main%b
15450 main.2.ada
15451 /gnat/project1/sources/main.2.ada
15452 @end example
15454 When the switch @code{-gnatem} is specified, the compiler will
15455 create in memory the two mappings from the specified file. If there is
15456 any problem (nonexistent file, truncated file or duplicate entries),
15457 no mapping will be created.
15459 Several @code{-gnatem} switches may be specified; however, only the
15460 last one on the command line will be taken into account.
15462 When using a project file, @code{gnatmake} creates a temporary
15463 mapping file and communicates it to the compiler using this switch.
15464 @end table
15466 @node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
15467 @anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{10b}
15468 @subsection Code Generation Control
15471 The GCC technology provides a wide range of target dependent
15472 @code{-m} switches for controlling
15473 details of code generation with respect to different versions of
15474 architectures. This includes variations in instruction sets (e.g.,
15475 different members of the power pc family), and different requirements
15476 for optimal arrangement of instructions (e.g., different members of
15477 the x86 family). The list of available @code{-m} switches may be
15478 found in the GCC documentation.
15480 Use of these @code{-m} switches may in some cases result in improved
15481 code performance.
15483 The GNAT technology is tested and qualified without any
15484 @code{-m} switches,
15485 so generally the most reliable approach is to avoid the use of these
15486 switches. However, we generally expect most of these switches to work
15487 successfully with GNAT, and many customers have reported successful
15488 use of these options.
15490 Our general advice is to avoid the use of @code{-m} switches unless
15491 special needs lead to requirements in this area. In particular,
15492 there is no point in using @code{-m} switches to improve performance
15493 unless you actually see a performance improvement.
15495 @node Linker Switches,Binding with gnatbind,Compiler Switches,Building Executable Programs with GNAT
15496 @anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{10c}@anchor{gnat_ugn/building_executable_programs_with_gnat linker-switches}@anchor{10d}
15497 @section Linker Switches
15500 Linker switches can be specified after @code{-largs} builder switch.
15502 @geindex -fuse-ld=name
15505 @table @asis
15507 @item @code{-fuse-ld=`name'}
15509 Linker to be used. The default is @code{bfd} for @code{ld.bfd}; @code{gold}
15510 (for @code{ld.gold}) and @code{mold} (for @code{ld.mold}) are more
15511 recent and faster alternatives, but only available on GNU/Linux
15512 platforms.
15514 @end table
15516 @node Binding with gnatbind,Linking with gnatlink,Linker Switches,Building Executable Programs with GNAT
15517 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{ca}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{10e}
15518 @section Binding with @code{gnatbind}
15521 @geindex gnatbind
15523 This chapter describes the GNAT binder, @code{gnatbind}, which is used
15524 to bind compiled GNAT objects.
15526 The @code{gnatbind} program performs four separate functions:
15529 @itemize *
15531 @item 
15532 Checks that a program is consistent, in accordance with the rules in
15533 Chapter 10 of the Ada Reference Manual. In particular, error
15534 messages are generated if a program uses inconsistent versions of a
15535 given unit.
15537 @item 
15538 Checks that an acceptable order of elaboration exists for the program
15539 and issues an error message if it cannot find an order of elaboration
15540 that satisfies the rules in Chapter 10 of the Ada Language Manual.
15542 @item 
15543 Generates a main program incorporating the given elaboration order.
15544 This program is a small Ada package (body and spec) that
15545 must be subsequently compiled
15546 using the GNAT compiler. The necessary compilation step is usually
15547 performed automatically by @code{gnatlink}. The two most important
15548 functions of this program
15549 are to call the elaboration routines of units in an appropriate order
15550 and to call the main program.
15552 @item 
15553 Determines the set of object files required by the given main program.
15554 This information is output in the forms of comments in the generated program,
15555 to be read by the @code{gnatlink} utility used to link the Ada application.
15556 @end itemize
15558 @menu
15559 * Running gnatbind:: 
15560 * Switches for gnatbind:: 
15561 * Command-Line Access:: 
15562 * Search Paths for gnatbind:: 
15563 * Examples of gnatbind Usage:: 
15565 @end menu
15567 @node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15568 @anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{10f}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{110}
15569 @subsection Running @code{gnatbind}
15572 The form of the @code{gnatbind} command is
15574 @example
15575 $ gnatbind [ switches ] mainprog[.ali] [ switches ]
15576 @end example
15578 where @code{mainprog.adb} is the Ada file containing the main program
15579 unit body. @code{gnatbind} constructs an Ada
15580 package in two files whose names are
15581 @code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15582 For example, if given the
15583 parameter @code{hello.ali}, for a main program contained in file
15584 @code{hello.adb}, the binder output files would be @code{b~hello.ads}
15585 and @code{b~hello.adb}.
15587 When doing consistency checking, the binder takes into consideration
15588 any source files it can locate. For example, if the binder determines
15589 that the given main program requires the package @code{Pack}, whose
15590 @code{.ALI}
15591 file is @code{pack.ali} and whose corresponding source spec file is
15592 @code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15593 (using the same search path conventions as previously described for the
15594 @code{gcc} command). If it can locate this source file, it checks that
15595 the time stamps
15596 or source checksums of the source and its references to in @code{ALI} files
15597 match. In other words, any @code{ALI} files that mentions this spec must have
15598 resulted from compiling this version of the source file (or in the case
15599 where the source checksums match, a version close enough that the
15600 difference does not matter).
15602 @geindex Source files
15603 @geindex use by binder
15605 The effect of this consistency checking, which includes source files, is
15606 that the binder ensures that the program is consistent with the latest
15607 version of the source files that can be located at bind time. Editing a
15608 source file without compiling files that depend on the source file cause
15609 error messages to be generated by the binder.
15611 For example, suppose you have a main program @code{hello.adb} and a
15612 package @code{P}, from file @code{p.ads} and you perform the following
15613 steps:
15616 @itemize *
15618 @item 
15619 Enter @code{gcc -c hello.adb} to compile the main program.
15621 @item 
15622 Enter @code{gcc -c p.ads} to compile package @code{P}.
15624 @item 
15625 Edit file @code{p.ads}.
15627 @item 
15628 Enter @code{gnatbind hello}.
15629 @end itemize
15631 At this point, the file @code{p.ali} contains an out-of-date time stamp
15632 because the file @code{p.ads} has been edited. The attempt at binding
15633 fails, and the binder generates the following error messages:
15635 @example
15636 error: "hello.adb" must be recompiled ("p.ads" has been modified)
15637 error: "p.ads" has been modified and must be recompiled
15638 @end example
15640 Now both files must be recompiled as indicated, and then the bind can
15641 succeed, generating a main program. You need not normally be concerned
15642 with the contents of this file, but for reference purposes a sample
15643 binder output file is given in @ref{e,,Example of Binder Output File}.
15645 In most normal usage, the default mode of @code{gnatbind} which is to
15646 generate the main package in Ada, as described in the previous section.
15647 In particular, this means that any Ada programmer can read and understand
15648 the generated main program. It can also be debugged just like any other
15649 Ada code provided the @code{-g} switch is used for
15650 @code{gnatbind} and @code{gnatlink}.
15652 @node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15653 @anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{111}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{112}
15654 @subsection Switches for @code{gnatbind}
15657 The following switches are available with @code{gnatbind}; details will
15658 be presented in subsequent sections.
15660 @geindex --version (gnatbind)
15663 @table @asis
15665 @item @code{--version}
15667 Display Copyright and version, then exit disregarding all other options.
15668 @end table
15670 @geindex --help (gnatbind)
15673 @table @asis
15675 @item @code{--help}
15677 If @code{--version} was not used, display usage, then exit disregarding
15678 all other options.
15679 @end table
15681 @geindex -a (gnatbind)
15684 @table @asis
15686 @item @code{-a}
15688 Indicates that, if supported by the platform, the adainit procedure should
15689 be treated as an initialisation routine by the linker (a constructor). This
15690 is intended to be used by the Project Manager to automatically initialize
15691 shared Stand-Alone Libraries.
15692 @end table
15694 @geindex -aO (gnatbind)
15697 @table @asis
15699 @item @code{-aO}
15701 Specify directory to be searched for ALI files.
15702 @end table
15704 @geindex -aI (gnatbind)
15707 @table @asis
15709 @item @code{-aI}
15711 Specify directory to be searched for source file.
15712 @end table
15714 @geindex -A (gnatbind)
15717 @table @asis
15719 @item @code{-A[=`filename']}
15721 Output ALI list (to standard output or to the named file).
15722 @end table
15724 @geindex -b (gnatbind)
15727 @table @asis
15729 @item @code{-b}
15731 Generate brief messages to @code{stderr} even if verbose mode set.
15732 @end table
15734 @geindex -c (gnatbind)
15737 @table @asis
15739 @item @code{-c}
15741 Check only, no generation of binder output file.
15742 @end table
15744 @geindex -dnn[k|m] (gnatbind)
15747 @table @asis
15749 @item @code{-d`nn'[k|m]}
15751 This switch can be used to change the default task stack size value
15752 to a specified size @code{nn}, which is expressed in bytes by default, or
15753 in kilobytes when suffixed with @code{k} or in megabytes when suffixed
15754 with @code{m}.
15755 In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15756 in effect, to completing all task specs with
15758 @example
15759 pragma Storage_Size (nn);
15760 @end example
15762 When they do not already have such a pragma.
15763 @end table
15765 @geindex -D (gnatbind)
15768 @table @asis
15770 @item @code{-D`nn'[k|m]}
15772 Set the default secondary stack size to @code{nn}. The suffix indicates whether
15773 the size is in bytes (no suffix), kilobytes (@code{k} suffix) or megabytes
15774 (@code{m} suffix).
15776 The secondary stack holds objects of unconstrained types that are returned by
15777 functions, for example unconstrained Strings. The size of the secondary stack
15778 can be dynamic or fixed depending on the target.
15780 For most targets, the secondary stack grows on demand and is implemented as
15781 a chain of blocks in the heap. In this case, the default secondary stack size
15782 determines the initial size of the secondary stack for each task and the
15783 smallest amount the secondary stack can grow by.
15785 For Ravenscar, ZFP, and Cert run-times the size of the secondary stack is
15786 fixed. This switch can be used to change the default size of these stacks.
15787 The default secondary stack size can be overridden on a per-task basis if
15788 individual tasks have different secondary stack requirements. This is
15789 achieved through the Secondary_Stack_Size aspect that takes the size of the
15790 secondary stack in bytes.
15791 @end table
15793 @geindex -e (gnatbind)
15796 @table @asis
15798 @item @code{-e}
15800 Output complete list of elaboration-order dependencies.
15801 @end table
15803 @geindex -Ea (gnatbind)
15806 @table @asis
15808 @item @code{-Ea}
15810 Store tracebacks in exception occurrences when the target supports it.
15811 The “a” is for “address”; tracebacks will contain hexadecimal addresses,
15812 unless symbolic tracebacks are enabled.
15814 See also the packages @code{GNAT.Traceback} and
15815 @code{GNAT.Traceback.Symbolic} for more information.
15816 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
15817 @code{gcc} option.
15818 @end table
15820 @geindex -Es (gnatbind)
15823 @table @asis
15825 @item @code{-Es}
15827 Store tracebacks in exception occurrences when the target supports it.
15828 The “s” is for “symbolic”; symbolic tracebacks are enabled.
15829 @end table
15831 @geindex -E (gnatbind)
15834 @table @asis
15836 @item @code{-E}
15838 Currently the same as @code{-Ea}.
15839 @end table
15841 @geindex -f (gnatbind)
15844 @table @asis
15846 @item @code{-f`elab-order'}
15848 Force elaboration order. For further details see @ref{113,,Elaboration Control}
15849 and @ref{f,,Elaboration Order Handling in GNAT}.
15850 @end table
15852 @geindex -F (gnatbind)
15855 @table @asis
15857 @item @code{-F}
15859 Force the checks of elaboration flags. @code{gnatbind} does not normally
15860 generate checks of elaboration flags for the main executable, except when
15861 a Stand-Alone Library is used. However, there are cases when this cannot be
15862 detected by gnatbind. An example is importing an interface of a Stand-Alone
15863 Library through a pragma Import and only specifying through a linker switch
15864 this Stand-Alone Library. This switch is used to guarantee that elaboration
15865 flag checks are generated.
15866 @end table
15868 @geindex -h (gnatbind)
15871 @table @asis
15873 @item @code{-h}
15875 Output usage (help) information.
15876 @end table
15878 @geindex -H (gnatbind)
15881 @table @asis
15883 @item @code{-H}
15885 Legacy elaboration order model enabled. For further details see
15886 @ref{f,,Elaboration Order Handling in GNAT}.
15887 @end table
15889 @geindex -H32 (gnatbind)
15892 @table @asis
15894 @item @code{-H32}
15896 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
15897 For further details see @ref{114,,Dynamic Allocation Control}.
15898 @end table
15900 @geindex -H64 (gnatbind)
15902 @geindex __gnat_malloc
15905 @table @asis
15907 @item @code{-H64}
15909 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
15910 For further details see @ref{114,,Dynamic Allocation Control}.
15912 @geindex -I (gnatbind)
15914 @item @code{-I}
15916 Specify directory to be searched for source and ALI files.
15918 @geindex -I- (gnatbind)
15920 @item @code{-I-}
15922 Do not look for sources in the current directory where @code{gnatbind} was
15923 invoked, and do not look for ALI files in the directory containing the
15924 ALI file named in the @code{gnatbind} command line.
15926 @geindex -k (gnatbind)
15928 @item @code{-k}
15930 Disable checking of elaboration flags. When using @code{-n}
15931 either explicitly or implicitly, @code{-F} is also implied,
15932 unless @code{-k} is used. This switch should be used with care
15933 and you should ensure manually that elaboration routines are not called
15934 twice unintentionally.
15936 @geindex -K (gnatbind)
15938 @item @code{-K}
15940 Give list of linker options specified for link.
15942 @geindex -l (gnatbind)
15944 @item @code{-l}
15946 Output chosen elaboration order.
15948 @geindex -L (gnatbind)
15950 @item @code{-L`xxx'}
15952 Bind the units for library building. In this case the @code{adainit} and
15953 @code{adafinal} procedures (@ref{7e,,Binding with Non-Ada Main Programs})
15954 are renamed to @code{@var{xxx}init} and
15955 @code{@var{xxx}final}.
15956 Implies -n.
15957 (@ref{2a,,GNAT and Libraries}, for more details.)
15959 @geindex -M (gnatbind)
15961 @item @code{-M`xyz'}
15963 Rename generated main program from main to xyz. This option is
15964 supported on cross environments only.
15966 @geindex -m (gnatbind)
15968 @item @code{-m`n'}
15970 Limit number of detected errors or warnings to @code{n}, where @code{n} is
15971 in the range 1..999999. The default value if no switch is
15972 given is 9999. If the number of warnings reaches this limit, then a
15973 message is output and further warnings are suppressed, the bind
15974 continues in this case. If the number of errors reaches this
15975 limit, then a message is output and the bind is abandoned.
15976 A value of zero means that no limit is enforced. The equal
15977 sign is optional.
15979 @geindex -minimal (gnatbind)
15981 @item @code{-minimal}
15983 Generate a binder file suitable for space-constrained applications. When
15984 active, binder-generated objects not required for program operation are no
15985 longer generated. `Warning:' this option comes with the following
15986 limitations:
15989 @itemize *
15991 @item 
15992 Starting the program’s execution in the debugger will cause it to
15993 stop at the start of the @code{main} function instead of the main subprogram.
15994 This can be worked around by manually inserting a breakpoint on that
15995 subprogram and resuming the program’s execution until reaching that breakpoint.
15997 @item 
15998 Programs using GNAT.Compiler_Version will not link.
15999 @end itemize
16001 @geindex -n (gnatbind)
16003 @item @code{-n}
16005 No main program.
16007 @geindex -nostdinc (gnatbind)
16009 @item @code{-nostdinc}
16011 Do not look for sources in the system default directory.
16013 @geindex -nostdlib (gnatbind)
16015 @item @code{-nostdlib}
16017 Do not look for library files in the system default directory.
16019 @geindex --RTS (gnatbind)
16021 @item @code{--RTS=`rts-path'}
16023 Specifies the default location of the run-time library. Same meaning as the
16024 equivalent @code{gnatmake} flag (@ref{d0,,Switches for gnatmake}).
16026 @geindex -o (gnatbind)
16028 @item @code{-o `file'}
16030 Name the output file @code{file} (default is @code{b~`xxx}.adb`).
16031 Note that if this option is used, then linking must be done manually,
16032 gnatlink cannot be used.
16034 @geindex -O (gnatbind)
16036 @item @code{-O[=`filename']}
16038 Output object list (to standard output or to the named file).
16040 @geindex -p (gnatbind)
16042 @item @code{-p}
16044 Pessimistic (worst-case) elaboration order.
16046 @geindex -P (gnatbind)
16048 @item @code{-P}
16050 Generate binder file suitable for CodePeer.
16052 @geindex -R (gnatbind)
16054 @item @code{-R}
16056 Output closure source list, which includes all non-run-time units that are
16057 included in the bind.
16059 @geindex -Ra (gnatbind)
16061 @item @code{-Ra}
16063 Like @code{-R} but the list includes run-time units.
16065 @geindex -s (gnatbind)
16067 @item @code{-s}
16069 Require all source files to be present.
16071 @geindex -S (gnatbind)
16073 @item @code{-S`xxx'}
16075 Specifies the value to be used when detecting uninitialized scalar
16076 objects with pragma Initialize_Scalars.
16077 The @code{xxx} string specified with the switch is one of:
16080 @itemize *
16082 @item 
16083 @code{in} for an invalid value.
16085 If zero is invalid for the discrete type in question,
16086 then the scalar value is set to all zero bits.
16087 For signed discrete types, the largest possible negative value of
16088 the underlying scalar is set (i.e. a one bit followed by all zero bits).
16089 For unsigned discrete types, the underlying scalar value is set to all
16090 one bits. For floating-point types, a NaN value is set
16091 (see body of package System.Scalar_Values for exact values).
16093 @item 
16094 @code{lo} for low value.
16096 If zero is invalid for the discrete type in question,
16097 then the scalar value is set to all zero bits.
16098 For signed discrete types, the largest possible negative value of
16099 the underlying scalar is set (i.e. a one bit followed by all zero bits).
16100 For unsigned discrete types, the underlying scalar value is set to all
16101 zero bits. For floating-point, a small value is set
16102 (see body of package System.Scalar_Values for exact values).
16104 @item 
16105 @code{hi} for high value.
16107 If zero is invalid for the discrete type in question,
16108 then the scalar value is set to all one bits.
16109 For signed discrete types, the largest possible positive value of
16110 the underlying scalar is set (i.e. a zero bit followed by all one bits).
16111 For unsigned discrete types, the underlying scalar value is set to all
16112 one bits. For floating-point, a large value is set
16113 (see body of package System.Scalar_Values for exact values).
16115 @item 
16116 @code{xx} for hex value (two hex digits).
16118 The underlying scalar is set to a value consisting of repeated bytes, whose
16119 value corresponds to the given value. For example if @code{BF} is given,
16120 then a 32-bit scalar value will be set to the bit pattern @code{16#BFBFBFBF#}.
16121 @end itemize
16123 @geindex GNAT_INIT_SCALARS
16125 In addition, you can specify @code{-Sev} to indicate that the value is
16126 to be set at run time. In this case, the program will look for an environment
16127 variable of the form @code{GNAT_INIT_SCALARS=@var{yy}}, where @code{yy} is one
16128 of @code{in/lo/hi/@var{xx}} with the same meanings as above.
16129 If no environment variable is found, or if it does not have a valid value,
16130 then the default is @code{in} (invalid values).
16131 @end table
16133 @geindex -static (gnatbind)
16136 @table @asis
16138 @item @code{-static}
16140 Link against a static GNAT run-time.
16142 @geindex -shared (gnatbind)
16144 @item @code{-shared}
16146 Link against a shared GNAT run-time when available.
16148 @geindex -t (gnatbind)
16150 @item @code{-t}
16152 Tolerate time stamp and other consistency errors.
16154 @geindex -T (gnatbind)
16156 @item @code{-T`n'}
16158 Set the time slice value to @code{n} milliseconds. If the system supports
16159 the specification of a specific time slice value, then the indicated value
16160 is used. If the system does not support specific time slice values, but
16161 does support some general notion of round-robin scheduling, then any
16162 nonzero value will activate round-robin scheduling.
16164 A value of zero is treated specially. It turns off time
16165 slicing, and in addition, indicates to the tasking run-time that the
16166 semantics should match as closely as possible the Annex D
16167 requirements of the Ada RM, and in particular sets the default
16168 scheduling policy to @code{FIFO_Within_Priorities}.
16170 @geindex -u (gnatbind)
16172 @item @code{-u`n'}
16174 Enable dynamic stack usage, with @code{n} results stored and displayed
16175 at program termination. A result is generated when a task
16176 terminates. Results that can’t be stored are displayed on the fly, at
16177 task termination. This option is currently not supported on Itanium
16178 platforms. (See @ref{115,,Dynamic Stack Usage Analysis} for details.)
16180 @geindex -v (gnatbind)
16182 @item @code{-v}
16184 Verbose mode. Write error messages, header, summary output to
16185 @code{stdout}.
16187 @geindex -V (gnatbind)
16189 @item @code{-V`key'=`value'}
16191 Store the given association of @code{key} to @code{value} in the bind environment.
16192 Values stored this way can be retrieved at run time using
16193 @code{GNAT.Bind_Environment}.
16195 @geindex -w (gnatbind)
16197 @item @code{-w`x'}
16199 Warning mode; @code{x} = s/e for suppress/treat as error.
16201 @geindex -Wx (gnatbind)
16203 @item @code{-Wx`e'}
16205 Override default wide character encoding for standard Text_IO files.
16207 @geindex -x (gnatbind)
16209 @item @code{-x}
16211 Exclude source files (check object consistency only).
16213 @geindex -xdr (gnatbind)
16215 @item @code{-xdr}
16217 Use the target-independent XDR protocol for stream oriented attributes
16218 instead of the default implementation which is based on direct binary
16219 representations and is therefore target-and endianness-dependent.
16220 However it does not support 128-bit integer types and the exception
16221 @code{Ada.IO_Exceptions.Device_Error} is raised if any attempt is made
16222 at streaming 128-bit integer types with it.
16224 @geindex -Xnnn (gnatbind)
16226 @item @code{-X`nnn'}
16228 Set default exit status value, normally 0 for POSIX compliance.
16230 @geindex -y (gnatbind)
16232 @item @code{-y}
16234 Enable leap seconds support in @code{Ada.Calendar} and its children.
16236 @geindex -z (gnatbind)
16238 @item @code{-z}
16240 No main subprogram.
16241 @end table
16243 You may obtain this listing of switches by running @code{gnatbind} with
16244 no arguments.
16246 @menu
16247 * Consistency-Checking Modes:: 
16248 * Binder Error Message Control:: 
16249 * Elaboration Control:: 
16250 * Output Control:: 
16251 * Dynamic Allocation Control:: 
16252 * Binding with Non-Ada Main Programs:: 
16253 * Binding Programs with No Main Subprogram:: 
16255 @end menu
16257 @node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
16258 @anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{116}@anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{117}
16259 @subsubsection Consistency-Checking Modes
16262 As described earlier, by default @code{gnatbind} checks
16263 that object files are consistent with one another and are consistent
16264 with any source files it can locate. The following switches control binder
16265 access to sources.
16267 @quotation
16269 @geindex -s (gnatbind)
16270 @end quotation
16273 @table @asis
16275 @item @code{-s}
16277 Require source files to be present. In this mode, the binder must be
16278 able to locate all source files that are referenced, in order to check
16279 their consistency. In normal mode, if a source file cannot be located it
16280 is simply ignored. If you specify this switch, a missing source
16281 file is an error.
16283 @geindex -Wx (gnatbind)
16285 @item @code{-Wx`e'}
16287 Override default wide character encoding for standard Text_IO files.
16288 Normally the default wide character encoding method used for standard
16289 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
16290 the main source input (see description of switch
16291 @code{-gnatWx} for the compiler). The
16292 use of this switch for the binder (which has the same set of
16293 possible arguments) overrides this default as specified.
16295 @geindex -x (gnatbind)
16297 @item @code{-x}
16299 Exclude source files. In this mode, the binder only checks that ALI
16300 files are consistent with one another. Source files are not accessed.
16301 The binder runs faster in this mode, and there is still a guarantee that
16302 the resulting program is self-consistent.
16303 If a source file has been edited since it was last compiled, and you
16304 specify this switch, the binder will not detect that the object
16305 file is out of date with respect to the source file. Note that this is the
16306 mode that is automatically used by @code{gnatmake} because in this
16307 case the checking against sources has already been performed by
16308 @code{gnatmake} in the course of compilation (i.e., before binding).
16309 @end table
16311 @node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
16312 @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}
16313 @subsubsection Binder Error Message Control
16316 The following switches provide control over the generation of error
16317 messages from the binder:
16319 @quotation
16321 @geindex -v (gnatbind)
16322 @end quotation
16325 @table @asis
16327 @item @code{-v}
16329 Verbose mode. In the normal mode, brief error messages are generated to
16330 @code{stderr}. If this switch is present, a header is written
16331 to @code{stdout} and any error messages are directed to @code{stdout}.
16332 All that is written to @code{stderr} is a brief summary message.
16334 @geindex -b (gnatbind)
16336 @item @code{-b}
16338 Generate brief error messages to @code{stderr} even if verbose mode is
16339 specified. This is relevant only when used with the
16340 @code{-v} switch.
16342 @geindex -m (gnatbind)
16344 @item @code{-m`n'}
16346 Limits the number of error messages to @code{n}, a decimal integer in the
16347 range 1-999. The binder terminates immediately if this limit is reached.
16349 @geindex -M (gnatbind)
16351 @item @code{-M`xxx'}
16353 Renames the generated main program from @code{main} to @code{xxx}.
16354 This is useful in the case of some cross-building environments, where
16355 the actual main program is separate from the one generated
16356 by @code{gnatbind}.
16358 @geindex -ws (gnatbind)
16360 @geindex Warnings
16362 @item @code{-ws}
16364 Suppress all warning messages.
16366 @geindex -we (gnatbind)
16368 @item @code{-we}
16370 Treat any warning messages as fatal errors.
16372 @geindex -t (gnatbind)
16374 @geindex Time stamp checks
16375 @geindex in binder
16377 @geindex Binder consistency checks
16379 @geindex Consistency checks
16380 @geindex in binder
16382 @item @code{-t}
16384 The binder performs a number of consistency checks including:
16387 @itemize *
16389 @item 
16390 Check that time stamps of a given source unit are consistent
16392 @item 
16393 Check that checksums of a given source unit are consistent
16395 @item 
16396 Check that consistent versions of @code{GNAT} were used for compilation
16398 @item 
16399 Check consistency of configuration pragmas as required
16400 @end itemize
16402 Normally failure of such checks, in accordance with the consistency
16403 requirements of the Ada Reference Manual, causes error messages to be
16404 generated which abort the binder and prevent the output of a binder
16405 file and subsequent link to obtain an executable.
16407 The @code{-t} switch converts these error messages
16408 into warnings, so that
16409 binding and linking can continue to completion even in the presence of such
16410 errors. The result may be a failed link (due to missing symbols), or a
16411 non-functional executable which has undefined semantics.
16413 @cartouche
16414 @quotation Note 
16415 This means that @code{-t} should be used only in unusual situations,
16416 with extreme care.
16417 @end quotation
16418 @end cartouche
16419 @end table
16421 @node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
16422 @anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{113}@anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{11a}
16423 @subsubsection Elaboration Control
16426 The following switches provide additional control over the elaboration
16427 order. For further details see @ref{f,,Elaboration Order Handling in GNAT}.
16429 @geindex -f (gnatbind)
16432 @table @asis
16434 @item @code{-f`elab-order'}
16436 Force elaboration order.
16438 @code{elab-order} should be the name of a “forced elaboration order file”, that
16439 is, a text file containing library item names, one per line. A name of the
16440 form “some.unit%s” or “some.unit (spec)” denotes the spec of Some.Unit. A
16441 name of the form “some.unit%b” or “some.unit (body)” denotes the body of
16442 Some.Unit. Each pair of lines is taken to mean that there is an elaboration
16443 dependence of the second line on the first. For example, if the file
16444 contains:
16446 @example
16447 this (spec)
16448 this (body)
16449 that (spec)
16450 that (body)
16451 @end example
16453 then the spec of This will be elaborated before the body of This, and the
16454 body of This will be elaborated before the spec of That, and the spec of That
16455 will be elaborated before the body of That. The first and last of these three
16456 dependences are already required by Ada rules, so this file is really just
16457 forcing the body of This to be elaborated before the spec of That.
16459 The given order must be consistent with Ada rules, or else @code{gnatbind} will
16460 give elaboration cycle errors. For example, if you say x (body) should be
16461 elaborated before x (spec), there will be a cycle, because Ada rules require
16462 x (spec) to be elaborated before x (body); you can’t have the spec and body
16463 both elaborated before each other.
16465 If you later add “with That;” to the body of This, there will be a cycle, in
16466 which case you should erase either “this (body)” or “that (spec)” from the
16467 above forced elaboration order file.
16469 Blank lines and Ada-style comments are ignored. Unit names that do not exist
16470 in the program are ignored. Units in the GNAT predefined library are also
16471 ignored.
16472 @end table
16474 @geindex -p (gnatbind)
16477 @table @asis
16479 @item @code{-p}
16481 Pessimistic elaboration order
16483 This switch is only applicable to the pre-20.x legacy elaboration models.
16484 The post-20.x elaboration model uses a more informed approach of ordering
16485 the units.
16487 Normally the binder attempts to choose an elaboration order that is likely to
16488 minimize the likelihood of an elaboration order error resulting in raising a
16489 @code{Program_Error} exception. This switch reverses the action of the binder,
16490 and requests that it deliberately choose an order that is likely to maximize
16491 the likelihood of an elaboration error. This is useful in ensuring
16492 portability and avoiding dependence on accidental fortuitous elaboration
16493 ordering.
16495 Normally it only makes sense to use the @code{-p} switch if dynamic
16496 elaboration checking is used (@code{-gnatE} switch used for compilation).
16497 This is because in the default static elaboration mode, all necessary
16498 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
16499 These implicit pragmas are still respected by the binder in @code{-p}
16500 mode, so a safe elaboration order is assured.
16502 Note that @code{-p} is not intended for production use; it is more for
16503 debugging/experimental use.
16504 @end table
16506 @node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
16507 @anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{11b}@anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{11c}
16508 @subsubsection Output Control
16511 The following switches allow additional control over the output
16512 generated by the binder.
16514 @quotation
16516 @geindex -c (gnatbind)
16517 @end quotation
16520 @table @asis
16522 @item @code{-c}
16524 Check only. Do not generate the binder output file. In this mode the
16525 binder performs all error checks but does not generate an output file.
16527 @geindex -e (gnatbind)
16529 @item @code{-e}
16531 Output complete list of elaboration-order dependencies, showing the
16532 reason for each dependency. This output can be rather extensive but may
16533 be useful in diagnosing problems with elaboration order. The output is
16534 written to @code{stdout}.
16536 @geindex -h (gnatbind)
16538 @item @code{-h}
16540 Output usage information. The output is written to @code{stdout}.
16542 @geindex -K (gnatbind)
16544 @item @code{-K}
16546 Output linker options to @code{stdout}. Includes library search paths,
16547 contents of pragmas Ident and Linker_Options, and libraries added
16548 by @code{gnatbind}.
16550 @geindex -l (gnatbind)
16552 @item @code{-l}
16554 Output chosen elaboration order. The output is written to @code{stdout}.
16556 @geindex -O (gnatbind)
16558 @item @code{-O}
16560 Output full names of all the object files that must be linked to provide
16561 the Ada component of the program. The output is written to @code{stdout}.
16562 This list includes the files explicitly supplied and referenced by the user
16563 as well as implicitly referenced run-time unit files. The latter are
16564 omitted if the corresponding units reside in shared libraries. The
16565 directory names for the run-time units depend on the system configuration.
16567 @geindex -o (gnatbind)
16569 @item @code{-o `file'}
16571 Set name of output file to @code{file} instead of the normal
16572 @code{b~`mainprog}.adb` default. Note that @code{file} denote the Ada
16573 binder generated body filename.
16574 Note that if this option is used, then linking must be done manually.
16575 It is not possible to use gnatlink in this case, since it cannot locate
16576 the binder file.
16578 @geindex -r (gnatbind)
16580 @item @code{-r}
16582 Generate list of @code{pragma Restrictions} that could be applied to
16583 the current unit. This is useful for code audit purposes, and also may
16584 be used to improve code generation in some cases.
16585 @end table
16587 @node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
16588 @anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{114}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{11d}
16589 @subsubsection Dynamic Allocation Control
16592 The heap control switches – @code{-H32} and @code{-H64} –
16593 determine whether dynamic allocation uses 32-bit or 64-bit memory.
16594 They only affect compiler-generated allocations via @code{__gnat_malloc};
16595 explicit calls to @code{malloc} and related functions from the C
16596 run-time library are unaffected.
16599 @table @asis
16601 @item @code{-H32}
16603 Allocate memory on 32-bit heap
16605 @item @code{-H64}
16607 Allocate memory on 64-bit heap.  This is the default
16608 unless explicitly overridden by a @code{'Size} clause on the access type.
16609 @end table
16611 These switches are only effective on VMS platforms.
16613 @node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
16614 @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}
16615 @subsubsection Binding with Non-Ada Main Programs
16618 The description so far has assumed that the main
16619 program is in Ada, and that the task of the binder is to generate a
16620 corresponding function @code{main} that invokes this Ada main
16621 program. GNAT also supports the building of executable programs where
16622 the main program is not in Ada, but some of the called routines are
16623 written in Ada and compiled using GNAT (@ref{2c,,Mixed Language Programming}).
16624 The following switch is used in this situation:
16626 @quotation
16628 @geindex -n (gnatbind)
16629 @end quotation
16632 @table @asis
16634 @item @code{-n}
16636 No main program. The main program is not in Ada.
16637 @end table
16639 In this case, most of the functions of the binder are still required,
16640 but instead of generating a main program, the binder generates a file
16641 containing the following callable routines:
16643 @quotation
16645 @geindex adainit
16648 @table @asis
16650 @item @code{adainit}
16652 You must call this routine to initialize the Ada part of the program by
16653 calling the necessary elaboration routines. A call to @code{adainit} is
16654 required before the first call to an Ada subprogram.
16656 Note that it is assumed that the basic execution environment must be setup
16657 to be appropriate for Ada execution at the point where the first Ada
16658 subprogram is called. In particular, if the Ada code will do any
16659 floating-point operations, then the FPU must be setup in an appropriate
16660 manner. For the case of the x86, for example, full precision mode is
16661 required. The procedure GNAT.Float_Control.Reset may be used to ensure
16662 that the FPU is in the right state.
16663 @end table
16665 @geindex adafinal
16668 @table @asis
16670 @item @code{adafinal}
16672 You must call this routine to perform any library-level finalization
16673 required by the Ada subprograms. A call to @code{adafinal} is required
16674 after the last call to an Ada subprogram, and before the program
16675 terminates.
16676 @end table
16677 @end quotation
16679 @geindex -n (gnatbind)
16681 @geindex Binder
16682 @geindex multiple input files
16684 If the @code{-n} switch
16685 is given, more than one ALI file may appear on
16686 the command line for @code{gnatbind}. The normal @code{closure}
16687 calculation is performed for each of the specified units. Calculating
16688 the closure means finding out the set of units involved by tracing
16689 `with' references. The reason it is necessary to be able to
16690 specify more than one ALI file is that a given program may invoke two or
16691 more quite separate groups of Ada units.
16693 The binder takes the name of its output file from the last specified ALI
16694 file, unless overridden by the use of the @code{-o file}.
16696 @geindex -o (gnatbind)
16698 The output is an Ada unit in source form that can be compiled with GNAT.
16699 This compilation occurs automatically as part of the @code{gnatlink}
16700 processing.
16702 Currently the GNAT run-time requires a FPU using 80 bits mode
16703 precision. Under targets where this is not the default it is required to
16704 call GNAT.Float_Control.Reset before using floating point numbers (this
16705 include float computation, float input and output) in the Ada code. A
16706 side effect is that this could be the wrong mode for the foreign code
16707 where floating point computation could be broken after this call.
16709 @node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16710 @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}
16711 @subsubsection Binding Programs with No Main Subprogram
16714 It is possible to have an Ada program which does not have a main
16715 subprogram. This program will call the elaboration routines of all the
16716 packages, then the finalization routines.
16718 The following switch is used to bind programs organized in this manner:
16720 @quotation
16722 @geindex -z (gnatbind)
16723 @end quotation
16726 @table @asis
16728 @item @code{-z}
16730 Normally the binder checks that the unit name given on the command line
16731 corresponds to a suitable main subprogram. When this switch is used,
16732 a list of ALI files can be given, and the execution of the program
16733 consists of elaboration of these units in an appropriate order. Note
16734 that the default wide character encoding method for standard Text_IO
16735 files is always set to Brackets if this switch is set (you can use
16736 the binder switch
16737 @code{-Wx} to override this default).
16738 @end table
16740 @node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16741 @anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{121}@anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{122}
16742 @subsection Command-Line Access
16745 The package @code{Ada.Command_Line} provides access to the command-line
16746 arguments and program name. In order for this interface to operate
16747 correctly, the two variables
16749 @example
16750 int gnat_argc;
16751 char **gnat_argv;
16752 @end example
16754 @geindex gnat_argv
16756 @geindex gnat_argc
16758 are declared in one of the GNAT library routines. These variables must
16759 be set from the actual @code{argc} and @code{argv} values passed to the
16760 main program. With no `n' present, @code{gnatbind}
16761 generates the C main program to automatically set these variables.
16762 If the `n' switch is used, there is no automatic way to
16763 set these variables. If they are not set, the procedures in
16764 @code{Ada.Command_Line} will not be available, and any attempt to use
16765 them will raise @code{Constraint_Error}. If command line access is
16766 required, your main program must set @code{gnat_argc} and
16767 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
16770 @node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16771 @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}
16772 @subsection Search Paths for @code{gnatbind}
16775 The binder takes the name of an ALI file as its argument and needs to
16776 locate source files as well as other ALI files to verify object consistency.
16778 For source files, it follows exactly the same search rules as @code{gcc}
16779 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16780 directories searched are:
16783 @itemize *
16785 @item 
16786 The directory containing the ALI file named in the command line, unless
16787 the switch @code{-I-} is specified.
16789 @item 
16790 All directories specified by @code{-I}
16791 switches on the @code{gnatbind}
16792 command line, in the order given.
16794 @geindex ADA_PRJ_OBJECTS_FILE
16796 @item 
16797 Each of the directories listed in the text file whose name is given
16798 by the 
16799 @geindex ADA_PRJ_OBJECTS_FILE
16800 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16801 @code{ADA_PRJ_OBJECTS_FILE} environment variable.
16803 @geindex ADA_PRJ_OBJECTS_FILE
16804 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16805 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16806 driver when project files are used. It should not normally be set
16807 by other means.
16809 @geindex ADA_OBJECTS_PATH
16811 @item 
16812 Each of the directories listed in the value of the
16813 @geindex ADA_OBJECTS_PATH
16814 @geindex environment variable; ADA_OBJECTS_PATH
16815 @code{ADA_OBJECTS_PATH} environment variable.
16816 Construct this value
16817 exactly as the 
16818 @geindex PATH
16819 @geindex environment variable; PATH
16820 @code{PATH} environment variable: a list of directory
16821 names separated by colons (semicolons when working with the NT version
16822 of GNAT).
16824 @item 
16825 The content of the @code{ada_object_path} file which is part of the GNAT
16826 installation tree and is used to store standard libraries such as the
16827 GNAT Run-Time Library (RTL) unless the switch @code{-nostdlib} is
16828 specified. See @ref{72,,Installing a library}
16829 @end itemize
16831 @geindex -I (gnatbind)
16833 @geindex -aI (gnatbind)
16835 @geindex -aO (gnatbind)
16837 In the binder the switch @code{-I}
16838 is used to specify both source and
16839 library file paths. Use @code{-aI}
16840 instead if you want to specify
16841 source paths only, and @code{-aO}
16842 if you want to specify library paths
16843 only. This means that for the binder
16844 @code{-I`dir'} is equivalent to
16845 @code{-aI`dir'}
16846 @code{-aO``dir'}.
16847 The binder generates the bind file (a C language source file) in the
16848 current working directory.
16850 @geindex Ada
16852 @geindex System
16854 @geindex Interfaces
16856 @geindex GNAT
16858 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
16859 children make up the GNAT Run-Time Library, together with the package
16860 GNAT and its children, which contain a set of useful additional
16861 library functions provided by GNAT. The sources for these units are
16862 needed by the compiler and are kept together in one directory. The ALI
16863 files and object files generated by compiling the RTL are needed by the
16864 binder and the linker and are kept together in one directory, typically
16865 different from the directory containing the sources. In a normal
16866 installation, you need not specify these directory names when compiling
16867 or binding. Either the environment variables or the built-in defaults
16868 cause these files to be found.
16870 Besides simplifying access to the RTL, a major use of search paths is
16871 in compiling sources from multiple directories. This can make
16872 development environments much more flexible.
16874 @node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16875 @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}
16876 @subsection Examples of @code{gnatbind} Usage
16879 Here are some examples of @code{gnatbind} invocations:
16881 @quotation
16883 @example
16884 gnatbind hello
16885 @end example
16887 The main program @code{Hello} (source program in @code{hello.adb}) is
16888 bound using the standard switch settings. The generated main program is
16889 @code{b~hello.adb}. This is the normal, default use of the binder.
16891 @example
16892 gnatbind hello -o mainprog.adb
16893 @end example
16895 The main program @code{Hello} (source program in @code{hello.adb}) is
16896 bound using the standard switch settings. The generated main program is
16897 @code{mainprog.adb} with the associated spec in
16898 @code{mainprog.ads}. Note that you must specify the body here not the
16899 spec. Note that if this option is used, then linking must be done manually,
16900 since gnatlink will not be able to find the generated file.
16901 @end quotation
16903 @node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16904 @anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{126}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{cb}
16905 @section Linking with @code{gnatlink}
16908 @geindex gnatlink
16910 This chapter discusses @code{gnatlink}, a tool that links
16911 an Ada program and builds an executable file. This utility
16912 invokes the system linker (via the @code{gcc} command)
16913 with a correct list of object files and library references.
16914 @code{gnatlink} automatically determines the list of files and
16915 references for the Ada part of a program. It uses the binder file
16916 generated by the @code{gnatbind} to determine this list.
16918 @menu
16919 * Running gnatlink:: 
16920 * Switches for gnatlink:: 
16922 @end menu
16924 @node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16925 @anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{127}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{128}
16926 @subsection Running @code{gnatlink}
16929 The form of the @code{gnatlink} command is
16931 @example
16932 $ gnatlink [ switches ] mainprog [.ali]
16933            [ non-Ada objects ] [ linker options ]
16934 @end example
16936 The arguments of @code{gnatlink} (switches, main @code{ALI} file,
16937 non-Ada objects
16938 or linker options) may be in any order, provided that no non-Ada object may
16939 be mistaken for a main @code{ALI} file.
16940 Any file name @code{F} without the @code{.ali}
16941 extension will be taken as the main @code{ALI} file if a file exists
16942 whose name is the concatenation of @code{F} and @code{.ali}.
16944 @code{mainprog.ali} references the ALI file of the main program.
16945 The @code{.ali} extension of this file can be omitted. From this
16946 reference, @code{gnatlink} locates the corresponding binder file
16947 @code{b~mainprog.adb} and, using the information in this file along
16948 with the list of non-Ada objects and linker options, constructs a
16949 linker command file to create the executable.
16951 The arguments other than the @code{gnatlink} switches and the main
16952 @code{ALI} file are passed to the linker uninterpreted.
16953 They typically include the names of
16954 object files for units written in other languages than Ada and any library
16955 references required to resolve references in any of these foreign language
16956 units, or in @code{Import} pragmas in any Ada units.
16958 @code{linker options} is an optional list of linker specific
16959 switches.
16960 The default linker called by gnatlink is @code{gcc} which in
16961 turn calls the appropriate system linker.
16963 One useful option for the linker is @code{-s}: it reduces the size of the
16964 executable by removing all symbol table and relocation information from the
16965 executable.
16967 Standard options for the linker such as @code{-lmy_lib} or
16968 @code{-Ldir} can be added as is.
16969 For options that are not recognized by
16970 @code{gcc} as linker options, use the @code{gcc} switches
16971 @code{-Xlinker} or @code{-Wl,}.
16973 Refer to the GCC documentation for
16974 details.
16976 Here is an example showing how to generate a linker map:
16978 @example
16979 $ gnatlink my_prog -Wl,-Map,MAPFILE
16980 @end example
16982 Using @code{linker options} it is possible to set the program stack and
16983 heap size.
16984 See @ref{129,,Setting Stack Size from gnatlink} and
16985 @ref{12a,,Setting Heap Size from gnatlink}.
16987 @code{gnatlink} determines the list of objects required by the Ada
16988 program and prepends them to the list of objects passed to the linker.
16989 @code{gnatlink} also gathers any arguments set by the use of
16990 @code{pragma Linker_Options} and adds them to the list of arguments
16991 presented to the linker.
16993 @node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
16994 @anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{12b}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{12c}
16995 @subsection Switches for @code{gnatlink}
16998 The following switches are available with the @code{gnatlink} utility:
17000 @geindex --version (gnatlink)
17003 @table @asis
17005 @item @code{--version}
17007 Display Copyright and version, then exit disregarding all other options.
17008 @end table
17010 @geindex --help (gnatlink)
17013 @table @asis
17015 @item @code{--help}
17017 If @code{--version} was not used, display usage, then exit disregarding
17018 all other options.
17019 @end table
17021 @geindex Command line length
17023 @geindex -f (gnatlink)
17026 @table @asis
17028 @item @code{-f}
17030 On some targets, the command line length is limited, and @code{gnatlink}
17031 will generate a separate file for the linker if the list of object files
17032 is too long.
17033 The @code{-f} switch forces this file
17034 to be generated even if
17035 the limit is not exceeded. This is useful in some cases to deal with
17036 special situations where the command line length is exceeded.
17037 @end table
17039 @geindex Debugging information
17040 @geindex including
17042 @geindex -g (gnatlink)
17045 @table @asis
17047 @item @code{-g}
17049 The option to include debugging information causes the Ada bind file (in
17050 other words, @code{b~mainprog.adb}) to be compiled with @code{-g}.
17051 In addition, the binder does not delete the @code{b~mainprog.adb},
17052 @code{b~mainprog.o} and @code{b~mainprog.ali} files.
17053 Without @code{-g}, the binder removes these files by default.
17054 @end table
17056 @geindex -n (gnatlink)
17059 @table @asis
17061 @item @code{-n}
17063 Do not compile the file generated by the binder. This may be used when
17064 a link is rerun with different options, but there is no need to recompile
17065 the binder file.
17066 @end table
17068 @geindex -v (gnatlink)
17071 @table @asis
17073 @item @code{-v}
17075 Verbose mode. Causes additional information to be output, including a full
17076 list of the included object files.
17077 This switch option is most useful when you want
17078 to see what set of object files are being used in the link step.
17079 @end table
17081 @geindex -v -v (gnatlink)
17084 @table @asis
17086 @item @code{-v -v}
17088 Very verbose mode. Requests that the compiler operate in verbose mode when
17089 it compiles the binder file, and that the system linker run in verbose mode.
17090 @end table
17092 @geindex -o (gnatlink)
17095 @table @asis
17097 @item @code{-o `exec-name'}
17099 @code{exec-name} specifies an alternate name for the generated
17100 executable program. If this switch is omitted, the executable has the same
17101 name as the main unit. For example, @code{gnatlink try.ali} creates
17102 an executable called @code{try}.
17103 @end table
17105 @geindex -B (gnatlink)
17108 @table @asis
17110 @item @code{-B`dir'}
17112 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
17113 from @code{dir} instead of the default location. Only use this switch
17114 when multiple versions of the GNAT compiler are available.
17115 See the @code{Directory Options} section in @cite{The_GNU_Compiler_Collection}
17116 for further details. You would normally use the @code{-b} or
17117 @code{-V} switch instead.
17118 @end table
17120 @geindex -M (gnatlink)
17123 @table @asis
17125 @item @code{-M}
17127 When linking an executable, create a map file. The name of the map file
17128 has the same name as the executable with extension “.map”.
17129 @end table
17131 @geindex -M= (gnatlink)
17134 @table @asis
17136 @item @code{-M=`mapfile'}
17138 When linking an executable, create a map file. The name of the map file is
17139 @code{mapfile}.
17140 @end table
17142 @geindex --GCC=compiler_name (gnatlink)
17145 @table @asis
17147 @item @code{--GCC=`compiler_name'}
17149 Program used for compiling the binder file. The default is
17150 @code{gcc}. You need to use quotes around @code{compiler_name} if
17151 @code{compiler_name} contains spaces or other separator characters.
17152 As an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to
17153 use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
17154 inserted after your command name. Thus in the above example the compiler
17155 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
17156 A limitation of this syntax is that the name and path name of the executable
17157 itself must not include any embedded spaces. If the compiler executable is
17158 different from the default one (gcc or <prefix>-gcc), then the back-end
17159 switches in the ALI file are not used to compile the binder generated source.
17160 For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
17161 switches will be used for @code{--GCC="gcc -gnatv"}. If several
17162 @code{--GCC=compiler_name} are used, only the last @code{compiler_name}
17163 is taken into account. However, all the additional switches are also taken
17164 into account. Thus,
17165 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
17166 @code{--GCC="bar -x -y -z -t"}.
17167 @end table
17169 @geindex --LINK= (gnatlink)
17172 @table @asis
17174 @item @code{--LINK=`name'}
17176 @code{name} is the name of the linker to be invoked. This is especially
17177 useful in mixed language programs since languages such as C++ require
17178 their own linker to be used. When this switch is omitted, the default
17179 name for the linker is @code{gcc}. When this switch is used, the
17180 specified linker is called instead of @code{gcc} with exactly the same
17181 parameters that would have been passed to @code{gcc} so if the desired
17182 linker requires different parameters it is necessary to use a wrapper
17183 script that massages the parameters before invoking the real linker. It
17184 may be useful to control the exact invocation by using the verbose
17185 switch.
17186 @end table
17188 @node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
17189 @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}
17190 @section Using the GNU @code{make} Utility
17193 @geindex make (GNU)
17194 @geindex GNU make
17196 This chapter offers some examples of makefiles that solve specific
17197 problems. It does not explain how to write a makefile, nor does it try to replace the
17198 @code{gnatmake} utility (@ref{c8,,Building with gnatmake}).
17200 All the examples in this section are specific to the GNU version of
17201 make. Although @code{make} is a standard utility, and the basic language
17202 is the same, these examples use some advanced features found only in
17203 @code{GNU make}.
17205 @menu
17206 * Using gnatmake in a Makefile:: 
17207 * Automatically Creating a List of Directories:: 
17208 * Generating the Command Line Switches:: 
17209 * Overcoming Command Line Length Limits:: 
17211 @end menu
17213 @node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
17214 @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}
17215 @subsection Using gnatmake in a Makefile
17218 @c index makefile (GNU make)
17220 Complex project organizations can be handled in a very powerful way by
17221 using GNU make combined with gnatmake. For instance, here is a Makefile
17222 which allows you to build each subsystem of a big project into a separate
17223 shared library. Such a makefile allows you to significantly reduce the link
17224 time of very big applications while maintaining full coherence at
17225 each step of the build process.
17227 The list of dependencies are handled automatically by
17228 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
17229 the appropriate directories.
17231 Note that you should also read the example on how to automatically
17232 create the list of directories
17233 (@ref{130,,Automatically Creating a List of Directories})
17234 which might help you in case your project has a lot of subdirectories.
17236 @example
17237 ## This Makefile is intended to be used with the following directory
17238 ## configuration:
17239 ##  - The sources are split into a series of csc (computer software components)
17240 ##    Each of these csc is put in its own directory.
17241 ##    Their name are referenced by the directory names.
17242 ##    They will be compiled into shared library (although this would also work
17243 ##    with static libraries)
17244 ##  - The main program (and possibly other packages that do not belong to any
17245 ##    csc) is put in the top level directory (where the Makefile is).
17246 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17247 ##                    \\_ second_csc (sources) __ lib (will contain the library)
17248 ##                    \\_ ...
17249 ## Although this Makefile is build for shared library, it is easy to modify
17250 ## to build partial link objects instead (modify the lines with -shared and
17251 ## gnatlink below)
17253 ## With this makefile, you can change any file in the system or add any new
17254 ## file, and everything will be recompiled correctly (only the relevant shared
17255 ## objects will be recompiled, and the main program will be re-linked).
17257 # The list of computer software component for your project. This might be
17258 # generated automatically.
17259 CSC_LIST=aa bb cc
17261 # Name of the main program (no extension)
17262 MAIN=main
17264 # If we need to build objects with -fPIC, uncomment the following line
17265 #NEED_FPIC=-fPIC
17267 # The following variable should give the directory containing libgnat.so
17268 # You can get this directory through 'gnatls -v'. This is usually the last
17269 # directory in the Object_Path.
17270 GLIB=...
17272 # The directories for the libraries
17273 # (This macro expands the list of CSC to the list of shared libraries, you
17274 # could simply use the expanded form:
17275 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17276 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17278 $@{MAIN@}: objects $@{LIB_DIR@}
17279     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17280     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17282 objects::
17283     # recompile the sources
17284     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17286 # Note: In a future version of GNAT, the following commands will be simplified
17287 # by a new tool, gnatmlib
17288 $@{LIB_DIR@}:
17289     mkdir -p $@{dir $@@ @}
17290     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17291     cd $@{dir $@@ @} && cp -f ../*.ali .
17293 # The dependencies for the modules
17294 # Note that we have to force the expansion of *.o, since in some cases
17295 # make won't be able to do it itself.
17296 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17297 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17298 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17300 # Make sure all of the shared libraries are in the path before starting the
17301 # program
17302 run::
17303     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17305 clean::
17306     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17307     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17308     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17309     $@{RM@} *.o *.ali $@{MAIN@}
17310 @end example
17312 @node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
17313 @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}
17314 @subsection Automatically Creating a List of Directories
17317 In most makefiles, you will have to specify a list of directories, and
17318 store it in a variable. For small projects, it is often easier to
17319 specify each of them by hand, since you then have full control over what
17320 is the proper order for these directories, which ones should be
17321 included.
17323 However, in larger projects, which might involve hundreds of
17324 subdirectories, it might be more convenient to generate this list
17325 automatically.
17327 The example below presents two methods. The first one, although less
17328 general, gives you more control over the list. It involves wildcard
17329 characters, that are automatically expanded by @code{make}. Its
17330 shortcoming is that you need to explicitly specify some of the
17331 organization of your project, such as for instance the directory tree
17332 depth, whether some directories are found in a separate tree, etc.
17334 The second method is the most general one. It requires an external
17335 program, called @code{find}, which is standard on all Unix systems. All
17336 the directories found under a given root directory will be added to the
17337 list.
17339 @example
17340 # The examples below are based on the following directory hierarchy:
17341 # All the directories can contain any number of files
17342 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17343 #                       ->  ab
17344 #                       ->  ac
17345 #                ->  b  ->  ba  ->  baa
17346 #                       ->  bb
17347 #                       ->  bc
17348 # This Makefile creates a variable called DIRS, that can be reused any time
17349 # you need this list (see the other examples in this section)
17351 # The root of your project's directory hierarchy
17352 ROOT_DIRECTORY=.
17354 ####
17355 # First method: specify explicitly the list of directories
17356 # This allows you to specify any subset of all the directories you need.
17357 ####
17359 DIRS := a/aa/ a/ab/ b/ba/
17361 ####
17362 # Second method: use wildcards
17363 # Note that the argument(s) to wildcard below should end with a '/'.
17364 # Since wildcards also return file names, we have to filter them out
17365 # to avoid duplicate directory names.
17366 # We thus use make's `@w{`}dir`@w{`} and `@w{`}sort`@w{`} functions.
17367 # It sets DIRs to the following value (note that the directories aaa and baa
17368 # are not given, unless you change the arguments to wildcard).
17369 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17370 ####
17372 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17373                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17375 ####
17376 # Third method: use an external program
17377 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17378 # This is the most complete command: it sets DIRs to the following value:
17379 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17380 ####
17382 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17383 @end example
17385 @node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
17386 @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}
17387 @subsection Generating the Command Line Switches
17390 Once you have created the list of directories as explained in the
17391 previous section (@ref{130,,Automatically Creating a List of Directories}),
17392 you can easily generate the command line arguments to pass to gnatmake.
17394 For the sake of completeness, this example assumes that the source path
17395 is not the same as the object path, and that you have two separate lists
17396 of directories.
17398 @example
17399 # see "Automatically creating a list of directories" to create
17400 # these variables
17401 SOURCE_DIRS=
17402 OBJECT_DIRS=
17404 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17405 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17407 all:
17408         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17409 @end example
17411 @node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
17412 @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}
17413 @subsection Overcoming Command Line Length Limits
17416 One problem that might be encountered on big projects is that many
17417 operating systems limit the length of the command line. It is thus hard to give
17418 gnatmake the list of source and object directories.
17420 This example shows how you can set up environment variables, which will
17421 make @code{gnatmake} behave exactly as if the directories had been
17422 specified on the command line, but have a much higher length limit (or
17423 even none on most systems).
17425 It assumes that you have created a list of directories in your Makefile,
17426 using one of the methods presented in
17427 @ref{130,,Automatically Creating a List of Directories}.
17428 For the sake of completeness, we assume that the object
17429 path (where the ALI files are found) is different from the sources patch.
17431 Note a small trick in the Makefile below: for efficiency reasons, we
17432 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17433 expanded immediately by @code{make}. This way we overcome the standard
17434 make behavior which is to expand the variables only when they are
17435 actually used.
17437 On Windows, if you are using the standard Windows command shell, you must
17438 replace colons with semicolons in the assignments to these variables.
17440 @example
17441 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17442 # This is the same thing as putting the -I arguments on the command line.
17443 # (the equivalent of using -aI on the command line would be to define
17444 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17445 # You can of course have different values for these variables.
17447 # Note also that we need to keep the previous values of these variables, since
17448 # they might have been set before running 'make' to specify where the GNAT
17449 # library is installed.
17451 # see "Automatically creating a list of directories" to create these
17452 # variables
17453 SOURCE_DIRS=
17454 OBJECT_DIRS=
17456 empty:=
17457 space:=$@{empty@} $@{empty@}
17458 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17459 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17460 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17461 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17462 export ADA_INCLUDE_PATH
17463 export ADA_OBJECTS_PATH
17465 all:
17466         gnatmake main_unit
17467 @end example
17469 @node GNAT Utility Programs,GNAT and Program Execution,Building Executable Programs with GNAT,Top
17470 @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}
17471 @chapter GNAT Utility Programs
17474 This chapter describes a number of utility programs:
17478 @itemize *
17480 @item 
17481 @ref{138,,The File Cleanup Utility gnatclean}
17483 @item 
17484 @ref{139,,The GNAT Library Browser gnatls}
17485 @end itemize
17487 Other GNAT utilities are described elsewhere in this manual:
17490 @itemize *
17492 @item 
17493 @ref{42,,Handling Arbitrary File Naming Conventions with gnatname}
17495 @item 
17496 @ref{4c,,File Name Krunching with gnatkr}
17498 @item 
17499 @ref{1d,,Renaming Files with gnatchop}
17501 @item 
17502 @ref{90,,Preprocessing with gnatprep}
17503 @end itemize
17505 @menu
17506 * The File Cleanup Utility gnatclean:: 
17507 * The GNAT Library Browser gnatls:: 
17509 @end menu
17511 @node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
17512 @anchor{gnat_ugn/gnat_utility_programs id2}@anchor{13a}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{138}
17513 @section The File Cleanup Utility @code{gnatclean}
17516 @geindex File cleanup tool
17518 @geindex gnatclean
17520 @code{gnatclean} is a tool that allows the deletion of files produced by the
17521 compiler, binder and linker, including ALI files, object files, tree files,
17522 expanded source files, library files, interface copy source files, binder
17523 generated files and executable files.
17525 @menu
17526 * Running gnatclean:: 
17527 * Switches for gnatclean:: 
17529 @end menu
17531 @node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
17532 @anchor{gnat_ugn/gnat_utility_programs id3}@anchor{13b}@anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{13c}
17533 @subsection Running @code{gnatclean}
17536 The @code{gnatclean} command has the form:
17538 @quotation
17540 @example
17541 $ gnatclean switches names
17542 @end example
17543 @end quotation
17545 where @code{names} is a list of source file names. Suffixes @code{.ads} and
17546 @code{adb} may be omitted. If a project file is specified using switch
17547 @code{-P}, then @code{names} may be completely omitted.
17549 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17550 if switch @code{-c} is not specified, by the binder and
17551 the linker. In informative-only mode, specified by switch
17552 @code{-n}, the list of files that would have been deleted in
17553 normal mode is listed, but no file is actually deleted.
17555 @node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
17556 @anchor{gnat_ugn/gnat_utility_programs id4}@anchor{13d}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{13e}
17557 @subsection Switches for @code{gnatclean}
17560 @code{gnatclean} recognizes the following switches:
17562 @geindex --version (gnatclean)
17565 @table @asis
17567 @item @code{--version}
17569 Display copyright and version, then exit disregarding all other options.
17570 @end table
17572 @geindex --help (gnatclean)
17575 @table @asis
17577 @item @code{--help}
17579 If @code{--version} was not used, display usage, then exit disregarding
17580 all other options.
17582 @item @code{--subdirs=`subdir'}
17584 Actual object directory of each project file is the subdirectory subdir of the
17585 object directory specified or defaulted in the project file.
17587 @item @code{--unchecked-shared-lib-imports}
17589 By default, shared library projects are not allowed to import static library
17590 projects. When this switch is used on the command line, this restriction is
17591 relaxed.
17592 @end table
17594 @geindex -c (gnatclean)
17597 @table @asis
17599 @item @code{-c}
17601 Only attempt to delete the files produced by the compiler, not those produced
17602 by the binder or the linker. The files that are not to be deleted are library
17603 files, interface copy files, binder generated files and executable files.
17604 @end table
17606 @geindex -D (gnatclean)
17609 @table @asis
17611 @item @code{-D `dir'}
17613 Indicate that ALI and object files should normally be found in directory @code{dir}.
17614 @end table
17616 @geindex -F (gnatclean)
17619 @table @asis
17621 @item @code{-F}
17623 When using project files, if some errors or warnings are detected during
17624 parsing and verbose mode is not in effect (no use of switch
17625 -v), then error lines start with the full path name of the project
17626 file, rather than its simple file name.
17627 @end table
17629 @geindex -h (gnatclean)
17632 @table @asis
17634 @item @code{-h}
17636 Output a message explaining the usage of @code{gnatclean}.
17637 @end table
17639 @geindex -n (gnatclean)
17642 @table @asis
17644 @item @code{-n}
17646 Informative-only mode. Do not delete any files. Output the list of the files
17647 that would have been deleted if this switch was not specified.
17648 @end table
17650 @geindex -P (gnatclean)
17653 @table @asis
17655 @item @code{-P`project'}
17657 Use project file @code{project}. Only one such switch can be used.
17658 When cleaning a project file, the files produced by the compilation of the
17659 immediate sources or inherited sources of the project files are to be
17660 deleted. This is not depending on the presence or not of executable names
17661 on the command line.
17662 @end table
17664 @geindex -q (gnatclean)
17667 @table @asis
17669 @item @code{-q}
17671 Quiet output. If there are no errors, do not output anything, except in
17672 verbose mode (switch -v) or in informative-only mode
17673 (switch -n).
17674 @end table
17676 @geindex -r (gnatclean)
17679 @table @asis
17681 @item @code{-r}
17683 When a project file is specified (using switch -P),
17684 clean all imported and extended project files, recursively. If this switch
17685 is not specified, only the files related to the main project file are to be
17686 deleted. This switch has no effect if no project file is specified.
17687 @end table
17689 @geindex -v (gnatclean)
17692 @table @asis
17694 @item @code{-v}
17696 Verbose mode.
17697 @end table
17699 @geindex -vP (gnatclean)
17702 @table @asis
17704 @item @code{-vP`x'}
17706 Indicates the verbosity of the parsing of GNAT project files.
17707 @ref{d1,,Switches Related to Project Files}.
17708 @end table
17710 @geindex -X (gnatclean)
17713 @table @asis
17715 @item @code{-X`name'=`value'}
17717 Indicates that external variable @code{name} has the value @code{value}.
17718 The Project Manager will use this value for occurrences of
17719 @code{external(name)} when parsing the project file.
17720 See @ref{d1,,Switches Related to Project Files}.
17721 @end table
17723 @geindex -aO (gnatclean)
17726 @table @asis
17728 @item @code{-aO`dir'}
17730 When searching for ALI and object files, look in directory @code{dir}.
17731 @end table
17733 @geindex -I (gnatclean)
17736 @table @asis
17738 @item @code{-I`dir'}
17740 Equivalent to @code{-aO`dir'}.
17741 @end table
17743 @geindex -I- (gnatclean)
17745 @geindex Source files
17746 @geindex suppressing search
17749 @table @asis
17751 @item @code{-I-}
17753 Do not look for ALI or object files in the directory
17754 where @code{gnatclean} was invoked.
17755 @end table
17757 @node The GNAT Library Browser gnatls,,The File Cleanup Utility gnatclean,GNAT Utility Programs
17758 @anchor{gnat_ugn/gnat_utility_programs id5}@anchor{13f}@anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{139}
17759 @section The GNAT Library Browser @code{gnatls}
17762 @geindex Library browser
17764 @geindex gnatls
17766 @code{gnatls} is a tool that outputs information about compiled
17767 units. It gives the relationship between objects, unit names and source
17768 files. It can also be used to check the source dependencies of a unit
17769 as well as various characteristics.
17771 @menu
17772 * Running gnatls:: 
17773 * Switches for gnatls:: 
17774 * Example of gnatls Usage:: 
17776 @end menu
17778 @node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
17779 @anchor{gnat_ugn/gnat_utility_programs id6}@anchor{140}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{141}
17780 @subsection Running @code{gnatls}
17783 The @code{gnatls} command has the form
17785 @quotation
17787 @example
17788 $ gnatls switches object_or_ali_file
17789 @end example
17790 @end quotation
17792 The main argument is the list of object or @code{ali} files
17793 (see @ref{28,,The Ada Library Information Files})
17794 for which information is requested.
17796 In normal mode, without additional option, @code{gnatls} produces a
17797 four-column listing. Each line represents information for a specific
17798 object. The first column gives the full path of the object, the second
17799 column gives the name of the principal unit in this object, the third
17800 column gives the status of the source and the fourth column gives the
17801 full path of the source representing this unit.
17802 Here is a simple example of use:
17804 @quotation
17806 @example
17807 $ gnatls *.o
17808 ./demo1.o            demo1            DIF demo1.adb
17809 ./demo2.o            demo2             OK demo2.adb
17810 ./hello.o            h1                OK hello.adb
17811 ./instr-child.o      instr.child      MOK instr-child.adb
17812 ./instr.o            instr             OK instr.adb
17813 ./tef.o              tef              DIF tef.adb
17814 ./text_io_example.o  text_io_example   OK text_io_example.adb
17815 ./tgef.o             tgef             DIF tgef.adb
17816 @end example
17817 @end quotation
17819 The first line can be interpreted as follows: the main unit which is
17820 contained in
17821 object file @code{demo1.o} is demo1, whose main source is in
17822 @code{demo1.adb}. Furthermore, the version of the source used for the
17823 compilation of demo1 has been modified (DIF). Each source file has a status
17824 qualifier which can be:
17827 @table @asis
17829 @item `OK (unchanged)'
17831 The version of the source file used for the compilation of the
17832 specified unit corresponds exactly to the actual source file.
17834 @item `MOK (slightly modified)'
17836 The version of the source file used for the compilation of the
17837 specified unit differs from the actual source file but not enough to
17838 require recompilation. If you use gnatmake with the option
17839 @code{-m} (minimal recompilation), a file marked
17840 MOK will not be recompiled.
17842 @item `DIF (modified)'
17844 No version of the source found on the path corresponds to the source
17845 used to build this object.
17847 @item `??? (file not found)'
17849 No source file was found for this unit.
17851 @item `HID (hidden,  unchanged version not first on PATH)'
17853 The version of the source that corresponds exactly to the source used
17854 for compilation has been found on the path but it is hidden by another
17855 version of the same source that has been modified.
17856 @end table
17858 @node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
17859 @anchor{gnat_ugn/gnat_utility_programs id7}@anchor{142}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{143}
17860 @subsection Switches for @code{gnatls}
17863 @code{gnatls} recognizes the following switches:
17865 @geindex --version (gnatls)
17868 @table @asis
17870 @item @code{--version}
17872 Display copyright and version, then exit disregarding all other options.
17873 @end table
17875 @geindex --help (gnatls)
17878 @table @asis
17880 @item @code{--help}
17882 If @code{--version} was not used, display usage, then exit disregarding
17883 all other options.
17884 @end table
17886 @geindex -a (gnatls)
17889 @table @asis
17891 @item @code{-a}
17893 Consider all units, including those of the predefined Ada library.
17894 Especially useful with @code{-d}.
17895 @end table
17897 @geindex -d (gnatls)
17900 @table @asis
17902 @item @code{-d}
17904 List sources from which specified units depend on.
17905 @end table
17907 @geindex -h (gnatls)
17910 @table @asis
17912 @item @code{-h}
17914 Output the list of options.
17915 @end table
17917 @geindex -o (gnatls)
17920 @table @asis
17922 @item @code{-o}
17924 Only output information about object files.
17925 @end table
17927 @geindex -s (gnatls)
17930 @table @asis
17932 @item @code{-s}
17934 Only output information about source files.
17935 @end table
17937 @geindex -u (gnatls)
17940 @table @asis
17942 @item @code{-u}
17944 Only output information about compilation units.
17945 @end table
17947 @geindex -files (gnatls)
17950 @table @asis
17952 @item @code{-files=`file'}
17954 Take as arguments the files listed in text file @code{file}.
17955 Text file @code{file} may contain empty lines that are ignored.
17956 Each nonempty line should contain the name of an existing file.
17957 Several such switches may be specified simultaneously.
17958 @end table
17960 @geindex -aO (gnatls)
17962 @geindex -aI (gnatls)
17964 @geindex -I (gnatls)
17966 @geindex -I- (gnatls)
17969 @table @asis
17971 @item @code{-aO`dir'}, @code{-aI`dir'}, @code{-I`dir'}, @code{-I-}, @code{-nostdinc}
17973 Source path manipulation. Same meaning as the equivalent @code{gnatmake}
17974 flags (@ref{d0,,Switches for gnatmake}).
17975 @end table
17977 @geindex -aP (gnatls)
17980 @table @asis
17982 @item @code{-aP`dir'}
17984 Add @code{dir} at the beginning of the project search dir.
17985 @end table
17987 @geindex --RTS (gnatls)
17990 @table @asis
17992 @item @code{--RTS=`rts-path'}
17994 Specifies the default location of the runtime library. Same meaning as the
17995 equivalent @code{gnatmake} flag (@ref{d0,,Switches for gnatmake}).
17996 @end table
17998 @geindex -v (gnatls)
18001 @table @asis
18003 @item @code{-v}
18005 Verbose mode. Output the complete source, object and project paths. Do not use
18006 the default column layout but instead use long format giving as much as
18007 information possible on each requested units, including special
18008 characteristics such as:
18011 @itemize *
18013 @item 
18014 `Preelaborable': The unit is preelaborable in the Ada sense.
18016 @item 
18017 `No_Elab_Code':  No elaboration code has been produced by the compiler for this unit.
18019 @item 
18020 `Pure': The unit is pure in the Ada sense.
18022 @item 
18023 `Elaborate_Body': The unit contains a pragma Elaborate_Body.
18025 @item 
18026 `Remote_Types': The unit contains a pragma Remote_Types.
18028 @item 
18029 `Shared_Passive': The unit contains a pragma Shared_Passive.
18031 @item 
18032 `Predefined': This unit is part of the predefined environment and cannot be modified
18033 by the user.
18035 @item 
18036 `Remote_Call_Interface': The unit contains a pragma Remote_Call_Interface.
18037 @end itemize
18038 @end table
18040 @node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
18041 @anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{144}@anchor{gnat_ugn/gnat_utility_programs id8}@anchor{145}
18042 @subsection Example of @code{gnatls} Usage
18045 Example of using the verbose switch. Note how the source and
18046 object paths are affected by the -I switch.
18048 @quotation
18050 @example
18051 $ gnatls -v -I.. demo1.o
18053 GNATLS 5.03w (20041123-34)
18054 Copyright 1997-2004 Free Software Foundation, Inc.
18056 Source Search Path:
18057    <Current_Directory>
18058    ../
18059    /home/comar/local/adainclude/
18061 Object Search Path:
18062    <Current_Directory>
18063    ../
18064    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18066 Project Search Path:
18067    <Current_Directory>
18068    /home/comar/local/lib/gnat/
18070 ./demo1.o
18071    Unit =>
18072      Name   => demo1
18073      Kind   => subprogram body
18074      Flags  => No_Elab_Code
18075      Source => demo1.adb    modified
18076 @end example
18077 @end quotation
18079 The following is an example of use of the dependency list.
18080 Note the use of the -s switch
18081 which gives a straight list of source files. This can be useful for
18082 building specialized scripts.
18084 @quotation
18086 @example
18087 $ gnatls -d demo2.o
18088 ./demo2.o   demo2        OK demo2.adb
18089                          OK gen_list.ads
18090                          OK gen_list.adb
18091                          OK instr.ads
18092                          OK instr-child.ads
18094 $ gnatls -d -s -a demo1.o
18095 demo1.adb
18096 /home/comar/local/adainclude/ada.ads
18097 /home/comar/local/adainclude/a-finali.ads
18098 /home/comar/local/adainclude/a-filico.ads
18099 /home/comar/local/adainclude/a-stream.ads
18100 /home/comar/local/adainclude/a-tags.ads
18101 gen_list.ads
18102 gen_list.adb
18103 /home/comar/local/adainclude/gnat.ads
18104 /home/comar/local/adainclude/g-io.ads
18105 instr.ads
18106 /home/comar/local/adainclude/system.ads
18107 /home/comar/local/adainclude/s-exctab.ads
18108 /home/comar/local/adainclude/s-finimp.ads
18109 /home/comar/local/adainclude/s-finroo.ads
18110 /home/comar/local/adainclude/s-secsta.ads
18111 /home/comar/local/adainclude/s-stalib.ads
18112 /home/comar/local/adainclude/s-stoele.ads
18113 /home/comar/local/adainclude/s-stratt.ads
18114 /home/comar/local/adainclude/s-tasoli.ads
18115 /home/comar/local/adainclude/s-unstyp.ads
18116 /home/comar/local/adainclude/unchconv.ads
18117 @end example
18118 @end quotation
18124 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
18126 @node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
18127 @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}
18128 @chapter GNAT and Program Execution
18131 This chapter covers several topics:
18134 @itemize *
18136 @item 
18137 @ref{148,,Running and Debugging Ada Programs}
18139 @item 
18140 @ref{149,,Profiling}
18142 @item 
18143 @ref{14a,,Improving Performance}
18145 @item 
18146 @ref{14b,,Overflow Check Handling in GNAT}
18148 @item 
18149 @ref{14c,,Performing Dimensionality Analysis in GNAT}
18151 @item 
18152 @ref{14d,,Stack Related Facilities}
18154 @item 
18155 @ref{14e,,Memory Management Issues}
18156 @end itemize
18158 @menu
18159 * Running and Debugging Ada Programs:: 
18160 * Profiling:: 
18161 * Improving Performance:: 
18162 * Overflow Check Handling in GNAT:: 
18163 * Performing Dimensionality Analysis in GNAT:: 
18164 * Stack Related Facilities:: 
18165 * Memory Management Issues:: 
18167 @end menu
18169 @node Running and Debugging Ada Programs,Profiling,,GNAT and Program Execution
18170 @anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{148}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{14f}
18171 @section Running and Debugging Ada Programs
18174 @geindex Debugging
18176 This section discusses how to debug Ada programs.
18178 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18181 @itemize *
18183 @item 
18184 The illegality may be a violation of the static semantics of Ada. In
18185 that case GNAT diagnoses the constructs in the program that are illegal.
18186 It is then a straightforward matter for the user to modify those parts of
18187 the program.
18189 @item 
18190 The illegality may be a violation of the dynamic semantics of Ada. In
18191 that case the program compiles and executes, but may generate incorrect
18192 results, or may terminate abnormally with some exception.
18194 @item 
18195 When presented with a program that contains convoluted errors, GNAT
18196 itself may terminate abnormally without providing full diagnostics on
18197 the incorrect user program.
18198 @end itemize
18200 @geindex Debugger
18202 @geindex gdb
18204 @menu
18205 * The GNAT Debugger GDB:: 
18206 * Running GDB:: 
18207 * Introduction to GDB Commands:: 
18208 * Using Ada Expressions:: 
18209 * Calling User-Defined Subprograms:: 
18210 * Using the next Command in a Function:: 
18211 * Stopping When Ada Exceptions Are Raised:: 
18212 * Ada Tasks:: 
18213 * Debugging Generic Units:: 
18214 * Remote Debugging with gdbserver:: 
18215 * GNAT Abnormal Termination or Failure to Terminate:: 
18216 * Naming Conventions for GNAT Source Files:: 
18217 * Getting Internal Debugging Information:: 
18218 * Stack Traceback:: 
18219 * Pretty-Printers for the GNAT runtime:: 
18221 @end menu
18223 @node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
18224 @anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{150}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{151}
18225 @subsection The GNAT Debugger GDB
18228 @code{GDB} is a general purpose, platform-independent debugger that
18229 can be used to debug mixed-language programs compiled with @code{gcc},
18230 and in particular is capable of debugging Ada programs compiled with
18231 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18232 complex Ada data structures.
18234 See @cite{Debugging with GDB},
18235 for full details on the usage of @code{GDB}, including a section on
18236 its usage on programs. This manual should be consulted for full
18237 details. The section that follows is a brief introduction to the
18238 philosophy and use of @code{GDB}.
18240 When GNAT programs are compiled, the compiler optionally writes debugging
18241 information into the generated object file, including information on
18242 line numbers, and on declared types and variables. This information is
18243 separate from the generated code. It makes the object files considerably
18244 larger, but it does not add to the size of the actual executable that
18245 will be loaded into memory, and has no impact on run-time performance. The
18246 generation of debug information is triggered by the use of the
18247 @code{-g} switch in the @code{gcc} or @code{gnatmake} command
18248 used to carry out the compilations. It is important to emphasize that
18249 the use of these options does not change the generated code.
18251 The debugging information is written in standard system formats that
18252 are used by many tools, including debuggers and profilers. The format
18253 of the information is typically designed to describe C types and
18254 semantics, but GNAT implements a translation scheme which allows full
18255 details about Ada types and variables to be encoded into these
18256 standard C formats. Details of this encoding scheme may be found in
18257 the file exp_dbug.ads in the GNAT source distribution. However, the
18258 details of this encoding are, in general, of no interest to a user,
18259 since @code{GDB} automatically performs the necessary decoding.
18261 When a program is bound and linked, the debugging information is
18262 collected from the object files, and stored in the executable image of
18263 the program. Again, this process significantly increases the size of
18264 the generated executable file, but it does not increase the size of
18265 the executable program itself. Furthermore, if this program is run in
18266 the normal manner, it runs exactly as if the debug information were
18267 not present, and takes no more actual memory.
18269 However, if the program is run under control of @code{GDB}, the
18270 debugger is activated.  The image of the program is loaded, at which
18271 point it is ready to run.  If a run command is given, then the program
18272 will run exactly as it would have if @code{GDB} were not present. This
18273 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18274 entirely non-intrusive until a breakpoint is encountered.  If no
18275 breakpoint is ever hit, the program will run exactly as it would if no
18276 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18277 the debugging information and can respond to user commands to inspect
18278 variables, and more generally to report on the state of execution.
18280 @node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
18281 @anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{152}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{153}
18282 @subsection Running GDB
18285 This section describes how to initiate the debugger.
18287 The debugger can be launched from a @code{GNAT Studio} menu or
18288 directly from the command line. The description below covers the latter use.
18289 All the commands shown can be used in the @code{GNAT Studio} debug console window,
18290 but there are usually more GUI-based ways to achieve the same effect.
18292 The command to run @code{GDB} is
18294 @quotation
18296 @example
18297 $ gdb program
18298 @end example
18299 @end quotation
18301 where @code{program} is the name of the executable file. This
18302 activates the debugger and results in a prompt for debugger commands.
18303 The simplest command is simply @code{run}, which causes the program to run
18304 exactly as if the debugger were not present. The following section
18305 describes some of the additional commands that can be given to @code{GDB}.
18307 @node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
18308 @anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{154}@anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{155}
18309 @subsection Introduction to GDB Commands
18312 @code{GDB} contains a large repertoire of commands.
18313 See @cite{Debugging with GDB} for extensive documentation on the use
18314 of these commands, together with examples of their use. Furthermore,
18315 the command `help' invoked from within GDB activates a simple help
18316 facility which summarizes the available commands and their options.
18317 In this section we summarize a few of the most commonly
18318 used commands to give an idea of what @code{GDB} is about. You should create
18319 a simple program with debugging information and experiment with the use of
18320 these @code{GDB} commands on the program as you read through the
18321 following section.
18324 @itemize *
18326 @item 
18328 @table @asis
18330 @item @code{set args @var{arguments}}
18332 The `arguments' list above is a list of arguments to be passed to
18333 the program on a subsequent run command, just as though the arguments
18334 had been entered on a normal invocation of the program. The @code{set args}
18335 command is not needed if the program does not require arguments.
18336 @end table
18338 @item 
18340 @table @asis
18342 @item @code{run}
18344 The @code{run} command causes execution of the program to start from
18345 the beginning. If the program is already running, that is to say if
18346 you are currently positioned at a breakpoint, then a prompt will ask
18347 for confirmation that you want to abandon the current execution and
18348 restart.
18349 @end table
18351 @item 
18353 @table @asis
18355 @item @code{breakpoint @var{location}}
18357 The breakpoint command sets a breakpoint, that is to say a point at which
18358 execution will halt and @code{GDB} will await further
18359 commands. `location' is
18360 either a line number within a file, given in the format @code{file:linenumber},
18361 or it is the name of a subprogram. If you request that a breakpoint be set on
18362 a subprogram that is overloaded, a prompt will ask you to specify on which of
18363 those subprograms you want to breakpoint. You can also
18364 specify that all of them should be breakpointed. If the program is run
18365 and execution encounters the breakpoint, then the program
18366 stops and @code{GDB} signals that the breakpoint was encountered by
18367 printing the line of code before which the program is halted.
18368 @end table
18370 @item 
18372 @table @asis
18374 @item @code{catch exception @var{name}}
18376 This command causes the program execution to stop whenever exception
18377 @code{name} is raised.  If @code{name} is omitted, then the execution is
18378 suspended when any exception is raised.
18379 @end table
18381 @item 
18383 @table @asis
18385 @item @code{print @var{expression}}
18387 This will print the value of the given expression. Most simple
18388 Ada expression formats are properly handled by @code{GDB}, so the expression
18389 can contain function calls, variables, operators, and attribute references.
18390 @end table
18392 @item 
18394 @table @asis
18396 @item @code{continue}
18398 Continues execution following a breakpoint, until the next breakpoint or the
18399 termination of the program.
18400 @end table
18402 @item 
18404 @table @asis
18406 @item @code{step}
18408 Executes a single line after a breakpoint. If the next statement
18409 is a subprogram call, execution continues into (the first statement of)
18410 the called subprogram.
18411 @end table
18413 @item 
18415 @table @asis
18417 @item @code{next}
18419 Executes a single line. If this line is a subprogram call, executes and
18420 returns from the call.
18421 @end table
18423 @item 
18425 @table @asis
18427 @item @code{list}
18429 Lists a few lines around the current source location. In practice, it
18430 is usually more convenient to have a separate edit window open with the
18431 relevant source file displayed. Successive applications of this command
18432 print subsequent lines. The command can be given an argument which is a
18433 line number, in which case it displays a few lines around the specified one.
18434 @end table
18436 @item 
18438 @table @asis
18440 @item @code{backtrace}
18442 Displays a backtrace of the call chain. This command is typically
18443 used after a breakpoint has occurred, to examine the sequence of calls that
18444 leads to the current breakpoint. The display includes one line for each
18445 activation record (frame) corresponding to an active subprogram.
18446 @end table
18448 @item 
18450 @table @asis
18452 @item @code{up}
18454 At a breakpoint, @code{GDB} can display the values of variables local
18455 to the current frame. The command @code{up} can be used to
18456 examine the contents of other active frames, by moving the focus up
18457 the stack, that is to say from callee to caller, one frame at a time.
18458 @end table
18460 @item 
18462 @table @asis
18464 @item @code{down}
18466 Moves the focus of @code{GDB} down from the frame currently being
18467 examined to the frame of its callee (the reverse of the previous command),
18468 @end table
18470 @item 
18472 @table @asis
18474 @item @code{frame @var{n}}
18476 Inspect the frame with the given number. The value 0 denotes the frame
18477 of the current breakpoint, that is to say the top of the call stack.
18478 @end table
18480 @item 
18482 @table @asis
18484 @item @code{kill}
18486 Kills the child process in which the program is running under GDB.
18487 This may be useful for several purposes:
18490 @itemize *
18492 @item 
18493 It allows you to recompile and relink your program, since on many systems
18494 you cannot regenerate an executable file while it is running in a process.
18496 @item 
18497 You can run your program outside the debugger, on systems that do not
18498 permit executing a program outside GDB while breakpoints are set
18499 within GDB.
18501 @item 
18502 It allows you to debug a core dump rather than a running process.
18503 @end itemize
18504 @end table
18505 @end itemize
18507 The above list is a very short introduction to the commands that
18508 @code{GDB} provides. Important additional capabilities, including conditional
18509 breakpoints, the ability to execute command sequences on a breakpoint,
18510 the ability to debug at the machine instruction level and many other
18511 features are described in detail in @cite{Debugging with GDB}.
18512 Note that most commands can be abbreviated
18513 (for example, c for continue, bt for backtrace).
18515 @node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
18516 @anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{156}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{157}
18517 @subsection Using Ada Expressions
18520 @geindex Ada expressions (in gdb)
18522 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18523 extensions. The philosophy behind the design of this subset is
18525 @quotation
18528 @itemize *
18530 @item 
18531 That @code{GDB} should provide basic literals and access to operations for
18532 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18533 leaving more sophisticated computations to subprograms written into the
18534 program (which therefore may be called from @code{GDB}).
18536 @item 
18537 That type safety and strict adherence to Ada language restrictions
18538 are not particularly relevant in a debugging context.
18540 @item 
18541 That brevity is important to the @code{GDB} user.
18542 @end itemize
18543 @end quotation
18545 Thus, for brevity, the debugger acts as if there were
18546 implicit @code{with} and @code{use} clauses in effect for all user-written
18547 packages, thus making it unnecessary to fully qualify most names with
18548 their packages, regardless of context. Where this causes ambiguity,
18549 @code{GDB} asks the user’s intent.
18551 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
18553 @node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
18554 @anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{158}@anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{159}
18555 @subsection Calling User-Defined Subprograms
18558 An important capability of @code{GDB} is the ability to call user-defined
18559 subprograms while debugging. This is achieved simply by entering
18560 a subprogram call statement in the form:
18562 @quotation
18564 @example
18565 call subprogram-name (parameters)
18566 @end example
18567 @end quotation
18569 The keyword @code{call} can be omitted in the normal case where the
18570 @code{subprogram-name} does not coincide with any of the predefined
18571 @code{GDB} commands.
18573 The effect is to invoke the given subprogram, passing it the
18574 list of parameters that is supplied. The parameters can be expressions and
18575 can include variables from the program being debugged. The
18576 subprogram must be defined
18577 at the library level within your program, and @code{GDB} will call the
18578 subprogram within the environment of your program execution (which
18579 means that the subprogram is free to access or even modify variables
18580 within your program).
18582 The most important use of this facility is in allowing the inclusion of
18583 debugging routines that are tailored to particular data structures
18584 in your program. Such debugging routines can be written to provide a suitably
18585 high-level description of an abstract type, rather than a low-level dump
18586 of its physical layout. After all, the standard
18587 @code{GDB print} command only knows the physical layout of your
18588 types, not their abstract meaning. Debugging routines can provide information
18589 at the desired semantic level and are thus enormously useful.
18591 For example, when debugging GNAT itself, it is crucial to have access to
18592 the contents of the tree nodes used to represent the program internally.
18593 But tree nodes are represented simply by an integer value (which in turn
18594 is an index into a table of nodes).
18595 Using the @code{print} command on a tree node would simply print this integer
18596 value, which is not very useful. But the PN routine (defined in file
18597 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18598 a useful high level representation of the tree node, which includes the
18599 syntactic category of the node, its position in the source, the integers
18600 that denote descendant nodes and parent node, as well as varied
18601 semantic information. To study this example in more detail, you might want to
18602 look at the body of the PN procedure in the stated file.
18604 Another useful application of this capability is to deal with situations of
18605 complex data which are not handled suitably by GDB. For example, if you specify
18606 Convention Fortran for a multi-dimensional array, GDB does not know that
18607 the ordering of array elements has been switched and will not properly
18608 address the array elements. In such a case, instead of trying to print the
18609 elements directly from GDB, you can write a callable procedure that prints
18610 the elements in the desired format.
18612 @node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
18613 @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}
18614 @subsection Using the `next' Command in a Function
18617 When you use the @code{next} command in a function, the current source
18618 location will advance to the next statement as usual. A special case
18619 arises in the case of a @code{return} statement.
18621 Part of the code for a return statement is the ‘epilogue’ of the function.
18622 This is the code that returns to the caller. There is only one copy of
18623 this epilogue code, and it is typically associated with the last return
18624 statement in the function if there is more than one return. In some
18625 implementations, this epilogue is associated with the first statement
18626 of the function.
18628 The result is that if you use the @code{next} command from a return
18629 statement that is not the last return statement of the function you
18630 may see a strange apparent jump to the last return statement or to
18631 the start of the function. You should simply ignore this odd jump.
18632 The value returned is always that from the first return statement
18633 that was stepped through.
18635 @node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
18636 @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}
18637 @subsection Stopping When Ada Exceptions Are Raised
18640 @geindex Exceptions (in gdb)
18642 You can set catchpoints that stop the program execution when your program
18643 raises selected exceptions.
18646 @itemize *
18648 @item 
18650 @table @asis
18652 @item @code{catch exception}
18654 Set a catchpoint that stops execution whenever (any task in the) program
18655 raises any exception.
18656 @end table
18658 @item 
18660 @table @asis
18662 @item @code{catch exception @var{name}}
18664 Set a catchpoint that stops execution whenever (any task in the) program
18665 raises the exception `name'.
18666 @end table
18668 @item 
18670 @table @asis
18672 @item @code{catch exception unhandled}
18674 Set a catchpoint that stops executing whenever (any task in the) program
18675 raises an exception for which there is no handler.
18676 @end table
18678 @item 
18680 @table @asis
18682 @item @code{info exceptions}, @code{info exceptions @var{regexp}}
18684 The @code{info exceptions} command permits the user to examine all defined
18685 exceptions within Ada programs. With a regular expression, `regexp', as
18686 argument, prints out only those exceptions whose name matches `regexp'.
18687 @end table
18688 @end itemize
18690 @geindex Tasks (in gdb)
18692 @node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
18693 @anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{15e}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{15f}
18694 @subsection Ada Tasks
18697 @code{GDB} allows the following task-related commands:
18700 @itemize *
18702 @item 
18704 @table @asis
18706 @item @code{info tasks}
18708 This command shows a list of current Ada tasks, as in the following example:
18710 @example
18711 (gdb) info tasks
18712   ID       TID P-ID   Thread Pri State                 Name
18713    1   8088000   0   807e000  15 Child Activation Wait main_task
18714    2   80a4000   1   80ae000  15 Accept/Select Wait    b
18715    3   809a800   1   80a4800  15 Child Activation Wait a
18716 *  4   80ae800   3   80b8000  15 Running               c
18717 @end example
18719 In this listing, the asterisk before the first task indicates it to be the
18720 currently running task. The first column lists the task ID that is used
18721 to refer to tasks in the following commands.
18722 @end table
18723 @end itemize
18725 @geindex Breakpoints and tasks
18728 @itemize *
18730 @item 
18731 @code{break} `linespec' @code{task} `taskid', @code{break} `linespec' @code{task} `taskid' @code{if} …
18733 @quotation
18735 These commands are like the @code{break ... thread ...}.
18736 `linespec' specifies source lines.
18738 Use the qualifier @code{task @var{taskid}} with a breakpoint command
18739 to specify that you only want @code{GDB} to stop the program when a
18740 particular Ada task reaches this breakpoint. `taskid' is one of the
18741 numeric task identifiers assigned by @code{GDB}, shown in the first
18742 column of the @code{info tasks} display.
18744 If you do not specify @code{task @var{taskid}} when you set a
18745 breakpoint, the breakpoint applies to `all' tasks of your
18746 program.
18748 You can use the @code{task} qualifier on conditional breakpoints as
18749 well; in this case, place @code{task @var{taskid}} before the
18750 breakpoint condition (before the @code{if}).
18751 @end quotation
18752 @end itemize
18754 @geindex Task switching (in gdb)
18757 @itemize *
18759 @item 
18760 @code{task @var{taskno}}
18762 @quotation
18764 This command allows switching to the task referred by `taskno'. In
18765 particular, this allows browsing of the backtrace of the specified
18766 task. It is advisable to switch back to the original task before
18767 continuing execution otherwise the scheduling of the program may be
18768 perturbed.
18769 @end quotation
18770 @end itemize
18772 For more detailed information on the tasking support,
18773 see @cite{Debugging with GDB}.
18775 @geindex Debugging Generic Units
18777 @geindex Generics
18779 @node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
18780 @anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{160}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{161}
18781 @subsection Debugging Generic Units
18784 GNAT always uses code expansion for generic instantiation. This means that
18785 each time an instantiation occurs, a complete copy of the original code is
18786 made, with appropriate substitutions of formals by actuals.
18788 It is not possible to refer to the original generic entities in
18789 @code{GDB}, but it is always possible to debug a particular instance of
18790 a generic, by using the appropriate expanded names. For example, if we have
18792 @quotation
18794 @example
18795 procedure g is
18797    generic package k is
18798       procedure kp (v1 : in out integer);
18799    end k;
18801    package body k is
18802       procedure kp (v1 : in out integer) is
18803       begin
18804          v1 := v1 + 1;
18805       end kp;
18806    end k;
18808    package k1 is new k;
18809    package k2 is new k;
18811    var : integer := 1;
18813 begin
18814    k1.kp (var);
18815    k2.kp (var);
18816    k1.kp (var);
18817    k2.kp (var);
18818 end;
18819 @end example
18820 @end quotation
18822 Then to break on a call to procedure kp in the k2 instance, simply
18823 use the command:
18825 @quotation
18827 @example
18828 (gdb) break g.k2.kp
18829 @end example
18830 @end quotation
18832 When the breakpoint occurs, you can step through the code of the
18833 instance in the normal manner and examine the values of local variables, as for
18834 other units.
18836 @geindex Remote Debugging with gdbserver
18838 @node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
18839 @anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{162}@anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{163}
18840 @subsection Remote Debugging with gdbserver
18843 On platforms where gdbserver is supported, it is possible to use this tool
18844 to debug your application remotely.  This can be useful in situations
18845 where the program needs to be run on a target host that is different
18846 from the host used for development, particularly when the target has
18847 a limited amount of resources (either CPU and/or memory).
18849 To do so, start your program using gdbserver on the target machine.
18850 gdbserver then automatically suspends the execution of your program
18851 at its entry point, waiting for a debugger to connect to it.  The
18852 following commands starts an application and tells gdbserver to
18853 wait for a connection with the debugger on localhost port 4444.
18855 @quotation
18857 @example
18858 $ gdbserver localhost:4444 program
18859 Process program created; pid = 5685
18860 Listening on port 4444
18861 @end example
18862 @end quotation
18864 Once gdbserver has started listening, we can tell the debugger to establish
18865 a connection with this gdbserver, and then start the same debugging session
18866 as if the program was being debugged on the same host, directly under
18867 the control of GDB.
18869 @quotation
18871 @example
18872 $ gdb program
18873 (gdb) target remote targethost:4444
18874 Remote debugging using targethost:4444
18875 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
18876 (gdb) b foo.adb:3
18877 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
18878 (gdb) continue
18879 Continuing.
18881 Breakpoint 1, foo () at foo.adb:4
18882 4       end foo;
18883 @end example
18884 @end quotation
18886 It is also possible to use gdbserver to attach to an already running
18887 program, in which case the execution of that program is simply suspended
18888 until the connection between the debugger and gdbserver is established.
18890 For more information on how to use gdbserver, see the `Using the gdbserver Program'
18891 section in @cite{Debugging with GDB}.
18892 GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
18894 @geindex Abnormal Termination or Failure to Terminate
18896 @node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
18897 @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}
18898 @subsection GNAT Abnormal Termination or Failure to Terminate
18901 When presented with programs that contain serious errors in syntax
18902 or semantics,
18903 GNAT may on rare occasions  experience problems in operation, such
18904 as aborting with a
18905 segmentation fault or illegal memory access, raising an internal
18906 exception, terminating abnormally, or failing to terminate at all.
18907 In such cases, you can activate
18908 various features of GNAT that can help you pinpoint the construct in your
18909 program that is the likely source of the problem.
18911 The following strategies are presented in increasing order of
18912 difficulty, corresponding to your experience in using GNAT and your
18913 familiarity with compiler internals.
18916 @itemize *
18918 @item 
18919 Run @code{gcc} with the @code{-gnatf}. This first
18920 switch causes all errors on a given line to be reported. In its absence,
18921 only the first error on a line is displayed.
18923 The @code{-gnatdO} switch causes errors to be displayed as soon as they
18924 are encountered, rather than after compilation is terminated. If GNAT
18925 terminates prematurely or goes into an infinite loop, the last error
18926 message displayed may help to pinpoint the culprit.
18928 @item 
18929 Run @code{gcc} with the @code{-v} (verbose) switch. In this
18930 mode, @code{gcc} produces ongoing information about the progress of the
18931 compilation and provides the name of each procedure as code is
18932 generated. This switch allows you to find which Ada procedure was being
18933 compiled when it encountered a code generation problem.
18934 @end itemize
18936 @geindex -gnatdc switch
18939 @itemize *
18941 @item 
18942 Run @code{gcc} with the @code{-gnatdc} switch. This is a GNAT specific
18943 switch that does for the front-end what @code{-v} does
18944 for the back end. The system prints the name of each unit,
18945 either a compilation unit or nested unit, as it is being analyzed.
18947 @item 
18948 Finally, you can start
18949 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
18950 front-end of GNAT, and can be run independently (normally it is just
18951 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
18952 would on a C program (but @ref{151,,The GNAT Debugger GDB} for caveats). The
18953 @code{where} command is the first line of attack; the variable
18954 @code{lineno} (seen by @code{print lineno}), used by the second phase of
18955 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
18956 which the execution stopped, and @code{input_file name} indicates the name of
18957 the source file.
18958 @end itemize
18960 @node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
18961 @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}
18962 @subsection Naming Conventions for GNAT Source Files
18965 In order to examine the workings of the GNAT system, the following
18966 brief description of its organization may be helpful:
18969 @itemize *
18971 @item 
18972 Files with prefix @code{sc} contain the lexical scanner.
18974 @item 
18975 All files prefixed with @code{par} are components of the parser. The
18976 numbers correspond to chapters of the Ada Reference Manual. For example,
18977 parsing of select statements can be found in @code{par-ch9.adb}.
18979 @item 
18980 All files prefixed with @code{sem} perform semantic analysis. The
18981 numbers correspond to chapters of the Ada standard. For example, all
18982 issues involving context clauses can be found in @code{sem_ch10.adb}. In
18983 addition, some features of the language require sufficient special processing
18984 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
18985 dynamic dispatching, etc.
18987 @item 
18988 All files prefixed with @code{exp} perform normalization and
18989 expansion of the intermediate representation (abstract syntax tree, or AST).
18990 these files use the same numbering scheme as the parser and semantics files.
18991 For example, the construction of record initialization procedures is done in
18992 @code{exp_ch3.adb}.
18994 @item 
18995 The files prefixed with @code{bind} implement the binder, which
18996 verifies the consistency of the compilation, determines an order of
18997 elaboration, and generates the bind file.
18999 @item 
19000 The files @code{atree.ads} and @code{atree.adb} detail the low-level
19001 data structures used by the front-end.
19003 @item 
19004 The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
19005 the abstract syntax tree as produced by the parser.
19007 @item 
19008 The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
19009 all entities, computed during semantic analysis.
19011 @item 
19012 Library management issues are dealt with in files with prefix
19013 @code{lib}.
19015 @geindex Annex A (in Ada Reference Manual)
19017 @item 
19018 Ada files with the prefix @code{a-} are children of @code{Ada}, as
19019 defined in Annex A.
19021 @geindex Annex B (in Ada reference Manual)
19023 @item 
19024 Files with prefix @code{i-} are children of @code{Interfaces}, as
19025 defined in Annex B.
19027 @geindex System (package in Ada Reference Manual)
19029 @item 
19030 Files with prefix @code{s-} are children of @code{System}. This includes
19031 both language-defined children and GNAT run-time routines.
19033 @geindex GNAT (package)
19035 @item 
19036 Files with prefix @code{g-} are children of @code{GNAT}. These are useful
19037 general-purpose packages, fully documented in their specs. All
19038 the other @code{.c} files are modifications of common @code{gcc} files.
19039 @end itemize
19041 @node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
19042 @anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{168}@anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{169}
19043 @subsection Getting Internal Debugging Information
19046 Most compilers have internal debugging switches and modes. GNAT
19047 does also, except GNAT internal debugging switches and modes are not
19048 secret. A summary and full description of all the compiler and binder
19049 debug flags are in the file @code{debug.adb}. You must obtain the
19050 sources of the compiler to see the full detailed effects of these flags.
19052 The switches that print the source of the program (reconstructed from
19053 the internal tree) are of general interest for user programs, as are the
19054 options to print
19055 the full internal tree, and the entity table (the symbol table
19056 information). The reconstructed source provides a readable version of the
19057 program after the front-end has completed analysis and  expansion,
19058 and is useful when studying the performance of specific constructs.
19059 For example, constraint checks are indicated, complex aggregates
19060 are replaced with loops and assignments, and tasking primitives
19061 are replaced with run-time calls.
19063 @geindex traceback
19065 @geindex stack traceback
19067 @geindex stack unwinding
19069 @node Stack Traceback,Pretty-Printers for the GNAT runtime,Getting Internal Debugging Information,Running and Debugging Ada Programs
19070 @anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{16a}@anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{16b}
19071 @subsection Stack Traceback
19074 Traceback is a mechanism to display the sequence of subprogram calls that
19075 leads to a specified execution point in a program. Often (but not always)
19076 the execution point is an instruction at which an exception has been raised.
19077 This mechanism is also known as `stack unwinding' because it obtains
19078 its information by scanning the run-time stack and recovering the activation
19079 records of all active subprograms. Stack unwinding is one of the most
19080 important tools for program debugging.
19082 The first entry stored in traceback corresponds to the deepest calling level,
19083 that is to say the subprogram currently executing the instruction
19084 from which we want to obtain the traceback.
19086 Note that there is no runtime performance penalty when stack traceback
19087 is enabled, and no exception is raised during program execution.
19089 @geindex traceback
19090 @geindex non-symbolic
19092 @menu
19093 * Non-Symbolic Traceback:: 
19094 * Symbolic Traceback:: 
19096 @end menu
19098 @node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
19099 @anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{16c}@anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{16d}
19100 @subsubsection Non-Symbolic Traceback
19103 Note: this feature is not supported on all platforms. See
19104 @code{GNAT.Traceback} spec in @code{g-traceb.ads}
19105 for a complete list of supported platforms.
19107 @subsubheading Tracebacks From an Unhandled Exception
19110 A runtime non-symbolic traceback is a list of addresses of call instructions.
19111 To enable this feature you must use the @code{-E} @code{gnatbind} option. With
19112 this option a stack traceback is stored as part of exception information.
19114 You can translate this information using the @code{addr2line} tool, provided that
19115 the program is compiled with debugging options (see @ref{dd,,Compiler Switches})
19116 and linked at a fixed position with @code{-no-pie}.
19118 Here is a simple example with @code{gnatmake}:
19120 @quotation
19122 @example
19123 procedure STB is
19125    procedure P1 is
19126    begin
19127       raise Constraint_Error;
19128    end P1;
19130    procedure P2 is
19131    begin
19132       P1;
19133    end P2;
19135 begin
19136    P2;
19137 end STB;
19138 @end example
19140 @example
19141 $ gnatmake stb -g -bargs -E -largs -no-pie
19142 $ stb
19144 Execution of stb terminated by unhandled exception
19145 raised CONSTRAINT_ERROR : stb.adb:5 explicit raise
19146 Load address: 0x400000
19147 Call stack traceback locations:
19148 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19149 @end example
19150 @end quotation
19152 As we see the traceback lists a sequence of addresses for the unhandled
19153 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19154 guess that this exception come from procedure P1. To translate these
19155 addresses into the source lines where the calls appear, the @code{addr2line}
19156 tool needs to be invoked like this:
19158 @quotation
19160 @example
19161 $ addr2line -e stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19162    0x4011f1 0x77e892a4
19164 d:/stb/stb.adb:5
19165 d:/stb/stb.adb:10
19166 d:/stb/stb.adb:14
19167 d:/stb/b~stb.adb:197
19168 crtexe.c:?
19169 crtexe.c:?
19170 ??:0
19171 @end example
19172 @end quotation
19174 The @code{addr2line} tool has several other useful options:
19176 @quotation
19179 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
19180 @item
19182 @code{-a --addresses}
19184 @tab
19186 to show the addresses alongside the line numbers
19188 @item
19190 @code{-f --functions}
19192 @tab
19194 to get the function name corresponding to a location
19196 @item
19198 @code{-p --pretty-print}
19200 @tab
19202 to print all the information on a single line
19204 @item
19206 @code{--demangle=gnat}
19208 @tab
19210 to use the GNAT decoding mode for the function names
19212 @end multitable
19215 @example
19216 $ addr2line -e stb -a -f -p --demangle=gnat 0x401373 0x40138b
19217    0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19219 0x00401373: stb.p1 at d:/stb/stb.adb:5
19220 0x0040138B: stb.p2 at d:/stb/stb.adb:10
19221 0x0040139C: stb at d:/stb/stb.adb:14
19222 0x00401335: main at d:/stb/b~stb.adb:197
19223 0x004011c4: ?? at crtexe.c:?
19224 0x004011f1: ?? at crtexe.c:?
19225 0x77e892a4: ?? ??:0
19226 @end example
19227 @end quotation
19229 From this traceback we can see that the exception was raised in @code{stb.adb}
19230 at line 5, which was reached from a procedure call in @code{stb.adb} at line
19231 10, and so on. The @code{b~std.adb} is the binder file, which contains the
19232 call to the main program. @ref{110,,Running gnatbind}. The remaining entries are
19233 assorted runtime routines and the output will vary from platform to platform.
19235 It is also possible to use @code{GDB} with these traceback addresses to debug
19236 the program. For example, we can break at a given code location, as reported
19237 in the stack traceback:
19239 @example
19240 $ gdb -nw stb
19242 (gdb) break *0x401373
19243 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19244 @end example
19246 It is important to note that the stack traceback addresses do not change when
19247 debug information is included. This is particularly useful because it makes it
19248 possible to release software without debug information (to minimize object
19249 size), get a field report that includes a stack traceback whenever an internal
19250 bug occurs, and then be able to retrieve the sequence of calls with the same
19251 program compiled with debug information.
19253 However the @code{addr2line} tool does not work with Position-Independent Code
19254 (PIC), the historical example being Linux dynamic libraries and Windows DLLs,
19255 which nowadays encompasse Position-Independent Executables (PIE) on recent
19256 Linux and Windows versions.
19258 In order to translate addresses the source lines with Position-Independent
19259 Executables on recent Linux and Windows versions, in other words without
19260 using the switch @code{-no-pie} during linking, you need to use the
19261 @code{gnatsymbolize} tool with @code{--load} instead of the @code{addr2line}
19262 tool. The main difference is that you need to copy the Load Address output
19263 in the traceback ahead of the sequence of addresses. And the default mode
19264 of @code{gnatsymbolize} is equivalent to that of @code{addr2line} with the above
19265 switches, so none of them is needed:
19267 @example
19268 $ gnatmake stb -g -bargs -E
19269 $ stb
19271 Execution of stb terminated by unhandled exception
19272 raised CONSTRAINT_ERROR : stb.adb:5 explicit raise
19273 Load address: 0x400000
19274 Call stack traceback locations:
19275 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19277 $ gnatsymbolize --load stb 0x400000 0x401373 0x40138b 0x40139c 0x401335 \
19278    0x4011c4 0x4011f1 0x77e892a4
19280 0x00401373 Stb.P1 at stb.adb:5
19281 0x0040138B Stb.P2 at stb.adb:10
19282 0x0040139C Stb at stb.adb:14
19283 0x00401335 Main at b~stb.adb:197
19284 0x004011c4 __tmainCRTStartup at ???
19285 0x004011f1 mainCRTStartup at ???
19286 0x77e892a4 ??? at ???
19287 @end example
19289 @subsubheading Tracebacks From Exception Occurrences
19292 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
19293 The stack traceback is attached to the exception information string, and can
19294 be retrieved in an exception handler within the Ada program, by means of the
19295 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19297 @quotation
19299 @example
19300 with Ada.Text_IO;
19301 with Ada.Exceptions;
19303 procedure STB is
19305    use Ada;
19306    use Ada.Exceptions;
19308    procedure P1 is
19309       K : Positive := 1;
19310    begin
19311       K := K - 1;
19312    exception
19313       when E : others =>
19314          Text_IO.Put_Line (Exception_Information (E));
19315    end P1;
19317    procedure P2 is
19318    begin
19319       P1;
19320    end P2;
19322 begin
19323    P2;
19324 end STB;
19325 @end example
19327 @example
19328 $ gnatmake stb -g -bargs -E -largs -no-pie
19329 $ stb
19331 raised CONSTRAINT_ERROR : stb.adb:12 range check failed
19332 Load address: 0x400000
19333 Call stack traceback locations:
19334 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19335 @end example
19336 @end quotation
19338 @subsubheading Tracebacks From Anywhere in a Program
19341 It is also possible to retrieve a stack traceback from anywhere in a program.
19342 For this you need to use the @code{GNAT.Traceback} API. This package includes a
19343 procedure called @code{Call_Chain} that computes a complete stack traceback, as
19344 well as useful display procedures described below. It is not necessary to use
19345 the @code{-E} @code{gnatbind} option in this case, because the stack traceback
19346 mechanism is invoked explicitly.
19348 In the following example we compute a traceback at a specific location in the
19349 program, and we display it using @code{GNAT.Debug_Utilities.Image} to convert
19350 addresses to strings:
19352 @quotation
19354 @example
19355 with Ada.Text_IO;
19356 with GNAT.Traceback;
19357 with GNAT.Debug_Utilities;
19358 with System;
19360 procedure STB is
19362    use Ada;
19363    use Ada.Text_IO;
19364    use GNAT;
19365    use GNAT.Traceback;
19366    use System;
19368    LA : constant Address := Executable_Load_Address;
19370    procedure P1 is
19371       TB  : Tracebacks_Array (1 .. 10);
19372       --  We are asking for a maximum of 10 stack frames.
19373       Len : Natural;
19374       --  Len will receive the actual number of stack frames returned.
19375    begin
19376       Call_Chain (TB, Len);
19378       Put ("In STB.P1 : ");
19380       for K in 1 .. Len loop
19381          Put (Debug_Utilities.Image_C (TB (K)));
19382          Put (' ');
19383       end loop;
19385       New_Line;
19386    end P1;
19388    procedure P2 is
19389    begin
19390       P1;
19391    end P2;
19393 begin
19394    if LA /= Null_Address then
19395       Put_Line ("Load address: " & Debug_Utilities.Image_C (LA));
19396    end if;
19398    P2;
19399 end STB;
19400 @end example
19402 @example
19403 $ gnatmake stb -g
19404 $ stb
19406 Load address: 0x400000
19407 In STB.P1 : 0x40F1E4 0x4014F2 0x40170B 0x40171C 0x401461 0x4011C4 \
19408   0x4011F1 0x77E892A4
19409 @end example
19410 @end quotation
19412 You can then get further information by invoking the @code{addr2line} tool or
19413 the @code{gnatsymbolize} tool as described earlier (note that the hexadecimal
19414 addresses need to be specified in C format, with a leading ‘0x’).
19416 @geindex traceback
19417 @geindex symbolic
19419 @node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
19420 @anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{16e}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{16f}
19421 @subsubsection Symbolic Traceback
19424 A symbolic traceback is a stack traceback in which procedure names are
19425 associated with each code location.
19427 Note that this feature is not supported on all platforms. See
19428 @code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
19429 list of currently supported platforms.
19431 Note that the symbolic traceback requires that the program be compiled
19432 with debug information. If it is not compiled with debug information
19433 only the non-symbolic information will be valid.
19435 @subsubheading Tracebacks From Exception Occurrences
19438 Here is an example:
19440 @quotation
19442 @example
19443 with Ada.Text_IO;
19444 with GNAT.Traceback.Symbolic;
19446 procedure STB is
19448    procedure P1 is
19449    begin
19450       raise Constraint_Error;
19451    end P1;
19453    procedure P2 is
19454    begin
19455       P1;
19456    end P2;
19458    procedure P3 is
19459    begin
19460       P2;
19461    end P3;
19463 begin
19464    P3;
19465 exception
19466    when E : others =>
19467       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19468 end STB;
19469 @end example
19471 @example
19472 $ gnatmake -g stb -bargs -E
19473 $ stb
19475 0040149F in stb.p1 at stb.adb:8
19476 004014B7 in stb.p2 at stb.adb:13
19477 004014CF in stb.p3 at stb.adb:18
19478 004015DD in ada.stb at stb.adb:22
19479 00401461 in main at b~stb.adb:168
19480 004011C4 in __mingw_CRTStartup at crt1.c:200
19481 004011F1 in mainCRTStartup at crt1.c:222
19482 77E892A4 in ?? at ??:0
19483 @end example
19484 @end quotation
19486 @subsubheading Tracebacks From Anywhere in a Program
19489 It is possible to get a symbolic stack traceback
19490 from anywhere in a program, just as for non-symbolic tracebacks.
19491 The first step is to obtain a non-symbolic
19492 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19493 information. Here is an example:
19495 @quotation
19497 @example
19498 with Ada.Text_IO;
19499 with GNAT.Traceback;
19500 with GNAT.Traceback.Symbolic;
19502 procedure STB is
19504    use Ada;
19505    use GNAT.Traceback;
19506    use GNAT.Traceback.Symbolic;
19508    procedure P1 is
19509       TB  : Tracebacks_Array (1 .. 10);
19510       --  We are asking for a maximum of 10 stack frames.
19511       Len : Natural;
19512       --  Len will receive the actual number of stack frames returned.
19513    begin
19514       Call_Chain (TB, Len);
19515       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19516    end P1;
19518    procedure P2 is
19519    begin
19520       P1;
19521    end P2;
19523 begin
19524    P2;
19525 end STB;
19526 @end example
19527 @end quotation
19529 @subsubheading Automatic Symbolic Tracebacks
19532 Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
19533 in @code{gprbuild -g ... -bargs -Es}).
19534 This will cause the Exception_Information to contain a symbolic traceback,
19535 which will also be printed if an unhandled exception terminates the
19536 program.
19538 @node Pretty-Printers for the GNAT runtime,,Stack Traceback,Running and Debugging Ada Programs
19539 @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}
19540 @subsection Pretty-Printers for the GNAT runtime
19543 As discussed in @cite{Calling User-Defined Subprograms}, GDB’s
19544 @code{print} command only knows about the physical layout of program data
19545 structures and therefore normally displays only low-level dumps, which
19546 are often hard to understand.
19548 An example of this is when trying to display the contents of an Ada
19549 standard container, such as @code{Ada.Containers.Ordered_Maps.Map}:
19551 @quotation
19553 @example
19554 with Ada.Containers.Ordered_Maps;
19556 procedure PP is
19557    package Int_To_Nat is
19558       new Ada.Containers.Ordered_Maps (Integer, Natural);
19560    Map : Int_To_Nat.Map;
19561 begin
19562    Map.Insert (1, 10);
19563    Map.Insert (2, 20);
19564    Map.Insert (3, 30);
19566    Map.Clear; --  BREAK HERE
19567 end PP;
19568 @end example
19569 @end quotation
19571 When this program is built with debugging information and run under
19572 GDB up to the @code{Map.Clear} statement, trying to print @code{Map} will
19573 yield information that is only relevant to the developers of our standard
19574 containers:
19576 @quotation
19578 @example
19579 (gdb) print map
19580 $1 = (
19581   tree => (
19582     first => 0x64e010,
19583     last => 0x64e070,
19584     root => 0x64e040,
19585     length => 3,
19586     tc => (
19587       busy => 0,
19588       lock => 0
19589     )
19590   )
19592 @end example
19593 @end quotation
19595 Fortunately, GDB has a feature called pretty-printers@footnote{http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Introduction},
19596 which allows customizing how GDB displays data structures. The GDB
19597 shipped with GNAT embeds such pretty-printers for the most common
19598 containers in the standard library.  To enable them, either run the
19599 following command manually under GDB or add it to your @code{.gdbinit} file:
19601 @quotation
19603 @example
19604 python import gnatdbg; gnatdbg.setup()
19605 @end example
19606 @end quotation
19608 Once this is done, GDB’s @code{print} command will automatically use
19609 these pretty-printers when appropriate. Using the previous example:
19611 @quotation
19613 @example
19614 (gdb) print map
19615 $1 = pp.int_to_nat.map of length 3 = @{
19616   [1] = 10,
19617   [2] = 20,
19618   [3] = 30
19620 @end example
19621 @end quotation
19623 Pretty-printers are invoked each time GDB tries to display a value,
19624 including when displaying the arguments of a called subprogram (in
19625 GDB’s @code{backtrace} command) or when printing the value returned by a
19626 function (in GDB’s @code{finish} command).
19628 To display a value without involving pretty-printers, @code{print} can be
19629 invoked with its @code{/r} option:
19631 @quotation
19633 @example
19634 (gdb) print/r map
19635 $1 = (
19636   tree => (...
19637 @end example
19638 @end quotation
19640 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}
19641 for more information.
19643 @geindex Profiling
19645 @node Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
19646 @anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{172}@anchor{gnat_ugn/gnat_and_program_execution profiling}@anchor{149}
19647 @section Profiling
19650 This section describes how to use the @code{gprof} profiler tool on Ada programs.
19652 @geindex gprof
19654 @geindex Profiling
19656 @menu
19657 * Profiling an Ada Program with gprof:: 
19659 @end menu
19661 @node Profiling an Ada Program with gprof,,,Profiling
19662 @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}
19663 @subsection Profiling an Ada Program with gprof
19666 This section is not meant to be an exhaustive documentation of @code{gprof}.
19667 Full documentation for it can be found in the @cite{GNU Profiler User’s Guide}
19668 documentation that is part of this GNAT distribution.
19670 Profiling a program helps determine the parts of a program that are executed
19671 most often, and are therefore the most time-consuming.
19673 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
19674 better handle Ada programs and multitasking.
19675 It is currently supported on the following platforms
19678 @itemize *
19680 @item 
19681 Linux x86/x86_64
19683 @item 
19684 Windows x86/x86_64 (without PIE support)
19685 @end itemize
19687 In order to profile a program using @code{gprof}, several steps are needed:
19690 @enumerate 
19692 @item 
19693 Instrument the code, which requires a full recompilation of the project with the
19694 proper switches.
19696 @item 
19697 Execute the program under the analysis conditions, i.e. with the desired
19698 input.
19700 @item 
19701 Analyze the results using the @code{gprof} tool.
19702 @end enumerate
19704 The following sections detail the different steps, and indicate how
19705 to interpret the results.
19707 @menu
19708 * Compilation for profiling:: 
19709 * Program execution:: 
19710 * Running gprof:: 
19711 * Interpretation of profiling results:: 
19713 @end menu
19715 @node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
19716 @anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{175}@anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{176}
19717 @subsubsection Compilation for profiling
19720 @geindex -pg (gcc)
19721 @geindex for profiling
19723 @geindex -pg (gnatlink)
19724 @geindex for profiling
19726 In order to profile a program the first step is to tell the compiler
19727 to generate the necessary profiling information. The compiler switch to be used
19728 is @code{-pg}, which must be added to other compilation switches. This
19729 switch needs to be specified both during compilation and link stages, and can
19730 be specified once when using gnatmake:
19732 @quotation
19734 @example
19735 $ gnatmake -f -pg -P my_project
19736 @end example
19737 @end quotation
19739 Note that only the objects that were compiled with the @code{-pg} switch will
19740 be profiled; if you need to profile your whole project, use the @code{-f}
19741 gnatmake switch to force full recompilation.
19743 Note that on Windows, gprof does not support PIE. The @code{-no-pie} switch
19744 should be added to the linker flags to disable this feature.
19746 @node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
19747 @anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{177}@anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{178}
19748 @subsubsection Program execution
19751 Once the program has been compiled for profiling, you can run it as usual.
19753 The only constraint imposed by profiling is that the program must terminate
19754 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
19755 properly analyzed.
19757 Once the program completes execution, a data file called @code{gmon.out} is
19758 generated in the directory where the program was launched from. If this file
19759 already exists, it will be overwritten.
19761 @node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
19762 @anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{179}@anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{17a}
19763 @subsubsection Running gprof
19766 The @code{gprof} tool is called as follow:
19768 @quotation
19770 @example
19771 $ gprof my_prog gmon.out
19772 @end example
19773 @end quotation
19775 or simply:
19777 @quotation
19779 @example
19780 $ gprof my_prog
19781 @end example
19782 @end quotation
19784 The complete form of the gprof command line is the following:
19786 @quotation
19788 @example
19789 $ gprof [switches] [executable [data-file]]
19790 @end example
19791 @end quotation
19793 @code{gprof} supports numerous switches. The order of these
19794 switch does not matter. The full list of options can be found in
19795 the GNU Profiler User’s Guide documentation that comes with this documentation.
19797 The following is the subset of those switches that is most relevant:
19799 @geindex --demangle (gprof)
19802 @table @asis
19804 @item @code{--demangle[=@var{style}]}, @code{--no-demangle}
19806 These options control whether symbol names should be demangled when
19807 printing output.  The default is to demangle C++ symbols.  The
19808 @code{--no-demangle} option may be used to turn off demangling. Different
19809 compilers have different mangling styles.  The optional demangling style
19810 argument can be used to choose an appropriate demangling style for your
19811 compiler, in particular Ada symbols generated by GNAT can be demangled using
19812 @code{--demangle=gnat}.
19813 @end table
19815 @geindex -e (gprof)
19818 @table @asis
19820 @item @code{-e @var{function_name}}
19822 The @code{-e @var{function}} option tells @code{gprof} not to print
19823 information about the function @code{function_name} (and its
19824 children…) in the call graph.  The function will still be listed
19825 as a child of any functions that call it, but its index number will be
19826 shown as @code{[not printed]}.  More than one @code{-e} option may be
19827 given; only one @code{function_name} may be indicated with each @code{-e}
19828 option.
19829 @end table
19831 @geindex -E (gprof)
19834 @table @asis
19836 @item @code{-E @var{function_name}}
19838 The @code{-E @var{function}} option works like the @code{-e} option, but
19839 execution time spent in the function (and children who were not called from
19840 anywhere else), will not be used to compute the percentages-of-time for
19841 the call graph.  More than one @code{-E} option may be given; only one
19842 @code{function_name} may be indicated with each @code{-E`} option.
19843 @end table
19845 @geindex -f (gprof)
19848 @table @asis
19850 @item @code{-f @var{function_name}}
19852 The @code{-f @var{function}} option causes @code{gprof} to limit the
19853 call graph to the function @code{function_name} and its children (and
19854 their children…).  More than one @code{-f} option may be given;
19855 only one @code{function_name} may be indicated with each @code{-f}
19856 option.
19857 @end table
19859 @geindex -F (gprof)
19862 @table @asis
19864 @item @code{-F @var{function_name}}
19866 The @code{-F @var{function}} option works like the @code{-f} option, but
19867 only time spent in the function and its children (and their
19868 children…) will be used to determine total-time and
19869 percentages-of-time for the call graph.  More than one @code{-F} option
19870 may be given; only one @code{function_name} may be indicated with each
19871 @code{-F} option.  The @code{-F} option overrides the @code{-E} option.
19872 @end table
19874 @node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
19875 @anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{17b}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{17c}
19876 @subsubsection Interpretation of profiling results
19879 The results of the profiling analysis are represented by two arrays: the
19880 ‘flat profile’ and the ‘call graph’. Full documentation of those outputs
19881 can be found in the GNU Profiler User’s Guide.
19883 The flat profile shows the time spent in each function of the program, and how
19884 many time it has been called. This allows you to locate easily the most
19885 time-consuming functions.
19887 The call graph shows, for each subprogram, the subprograms that call it,
19888 and the subprograms that it calls. It also provides an estimate of the time
19889 spent in each of those callers/called subprograms.
19891 @node Improving Performance,Overflow Check Handling in GNAT,Profiling,GNAT and Program Execution
19892 @anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{14a}@anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{17d}
19893 @section Improving Performance
19896 @geindex Improving performance
19898 This section presents several topics related to program performance.
19899 It first describes some of the tradeoffs that need to be considered
19900 and some of the techniques for making your program run faster.
19902 It then documents the unused subprogram/data elimination feature,
19903 which can reduce the size of program executables.
19905 @menu
19906 * Performance Considerations:: 
19907 * Text_IO Suggestions:: 
19908 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
19910 @end menu
19912 @node Performance Considerations,Text_IO Suggestions,,Improving Performance
19913 @anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{17e}@anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{17f}
19914 @subsection Performance Considerations
19917 The GNAT system provides a number of options that allow a trade-off
19918 between
19921 @itemize *
19923 @item 
19924 performance of the generated code
19926 @item 
19927 speed of compilation
19929 @item 
19930 minimization of dependences and recompilation
19932 @item 
19933 the degree of run-time checking.
19934 @end itemize
19936 The defaults (if no options are selected) aim at improving the speed
19937 of compilation and minimizing dependences, at the expense of performance
19938 of the generated code:
19941 @itemize *
19943 @item 
19944 no optimization
19946 @item 
19947 no inlining of subprogram calls
19949 @item 
19950 all run-time checks enabled except overflow and elaboration checks
19951 @end itemize
19953 These options are suitable for most program development purposes. This
19954 section describes how you can modify these choices, and also provides
19955 some guidelines on debugging optimized code.
19957 @menu
19958 * Controlling Run-Time Checks:: 
19959 * Use of Restrictions:: 
19960 * Optimization Levels:: 
19961 * Debugging Optimized Code:: 
19962 * Inlining of Subprograms:: 
19963 * Floating Point Operations:: 
19964 * Vectorization of loops:: 
19965 * Other Optimization Switches:: 
19966 * Optimization and Strict Aliasing:: 
19967 * Aliased Variables and Optimization:: 
19968 * Atomic Variables and Optimization:: 
19969 * Passive Task Optimization:: 
19971 @end menu
19973 @node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
19974 @anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{180}@anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{181}
19975 @subsubsection Controlling Run-Time Checks
19978 By default, GNAT generates all run-time checks, except stack overflow
19979 checks, and checks for access before elaboration on subprogram
19980 calls. The latter are not required in default mode, because all
19981 necessary checking is done at compile time.
19983 @geindex -gnatp (gcc)
19985 @geindex -gnato (gcc)
19987 The gnat switch, @code{-gnatp} allows this default to be modified. See
19988 @ref{ec,,Run-Time Checks}.
19990 Our experience is that the default is suitable for most development
19991 purposes.
19993 Elaboration checks are off by default, and also not needed by default, since
19994 GNAT uses a static elaboration analysis approach that avoids the need for
19995 run-time checking. This manual contains a full chapter discussing the issue
19996 of elaboration checks, and if the default is not satisfactory for your use,
19997 you should read this chapter.
19999 For validity checks, the minimal checks required by the Ada Reference
20000 Manual (for case statements and assignments to array elements) are on
20001 by default. These can be suppressed by use of the @code{-gnatVn} switch.
20002 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20003 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20004 it may be reasonable to routinely use @code{-gnatVn}. Validity checks
20005 are also suppressed entirely if @code{-gnatp} is used.
20007 @geindex Overflow checks
20009 @geindex Checks
20010 @geindex overflow
20012 @geindex Suppress
20014 @geindex Unsuppress
20016 @geindex pragma Suppress
20018 @geindex pragma Unsuppress
20020 Note that the setting of the switches controls the default setting of
20021 the checks. They may be modified using either @code{pragma Suppress} (to
20022 remove checks) or @code{pragma Unsuppress} (to add back suppressed
20023 checks) in the program source.
20025 @node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
20026 @anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{182}@anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{183}
20027 @subsubsection Use of Restrictions
20030 The use of pragma Restrictions allows you to control which features are
20031 permitted in your program. Apart from the obvious point that if you avoid
20032 relatively expensive features like finalization (enforceable by the use
20033 of pragma Restrictions (No_Finalization)), the use of this pragma does not
20034 affect the generated code in most cases.
20036 One notable exception to this rule is that the possibility of task abort
20037 results in some distributed overhead, particularly if finalization or
20038 exception handlers are used. The reason is that certain sections of code
20039 have to be marked as non-abortable.
20041 If you use neither the @code{abort} statement, nor asynchronous transfer
20042 of control (@code{select ... then abort}), then this distributed overhead
20043 is removed, which may have a general positive effect in improving
20044 overall performance.  Especially code involving frequent use of tasking
20045 constructs and controlled types will show much improved performance.
20046 The relevant restrictions pragmas are
20048 @quotation
20050 @example
20051 pragma Restrictions (No_Abort_Statements);
20052 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
20053 @end example
20054 @end quotation
20056 It is recommended that these restriction pragmas be used if possible. Note
20057 that this also means that you can write code without worrying about the
20058 possibility of an immediate abort at any point.
20060 @node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
20061 @anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{184}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{ef}
20062 @subsubsection Optimization Levels
20065 @geindex -O (gcc)
20067 Without any optimization option,
20068 the compiler’s goal is to reduce the cost of
20069 compilation and to make debugging produce the expected results.
20070 Statements are independent: if you stop the program with a breakpoint between
20071 statements, you can then assign a new value to any variable or change
20072 the program counter to any other statement in the subprogram and get exactly
20073 the results you would expect from the source code.
20075 Turning on optimization makes the compiler attempt to improve the
20076 performance and/or code size at the expense of compilation time and
20077 possibly the ability to debug the program.
20079 If you use multiple
20080 -O options, with or without level numbers,
20081 the last such option is the one that is effective.
20083 The default is optimization off. This results in the fastest compile
20084 times, but GNAT makes absolutely no attempt to optimize, and the
20085 generated programs are considerably larger and slower than when
20086 optimization is enabled. You can use the
20087 @code{-O} switch (the permitted forms are @code{-O0}, @code{-O1}
20088 @code{-O2}, @code{-O3}, and @code{-Os})
20089 to @code{gcc} to control the optimization level:
20092 @itemize *
20094 @item 
20096 @table @asis
20098 @item @code{-O0}
20100 No optimization (the default);
20101 generates unoptimized code but has
20102 the fastest compilation time.
20104 Note that many other compilers do substantial optimization even
20105 if ‘no optimization’ is specified. With gcc, it is very unusual
20106 to use @code{-O0} for production if execution time is of any concern,
20107 since @code{-O0} means (almost) no optimization. This difference
20108 between gcc and other compilers should be kept in mind when
20109 doing performance comparisons.
20110 @end table
20112 @item 
20114 @table @asis
20116 @item @code{-O1}
20118 Moderate optimization;
20119 optimizes reasonably well but does not
20120 degrade compilation time significantly.
20121 @end table
20123 @item 
20125 @table @asis
20127 @item @code{-O2}
20129 Full optimization;
20130 generates highly optimized code and has
20131 the slowest compilation time.
20132 @end table
20134 @item 
20136 @table @asis
20138 @item @code{-O3}
20140 Full optimization as in @code{-O2};
20141 also uses more aggressive automatic inlining of subprograms within a unit
20142 (@ref{102,,Inlining of Subprograms}) and attempts to vectorize loops.
20143 @end table
20145 @item 
20147 @table @asis
20149 @item @code{-Os}
20151 Optimize space usage (code and data) of resulting program.
20152 @end table
20153 @end itemize
20155 Higher optimization levels perform more global transformations on the
20156 program and apply more expensive analysis algorithms in order to generate
20157 faster and more compact code. The price in compilation time, and the
20158 resulting improvement in execution time,
20159 both depend on the particular application and the hardware environment.
20160 You should experiment to find the best level for your application.
20162 Since the precise set of optimizations done at each level will vary from
20163 release to release (and sometime from target to target), it is best to think
20164 of the optimization settings in general terms.
20165 See the `Options That Control Optimization' section in
20166 @cite{Using the GNU Compiler Collection (GCC)}
20167 for details about
20168 the @code{-O} settings and a number of @code{-f} options that
20169 individually enable or disable specific optimizations.
20171 Unlike some other compilation systems, @code{gcc} has
20172 been tested extensively at all optimization levels. There are some bugs
20173 which appear only with optimization turned on, but there have also been
20174 bugs which show up only in `unoptimized' code. Selecting a lower
20175 level of optimization does not improve the reliability of the code
20176 generator, which in practice is highly reliable at all optimization
20177 levels.
20179 Note regarding the use of @code{-O3}: The use of this optimization level
20180 ought not to be automatically preferred over that of level @code{-O2},
20181 since it often results in larger executables which may run more slowly.
20182 See further discussion of this point in @ref{102,,Inlining of Subprograms}.
20184 @node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
20185 @anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{185}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{186}
20186 @subsubsection Debugging Optimized Code
20189 @geindex Debugging optimized code
20191 @geindex Optimization and debugging
20193 Although it is possible to do a reasonable amount of debugging at
20194 nonzero optimization levels,
20195 the higher the level the more likely that
20196 source-level constructs will have been eliminated by optimization.
20197 For example, if a loop is strength-reduced, the loop
20198 control variable may be completely eliminated and thus cannot be
20199 displayed in the debugger.
20200 This can only happen at @code{-O2} or @code{-O3}.
20201 Explicit temporary variables that you code might be eliminated at
20202 level @code{-O1} or higher.
20204 @geindex -g (gcc)
20206 The use of the @code{-g} switch,
20207 which is needed for source-level debugging,
20208 affects the size of the program executable on disk,
20209 and indeed the debugging information can be quite large.
20210 However, it has no effect on the generated code (and thus does not
20211 degrade performance)
20213 Since the compiler generates debugging tables for a compilation unit before
20214 it performs optimizations, the optimizing transformations may invalidate some
20215 of the debugging data.  You therefore need to anticipate certain
20216 anomalous situations that may arise while debugging optimized code.
20217 These are the most common cases:
20220 @itemize *
20222 @item 
20223 `The ‘hopping Program Counter’:'  Repeated @code{step} or @code{next}
20224 commands show
20225 the PC bouncing back and forth in the code.  This may result from any of
20226 the following optimizations:
20229 @itemize -
20231 @item 
20232 `Common subexpression elimination:' using a single instance of code for a
20233 quantity that the source computes several times.  As a result you
20234 may not be able to stop on what looks like a statement.
20236 @item 
20237 `Invariant code motion:' moving an expression that does not change within a
20238 loop, to the beginning of the loop.
20240 @item 
20241 `Instruction scheduling:' moving instructions so as to
20242 overlap loads and stores (typically) with other code, or in
20243 general to move computations of values closer to their uses. Often
20244 this causes you to pass an assignment statement without the assignment
20245 happening and then later bounce back to the statement when the
20246 value is actually needed.  Placing a breakpoint on a line of code
20247 and then stepping over it may, therefore, not always cause all the
20248 expected side-effects.
20249 @end itemize
20251 @item 
20252 `The ‘big leap’:' More commonly known as `cross-jumping', in which
20253 two identical pieces of code are merged and the program counter suddenly
20254 jumps to a statement that is not supposed to be executed, simply because
20255 it (and the code following) translates to the same thing as the code
20256 that `was' supposed to be executed.  This effect is typically seen in
20257 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
20258 a @code{break} in a C @code{switch} statement.
20260 @item 
20261 `The ‘roving variable’:' The symptom is an unexpected value in a variable.
20262 There are various reasons for this effect:
20265 @itemize -
20267 @item 
20268 In a subprogram prologue, a parameter may not yet have been moved to its
20269 ‘home’.
20271 @item 
20272 A variable may be dead, and its register re-used.  This is
20273 probably the most common cause.
20275 @item 
20276 As mentioned above, the assignment of a value to a variable may
20277 have been moved.
20279 @item 
20280 A variable may be eliminated entirely by value propagation or
20281 other means.  In this case, GCC may incorrectly generate debugging
20282 information for the variable
20283 @end itemize
20285 In general, when an unexpected value appears for a local variable or parameter
20286 you should first ascertain if that value was actually computed by
20287 your program, as opposed to being incorrectly reported by the debugger.
20288 Record fields or
20289 array elements in an object designated by an access value
20290 are generally less of a problem, once you have ascertained that the access
20291 value is sensible.
20292 Typically, this means checking variables in the preceding code and in the
20293 calling subprogram to verify that the value observed is explainable from other
20294 values (one must apply the procedure recursively to those
20295 other values); or re-running the code and stopping a little earlier
20296 (perhaps before the call) and stepping to better see how the variable obtained
20297 the value in question; or continuing to step `from' the point of the
20298 strange value to see if code motion had simply moved the variable’s
20299 assignments later.
20300 @end itemize
20302 In light of such anomalies, a recommended technique is to use @code{-O0}
20303 early in the software development cycle, when extensive debugging capabilities
20304 are most needed, and then move to @code{-O1} and later @code{-O2} as
20305 the debugger becomes less critical.
20306 Whether to use the @code{-g} switch in the release version is
20307 a release management issue.
20308 Note that if you use @code{-g} you can then use the @code{strip} program
20309 on the resulting executable,
20310 which removes both debugging information and global symbols.
20312 @node Inlining of Subprograms,Floating Point Operations,Debugging Optimized Code,Performance Considerations
20313 @anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{187}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{102}
20314 @subsubsection Inlining of Subprograms
20317 A call to a subprogram in the current unit is inlined if all the
20318 following conditions are met:
20321 @itemize *
20323 @item 
20324 The optimization level is at least @code{-O1}.
20326 @item 
20327 The called subprogram is suitable for inlining: It must be small enough
20328 and not contain something that @code{gcc} cannot support in inlined
20329 subprograms.
20331 @geindex pragma Inline
20333 @geindex Inline
20335 @item 
20336 Any one of the following applies: @code{pragma Inline} is applied to the
20337 subprogram; the subprogram is local to the unit and called once from
20338 within it; the subprogram is small and optimization level @code{-O2} is
20339 specified; optimization level @code{-O3} is specified.
20340 @end itemize
20342 Calls to subprograms in `with'ed units are normally not inlined.
20343 To achieve actual inlining (that is, replacement of the call by the code
20344 in the body of the subprogram), the following conditions must all be true:
20347 @itemize *
20349 @item 
20350 The optimization level is at least @code{-O1}.
20352 @item 
20353 The called subprogram is suitable for inlining: It must be small enough
20354 and not contain something that @code{gcc} cannot support in inlined
20355 subprograms.
20357 @item 
20358 There is a @code{pragma Inline} for the subprogram.
20360 @item 
20361 The @code{-gnatn} switch is used on the command line.
20362 @end itemize
20364 Even if all these conditions are met, it may not be possible for
20365 the compiler to inline the call, due to the length of the body,
20366 or features in the body that make it impossible for the compiler
20367 to do the inlining.
20369 Note that specifying the @code{-gnatn} switch causes additional
20370 compilation dependencies. Consider the following:
20372 @quotation
20374 @example
20375 package R is
20376    procedure Q;
20377    pragma Inline (Q);
20378 end R;
20379 package body R is
20380    ...
20381 end R;
20383 with R;
20384 procedure Main is
20385 begin
20386    ...
20387    R.Q;
20388 end Main;
20389 @end example
20390 @end quotation
20392 With the default behavior (no @code{-gnatn} switch specified), the
20393 compilation of the @code{Main} procedure depends only on its own source,
20394 @code{main.adb}, and the spec of the package in file @code{r.ads}. This
20395 means that editing the body of @code{R} does not require recompiling
20396 @code{Main}.
20398 On the other hand, the call @code{R.Q} is not inlined under these
20399 circumstances. If the @code{-gnatn} switch is present when @code{Main}
20400 is compiled, the call will be inlined if the body of @code{Q} is small
20401 enough, but now @code{Main} depends on the body of @code{R} in
20402 @code{r.adb} as well as on the spec. This means that if this body is edited,
20403 the main program must be recompiled. Note that this extra dependency
20404 occurs whether or not the call is in fact inlined by @code{gcc}.
20406 The use of front end inlining with @code{-gnatN} generates similar
20407 additional dependencies.
20409 @geindex -fno-inline (gcc)
20411 Note: The @code{-fno-inline} switch overrides all other conditions and ensures that
20412 no inlining occurs, unless requested with pragma Inline_Always for @code{gcc}
20413 back-ends. The extra dependences resulting from @code{-gnatn} will still be active,
20414 even if this switch is used to suppress the resulting inlining actions.
20416 @geindex -fno-inline-functions (gcc)
20418 Note: The @code{-fno-inline-functions} switch can be used to prevent
20419 automatic inlining of subprograms if @code{-O3} is used.
20421 @geindex -fno-inline-small-functions (gcc)
20423 Note: The @code{-fno-inline-small-functions} switch can be used to prevent
20424 automatic inlining of small subprograms if @code{-O2} is used.
20426 @geindex -fno-inline-functions-called-once (gcc)
20428 Note: The @code{-fno-inline-functions-called-once} switch
20429 can be used to prevent inlining of subprograms local to the unit
20430 and called once from within it if @code{-O1} is used.
20432 Note regarding the use of @code{-O3}: @code{-gnatn} is made up of two
20433 sub-switches @code{-gnatn1} and @code{-gnatn2} that can be directly
20434 specified in lieu of it, @code{-gnatn} being translated into one of them
20435 based on the optimization level. With @code{-O2} or below, @code{-gnatn}
20436 is equivalent to @code{-gnatn1} which activates pragma @code{Inline} with
20437 moderate inlining across modules. With @code{-O3}, @code{-gnatn} is
20438 equivalent to @code{-gnatn2} which activates pragma @code{Inline} with
20439 full inlining across modules. If you have used pragma @code{Inline} in
20440 appropriate cases, then it is usually much better to use @code{-O2}
20441 and @code{-gnatn} and avoid the use of @code{-O3} which has the additional
20442 effect of inlining subprograms you did not think should be inlined. We have
20443 found that the use of @code{-O3} may slow down the compilation and increase
20444 the code size by performing excessive inlining, leading to increased
20445 instruction cache pressure from the increased code size and thus minor
20446 performance improvements. So the bottom line here is that you should not
20447 automatically assume that @code{-O3} is better than @code{-O2}, and
20448 indeed you should use @code{-O3} only if tests show that it actually
20449 improves performance for your program.
20451 @node Floating Point Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
20452 @anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{188}@anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{189}
20453 @subsubsection Floating Point Operations
20456 @geindex Floating-Point Operations
20458 On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
20459 64-bit standard IEEE floating-point representations, and operations will
20460 use standard IEEE arithmetic as provided by the processor. On most, but
20461 not all, architectures, the attribute Machine_Overflows is False for these
20462 types, meaning that the semantics of overflow is implementation-defined.
20463 In the case of GNAT, these semantics correspond to the normal IEEE
20464 treatment of infinities and NaN (not a number) values. For example,
20465 1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
20466 avoiding explicit overflow checks, the performance is greatly improved
20467 on many targets. However, if required, floating-point overflow can be
20468 enabled by the use of the pragma Check_Float_Overflow.
20470 Another consideration that applies specifically to x86 32-bit
20471 architectures is which form of floating-point arithmetic is used.
20472 By default the operations use the old style x86 floating-point,
20473 which implements an 80-bit extended precision form (on these
20474 architectures the type Long_Long_Float corresponds to that form).
20475 In addition, generation of efficient code in this mode means that
20476 the extended precision form will be used for intermediate results.
20477 This may be helpful in improving the final precision of a complex
20478 expression. However it means that the results obtained on the x86
20479 will be different from those on other architectures, and for some
20480 algorithms, the extra intermediate precision can be detrimental.
20482 In addition to this old-style floating-point, all modern x86 chips
20483 implement an alternative floating-point operation model referred
20484 to as SSE2. In this model there is no extended form, and furthermore
20485 execution performance is significantly enhanced. To force GNAT to use
20486 this more modern form, use both of the switches:
20488 @quotation
20490 -msse2 -mfpmath=sse
20491 @end quotation
20493 A unit compiled with these switches will automatically use the more
20494 efficient SSE2 instruction set for Float and Long_Float operations.
20495 Note that the ABI has the same form for both floating-point models,
20496 so it is permissible to mix units compiled with and without these
20497 switches.
20499 @node Vectorization of loops,Other Optimization Switches,Floating Point Operations,Performance Considerations
20500 @anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{18a}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{18b}
20501 @subsubsection Vectorization of loops
20504 @geindex Optimization Switches
20506 You can take advantage of the auto-vectorizer present in the @code{gcc}
20507 back end to vectorize loops with GNAT.  The corresponding command line switch
20508 is @code{-ftree-vectorize} but, as it is enabled by default at @code{-O3}
20509 and other aggressive optimizations helpful for vectorization also are enabled
20510 by default at this level, using @code{-O3} directly is recommended.
20512 You also need to make sure that the target architecture features a supported
20513 SIMD instruction set.  For example, for the x86 architecture, you should at
20514 least specify @code{-msse2} to get significant vectorization (but you don’t
20515 need to specify it for x86-64 as it is part of the base 64-bit architecture).
20516 Similarly, for the PowerPC architecture, you should specify @code{-maltivec}.
20518 The preferred loop form for vectorization is the @code{for} iteration scheme.
20519 Loops with a @code{while} iteration scheme can also be vectorized if they are
20520 very simple, but the vectorizer will quickly give up otherwise.  With either
20521 iteration scheme, the flow of control must be straight, in particular no
20522 @code{exit} statement may appear in the loop body.  The loop may however
20523 contain a single nested loop, if it can be vectorized when considered alone:
20525 @quotation
20527 @example
20528 A : array (1..4, 1..4) of Long_Float;
20529 S : array (1..4) of Long_Float;
20531 procedure Sum is
20532 begin
20533    for I in A'Range(1) loop
20534       for J in A'Range(2) loop
20535          S (I) := S (I) + A (I, J);
20536       end loop;
20537    end loop;
20538 end Sum;
20539 @end example
20540 @end quotation
20542 The vectorizable operations depend on the targeted SIMD instruction set, but
20543 the adding and some of the multiplying operators are generally supported, as
20544 well as the logical operators for modular types. Note that compiling
20545 with @code{-gnatp} might well reveal cases where some checks do thwart
20546 vectorization.
20548 Type conversions may also prevent vectorization if they involve semantics that
20549 are not directly supported by the code generator or the SIMD instruction set.
20550 A typical example is direct conversion from floating-point to integer types.
20551 The solution in this case is to use the following idiom:
20553 @quotation
20555 @example
20556 Integer (S'Truncation (F))
20557 @end example
20558 @end quotation
20560 if @code{S} is the subtype of floating-point object @code{F}.
20562 In most cases, the vectorizable loops are loops that iterate over arrays.
20563 All kinds of array types are supported, i.e. constrained array types with
20564 static bounds:
20566 @quotation
20568 @example
20569 type Array_Type is array (1 .. 4) of Long_Float;
20570 @end example
20571 @end quotation
20573 constrained array types with dynamic bounds:
20575 @quotation
20577 @example
20578 type Array_Type is array (1 .. Q.N) of Long_Float;
20580 type Array_Type is array (Q.K .. 4) of Long_Float;
20582 type Array_Type is array (Q.K .. Q.N) of Long_Float;
20583 @end example
20584 @end quotation
20586 or unconstrained array types:
20588 @quotation
20590 @example
20591 type Array_Type is array (Positive range <>) of Long_Float;
20592 @end example
20593 @end quotation
20595 The quality of the generated code decreases when the dynamic aspect of the
20596 array type increases, the worst code being generated for unconstrained array
20597 types.  This is so because, the less information the compiler has about the
20598 bounds of the array, the more fallback code it needs to generate in order to
20599 fix things up at run time.
20601 It is possible to specify that a given loop should be subject to vectorization
20602 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
20604 @quotation
20606 @example
20607 pragma Loop_Optimize (Vector);
20608 @end example
20609 @end quotation
20611 placed immediately within the loop will convey the appropriate hint to the
20612 compiler for this loop.
20614 It is also possible to help the compiler generate better vectorized code
20615 for a given loop by asserting that there are no loop-carried dependencies
20616 in the loop.  Consider for example the procedure:
20618 @quotation
20620 @example
20621 type Arr is array (1 .. 4) of Long_Float;
20623 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
20624 begin
20625   for I in Arr'Range loop
20626     R(I) := X(I) + Y(I);
20627   end loop;
20628 end;
20629 @end example
20630 @end quotation
20632 By default, the compiler cannot unconditionally vectorize the loop because
20633 assigning to a component of the array designated by R in one iteration could
20634 change the value read from the components of the array designated by X or Y
20635 in a later iteration.  As a result, the compiler will generate two versions
20636 of the loop in the object code, one vectorized and the other not vectorized,
20637 as well as a test to select the appropriate version at run time.  This can
20638 be overcome by another hint:
20640 @quotation
20642 @example
20643 pragma Loop_Optimize (Ivdep);
20644 @end example
20645 @end quotation
20647 placed immediately within the loop will tell the compiler that it can safely
20648 omit the non-vectorized version of the loop as well as the run-time test.
20650 @node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
20651 @anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{18c}@anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{18d}
20652 @subsubsection Other Optimization Switches
20655 @geindex Optimization Switches
20657 Since GNAT uses the @code{gcc} back end, all the specialized
20658 @code{gcc} optimization switches are potentially usable. These switches
20659 have not been extensively tested with GNAT but can generally be expected
20660 to work. Examples of switches in this category are @code{-funroll-loops}
20661 and the various target-specific @code{-m} options (in particular, it has
20662 been observed that @code{-march=xxx} can significantly improve performance
20663 on appropriate machines). For full details of these switches, see
20664 the `Submodel Options' section in the `Hardware Models and Configurations'
20665 chapter of @cite{Using the GNU Compiler Collection (GCC)}.
20667 @node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
20668 @anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{18e}@anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{e6}
20669 @subsubsection Optimization and Strict Aliasing
20672 @geindex Aliasing
20674 @geindex Strict Aliasing
20676 @geindex No_Strict_Aliasing
20678 The strong typing capabilities of Ada allow an optimizer to generate
20679 efficient code in situations where other languages would be forced to
20680 make worst case assumptions preventing such optimizations. Consider
20681 the following example:
20683 @quotation
20685 @example
20686 procedure R is
20687    type Int1 is new Integer;
20688    type Int2 is new Integer;
20689    type Int1A is access Int1;
20690    type Int2A is access Int2;
20691    Int1V : Int1A;
20692    Int2V : Int2A;
20693    ...
20695 begin
20696    ...
20697    for J in Data'Range loop
20698       if Data (J) = Int1V.all then
20699          Int2V.all := Int2V.all + 1;
20700       end if;
20701    end loop;
20702    ...
20703 end R;
20704 @end example
20705 @end quotation
20707 In this example, since the variable @code{Int1V} can only access objects
20708 of type @code{Int1}, and @code{Int2V} can only access objects of type
20709 @code{Int2}, there is no possibility that the assignment to
20710 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
20711 the compiler optimizer can “know” that the value @code{Int1V.all} is constant
20712 for all iterations of the loop and avoid the extra memory reference
20713 required to dereference it each time through the loop.
20715 This kind of optimization, called strict aliasing analysis, is
20716 triggered by specifying an optimization level of @code{-O2} or
20717 higher or @code{-Os} and allows GNAT to generate more efficient code
20718 when access values are involved.
20720 However, although this optimization is always correct in terms of
20721 the formal semantics of the Ada Reference Manual, difficulties can
20722 arise if features like @code{Unchecked_Conversion} are used to break
20723 the typing system. Consider the following complete program example:
20725 @quotation
20727 @example
20728 package p1 is
20729    type int1 is new integer;
20730    type int2 is new integer;
20731    type a1 is access int1;
20732    type a2 is access int2;
20733 end p1;
20735 with p1; use p1;
20736 package p2 is
20737    function to_a2 (Input : a1) return a2;
20738 end p2;
20740 with Ada.Unchecked_Conversion;
20741 package body p2 is
20742    function to_a2 (Input : a1) return a2 is
20743       function to_a2u is
20744         new Ada.Unchecked_Conversion (a1, a2);
20745    begin
20746       return to_a2u (Input);
20747    end to_a2;
20748 end p2;
20750 with p2; use p2;
20751 with p1; use p1;
20752 with Text_IO; use Text_IO;
20753 procedure m is
20754    v1 : a1 := new int1;
20755    v2 : a2 := to_a2 (v1);
20756 begin
20757    v1.all := 1;
20758    v2.all := 0;
20759    put_line (int1'image (v1.all));
20760 end;
20761 @end example
20762 @end quotation
20764 This program prints out 0 in @code{-O0} or @code{-O1}
20765 mode, but it prints out 1 in @code{-O2} mode. That’s
20766 because in strict aliasing mode, the compiler can and
20767 does assume that the assignment to @code{v2.all} could not
20768 affect the value of @code{v1.all}, since different types
20769 are involved.
20771 This behavior is not a case of non-conformance with the standard, since
20772 the Ada RM specifies that an unchecked conversion where the resulting
20773 bit pattern is not a correct value of the target type can result in an
20774 abnormal value and attempting to reference an abnormal value makes the
20775 execution of a program erroneous.  That’s the case here since the result
20776 does not point to an object of type @code{int2}.  This means that the
20777 effect is entirely unpredictable.
20779 However, although that explanation may satisfy a language
20780 lawyer, in practice an applications programmer expects an
20781 unchecked conversion involving pointers to create true
20782 aliases and the behavior of printing 1 seems plain wrong.
20783 In this case, the strict aliasing optimization is unwelcome.
20785 Indeed the compiler recognizes this possibility, and the
20786 unchecked conversion generates a warning:
20788 @quotation
20790 @example
20791 p2.adb:5:07: warning: possible aliasing problem with type "a2"
20792 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
20793 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
20794 @end example
20795 @end quotation
20797 Unfortunately the problem is recognized when compiling the body of
20798 package @code{p2}, but the actual “bad” code is generated while
20799 compiling the body of @code{m} and this latter compilation does not see
20800 the suspicious @code{Unchecked_Conversion}.
20802 As implied by the warning message, there are approaches you can use to
20803 avoid the unwanted strict aliasing optimization in a case like this.
20805 One possibility is to simply avoid the use of @code{-O2}, but
20806 that is a bit drastic, since it throws away a number of useful
20807 optimizations that do not involve strict aliasing assumptions.
20809 A less drastic approach is to compile the program using the
20810 option @code{-fno-strict-aliasing}. Actually it is only the
20811 unit containing the dereferencing of the suspicious pointer
20812 that needs to be compiled. So in this case, if we compile
20813 unit @code{m} with this switch, then we get the expected
20814 value of zero printed. Analyzing which units might need
20815 the switch can be painful, so a more reasonable approach
20816 is to compile the entire program with options @code{-O2}
20817 and @code{-fno-strict-aliasing}. If the performance is
20818 satisfactory with this combination of options, then the
20819 advantage is that the entire issue of possible “wrong”
20820 optimization due to strict aliasing is avoided.
20822 To avoid the use of compiler switches, the configuration
20823 pragma @code{No_Strict_Aliasing} with no parameters may be
20824 used to specify that for all access types, the strict
20825 aliasing optimization should be suppressed.
20827 However, these approaches are still overkill, in that they causes
20828 all manipulations of all access values to be deoptimized. A more
20829 refined approach is to concentrate attention on the specific
20830 access type identified as problematic.
20832 First, if a careful analysis of uses of the pointer shows
20833 that there are no possible problematic references, then
20834 the warning can be suppressed by bracketing the
20835 instantiation of @code{Unchecked_Conversion} to turn
20836 the warning off:
20838 @quotation
20840 @example
20841 pragma Warnings (Off);
20842 function to_a2u is
20843   new Ada.Unchecked_Conversion (a1, a2);
20844 pragma Warnings (On);
20845 @end example
20846 @end quotation
20848 Of course that approach is not appropriate for this particular
20849 example, since indeed there is a problematic reference. In this
20850 case we can take one of two other approaches.
20852 The first possibility is to move the instantiation of unchecked
20853 conversion to the unit in which the type is declared. In
20854 this example, we would move the instantiation of
20855 @code{Unchecked_Conversion} from the body of package
20856 @code{p2} to the spec of package @code{p1}. Now the
20857 warning disappears. That’s because any use of the
20858 access type knows there is a suspicious unchecked
20859 conversion, and the strict aliasing optimization
20860 is automatically suppressed for the type.
20862 If it is not practical to move the unchecked conversion to the same unit
20863 in which the destination access type is declared (perhaps because the
20864 source type is not visible in that unit), you may use pragma
20865 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
20866 same declarative sequence as the declaration of the access type:
20868 @quotation
20870 @example
20871 type a2 is access int2;
20872 pragma No_Strict_Aliasing (a2);
20873 @end example
20874 @end quotation
20876 Here again, the compiler now knows that the strict aliasing optimization
20877 should be suppressed for any reference to type @code{a2} and the
20878 expected behavior is obtained.
20880 Finally, note that although the compiler can generate warnings for
20881 simple cases of unchecked conversions, there are tricker and more
20882 indirect ways of creating type incorrect aliases which the compiler
20883 cannot detect. Examples are the use of address overlays and unchecked
20884 conversions involving composite types containing access types as
20885 components. In such cases, no warnings are generated, but there can
20886 still be aliasing problems. One safe coding practice is to forbid the
20887 use of address clauses for type overlaying, and to allow unchecked
20888 conversion only for primitive types. This is not really a significant
20889 restriction since any possible desired effect can be achieved by
20890 unchecked conversion of access values.
20892 The aliasing analysis done in strict aliasing mode can certainly
20893 have significant benefits. We have seen cases of large scale
20894 application code where the time is increased by up to 5% by turning
20895 this optimization off. If you have code that includes significant
20896 usage of unchecked conversion, you might want to just stick with
20897 @code{-O1} and avoid the entire issue. If you get adequate
20898 performance at this level of optimization level, that’s probably
20899 the safest approach. If tests show that you really need higher
20900 levels of optimization, then you can experiment with @code{-O2}
20901 and @code{-O2 -fno-strict-aliasing} to see how much effect this
20902 has on size and speed of the code. If you really need to use
20903 @code{-O2} with strict aliasing in effect, then you should
20904 review any uses of unchecked conversion of access types,
20905 particularly if you are getting the warnings described above.
20907 @node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
20908 @anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{18f}@anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{190}
20909 @subsubsection Aliased Variables and Optimization
20912 @geindex Aliasing
20914 There are scenarios in which programs may
20915 use low level techniques to modify variables
20916 that otherwise might be considered to be unassigned. For example,
20917 a variable can be passed to a procedure by reference, which takes
20918 the address of the parameter and uses the address to modify the
20919 variable’s value, even though it is passed as an IN parameter.
20920 Consider the following example:
20922 @quotation
20924 @example
20925 procedure P is
20926    Max_Length : constant Natural := 16;
20927    type Char_Ptr is access all Character;
20929    procedure Get_String(Buffer: Char_Ptr; Size : Integer);
20930    pragma Import (C, Get_String, "get_string");
20932    Name : aliased String (1 .. Max_Length) := (others => ' ');
20933    Temp : Char_Ptr;
20935    function Addr (S : String) return Char_Ptr is
20936       function To_Char_Ptr is
20937         new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
20938    begin
20939       return To_Char_Ptr (S (S'First)'Address);
20940    end;
20942 begin
20943    Temp := Addr (Name);
20944    Get_String (Temp, Max_Length);
20945 end;
20946 @end example
20947 @end quotation
20949 where Get_String is a C function that uses the address in Temp to
20950 modify the variable @code{Name}. This code is dubious, and arguably
20951 erroneous, and the compiler would be entitled to assume that
20952 @code{Name} is never modified, and generate code accordingly.
20954 However, in practice, this would cause some existing code that
20955 seems to work with no optimization to start failing at high
20956 levels of optimization.
20958 What the compiler does for such cases is to assume that marking
20959 a variable as aliased indicates that some “funny business” may
20960 be going on. The optimizer recognizes the aliased keyword and
20961 inhibits optimizations that assume the value cannot be assigned.
20962 This means that the above example will in fact “work” reliably,
20963 that is, it will produce the expected results.
20965 @node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
20966 @anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{191}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{192}
20967 @subsubsection Atomic Variables and Optimization
20970 @geindex Atomic
20972 There are two considerations with regard to performance when
20973 atomic variables are used.
20975 First, the RM only guarantees that access to atomic variables
20976 be atomic, it has nothing to say about how this is achieved,
20977 though there is a strong implication that this should not be
20978 achieved by explicit locking code. Indeed GNAT will never
20979 generate any locking code for atomic variable access (it will
20980 simply reject any attempt to make a variable or type atomic
20981 if the atomic access cannot be achieved without such locking code).
20983 That being said, it is important to understand that you cannot
20984 assume that the entire variable will always be accessed. Consider
20985 this example:
20987 @quotation
20989 @example
20990 type R is record
20991    A,B,C,D : Character;
20992 end record;
20993 for R'Size use 32;
20994 for R'Alignment use 4;
20996 RV : R;
20997 pragma Atomic (RV);
20998 X : Character;
21000 X := RV.B;
21001 @end example
21002 @end quotation
21004 You cannot assume that the reference to @code{RV.B}
21005 will read the entire 32-bit
21006 variable with a single load instruction. It is perfectly legitimate if
21007 the hardware allows it to do a byte read of just the B field. This read
21008 is still atomic, which is all the RM requires. GNAT can and does take
21009 advantage of this, depending on the architecture and optimization level.
21010 Any assumption to the contrary is non-portable and risky. Even if you
21011 examine the assembly language and see a full 32-bit load, this might
21012 change in a future version of the compiler.
21014 If your application requires that all accesses to @code{RV} in this
21015 example be full 32-bit loads, you need to make a copy for the access
21016 as in:
21018 @quotation
21020 @example
21021 declare
21022    RV_Copy : constant R := RV;
21023 begin
21024    X := RV_Copy.B;
21025 end;
21026 @end example
21027 @end quotation
21029 Now the reference to RV must read the whole variable.
21030 Actually one can imagine some compiler which figures
21031 out that the whole copy is not required (because only
21032 the B field is actually accessed), but GNAT
21033 certainly won’t do that, and we don’t know of any
21034 compiler that would not handle this right, and the
21035 above code will in practice work portably across
21036 all architectures (that permit the Atomic declaration).
21038 The second issue with atomic variables has to do with
21039 the possible requirement of generating synchronization
21040 code. For more details on this, consult the sections on
21041 the pragmas Enable/Disable_Atomic_Synchronization in the
21042 GNAT Reference Manual. If performance is critical, and
21043 such synchronization code is not required, it may be
21044 useful to disable it.
21046 @node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
21047 @anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{193}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{194}
21048 @subsubsection Passive Task Optimization
21051 @geindex Passive Task
21053 A passive task is one which is sufficiently simple that
21054 in theory a compiler could recognize it an implement it
21055 efficiently without creating a new thread. The original design
21056 of Ada 83 had in mind this kind of passive task optimization, but
21057 only a few Ada 83 compilers attempted it. The problem was that
21058 it was difficult to determine the exact conditions under which
21059 the optimization was possible. The result is a very fragile
21060 optimization where a very minor change in the program can
21061 suddenly silently make a task non-optimizable.
21063 With the revisiting of this issue in Ada 95, there was general
21064 agreement that this approach was fundamentally flawed, and the
21065 notion of protected types was introduced. When using protected
21066 types, the restrictions are well defined, and you KNOW that the
21067 operations will be optimized, and furthermore this optimized
21068 performance is fully portable.
21070 Although it would theoretically be possible for GNAT to attempt to
21071 do this optimization, but it really doesn’t make sense in the
21072 context of Ada 95, and none of the Ada 95 compilers implement
21073 this optimization as far as we know. In particular GNAT never
21074 attempts to perform this optimization.
21076 In any new Ada 95 code that is written, you should always
21077 use protected types in place of tasks that might be able to
21078 be optimized in this manner.
21079 Of course this does not help if you have legacy Ada 83 code
21080 that depends on this optimization, but it is unusual to encounter
21081 a case where the performance gains from this optimization
21082 are significant.
21084 Your program should work correctly without this optimization. If
21085 you have performance problems, then the most practical
21086 approach is to figure out exactly where these performance problems
21087 arise, and update those particular tasks to be protected types. Note
21088 that typically clients of the tasks who call entries, will not have
21089 to be modified, only the task definition itself.
21091 @node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
21092 @anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{195}@anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{196}
21093 @subsection @code{Text_IO} Suggestions
21096 @geindex Text_IO and performance
21098 The @code{Ada.Text_IO} package has fairly high overheads due in part to
21099 the requirement of maintaining page and line counts. If performance
21100 is critical, a recommendation is to use @code{Stream_IO} instead of
21101 @code{Text_IO} for volume output, since this package has less overhead.
21103 If @code{Text_IO} must be used, note that by default output to the standard
21104 output and standard error files is unbuffered (this provides better
21105 behavior when output statements are used for debugging, or if the
21106 progress of a program is observed by tracking the output, e.g. by
21107 using the Unix `tail -f' command to watch redirected output).
21109 If you are generating large volumes of output with @code{Text_IO} and
21110 performance is an important factor, use a designated file instead
21111 of the standard output file, or change the standard output file to
21112 be buffered using @code{Interfaces.C_Streams.setvbuf}.
21114 @node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
21115 @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}
21116 @subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
21119 @geindex Uunused subprogram/data elimination
21121 This section describes how you can eliminate unused subprograms and data from
21122 your executable just by setting options at compilation time.
21124 @menu
21125 * About unused subprogram/data elimination:: 
21126 * Compilation options:: 
21127 * Example of unused subprogram/data elimination:: 
21129 @end menu
21131 @node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
21132 @anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{199}@anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{19a}
21133 @subsubsection About unused subprogram/data elimination
21136 By default, an executable contains all code and data of its composing objects
21137 (directly linked or coming from statically linked libraries), even data or code
21138 never used by this executable.
21140 This feature will allow you to eliminate such unused code from your
21141 executable, making it smaller (in disk and in memory).
21143 This functionality is available on all Linux platforms except for the IA-64
21144 architecture and on all cross platforms using the ELF binary file format.
21145 In both cases GNU binutils version 2.16 or later are required to enable it.
21147 @node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
21148 @anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{19b}@anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{19c}
21149 @subsubsection Compilation options
21152 The operation of eliminating the unused code and data from the final executable
21153 is directly performed by the linker.
21155 @geindex -ffunction-sections (gcc)
21157 @geindex -fdata-sections (gcc)
21159 In order to do this, it has to work with objects compiled with the
21160 following options:
21161 @code{-ffunction-sections} @code{-fdata-sections}.
21163 These options are usable with C and Ada files.
21164 They will place respectively each
21165 function or data in a separate section in the resulting object file.
21167 Once the objects and static libraries are created with these options, the
21168 linker can perform the dead code elimination. You can do this by setting
21169 the @code{-Wl,--gc-sections} option to gcc command or in the
21170 @code{-largs} section of @code{gnatmake}. This will perform a
21171 garbage collection of code and data never referenced.
21173 If the linker performs a partial link (@code{-r} linker option), then you
21174 will need to provide the entry point using the @code{-e} / @code{--entry}
21175 linker option.
21177 Note that objects compiled without the @code{-ffunction-sections} and
21178 @code{-fdata-sections} options can still be linked with the executable.
21179 However, no dead code elimination will be performed on those objects (they will
21180 be linked as is).
21182 The GNAT static library is now compiled with -ffunction-sections and
21183 -fdata-sections on some platforms. This allows you to eliminate the unused code
21184 and data of the GNAT library from your executable.
21186 @node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
21187 @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}
21188 @subsubsection Example of unused subprogram/data elimination
21191 Here is a simple example:
21193 @quotation
21195 @example
21196 with Aux;
21198 procedure Test is
21199 begin
21200    Aux.Used (10);
21201 end Test;
21203 package Aux is
21204    Used_Data   : Integer;
21205    Unused_Data : Integer;
21207    procedure Used   (Data : Integer);
21208    procedure Unused (Data : Integer);
21209 end Aux;
21211 package body Aux is
21212    procedure Used (Data : Integer) is
21213    begin
21214       Used_Data := Data;
21215    end Used;
21217    procedure Unused (Data : Integer) is
21218    begin
21219       Unused_Data := Data;
21220    end Unused;
21221 end Aux;
21222 @end example
21223 @end quotation
21225 @code{Unused} and @code{Unused_Data} are never referenced in this code
21226 excerpt, and hence they may be safely removed from the final executable.
21228 @quotation
21230 @example
21231 $ gnatmake test
21233 $ nm test | grep used
21234 020015f0 T aux__unused
21235 02005d88 B aux__unused_data
21236 020015cc T aux__used
21237 02005d84 B aux__used_data
21239 $ gnatmake test -cargs -fdata-sections -ffunction-sections \\
21240      -largs -Wl,--gc-sections
21242 $ nm test | grep used
21243 02005350 T aux__used
21244 0201ffe0 B aux__used_data
21245 @end example
21246 @end quotation
21248 It can be observed that the procedure @code{Unused} and the object
21249 @code{Unused_Data} are removed by the linker when using the
21250 appropriate options.
21252 @geindex Overflow checks
21254 @geindex Checks (overflow)
21256 @node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
21257 @anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{14b}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{19f}
21258 @section Overflow Check Handling in GNAT
21261 This section explains how to control the handling of overflow checks.
21263 @menu
21264 * Background:: 
21265 * Management of Overflows in GNAT:: 
21266 * Specifying the Desired Mode:: 
21267 * Default Settings:: 
21268 * Implementation Notes:: 
21270 @end menu
21272 @node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
21273 @anchor{gnat_ugn/gnat_and_program_execution background}@anchor{1a0}@anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{1a1}
21274 @subsection Background
21277 Overflow checks are checks that the compiler may make to ensure
21278 that intermediate results are not out of range. For example:
21280 @quotation
21282 @example
21283 A : Integer;
21285 A := A + 1;
21286 @end example
21287 @end quotation
21289 If @code{A} has the value @code{Integer'Last}, then the addition may cause
21290 overflow since the result is out of range of the type @code{Integer}.
21291 In this case @code{Constraint_Error} will be raised if checks are
21292 enabled.
21294 A trickier situation arises in examples like the following:
21296 @quotation
21298 @example
21299 A, C : Integer;
21301 A := (A + 1) + C;
21302 @end example
21303 @end quotation
21305 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
21306 Now the final result of the expression on the right hand side is
21307 @code{Integer'Last} which is in range, but the question arises whether the
21308 intermediate addition of @code{(A + 1)} raises an overflow error.
21310 The (perhaps surprising) answer is that the Ada language
21311 definition does not answer this question. Instead it leaves
21312 it up to the implementation to do one of two things if overflow
21313 checks are enabled.
21316 @itemize *
21318 @item 
21319 raise an exception (@code{Constraint_Error}), or
21321 @item 
21322 yield the correct mathematical result which is then used in
21323 subsequent operations.
21324 @end itemize
21326 If the compiler chooses the first approach, then the assignment of this
21327 example will indeed raise @code{Constraint_Error} if overflow checking is
21328 enabled, or result in erroneous execution if overflow checks are suppressed.
21330 But if the compiler
21331 chooses the second approach, then it can perform both additions yielding
21332 the correct mathematical result, which is in range, so no exception
21333 will be raised, and the right result is obtained, regardless of whether
21334 overflow checks are suppressed.
21336 Note that in the first example an
21337 exception will be raised in either case, since if the compiler
21338 gives the correct mathematical result for the addition, it will
21339 be out of range of the target type of the assignment, and thus
21340 fails the range check.
21342 This lack of specified behavior in the handling of overflow for
21343 intermediate results is a source of non-portability, and can thus
21344 be problematic when programs are ported. Most typically this arises
21345 in a situation where the original compiler did not raise an exception,
21346 and then the application is moved to a compiler where the check is
21347 performed on the intermediate result and an unexpected exception is
21348 raised.
21350 Furthermore, when using Ada 2012’s preconditions and other
21351 assertion forms, another issue arises. Consider:
21353 @quotation
21355 @example
21356 procedure P (A, B : Integer) with
21357   Pre => A + B <= Integer'Last;
21358 @end example
21359 @end quotation
21361 One often wants to regard arithmetic in a context like this from
21362 a mathematical point of view. So for example, if the two actual parameters
21363 for a call to @code{P} are both @code{Integer'Last}, then
21364 the precondition should be regarded as False. If we are executing
21365 in a mode with run-time checks enabled for preconditions, then we would
21366 like this precondition to fail, rather than raising an exception
21367 because of the intermediate overflow.
21369 However, the language definition leaves the specification of
21370 whether the above condition fails (raising @code{Assert_Error}) or
21371 causes an intermediate overflow (raising @code{Constraint_Error})
21372 up to the implementation.
21374 The situation is worse in a case such as the following:
21376 @quotation
21378 @example
21379 procedure Q (A, B, C : Integer) with
21380   Pre => A + B + C <= Integer'Last;
21381 @end example
21382 @end quotation
21384 Consider the call
21386 @quotation
21388 @example
21389 Q (A => Integer'Last, B => 1, C => -1);
21390 @end example
21391 @end quotation
21393 From a mathematical point of view the precondition
21394 is True, but at run time we may (but are not guaranteed to) get an
21395 exception raised because of the intermediate overflow (and we really
21396 would prefer this precondition to be considered True at run time).
21398 @node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
21399 @anchor{gnat_ugn/gnat_and_program_execution id47}@anchor{1a2}@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{1a3}
21400 @subsection Management of Overflows in GNAT
21403 To deal with the portability issue, and with the problem of
21404 mathematical versus run-time interpretation of the expressions in
21405 assertions, GNAT provides comprehensive control over the handling
21406 of intermediate overflow. GNAT can operate in three modes, and
21407 furthermore, permits separate selection of operating modes for
21408 the expressions within assertions (here the term ‘assertions’
21409 is used in the technical sense, which includes preconditions and so forth)
21410 and for expressions appearing outside assertions.
21412 The three modes are:
21415 @itemize *
21417 @item 
21418 `Use base type for intermediate operations' (@code{STRICT})
21420 In this mode, all intermediate results for predefined arithmetic
21421 operators are computed using the base type, and the result must
21422 be in range of the base type. If this is not the
21423 case then either an exception is raised (if overflow checks are
21424 enabled) or the execution is erroneous (if overflow checks are suppressed).
21425 This is the normal default mode.
21427 @item 
21428 `Most intermediate overflows avoided' (@code{MINIMIZED})
21430 In this mode, the compiler attempts to avoid intermediate overflows by
21431 using a larger integer type, typically @code{Long_Long_Integer},
21432 as the type in which arithmetic is
21433 performed for predefined arithmetic operators. This may be slightly more
21434 expensive at
21435 run time (compared to suppressing intermediate overflow checks), though
21436 the cost is negligible on modern 64-bit machines. For the examples given
21437 earlier, no intermediate overflows would have resulted in exceptions,
21438 since the intermediate results are all in the range of
21439 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
21440 of GNAT). In addition, if checks are enabled, this reduces the number of
21441 checks that must be made, so this choice may actually result in an
21442 improvement in space and time behavior.
21444 However, there are cases where @code{Long_Long_Integer} is not large
21445 enough, consider the following example:
21447 @quotation
21449 @example
21450 procedure R (A, B, C, D : Integer) with
21451   Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
21452 @end example
21453 @end quotation
21455 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
21456 Now the intermediate results are
21457 out of the range of @code{Long_Long_Integer} even though the final result
21458 is in range and the precondition is True (from a mathematical point
21459 of view). In such a case, operating in this mode, an overflow occurs
21460 for the intermediate computation (which is why this mode
21461 says `most' intermediate overflows are avoided). In this case,
21462 an exception is raised if overflow checks are enabled, and the
21463 execution is erroneous if overflow checks are suppressed.
21465 @item 
21466 `All intermediate overflows avoided' (@code{ELIMINATED})
21468 In this mode, the compiler  avoids all intermediate overflows
21469 by using arbitrary precision arithmetic as required. In this
21470 mode, the above example with @code{A**2 * B**2} would
21471 not cause intermediate overflow, because the intermediate result
21472 would be evaluated using sufficient precision, and the result
21473 of evaluating the precondition would be True.
21475 This mode has the advantage of avoiding any intermediate
21476 overflows, but at the expense of significant run-time overhead,
21477 including the use of a library (included automatically in this
21478 mode) for multiple-precision arithmetic.
21480 This mode provides cleaner semantics for assertions, since now
21481 the run-time behavior emulates true arithmetic behavior for the
21482 predefined arithmetic operators, meaning that there is never a
21483 conflict between the mathematical view of the assertion, and its
21484 run-time behavior.
21486 Note that in this mode, the behavior is unaffected by whether or
21487 not overflow checks are suppressed, since overflow does not occur.
21488 It is possible for gigantic intermediate expressions to raise
21489 @code{Storage_Error} as a result of attempting to compute the
21490 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
21491 but overflow is impossible.
21492 @end itemize
21494 Note that these modes apply only to the evaluation of predefined
21495 arithmetic, membership, and comparison operators for signed integer
21496 arithmetic.
21498 For fixed-point arithmetic, checks can be suppressed. But if checks
21499 are enabled
21500 then fixed-point values are always checked for overflow against the
21501 base type for intermediate expressions (that is such checks always
21502 operate in the equivalent of @code{STRICT} mode).
21504 For floating-point, on nearly all architectures, @code{Machine_Overflows}
21505 is False, and IEEE infinities are generated, so overflow exceptions
21506 are never raised. If you want to avoid infinities, and check that
21507 final results of expressions are in range, then you can declare a
21508 constrained floating-point type, and range checks will be carried
21509 out in the normal manner (with infinite values always failing all
21510 range checks).
21512 @node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
21513 @anchor{gnat_ugn/gnat_and_program_execution id48}@anchor{1a4}@anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{eb}
21514 @subsection Specifying the Desired Mode
21517 @geindex pragma Overflow_Mode
21519 The desired mode of for handling intermediate overflow can be specified using
21520 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
21521 The pragma has the form
21523 @quotation
21525 @example
21526 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
21527 @end example
21528 @end quotation
21530 where @code{MODE} is one of
21533 @itemize *
21535 @item 
21536 @code{STRICT}:  intermediate overflows checked (using base type)
21538 @item 
21539 @code{MINIMIZED}: minimize intermediate overflows
21541 @item 
21542 @code{ELIMINATED}: eliminate intermediate overflows
21543 @end itemize
21545 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
21546 @code{minimized} all have the same effect.
21548 If only the @code{General} parameter is present, then the given @code{MODE} applies
21549 to expressions both within and outside assertions. If both arguments
21550 are present, then @code{General} applies to expressions outside assertions,
21551 and @code{Assertions} applies to expressions within assertions. For example:
21553 @quotation
21555 @example
21556 pragma Overflow_Mode
21557   (General => Minimized, Assertions => Eliminated);
21558 @end example
21559 @end quotation
21561 specifies that general expressions outside assertions be evaluated
21562 in ‘minimize intermediate overflows’ mode, and expressions within
21563 assertions be evaluated in ‘eliminate intermediate overflows’ mode.
21564 This is often a reasonable choice, avoiding excessive overhead
21565 outside assertions, but assuring a high degree of portability
21566 when importing code from another compiler, while incurring
21567 the extra overhead for assertion expressions to ensure that
21568 the behavior at run time matches the expected mathematical
21569 behavior.
21571 The @code{Overflow_Mode} pragma has the same scoping and placement
21572 rules as pragma @code{Suppress}, so it can occur either as a
21573 configuration pragma, specifying a default for the whole
21574 program, or in a declarative scope, where it applies to the
21575 remaining declarations and statements in that scope.
21577 Note that pragma @code{Overflow_Mode} does not affect whether
21578 overflow checks are enabled or suppressed. It only controls the
21579 method used to compute intermediate values. To control whether
21580 overflow checking is enabled or suppressed, use pragma @code{Suppress}
21581 or @code{Unsuppress} in the usual manner.
21583 @geindex -gnato? (gcc)
21585 @geindex -gnato?? (gcc)
21587 Additionally, a compiler switch @code{-gnato?} or @code{-gnato??}
21588 can be used to control the checking mode default (which can be subsequently
21589 overridden using pragmas).
21591 Here @code{?} is one of the digits @code{1} through @code{3}:
21593 @quotation
21596 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
21597 @item
21599 @code{1}
21601 @tab
21603 use base type for intermediate operations (@code{STRICT})
21605 @item
21607 @code{2}
21609 @tab
21611 minimize intermediate overflows (@code{MINIMIZED})
21613 @item
21615 @code{3}
21617 @tab
21619 eliminate intermediate overflows (@code{ELIMINATED})
21621 @end multitable
21623 @end quotation
21625 As with the pragma, if only one digit appears then it applies to all
21626 cases; if two digits are given, then the first applies outside
21627 assertions, and the second within assertions. Thus the equivalent
21628 of the example pragma above would be
21629 @code{-gnato23}.
21631 If no digits follow the @code{-gnato}, then it is equivalent to
21632 @code{-gnato11},
21633 causing all intermediate operations to be computed using the base
21634 type (@code{STRICT} mode).
21636 @node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
21637 @anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{1a5}@anchor{gnat_ugn/gnat_and_program_execution id49}@anchor{1a6}
21638 @subsection Default Settings
21641 The default mode for overflow checks is
21643 @quotation
21645 @example
21646 General => Strict
21647 @end example
21648 @end quotation
21650 which causes all computations both inside and outside assertions to use the
21651 base type, and is equivalent to @code{-gnato} (with no digits following).
21653 The pragma @code{Suppress (Overflow_Check)} disables overflow
21654 checking, but it has no effect on the method used for computing
21655 intermediate results.
21657 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
21658 checking, but it has no effect on the method used for computing
21659 intermediate results.
21661 @node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
21662 @anchor{gnat_ugn/gnat_and_program_execution id50}@anchor{1a7}@anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{1a8}
21663 @subsection Implementation Notes
21666 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
21667 reasonably efficient, and can be generally used. It also helps
21668 to ensure compatibility with code imported from some other
21669 compiler to GNAT.
21671 Setting all intermediate overflows checking (@code{STRICT} mode)
21672 makes sense if you want to
21673 make sure that your code is compatible with any other possible
21674 Ada implementation. This may be useful in ensuring portability
21675 for code that is to be exported to some other compiler than GNAT.
21677 The Ada standard allows the reassociation of expressions at
21678 the same precedence level if no parentheses are present. For
21679 example, @code{A+B+C} parses as though it were @code{(A+B)+C}, but
21680 the compiler can reintepret this as @code{A+(B+C)}, possibly
21681 introducing or eliminating an overflow exception. The GNAT
21682 compiler never takes advantage of this freedom, and the
21683 expression @code{A+B+C} will be evaluated as @code{(A+B)+C}.
21684 If you need the other order, you can write the parentheses
21685 explicitly @code{A+(B+C)} and GNAT will respect this order.
21687 The use of @code{ELIMINATED} mode will cause the compiler to
21688 automatically include an appropriate arbitrary precision
21689 integer arithmetic package. The compiler will make calls
21690 to this package, though only in cases where it cannot be
21691 sure that @code{Long_Long_Integer} is sufficient to guard against
21692 intermediate overflows. This package does not use dynamic
21693 allocation, but it does use the secondary stack, so an
21694 appropriate secondary stack package must be present (this
21695 is always true for standard full Ada, but may require
21696 specific steps for restricted run times such as ZFP).
21698 Although @code{ELIMINATED} mode causes expressions to use arbitrary
21699 precision arithmetic, avoiding overflow, the final result
21700 must be in an appropriate range. This is true even if the
21701 final result is of type @code{[Long_[Long_]]Integer'Base}, which
21702 still has the same bounds as its associated constrained
21703 type at run-time.
21705 Currently, the @code{ELIMINATED} mode is only available on target
21706 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
21707 platforms).
21709 @node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
21710 @anchor{gnat_ugn/gnat_and_program_execution id51}@anchor{14c}@anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{1a9}
21711 @section Performing Dimensionality Analysis in GNAT
21714 @geindex Dimensionality analysis
21716 The GNAT compiler supports dimensionality checking. The user can
21717 specify physical units for objects, and the compiler will verify that uses
21718 of these objects are compatible with their dimensions, in a fashion that is
21719 familiar to engineering practice. The dimensions of algebraic expressions
21720 (including powers with static exponents) are computed from their constituents.
21722 @geindex Dimension_System aspect
21724 @geindex Dimension aspect
21726 This feature depends on Ada 2012 aspect specifications, and is available from
21727 version 7.0.1 of GNAT onwards.
21728 The GNAT-specific aspect @code{Dimension_System}
21729 allows you to define a system of units; the aspect @code{Dimension}
21730 then allows the user to declare dimensioned quantities within a given system.
21731 (These aspects are described in the `Implementation Defined Aspects'
21732 chapter of the `GNAT Reference Manual').
21734 The major advantage of this model is that it does not require the declaration of
21735 multiple operators for all possible combinations of types: it is only necessary
21736 to use the proper subtypes in object declarations.
21738 @geindex System.Dim.Mks package (GNAT library)
21740 @geindex MKS_Type type
21742 The simplest way to impose dimensionality checking on a computation is to make
21743 use of one of the instantiations of the package @code{System.Dim.Generic_Mks}, which
21744 are part of the GNAT library. This generic package defines a floating-point
21745 type @code{MKS_Type}, for which a sequence of dimension names are specified,
21746 together with their conventional abbreviations.  The following should be read
21747 together with the full specification of the package, in file
21748 @code{s-digemk.ads}.
21750 @quotation
21752 @geindex s-digemk.ads file
21754 @example
21755 type Mks_Type is new Float_Type
21756   with
21757    Dimension_System => (
21758      (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
21759      (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
21760      (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
21761      (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
21762      (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
21763      (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
21764      (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
21765 @end example
21766 @end quotation
21768 The package then defines a series of subtypes that correspond to these
21769 conventional units. For example:
21771 @quotation
21773 @example
21774 subtype Length is Mks_Type
21775   with
21776    Dimension => (Symbol => 'm', Meter  => 1, others => 0);
21777 @end example
21778 @end quotation
21780 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
21781 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
21782 @code{Luminous_Intensity} (the standard set of units of the SI system).
21784 The package also defines conventional names for values of each unit, for
21785 example:
21787 @quotation
21789 @example
21790 m   : constant Length           := 1.0;
21791 kg  : constant Mass             := 1.0;
21792 s   : constant Time             := 1.0;
21793 A   : constant Electric_Current := 1.0;
21794 @end example
21795 @end quotation
21797 as well as useful multiples of these units:
21799 @quotation
21801 @example
21802  cm  : constant Length := 1.0E-02;
21803  g   : constant Mass   := 1.0E-03;
21804  min : constant Time   := 60.0;
21805  day : constant Time   := 60.0 * 24.0 * min;
21807 @end example
21808 @end quotation
21810 There are three instantiations of @code{System.Dim.Generic_Mks} defined in the
21811 GNAT library:
21814 @itemize *
21816 @item 
21817 @code{System.Dim.Float_Mks} based on @code{Float} defined in @code{s-diflmk.ads}.
21819 @item 
21820 @code{System.Dim.Long_Mks} based on @code{Long_Float} defined in @code{s-dilomk.ads}.
21822 @item 
21823 @code{System.Dim.Mks} based on @code{Long_Long_Float} defined in @code{s-dimmks.ads}.
21824 @end itemize
21826 Using one of these packages, you can then define a derived unit by providing
21827 the aspect that specifies its dimensions within the MKS system, as well as the
21828 string to be used for output of a value of that unit:
21830 @quotation
21832 @example
21833 subtype Acceleration is Mks_Type
21834   with Dimension => ("m/sec^2",
21835                      Meter => 1,
21836                      Second => -2,
21837                      others => 0);
21838 @end example
21839 @end quotation
21841 Here is a complete example of use:
21843 @quotation
21845 @example
21846 with System.Dim.MKS; use System.Dim.Mks;
21847 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
21848 with Text_IO; use Text_IO;
21849 procedure Free_Fall is
21850   subtype Acceleration is Mks_Type
21851     with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
21852   G : constant acceleration := 9.81 * m / (s ** 2);
21853   T : Time := 10.0*s;
21854   Distance : Length;
21856 begin
21857   Put ("Gravitational constant: ");
21858   Put (G, Aft => 2, Exp => 0); Put_Line ("");
21859   Distance := 0.5 * G * T ** 2;
21860   Put ("distance travelled in 10 seconds of free fall ");
21861   Put (Distance, Aft => 2, Exp => 0);
21862   Put_Line ("");
21863 end Free_Fall;
21864 @end example
21865 @end quotation
21867 Execution of this program yields:
21869 @quotation
21871 @example
21872 Gravitational constant:  9.81 m/sec^2
21873 distance travelled in 10 seconds of free fall 490.50 m
21874 @end example
21875 @end quotation
21877 However, incorrect assignments such as:
21879 @quotation
21881 @example
21882 Distance := 5.0;
21883 Distance := 5.0 * kg;
21884 @end example
21885 @end quotation
21887 are rejected with the following diagnoses:
21889 @quotation
21891 @example
21892 Distance := 5.0;
21893    >>> dimensions mismatch in assignment
21894    >>> left-hand side has dimension [L]
21895    >>> right-hand side is dimensionless
21897 Distance := 5.0 * kg:
21898    >>> dimensions mismatch in assignment
21899    >>> left-hand side has dimension [L]
21900    >>> right-hand side has dimension [M]
21901 @end example
21902 @end quotation
21904 The dimensions of an expression are properly displayed, even if there is
21905 no explicit subtype for it. If we add to the program:
21907 @quotation
21909 @example
21910 Put ("Final velocity: ");
21911 Put (G * T, Aft =>2, Exp =>0);
21912 Put_Line ("");
21913 @end example
21914 @end quotation
21916 then the output includes:
21918 @quotation
21920 @example
21921 Final velocity: 98.10 m.s**(-1)
21922 @end example
21924 @geindex Dimensionable type
21926 @geindex Dimensioned subtype
21927 @end quotation
21929 The type @code{Mks_Type} is said to be a `dimensionable type' since it has a
21930 @code{Dimension_System} aspect, and the subtypes @code{Length}, @code{Mass}, etc.,
21931 are said to be `dimensioned subtypes' since each one has a @code{Dimension}
21932 aspect.
21934 @quotation
21936 @geindex Dimension Vector (for a dimensioned subtype)
21938 @geindex Dimension aspect
21940 @geindex Dimension_System aspect
21941 @end quotation
21943 The @code{Dimension} aspect of a dimensioned subtype @code{S} defines a mapping
21944 from the base type’s Unit_Names to integer (or, more generally, rational)
21945 values. This mapping is the `dimension vector' (also referred to as the
21946 `dimensionality') for that subtype, denoted by @code{DV(S)}, and thus for each
21947 object of that subtype. Intuitively, the value specified for each
21948 @code{Unit_Name} is the exponent associated with that unit; a zero value
21949 means that the unit is not used. For example:
21951 @quotation
21953 @example
21954 declare
21955    Acc : Acceleration;
21956    ...
21957 begin
21958    ...
21959 end;
21960 @end example
21961 @end quotation
21963 Here @code{DV(Acc)} = @code{DV(Acceleration)} =
21964 @code{(Meter=>1, Kilogram=>0, Second=>-2, Ampere=>0, Kelvin=>0, Mole=>0, Candela=>0)}.
21965 Symbolically, we can express this as @code{Meter / Second**2}.
21967 The dimension vector of an arithmetic expression is synthesized from the
21968 dimension vectors of its components, with compile-time dimensionality checks
21969 that help prevent mismatches such as using an @code{Acceleration} where a
21970 @code{Length} is required.
21972 The dimension vector of the result of an arithmetic expression `expr', or
21973 @code{DV(@var{expr})}, is defined as follows, assuming conventional
21974 mathematical definitions for the vector operations that are used:
21977 @itemize *
21979 @item 
21980 If `expr' is of the type `universal_real', or is not of a dimensioned subtype,
21981 then `expr' is dimensionless; @code{DV(@var{expr})} is the empty vector.
21983 @item 
21984 @code{DV(@var{op expr})}, where `op' is a unary operator, is @code{DV(@var{expr})}
21986 @item 
21987 @code{DV(@var{expr1 op expr2})} where `op' is “+” or “-” is @code{DV(@var{expr1})}
21988 provided that @code{DV(@var{expr1})} = @code{DV(@var{expr2})}.
21989 If this condition is not met then the construct is illegal.
21991 @item 
21992 @code{DV(@var{expr1} * @var{expr2})} is @code{DV(@var{expr1})} + @code{DV(@var{expr2})},
21993 and @code{DV(@var{expr1} / @var{expr2})} = @code{DV(@var{expr1})} - @code{DV(@var{expr2})}.
21994 In this context if one of the `expr's is dimensionless then its empty
21995 dimension vector is treated as @code{(others => 0)}.
21997 @item 
21998 @code{DV(@var{expr} ** @var{power})} is `power' * @code{DV(@var{expr})},
21999 provided that `power' is a static rational value. If this condition is not
22000 met then the construct is illegal.
22001 @end itemize
22003 Note that, by the above rules, it is illegal to use binary “+” or “-” to
22004 combine a dimensioned and dimensionless value.  Thus an expression such as
22005 @code{acc-10.0} is illegal, where @code{acc} is an object of subtype
22006 @code{Acceleration}.
22008 The dimensionality checks for relationals use the same rules as
22009 for “+” and “-”, except when comparing to a literal; thus
22011 @quotation
22013 @example
22014 acc > len
22015 @end example
22016 @end quotation
22018 is equivalent to
22020 @quotation
22022 @example
22023 acc-len > 0.0
22024 @end example
22025 @end quotation
22027 and is thus illegal, but
22029 @quotation
22031 @example
22032 acc > 10.0
22033 @end example
22034 @end quotation
22036 is accepted with a warning. Analogously a conditional expression requires the
22037 same dimension vector for each branch (with no exception for literals).
22039 The dimension vector of a type conversion @code{T(@var{expr})} is defined
22040 as follows, based on the nature of @code{T}:
22043 @itemize *
22045 @item 
22046 If @code{T} is a dimensioned subtype then @code{DV(T(@var{expr}))} is @code{DV(T)}
22047 provided that either `expr' is dimensionless or
22048 @code{DV(T)} = @code{DV(@var{expr})}. The conversion is illegal
22049 if `expr' is dimensioned and @code{DV(@var{expr})} /= @code{DV(T)}.
22050 Note that vector equality does not require that the corresponding
22051 Unit_Names be the same.
22053 As a consequence of the above rule, it is possible to convert between
22054 different dimension systems that follow the same international system
22055 of units, with the seven physical components given in the standard order
22056 (length, mass, time, etc.). Thus a length in meters can be converted to
22057 a length in inches (with a suitable conversion factor) but cannot be
22058 converted, for example, to a mass in pounds.
22060 @item 
22061 If @code{T} is the base type for `expr' (and the dimensionless root type of
22062 the dimension system), then @code{DV(T(@var{expr}))} is @code{DV(expr)}.
22063 Thus, if `expr' is of a dimensioned subtype of @code{T}, the conversion may
22064 be regarded as a “view conversion” that preserves dimensionality.
22066 This rule makes it possible to write generic code that can be instantiated
22067 with compatible dimensioned subtypes.  The generic unit will contain
22068 conversions that will consequently be present in instantiations, but
22069 conversions to the base type will preserve dimensionality and make it
22070 possible to write generic code that is correct with respect to
22071 dimensionality.
22073 @item 
22074 Otherwise (i.e., @code{T} is neither a dimensioned subtype nor a dimensionable
22075 base type), @code{DV(T(@var{expr}))} is the empty vector. Thus a dimensioned
22076 value can be explicitly converted to a non-dimensioned subtype, which
22077 of course then escapes dimensionality analysis.
22078 @end itemize
22080 The dimension vector for a type qualification @code{T'(@var{expr})} is the same
22081 as for the type conversion @code{T(@var{expr})}.
22083 An assignment statement
22085 @quotation
22087 @example
22088 Source := Target;
22089 @end example
22090 @end quotation
22092 requires @code{DV(Source)} = @code{DV(Target)}, and analogously for parameter
22093 passing (the dimension vector for the actual parameter must be equal to the
22094 dimension vector for the formal parameter).
22096 @node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
22097 @anchor{gnat_ugn/gnat_and_program_execution id52}@anchor{14d}@anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{1aa}
22098 @section Stack Related Facilities
22101 This section describes some useful tools associated with stack
22102 checking and analysis. In
22103 particular, it deals with dynamic and static stack usage measurements.
22105 @menu
22106 * Stack Overflow Checking:: 
22107 * Static Stack Usage Analysis:: 
22108 * Dynamic Stack Usage Analysis:: 
22110 @end menu
22112 @node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
22113 @anchor{gnat_ugn/gnat_and_program_execution id53}@anchor{1ab}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{e7}
22114 @subsection Stack Overflow Checking
22117 @geindex Stack Overflow Checking
22119 @geindex -fstack-check (gcc)
22121 For most operating systems, @code{gcc} does not perform stack overflow
22122 checking by default. This means that if the main environment task or
22123 some other task exceeds the available stack space, then unpredictable
22124 behavior will occur. Most native systems offer some level of protection by
22125 adding a guard page at the end of each task stack. This mechanism is usually
22126 not enough for dealing properly with stack overflow situations because
22127 a large local variable could “jump” above the guard page.
22128 Furthermore, when the
22129 guard page is hit, there may not be any space left on the stack for executing
22130 the exception propagation code. Enabling stack checking avoids
22131 such situations.
22133 To activate stack checking, compile all units with the @code{gcc} option
22134 @code{-fstack-check}. For example:
22136 @quotation
22138 @example
22139 $ gcc -c -fstack-check package1.adb
22140 @end example
22141 @end quotation
22143 Units compiled with this option will generate extra instructions to check
22144 that any use of the stack (for procedure calls or for declaring local
22145 variables in declare blocks) does not exceed the available stack space.
22146 If the space is exceeded, then a @code{Storage_Error} exception is raised.
22148 For declared tasks, the default stack size is defined by the GNAT runtime,
22149 whose size may be modified at bind time through the @code{-d} bind switch
22150 (@ref{112,,Switches for gnatbind}). Task specific stack sizes may be set using the
22151 @code{Storage_Size} pragma.
22153 For the environment task, the stack size is determined by the operating system.
22154 Consequently, to modify the size of the environment task please refer to your
22155 operating system documentation.
22157 @node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
22158 @anchor{gnat_ugn/gnat_and_program_execution id54}@anchor{1ac}@anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{e8}
22159 @subsection Static Stack Usage Analysis
22162 @geindex Static Stack Usage Analysis
22164 @geindex -fstack-usage
22166 A unit compiled with @code{-fstack-usage} will generate an extra file
22167 that specifies
22168 the maximum amount of stack used, on a per-function basis.
22169 The file has the same
22170 basename as the target object file with a @code{.su} extension.
22171 Each line of this file is made up of three fields:
22174 @itemize *
22176 @item 
22177 The name of the function.
22179 @item 
22180 A number of bytes.
22182 @item 
22183 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
22184 @end itemize
22186 The second field corresponds to the size of the known part of the function
22187 frame.
22189 The qualifier @code{static} means that the function frame size
22190 is purely static.
22191 It usually means that all local variables have a static size.
22192 In this case, the second field is a reliable measure of the function stack
22193 utilization.
22195 The qualifier @code{dynamic} means that the function frame size is not static.
22196 It happens mainly when some local variables have a dynamic size. When this
22197 qualifier appears alone, the second field is not a reliable measure
22198 of the function stack analysis. When it is qualified with  @code{bounded}, it
22199 means that the second field is a reliable maximum of the function stack
22200 utilization.
22202 A unit compiled with @code{-Wstack-usage} will issue a warning for each
22203 subprogram whose stack usage might be larger than the specified amount of
22204 bytes.  The wording is in keeping with the qualifier documented above.
22206 @node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
22207 @anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{115}@anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{1ad}
22208 @subsection Dynamic Stack Usage Analysis
22211 It is possible to measure the maximum amount of stack used by a task, by
22212 adding a switch to @code{gnatbind}, as:
22214 @quotation
22216 @example
22217 $ gnatbind -u0 file
22218 @end example
22219 @end quotation
22221 With this option, at each task termination, its stack usage is output on
22222 @code{stderr}.
22223 Note that this switch is not compatible with tools like
22224 Valgrind and DrMemory; they will report errors.
22226 It is not always convenient to output the stack usage when the program
22227 is still running. Hence, it is possible to delay this output until program
22228 termination. for a given number of tasks specified as the argument of the
22229 @code{-u} option. For instance:
22231 @quotation
22233 @example
22234 $ gnatbind -u100 file
22235 @end example
22236 @end quotation
22238 will buffer the stack usage information of the first 100 tasks to terminate and
22239 output this info at program termination. Results are displayed in four
22240 columns:
22242 @quotation
22244 @example
22245 Index | Task Name | Stack Size | Stack Usage
22246 @end example
22247 @end quotation
22249 where:
22252 @itemize *
22254 @item 
22255 `Index' is a number associated with each task.
22257 @item 
22258 `Task Name' is the name of the task analyzed.
22260 @item 
22261 `Stack Size' is the maximum size for the stack.
22263 @item 
22264 `Stack Usage' is the measure done by the stack analyzer.
22265 In order to prevent overflow, the stack
22266 is not entirely analyzed, and it’s not possible to know exactly how
22267 much has actually been used.
22268 @end itemize
22270 By default the environment task stack, the stack that contains the main unit,
22271 is not processed. To enable processing of the environment task stack, the
22272 environment variable GNAT_STACK_LIMIT needs to be set to the maximum size of
22273 the environment task stack. This amount is given in kilobytes. For example:
22275 @quotation
22277 @example
22278 $ set GNAT_STACK_LIMIT 1600
22279 @end example
22280 @end quotation
22282 would specify to the analyzer that the environment task stack has a limit
22283 of 1.6 megabytes. Any stack usage beyond this will be ignored by the analysis.
22285 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
22286 stack-usage reports at run time. See its body for the details.
22288 @node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
22289 @anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{14e}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{1ae}
22290 @section Memory Management Issues
22293 This section describes some useful memory pools provided in the GNAT library
22294 and in particular the GNAT Debug Pool facility, which can be used to detect
22295 incorrect uses of access values (including ‘dangling references’).
22298 @menu
22299 * Some Useful Memory Pools:: 
22300 * The GNAT Debug Pool Facility:: 
22302 @end menu
22304 @node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
22305 @anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{1af}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{1b0}
22306 @subsection Some Useful Memory Pools
22309 @geindex Memory Pool
22311 @geindex storage
22312 @geindex pool
22314 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
22315 storage pool. Allocations use the standard system call @code{malloc} while
22316 deallocations use the standard system call @code{free}. No reclamation is
22317 performed when the pool goes out of scope. For performance reasons, the
22318 standard default Ada allocators/deallocators do not use any explicit storage
22319 pools but if they did, they could use this storage pool without any change in
22320 behavior. That is why this storage pool is used  when the user
22321 manages to make the default implicit allocator explicit as in this example:
22323 @quotation
22325 @example
22326 type T1 is access Something;
22327  -- no Storage pool is defined for T2
22329 type T2 is access Something_Else;
22330 for T2'Storage_Pool use T1'Storage_Pool;
22331 -- the above is equivalent to
22332 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
22333 @end example
22334 @end quotation
22336 The @code{System.Pool_Local} package offers the @code{Unbounded_Reclaim_Pool} storage
22337 pool. The allocation strategy is similar to @code{Pool_Local}
22338 except that the all
22339 storage allocated with this pool is reclaimed when the pool object goes out of
22340 scope. This pool provides a explicit mechanism similar to the implicit one
22341 provided by several Ada 83 compilers for allocations performed through a local
22342 access type and whose purpose was to reclaim memory when exiting the
22343 scope of a given local access. As an example, the following program does not
22344 leak memory even though it does not perform explicit deallocation:
22346 @quotation
22348 @example
22349 with System.Pool_Local;
22350 procedure Pooloc1 is
22351    procedure Internal is
22352       type A is access Integer;
22353       X : System.Pool_Local.Unbounded_Reclaim_Pool;
22354       for A'Storage_Pool use X;
22355       v : A;
22356    begin
22357       for I in 1 .. 50 loop
22358          v := new Integer;
22359       end loop;
22360    end Internal;
22361 begin
22362    for I in 1 .. 100 loop
22363       Internal;
22364    end loop;
22365 end Pooloc1;
22366 @end example
22367 @end quotation
22369 The @code{System.Pool_Size} package implements the @code{Stack_Bounded_Pool} used when
22370 @code{Storage_Size} is specified for an access type.
22371 The whole storage for the pool is
22372 allocated at once, usually on the stack at the point where the access type is
22373 elaborated. It is automatically reclaimed when exiting the scope where the
22374 access type is defined. This package is not intended to be used directly by the
22375 user and it is implicitly used for each such declaration:
22377 @quotation
22379 @example
22380 type T1 is access Something;
22381 for T1'Storage_Size use 10_000;
22382 @end example
22383 @end quotation
22385 @node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
22386 @anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{1b1}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{1b2}
22387 @subsection The GNAT Debug Pool Facility
22390 @geindex Debug Pool
22392 @geindex storage
22393 @geindex pool
22394 @geindex memory corruption
22396 The use of unchecked deallocation and unchecked conversion can easily
22397 lead to incorrect memory references. The problems generated by such
22398 references are usually difficult to tackle because the symptoms can be
22399 very remote from the origin of the problem. In such cases, it is
22400 very helpful to detect the problem as early as possible. This is the
22401 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
22403 In order to use the GNAT specific debugging pool, the user must
22404 associate a debug pool object with each of the access types that may be
22405 related to suspected memory problems. See Ada Reference Manual 13.11.
22407 @quotation
22409 @example
22410 type Ptr is access Some_Type;
22411 Pool : GNAT.Debug_Pools.Debug_Pool;
22412 for Ptr'Storage_Pool use Pool;
22413 @end example
22414 @end quotation
22416 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
22417 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
22418 allow the user to redefine allocation and deallocation strategies. They
22419 also provide a checkpoint for each dereference, through the use of
22420 the primitive operation @code{Dereference} which is implicitly called at
22421 each dereference of an access value.
22423 Once an access type has been associated with a debug pool, operations on
22424 values of the type may raise four distinct exceptions,
22425 which correspond to four potential kinds of memory corruption:
22428 @itemize *
22430 @item 
22431 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
22433 @item 
22434 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
22436 @item 
22437 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
22439 @item 
22440 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
22441 @end itemize
22443 For types associated with a Debug_Pool, dynamic allocation is performed using
22444 the standard GNAT allocation routine. References to all allocated chunks of
22445 memory are kept in an internal dictionary. Several deallocation strategies are
22446 provided, whereupon the user can choose to release the memory to the system,
22447 keep it allocated for further invalid access checks, or fill it with an easily
22448 recognizable pattern for debug sessions. The memory pattern is the old IBM
22449 hexadecimal convention: @code{16#DEADBEEF#}.
22451 See the documentation in the file g-debpoo.ads for more information on the
22452 various strategies.
22454 Upon each dereference, a check is made that the access value denotes a
22455 properly allocated memory location. Here is a complete example of use of
22456 @code{Debug_Pools}, that includes typical instances of  memory corruption:
22458 @quotation
22460 @example
22461 with GNAT.IO; use GNAT.IO;
22462 with Ada.Unchecked_Deallocation;
22463 with Ada.Unchecked_Conversion;
22464 with GNAT.Debug_Pools;
22465 with System.Storage_Elements;
22466 with Ada.Exceptions; use Ada.Exceptions;
22467 procedure Debug_Pool_Test is
22469    type T is access Integer;
22470    type U is access all T;
22472    P : GNAT.Debug_Pools.Debug_Pool;
22473    for T'Storage_Pool use P;
22475    procedure Free is new Ada.Unchecked_Deallocation (Integer, T);
22476    function UC is new Ada.Unchecked_Conversion (U, T);
22477    A, B : aliased T;
22479    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
22481 begin
22482    Info (P);
22483    A := new Integer;
22484    B := new Integer;
22485    B := A;
22486    Info (P);
22487    Free (A);
22488    begin
22489       Put_Line (Integer'Image(B.all));
22490    exception
22491       when E : others => Put_Line ("raised: " & Exception_Name (E));
22492    end;
22493    begin
22494       Free (B);
22495    exception
22496       when E : others => Put_Line ("raised: " & Exception_Name (E));
22497    end;
22498    B := UC(A'Access);
22499    begin
22500       Put_Line (Integer'Image(B.all));
22501    exception
22502       when E : others => Put_Line ("raised: " & Exception_Name (E));
22503    end;
22504    begin
22505       Free (B);
22506    exception
22507       when E : others => Put_Line ("raised: " & Exception_Name (E));
22508    end;
22509    Info (P);
22510 end Debug_Pool_Test;
22511 @end example
22512 @end quotation
22514 The debug pool mechanism provides the following precise diagnostics on the
22515 execution of this erroneous program:
22517 @quotation
22519 @example
22520 Debug Pool info:
22521   Total allocated bytes :  0
22522   Total deallocated bytes :  0
22523   Current Water Mark:  0
22524   High Water Mark:  0
22526 Debug Pool info:
22527   Total allocated bytes :  8
22528   Total deallocated bytes :  0
22529   Current Water Mark:  8
22530   High Water Mark:  8
22532 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
22533 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
22534 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
22535 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
22536 Debug Pool info:
22537   Total allocated bytes :  8
22538   Total deallocated bytes :  4
22539   Current Water Mark:  4
22540   High Water Mark:  8
22541 @end example
22542 @end quotation
22545 @c -- Non-breaking space in running text
22546 @c -- E.g. Ada |nbsp| 95
22548 @node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
22549 @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}
22550 @chapter Platform-Specific Information
22553 This appendix contains information relating to the implementation
22554 of run-time libraries on various platforms and also covers topics
22555 related to the GNAT implementation on specific Operating Systems.
22557 @menu
22558 * Run-Time Libraries:: 
22559 * Specifying a Run-Time Library:: 
22560 * GNU/Linux Topics:: 
22561 * Microsoft Windows Topics:: 
22562 * Mac OS Topics:: 
22564 @end menu
22566 @node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
22567 @anchor{gnat_ugn/platform_specific_information id2}@anchor{1b5}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{1b6}
22568 @section Run-Time Libraries
22571 @geindex Tasking and threads libraries
22573 @geindex Threads libraries and tasking
22575 @geindex Run-time libraries (platform-specific information)
22577 The GNAT run-time implementation may vary with respect to both the
22578 underlying threads library and the exception-handling scheme.
22579 For threads support, the default run-time will bind to the thread
22580 package of the underlying operating system.
22582 For exception handling, either or both of two models are supplied:
22584 @quotation
22586 @geindex Zero-Cost Exceptions
22588 @geindex ZCX (Zero-Cost Exceptions)
22589 @end quotation
22592 @itemize *
22594 @item 
22595 `Zero-Cost Exceptions' (“ZCX”),
22596 which uses binder-generated tables that
22597 are interrogated at run time to locate a handler.
22599 @geindex setjmp/longjmp Exception Model
22601 @geindex SJLJ (setjmp/longjmp Exception Model)
22603 @item 
22604 `setjmp / longjmp' (‘SJLJ’),
22605 which uses dynamically-set data to establish
22606 the set of handlers
22607 @end itemize
22609 Most programs should experience a substantial speed improvement by
22610 being compiled with a ZCX run-time.
22611 This is especially true for
22612 tasking applications or applications with many exception handlers.
22613 Note however that the ZCX run-time does not support asynchronous abort
22614 of tasks (@code{abort} and @code{select-then-abort} constructs) and will instead
22615 implement abort by polling points in the runtime. You can also add additional
22616 polling points explicitly if needed in your application via @code{pragma
22617 Abort_Defer}.
22619 This section summarizes which combinations of threads and exception support
22620 are supplied on various GNAT platforms.
22622 @menu
22623 * Summary of Run-Time Configurations:: 
22625 @end menu
22627 @node Summary of Run-Time Configurations,,,Run-Time Libraries
22628 @anchor{gnat_ugn/platform_specific_information id3}@anchor{1b7}@anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{1b8}
22629 @subsection Summary of Run-Time Configurations
22633 @multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
22634 @headitem
22636 Platform
22638 @tab
22640 Run-Time
22642 @tab
22644 Tasking
22646 @tab
22648 Exceptions
22650 @item
22652 GNU/Linux
22654 @tab
22656 rts-native
22657 (default)
22659 @tab
22661 pthread library
22663 @tab
22667 @item
22669 rts-sjlj
22671 @tab
22673 pthread library
22675 @tab
22677 SJLJ
22679 @item
22681 Windows
22683 @tab
22685 rts-native
22686 (default)
22688 @tab
22690 native Win32 threads
22692 @tab
22696 @item
22698 rts-sjlj
22700 @tab
22702 native Win32 threads
22704 @tab
22706 SJLJ
22708 @item
22710 Mac OS
22712 @tab
22714 rts-native
22716 @tab
22718 pthread library
22720 @tab
22724 @end multitable
22727 @node Specifying a Run-Time Library,GNU/Linux Topics,Run-Time Libraries,Platform-Specific Information
22728 @anchor{gnat_ugn/platform_specific_information id4}@anchor{1b9}@anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{1ba}
22729 @section Specifying a Run-Time Library
22732 The @code{adainclude} subdirectory containing the sources of the GNAT
22733 run-time library, and the @code{adalib} subdirectory containing the
22734 @code{ALI} files and the static and/or shared GNAT library, are located
22735 in the gcc target-dependent area:
22737 @quotation
22739 @example
22740 target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
22741 @end example
22742 @end quotation
22744 As indicated above, on some platforms several run-time libraries are supplied.
22745 These libraries are installed in the target dependent area and
22746 contain a complete source and binary subdirectory. The detailed description
22747 below explains the differences between the different libraries in terms of
22748 their thread support.
22750 The default run-time library (when GNAT is installed) is `rts-native'.
22751 This default run-time is selected by the means of soft links.
22752 For example on x86-linux:
22754 @c --
22755 @c --  $(target-dir)
22756 @c --      |
22757 @c --      +--- adainclude----------+
22758 @c --      |                        |
22759 @c --      +--- adalib-----------+  |
22760 @c --      |                     |  |
22761 @c --      +--- rts-native       |  |
22762 @c --      |    |                |  |
22763 @c --      |    +--- adainclude <---+
22764 @c --      |    |                |
22765 @c --      |    +--- adalib <----+
22766 @c --      |
22767 @c --      +--- rts-sjlj
22768 @c --           |
22769 @c --           +--- adainclude
22770 @c --           |
22771 @c --           +--- adalib
22774 @example
22775                $(target-dir)
22776               __/ /      \ \___
22777       _______/   /        \    \_________________
22778      /          /          \                     \
22779     /          /            \                     \
22780 ADAINCLUDE  ADALIB      rts-native             rts-sjlj
22781    :          :            /    \                 /   \
22782    :          :           /      \               /     \
22783    :          :          /        \             /       \
22784    :          :         /          \           /         \
22785    +-------------> adainclude     adalib   adainclude   adalib
22786               :                     ^
22787               :                     :
22788               +---------------------+
22790               Run-Time Library Directory Structure
22791    (Upper-case names and dotted/dashed arrows represent soft links)
22792 @end example
22794 If the `rts-sjlj' library is to be selected on a permanent basis,
22795 these soft links can be modified with the following commands:
22797 @quotation
22799 @example
22800 $ cd $target
22801 $ rm -f adainclude adalib
22802 $ ln -s rts-sjlj/adainclude adainclude
22803 $ ln -s rts-sjlj/adalib adalib
22804 @end example
22805 @end quotation
22807 Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
22808 @code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
22809 @code{$target/ada_object_path}.
22811 @geindex --RTS option
22813 Selecting another run-time library temporarily can be
22814 achieved by using the @code{--RTS} switch, e.g., @code{--RTS=sjlj}
22815 @anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{1bb}
22816 @geindex SCHED_FIFO scheduling policy
22818 @geindex SCHED_RR scheduling policy
22820 @geindex SCHED_OTHER scheduling policy
22822 @menu
22823 * Choosing the Scheduling Policy:: 
22825 @end menu
22827 @node Choosing the Scheduling Policy,,,Specifying a Run-Time Library
22828 @anchor{gnat_ugn/platform_specific_information id5}@anchor{1bc}
22829 @subsection Choosing the Scheduling Policy
22832 When using a POSIX threads implementation, you have a choice of several
22833 scheduling policies: @code{SCHED_FIFO}, @code{SCHED_RR} and @code{SCHED_OTHER}.
22835 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
22836 or @code{SCHED_RR} requires special (e.g., root) privileges.
22838 @geindex pragma Time_Slice
22840 @geindex -T0 option
22842 @geindex pragma Task_Dispatching_Policy
22844 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
22845 @code{SCHED_FIFO},
22846 you can use one of the following:
22849 @itemize *
22851 @item 
22852 @code{pragma Time_Slice (0.0)}
22854 @item 
22855 the corresponding binder option @code{-T0}
22857 @item 
22858 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
22859 @end itemize
22861 To specify @code{SCHED_RR},
22862 you should use @code{pragma Time_Slice} with a
22863 value greater than 0.0, or else use the corresponding @code{-T}
22864 binder option.
22866 To make sure a program is running as root, you can put something like
22867 this in a library package body in your application:
22869 @quotation
22871 @example
22872 function geteuid return Integer;
22873 pragma Import (C, geteuid, "geteuid");
22874 Ignore : constant Boolean :=
22875   (if geteuid = 0 then True else raise Program_Error with "must be root");
22876 @end example
22877 @end quotation
22879 It gets the effective user id, and if it’s not 0 (i.e. root), it raises
22880 Program_Error. Note that if you re running the code in a container, this may
22881 not be sufficient, as you may have sufficient priviledge on the container,
22882 but not on the host machine running the container, so check that you also
22883 have sufficient priviledge for running the container image.
22885 @geindex Linux
22887 @geindex GNU/Linux
22889 @node GNU/Linux Topics,Microsoft Windows Topics,Specifying a Run-Time Library,Platform-Specific Information
22890 @anchor{gnat_ugn/platform_specific_information gnu-linux-topics}@anchor{1bd}@anchor{gnat_ugn/platform_specific_information id6}@anchor{1be}
22891 @section GNU/Linux Topics
22894 This section describes topics that are specific to GNU/Linux platforms.
22896 @menu
22897 * Required Packages on GNU/Linux:: 
22898 * Position Independent Executable (PIE) Enabled by Default on Linux: Position Independent Executable PIE Enabled by Default on Linux. 
22899 * A GNU/Linux Debug Quirk:: 
22901 @end menu
22903 @node Required Packages on GNU/Linux,Position Independent Executable PIE Enabled by Default on Linux,,GNU/Linux Topics
22904 @anchor{gnat_ugn/platform_specific_information id7}@anchor{1bf}@anchor{gnat_ugn/platform_specific_information required-packages-on-gnu-linux}@anchor{1c0}
22905 @subsection Required Packages on GNU/Linux
22908 GNAT requires the C library developer’s package to be installed.
22909 The name of of that package depends on your GNU/Linux distribution:
22912 @itemize *
22914 @item 
22915 RedHat, SUSE: @code{glibc-devel};
22917 @item 
22918 Debian, Ubuntu: @code{libc6-dev} (normally installed by default).
22919 @end itemize
22921 If using the 32-bit version of GNAT on a 64-bit version of GNU/Linux,
22922 you’ll need the 32-bit version of the following packages:
22925 @itemize *
22927 @item 
22928 RedHat, SUSE: @code{glibc.i686}, @code{glibc-devel.i686}, @code{ncurses-libs.i686}
22930 @item 
22931 SUSE: @code{glibc-locale-base-32bit}
22933 @item 
22934 Debian, Ubuntu: @code{libc6:i386}, @code{libc6-dev:i386}, @code{lib32ncursesw5}
22935 @end itemize
22937 Other GNU/Linux distributions might be choosing a different name
22938 for those packages.
22940 @node Position Independent Executable PIE Enabled by Default on Linux,A GNU/Linux Debug Quirk,Required Packages on GNU/Linux,GNU/Linux Topics
22941 @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}
22942 @subsection Position Independent Executable (PIE) Enabled by Default on Linux
22945 GNAT generates Position Independent Executable (PIE) code by default.
22946 PIE binaries are loaded into random memory locations, introducing
22947 an additional layer of protection against attacks.
22949 Building PIE binaries requires that all of their dependencies also be
22950 built as Position Independent. If the link of your project fails with
22951 an error like:
22953 @example
22954 /[...]/ld: /path/to/object/file: relocation R_X86_64_32S against symbol
22955 `symbol name' can not be used when making a PIE object;
22956 recompile with -fPIE
22957 @end example
22959 it means the identified object file has not been built as Position
22960 Independent.
22962 If you are not interested in building PIE binaries, you can simply
22963 turn this feature off by first compiling your code with @code{-fno-pie}
22964 and then by linking with @code{-no-pie} (note the subtle but important
22965 difference in the names of the options – the linker option does `not'
22966 have an @cite{f} after the dash!). When using gprbuild, this is
22967 achieved by updating the `Required_Switches' attribute in package @cite{Compiler}
22968 and, depending on your type of project, either attribute `Switches'
22969 or attribute `Library_Options' in package @cite{Linker}.
22971 On the other hand, if you would like to build PIE binaries and you are
22972 getting the error above, a quick and easy workaround to allow linking
22973 to succeed again is to disable PIE during the link, thus temporarily
22974 lifting the requirement that all dependencies also be Position
22975 Independent code. To do so, you simply need to add @code{-no-pie} to
22976 the list of switches passed to the linker. As part of this workaround,
22977 there is no need to adjust the compiler switches.
22979 From there, to be able to link your binaries with PIE and therefore
22980 drop the @code{-no-pie} workaround, you’ll need to get the identified
22981 dependencies rebuilt with PIE enabled (compiled with @code{-fPIE}
22982 and linked with @code{-pie}).
22984 @node A GNU/Linux Debug Quirk,,Position Independent Executable PIE Enabled by Default on Linux,GNU/Linux Topics
22985 @anchor{gnat_ugn/platform_specific_information a-gnu-linux-debug-quirk}@anchor{1c3}@anchor{gnat_ugn/platform_specific_information id8}@anchor{1c4}
22986 @subsection A GNU/Linux Debug Quirk
22989 On SuSE 15, some kernels have a defect causing issues when debugging
22990 programs using threads or Ada tasks. Due to the lack of documentation
22991 found regarding this kernel issue, we can only provide limited
22992 information about which kernels are impacted: kernel version 5.3.18 is
22993 known to be impacted, and kernels in the 5.14 range or newer are
22994 believed to fix this problem.
22996 The bug affects the debugging of 32-bit processes on a 64-bit system.
22997 Symptoms can vary: Unexpected @code{SIGABRT} signals being received by
22998 the program, “The futex facility returned an unexpected error code”
22999 error message, and inferior programs hanging indefinitely range among
23000 the symptoms most commonly observed.
23002 @geindex Windows
23004 @node Microsoft Windows Topics,Mac OS Topics,GNU/Linux Topics,Platform-Specific Information
23005 @anchor{gnat_ugn/platform_specific_information id9}@anchor{1c5}@anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{1c6}
23006 @section Microsoft Windows Topics
23009 This section describes topics that are specific to the Microsoft Windows
23010 platforms.
23013 @menu
23014 * Using GNAT on Windows:: 
23015 * Using a network installation of GNAT:: 
23016 * CONSOLE and WINDOWS subsystems:: 
23017 * Temporary Files:: 
23018 * Disabling Command Line Argument Expansion:: 
23019 * Windows Socket Timeouts:: 
23020 * Mixed-Language Programming on Windows:: 
23021 * Windows Specific Add-Ons:: 
23023 @end menu
23025 @node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
23026 @anchor{gnat_ugn/platform_specific_information id10}@anchor{1c7}@anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{1c8}
23027 @subsection Using GNAT on Windows
23030 One of the strengths of the GNAT technology is that its tool set
23031 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
23032 @code{gdb} debugger, etc.) is used in the same way regardless of the
23033 platform.
23035 On Windows this tool set is complemented by a number of Microsoft-specific
23036 tools that have been provided to facilitate interoperability with Windows
23037 when this is required. With these tools:
23040 @itemize *
23042 @item 
23043 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
23044 subsystems.
23046 @item 
23047 You can use any Dynamically Linked Library (DLL) in your Ada code (both
23048 relocatable and non-relocatable DLLs are supported).
23050 @item 
23051 You can build Ada DLLs for use in other applications. These applications
23052 can be written in a language other than Ada (e.g., C, C++, etc). Again both
23053 relocatable and non-relocatable Ada DLLs are supported.
23055 @item 
23056 You can include Windows resources in your Ada application.
23058 @item 
23059 You can use or create COM/DCOM objects.
23060 @end itemize
23062 Immediately below are listed all known general GNAT-for-Windows restrictions.
23063 Other restrictions about specific features like Windows Resources and DLLs
23064 are listed in separate sections below.
23067 @itemize *
23069 @item 
23070 It is not possible to use @code{GetLastError} and @code{SetLastError}
23071 when tasking, protected records, or exceptions are used. In these
23072 cases, in order to implement Ada semantics, the GNAT run-time system
23073 calls certain Win32 routines that set the last error variable to 0 upon
23074 success. It should be possible to use @code{GetLastError} and
23075 @code{SetLastError} when tasking, protected record, and exception
23076 features are not used, but it is not guaranteed to work.
23078 @item 
23079 It is not possible to link against Microsoft C++ libraries except for
23080 import libraries. Interfacing must be done by the mean of DLLs.
23082 @item 
23083 It is possible to link against Microsoft C libraries. Yet the preferred
23084 solution is to use C/C++ compiler that comes with GNAT, since it
23085 doesn’t require having two different development environments and makes the
23086 inter-language debugging experience smoother.
23088 @item 
23089 When the compilation environment is located on FAT32 drives, users may
23090 experience recompilations of the source files that have not changed if
23091 Daylight Saving Time (DST) state has changed since the last time files
23092 were compiled. NTFS drives do not have this problem.
23094 @item 
23095 No components of the GNAT toolset use any entries in the Windows
23096 registry. The only entries that can be created are file associations and
23097 PATH settings, provided the user has chosen to create them at installation
23098 time, as well as some minimal book-keeping information needed to correctly
23099 uninstall or integrate different GNAT products.
23100 @end itemize
23102 @node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
23103 @anchor{gnat_ugn/platform_specific_information id11}@anchor{1c9}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{1ca}
23104 @subsection Using a network installation of GNAT
23107 Make sure the system on which GNAT is installed is accessible from the
23108 current machine, i.e., the install location is shared over the network.
23109 Shared resources are accessed on Windows by means of UNC paths, which
23110 have the format @code{\\\\server\\sharename\\path}
23112 In order to use such a network installation, simply add the UNC path of the
23113 @code{bin} directory of your GNAT installation in front of your PATH. For
23114 example, if GNAT is installed in @code{\GNAT} directory of a share location
23115 called @code{c-drive} on a machine @code{LOKI}, the following command will
23116 make it available:
23118 @quotation
23120 @example
23121 $ path \\loki\c-drive\gnat\bin;%path%`
23122 @end example
23123 @end quotation
23125 Be aware that every compilation using the network installation results in the
23126 transfer of large amounts of data across the network and will likely cause
23127 serious performance penalty.
23129 @node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
23130 @anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{1cb}@anchor{gnat_ugn/platform_specific_information id12}@anchor{1cc}
23131 @subsection CONSOLE and WINDOWS subsystems
23134 @geindex CONSOLE Subsystem
23136 @geindex WINDOWS Subsystem
23138 @geindex -mwindows
23140 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
23141 (which is the default subsystem) will always create a console when
23142 launching the application. This is not something desirable when the
23143 application has a Windows GUI. To get rid of this console the
23144 application must be using the @code{WINDOWS} subsystem. To do so
23145 the @code{-mwindows} linker option must be specified.
23147 @quotation
23149 @example
23150 $ gnatmake winprog -largs -mwindows
23151 @end example
23152 @end quotation
23154 @node Temporary Files,Disabling Command Line Argument Expansion,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
23155 @anchor{gnat_ugn/platform_specific_information id13}@anchor{1cd}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{1ce}
23156 @subsection Temporary Files
23159 @geindex Temporary files
23161 It is possible to control where temporary files gets created by setting
23162 the 
23163 @geindex TMP
23164 @geindex environment variable; TMP
23165 @code{TMP} environment variable. The file will be created:
23168 @itemize *
23170 @item 
23171 Under the directory pointed to by the 
23172 @geindex TMP
23173 @geindex environment variable; TMP
23174 @code{TMP} environment variable if
23175 this directory exists.
23177 @item 
23178 Under @code{c:\temp}, if the 
23179 @geindex TMP
23180 @geindex environment variable; TMP
23181 @code{TMP} environment variable is not
23182 set (or not pointing to a directory) and if this directory exists.
23184 @item 
23185 Under the current working directory otherwise.
23186 @end itemize
23188 This allows you to determine exactly where the temporary
23189 file will be created. This is particularly useful in networked
23190 environments where you may not have write access to some
23191 directories.
23193 @node Disabling Command Line Argument Expansion,Windows Socket Timeouts,Temporary Files,Microsoft Windows Topics
23194 @anchor{gnat_ugn/platform_specific_information disabling-command-line-argument-expansion}@anchor{1cf}
23195 @subsection Disabling Command Line Argument Expansion
23198 @geindex Command Line Argument Expansion
23200 By default, an executable compiled for the Windows platform will do
23201 the following postprocessing on the arguments passed on the command
23202 line:
23205 @itemize *
23207 @item 
23208 If the argument contains the characters @code{*} and/or @code{?}, then
23209 file expansion will be attempted. For example, if the current directory
23210 contains @code{a.txt} and @code{b.txt}, then when calling:
23212 @example
23213 $ my_ada_program *.txt
23214 @end example
23216 The following arguments will effectively be passed to the main program
23217 (for example when using @code{Ada.Command_Line.Argument}):
23219 @example
23220 Ada.Command_Line.Argument (1) -> "a.txt"
23221 Ada.Command_Line.Argument (2) -> "b.txt"
23222 @end example
23224 @item 
23225 Filename expansion can be disabled for a given argument by using single
23226 quotes. Thus, calling:
23228 @example
23229 $ my_ada_program '*.txt'
23230 @end example
23232 will result in:
23234 @example
23235 Ada.Command_Line.Argument (1) -> "*.txt"
23236 @end example
23237 @end itemize
23239 Note that if the program is launched from a shell such as Cygwin Bash
23240 then quote removal might be performed by the shell.
23242 In some contexts it might be useful to disable this feature (for example if
23243 the program performs its own argument expansion). In order to do this, a C
23244 symbol needs to be defined and set to @code{0}. You can do this by
23245 adding the following code fragment in one of your Ada units:
23247 @example
23248 Do_Argv_Expansion : Integer := 0;
23249 pragma Export (C, Do_Argv_Expansion, "__gnat_do_argv_expansion");
23250 @end example
23252 The results of previous examples will be respectively:
23254 @example
23255 Ada.Command_Line.Argument (1) -> "*.txt"
23256 @end example
23258 and:
23260 @example
23261 Ada.Command_Line.Argument (1) -> "'*.txt'"
23262 @end example
23264 @node Windows Socket Timeouts,Mixed-Language Programming on Windows,Disabling Command Line Argument Expansion,Microsoft Windows Topics
23265 @anchor{gnat_ugn/platform_specific_information windows-socket-timeouts}@anchor{1d0}
23266 @subsection Windows Socket Timeouts
23269 Microsoft Windows desktops older than @code{8.0} and Microsoft Windows Servers
23270 older than @code{2019} set a socket timeout 500 milliseconds longer than the value
23271 set by setsockopt with @code{SO_RCVTIMEO} and @code{SO_SNDTIMEO} options. The GNAT
23272 runtime makes a correction for the difference in the corresponding Windows
23273 versions. For Windows Server starting with version @code{2019}, the user must
23274 provide a manifest file for the GNAT runtime to be able to recognize that
23275 the Windows version does not need the timeout correction. The manifest file
23276 should be located in the same directory as the executable file, and its file
23277 name must match the executable name suffixed by @code{.manifest}. For example,
23278 if the executable name is @code{sock_wto.exe}, then the manifest file name
23279 has to be @code{sock_wto.exe.manifest}. The manifest file must contain at
23280 least the following data:
23282 @example
23283 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
23284 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
23285 <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
23286 <application>
23287    <!-- Windows Vista -->
23288    <supportedOS Id="@{e2011457-1546-43c5-a5fe-008deee3d3f0@}"/>
23289    <!-- Windows 7 -->
23290    <supportedOS Id="@{35138b9a-5d96-4fbd-8e2d-a2440225f93a@}"/>
23291    <!-- Windows 8 -->
23292    <supportedOS Id="@{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38@}"/>
23293    <!-- Windows 8.1 -->
23294    <supportedOS Id="@{1f676c76-80e1-4239-95bb-83d0f6d0da78@}"/>
23295    <!-- Windows 10 -->
23296    <supportedOS Id="@{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a@}"/>
23297 </application>
23298 </compatibility>
23299 </assembly>
23300 @end example
23302 Without the manifest file, the socket timeout is going to be overcorrected on
23303 these Windows Server versions and the actual time is going to be 500
23304 milliseconds shorter than what was set with GNAT.Sockets.Set_Socket_Option.
23305 Note that on Microsoft Windows versions where correction is necessary, there
23306 is no way to set a socket timeout shorter than 500 ms. If a socket timeout
23307 shorter than 500 ms is needed on these Windows versions, a call to
23308 Check_Selector should be added before any socket read or write operations.
23310 @node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Windows Socket Timeouts,Microsoft Windows Topics
23311 @anchor{gnat_ugn/platform_specific_information id14}@anchor{1d1}@anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{1d2}
23312 @subsection Mixed-Language Programming on Windows
23315 Developing pure Ada applications on Windows is no different than on
23316 other GNAT-supported platforms. However, when developing or porting an
23317 application that contains a mix of Ada and C/C++, the choice of your
23318 Windows C/C++ development environment conditions your overall
23319 interoperability strategy.
23321 If you use @code{gcc} or Microsoft C to compile the non-Ada part of
23322 your application, there are no Windows-specific restrictions that
23323 affect the overall interoperability with your Ada code. If you do want
23324 to use the Microsoft tools for your C++ code, you have two choices:
23327 @itemize *
23329 @item 
23330 Encapsulate your C++ code in a DLL to be linked with your Ada
23331 application. In this case, use the Microsoft or whatever environment to
23332 build the DLL and use GNAT to build your executable
23333 (@ref{1d3,,Using DLLs with GNAT}).
23335 @item 
23336 Or you can encapsulate your Ada code in a DLL to be linked with the
23337 other part of your application. In this case, use GNAT to build the DLL
23338 (@ref{1d4,,Building DLLs with GNAT Project files}) and use the Microsoft
23339 or whatever environment to build your executable.
23340 @end itemize
23342 In addition to the description about C main in
23343 @ref{2c,,Mixed Language Programming} section, if the C main uses a
23344 stand-alone library it is required on x86-windows to
23345 setup the SEH context. For this the C main must looks like this:
23347 @quotation
23349 @example
23350 /* main.c */
23351 extern void adainit (void);
23352 extern void adafinal (void);
23353 extern void __gnat_initialize(void*);
23354 extern void call_to_ada (void);
23356 int main (int argc, char *argv[])
23358   int SEH [2];
23360   /* Initialize the SEH context */
23361   __gnat_initialize (&SEH);
23363   adainit();
23365   /* Then call Ada services in the stand-alone library */
23367   call_to_ada();
23369   adafinal();
23371 @end example
23372 @end quotation
23374 Note that this is not needed on x86_64-windows where the Windows
23375 native SEH support is used.
23377 @menu
23378 * Windows Calling Conventions:: 
23379 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
23380 * Using DLLs with GNAT:: 
23381 * Building DLLs with GNAT Project files:: 
23382 * Building DLLs with GNAT:: 
23383 * Building DLLs with gnatdll:: 
23384 * Ada DLLs and Finalization:: 
23385 * Creating a Spec for Ada DLLs:: 
23386 * GNAT and Windows Resources:: 
23387 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
23388 * Debugging a DLL:: 
23389 * Setting Stack Size from gnatlink:: 
23390 * Setting Heap Size from gnatlink:: 
23392 @end menu
23394 @node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
23395 @anchor{gnat_ugn/platform_specific_information id15}@anchor{1d5}@anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{1d6}
23396 @subsubsection Windows Calling Conventions
23399 @geindex Stdcall
23401 @geindex APIENTRY
23403 This section pertain only to Win32. On Win64 there is a single native
23404 calling convention. All convention specifiers are ignored on this
23405 platform.
23407 When a subprogram @code{F} (caller) calls a subprogram @code{G}
23408 (callee), there are several ways to push @code{G}‘s parameters on the
23409 stack and there are several possible scenarios to clean up the stack
23410 upon @code{G}‘s return. A calling convention is an agreed upon software
23411 protocol whereby the responsibilities between the caller (@code{F}) and
23412 the callee (@code{G}) are clearly defined. Several calling conventions
23413 are available for Windows:
23416 @itemize *
23418 @item 
23419 @code{C} (Microsoft defined)
23421 @item 
23422 @code{Stdcall} (Microsoft defined)
23424 @item 
23425 @code{Win32} (GNAT specific)
23427 @item 
23428 @code{DLL} (GNAT specific)
23429 @end itemize
23431 @menu
23432 * C Calling Convention:: 
23433 * Stdcall Calling Convention:: 
23434 * Win32 Calling Convention:: 
23435 * DLL Calling Convention:: 
23437 @end menu
23439 @node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
23440 @anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{1d7}@anchor{gnat_ugn/platform_specific_information id16}@anchor{1d8}
23441 @subsubsection @code{C} Calling Convention
23444 This is the default calling convention used when interfacing to C/C++
23445 routines compiled with either @code{gcc} or Microsoft Visual C++.
23447 In the @code{C} calling convention subprogram parameters are pushed on the
23448 stack by the caller from right to left. The caller itself is in charge of
23449 cleaning up the stack after the call. In addition, the name of a routine
23450 with @code{C} calling convention is mangled by adding a leading underscore.
23452 The name to use on the Ada side when importing (or exporting) a routine
23453 with @code{C} calling convention is the name of the routine. For
23454 instance the C function:
23456 @quotation
23458 @example
23459 int get_val (long);
23460 @end example
23461 @end quotation
23463 should be imported from Ada as follows:
23465 @quotation
23467 @example
23468 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23469 pragma Import (C, Get_Val, External_Name => "get_val");
23470 @end example
23471 @end quotation
23473 Note that in this particular case the @code{External_Name} parameter could
23474 have been omitted since, when missing, this parameter is taken to be the
23475 name of the Ada entity in lower case. When the @code{Link_Name} parameter
23476 is missing, as in the above example, this parameter is set to be the
23477 @code{External_Name} with a leading underscore.
23479 When importing a variable defined in C, you should always use the @code{C}
23480 calling convention unless the object containing the variable is part of a
23481 DLL (in which case you should use the @code{Stdcall} calling
23482 convention, @ref{1d9,,Stdcall Calling Convention}).
23484 @node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
23485 @anchor{gnat_ugn/platform_specific_information id17}@anchor{1da}@anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{1d9}
23486 @subsubsection @code{Stdcall} Calling Convention
23489 This convention, which was the calling convention used for Pascal
23490 programs, is used by Microsoft for all the routines in the Win32 API for
23491 efficiency reasons. It must be used to import any routine for which this
23492 convention was specified.
23494 In the @code{Stdcall} calling convention subprogram parameters are pushed
23495 on the stack by the caller from right to left. The callee (and not the
23496 caller) is in charge of cleaning the stack on routine exit. In addition,
23497 the name of a routine with @code{Stdcall} calling convention is mangled by
23498 adding a leading underscore (as for the @code{C} calling convention) and a
23499 trailing @code{@@@var{nn}}, where @code{nn} is the overall size (in
23500 bytes) of the parameters passed to the routine.
23502 The name to use on the Ada side when importing a C routine with a
23503 @code{Stdcall} calling convention is the name of the C routine. The leading
23504 underscore and trailing @code{@@@var{nn}} are added automatically by
23505 the compiler. For instance the Win32 function:
23507 @quotation
23509 @example
23510 APIENTRY int get_val (long);
23511 @end example
23512 @end quotation
23514 should be imported from Ada as follows:
23516 @quotation
23518 @example
23519 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23520 pragma Import (Stdcall, Get_Val);
23521 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
23522 @end example
23523 @end quotation
23525 As for the @code{C} calling convention, when the @code{External_Name}
23526 parameter is missing, it is taken to be the name of the Ada entity in lower
23527 case. If instead of writing the above import pragma you write:
23529 @quotation
23531 @example
23532 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23533 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
23534 @end example
23535 @end quotation
23537 then the imported routine is @code{_retrieve_val@@4}. However, if instead
23538 of specifying the @code{External_Name} parameter you specify the
23539 @code{Link_Name} as in the following example:
23541 @quotation
23543 @example
23544 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23545 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
23546 @end example
23547 @end quotation
23549 then the imported routine is @code{retrieve_val}, that is, there is no
23550 decoration at all. No leading underscore and no Stdcall suffix
23551 @code{@@@var{nn}}.
23553 This is especially important as in some special cases a DLL’s entry
23554 point name lacks a trailing @code{@@@var{nn}} while the exported
23555 name generated for a call has it.
23557 It is also possible to import variables defined in a DLL by using an
23558 import pragma for a variable. As an example, if a DLL contains a
23559 variable defined as:
23561 @quotation
23563 @example
23564 int my_var;
23565 @end example
23566 @end quotation
23568 then, to access this variable from Ada you should write:
23570 @quotation
23572 @example
23573 My_Var : Interfaces.C.int;
23574 pragma Import (Stdcall, My_Var);
23575 @end example
23576 @end quotation
23578 Note that to ease building cross-platform bindings this convention
23579 will be handled as a @code{C} calling convention on non-Windows platforms.
23581 @node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
23582 @anchor{gnat_ugn/platform_specific_information id18}@anchor{1db}@anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{1dc}
23583 @subsubsection @code{Win32} Calling Convention
23586 This convention, which is GNAT-specific is fully equivalent to the
23587 @code{Stdcall} calling convention described above.
23589 @node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
23590 @anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{1dd}@anchor{gnat_ugn/platform_specific_information id19}@anchor{1de}
23591 @subsubsection @code{DLL} Calling Convention
23594 This convention, which is GNAT-specific is fully equivalent to the
23595 @code{Stdcall} calling convention described above.
23597 @node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
23598 @anchor{gnat_ugn/platform_specific_information id20}@anchor{1df}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{1e0}
23599 @subsubsection Introduction to Dynamic Link Libraries (DLLs)
23602 @geindex DLL
23604 A Dynamically Linked Library (DLL) is a library that can be shared by
23605 several applications running under Windows. A DLL can contain any number of
23606 routines and variables.
23608 One advantage of DLLs is that you can change and enhance them without
23609 forcing all the applications that depend on them to be relinked or
23610 recompiled. However, you should be aware than all calls to DLL routines are
23611 slower since, as you will understand below, such calls are indirect.
23613 To illustrate the remainder of this section, suppose that an application
23614 wants to use the services of a DLL @code{API.dll}. To use the services
23615 provided by @code{API.dll} you must statically link against the DLL or
23616 an import library which contains a jump table with an entry for each
23617 routine and variable exported by the DLL. In the Microsoft world this
23618 import library is called @code{API.lib}. When using GNAT this import
23619 library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
23620 @code{libAPI.a} or @code{libapi.a} (names are case insensitive).
23622 After you have linked your application with the DLL or the import library
23623 and you run your application, here is what happens:
23626 @itemize *
23628 @item 
23629 Your application is loaded into memory.
23631 @item 
23632 The DLL @code{API.dll} is mapped into the address space of your
23633 application. This means that:
23636 @itemize -
23638 @item 
23639 The DLL will use the stack of the calling thread.
23641 @item 
23642 The DLL will use the virtual address space of the calling process.
23644 @item 
23645 The DLL will allocate memory from the virtual address space of the calling
23646 process.
23648 @item 
23649 Handles (pointers) can be safely exchanged between routines in the DLL
23650 routines and routines in the application using the DLL.
23651 @end itemize
23653 @item 
23654 The entries in the jump table (from the import library @code{libAPI.dll.a}
23655 or @code{API.lib} or automatically created when linking against a DLL)
23656 which is part of your application are initialized with the addresses
23657 of the routines and variables in @code{API.dll}.
23659 @item 
23660 If present in @code{API.dll}, routines @code{DllMain} or
23661 @code{DllMainCRTStartup} are invoked. These routines typically contain
23662 the initialization code needed for the well-being of the routines and
23663 variables exported by the DLL.
23664 @end itemize
23666 There is an additional point which is worth mentioning. In the Windows
23667 world there are two kind of DLLs: relocatable and non-relocatable
23668 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
23669 in the target application address space. If the addresses of two
23670 non-relocatable DLLs overlap and these happen to be used by the same
23671 application, a conflict will occur and the application will run
23672 incorrectly. Hence, when possible, it is always preferable to use and
23673 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
23674 supported by GNAT. Note that the @code{-s} linker option (see GNU Linker
23675 User’s Guide) removes the debugging symbols from the DLL but the DLL can
23676 still be relocated.
23678 As a side note, an interesting difference between Microsoft DLLs and
23679 Unix shared libraries, is the fact that on most Unix systems all public
23680 routines are exported by default in a Unix shared library, while under
23681 Windows it is possible (but not required) to list exported routines in
23682 a definition file (see @ref{1e1,,The Definition File}).
23684 @node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
23685 @anchor{gnat_ugn/platform_specific_information id21}@anchor{1e2}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{1d3}
23686 @subsubsection Using DLLs with GNAT
23689 To use the services of a DLL, say @code{API.dll}, in your Ada application
23690 you must have:
23693 @itemize *
23695 @item 
23696 The Ada spec for the routines and/or variables you want to access in
23697 @code{API.dll}. If not available this Ada spec must be built from the C/C++
23698 header files provided with the DLL.
23700 @item 
23701 The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
23702 mentioned an import library is a statically linked library containing the
23703 import table which will be filled at load time to point to the actual
23704 @code{API.dll} routines. Sometimes you don’t have an import library for the
23705 DLL you want to use. The following sections will explain how to build
23706 one. Note that this is optional.
23708 @item 
23709 The actual DLL, @code{API.dll}.
23710 @end itemize
23712 Once you have all the above, to compile an Ada application that uses the
23713 services of @code{API.dll} and whose main subprogram is @code{My_Ada_App},
23714 you simply issue the command
23716 @quotation
23718 @example
23719 $ gnatmake my_ada_app -largs -lAPI
23720 @end example
23721 @end quotation
23723 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
23724 tells the GNAT linker to look for an import library. The linker will
23725 look for a library name in this specific order:
23728 @itemize *
23730 @item 
23731 @code{libAPI.dll.a}
23733 @item 
23734 @code{API.dll.a}
23736 @item 
23737 @code{libAPI.a}
23739 @item 
23740 @code{API.lib}
23742 @item 
23743 @code{libAPI.dll}
23745 @item 
23746 @code{API.dll}
23747 @end itemize
23749 The first three are the GNU style import libraries. The third is the
23750 Microsoft style import libraries. The last two are the actual DLL names.
23752 Note that if the Ada package spec for @code{API.dll} contains the
23753 following pragma
23755 @quotation
23757 @example
23758 pragma Linker_Options ("-lAPI");
23759 @end example
23760 @end quotation
23762 you do not have to add @code{-largs -lAPI} at the end of the
23763 @code{gnatmake} command.
23765 If any one of the items above is missing you will have to create it
23766 yourself. The following sections explain how to do so using as an
23767 example a fictitious DLL called @code{API.dll}.
23769 @menu
23770 * Creating an Ada Spec for the DLL Services:: 
23771 * Creating an Import Library:: 
23773 @end menu
23775 @node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
23776 @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}
23777 @subsubsection Creating an Ada Spec for the DLL Services
23780 A DLL typically comes with a C/C++ header file which provides the
23781 definitions of the routines and variables exported by the DLL. The Ada
23782 equivalent of this header file is a package spec that contains definitions
23783 for the imported entities. If the DLL you intend to use does not come with
23784 an Ada spec you have to generate one such spec yourself. For example if
23785 the header file of @code{API.dll} is a file @code{api.h} containing the
23786 following two definitions:
23788 @quotation
23790 @example
23791 int some_var;
23792 int get (char *);
23793 @end example
23794 @end quotation
23796 then the equivalent Ada spec could be:
23798 @quotation
23800 @example
23801 with Interfaces.C.Strings;
23802 package API is
23803    use Interfaces;
23805    Some_Var : C.int;
23806    function Get (Str : C.Strings.Chars_Ptr) return C.int;
23808 private
23809    pragma Import (C, Get);
23810    pragma Import (DLL, Some_Var);
23811 end API;
23812 @end example
23813 @end quotation
23815 @node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
23816 @anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{1e5}@anchor{gnat_ugn/platform_specific_information id23}@anchor{1e6}
23817 @subsubsection Creating an Import Library
23820 @geindex Import library
23822 If a Microsoft-style import library @code{API.lib} or a GNAT-style
23823 import library @code{libAPI.dll.a} or @code{libAPI.a} is available
23824 with @code{API.dll} you can skip this section. You can also skip this
23825 section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
23826 as in this case it is possible to link directly against the
23827 DLL. Otherwise read on.
23829 @geindex Definition file
23830 @anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{1e1}
23831 @subsubheading The Definition File
23834 As previously mentioned, and unlike Unix systems, the list of symbols
23835 that are exported from a DLL must be provided explicitly in Windows.
23836 The main goal of a definition file is precisely that: list the symbols
23837 exported by a DLL. A definition file (usually a file with a @code{.def}
23838 suffix) has the following structure:
23840 @quotation
23842 @example
23843 [LIBRARY `@w{`}name`@w{`}]
23844 [DESCRIPTION `@w{`}string`@w{`}]
23845 EXPORTS
23846    `@w{`}symbol1`@w{`}
23847    `@w{`}symbol2`@w{`}
23848    ...
23849 @end example
23850 @end quotation
23853 @table @asis
23855 @item `LIBRARY name'
23857 This section, which is optional, gives the name of the DLL.
23859 @item `DESCRIPTION string'
23861 This section, which is optional, gives a description string that will be
23862 embedded in the import library.
23864 @item `EXPORTS'
23866 This section gives the list of exported symbols (procedures, functions or
23867 variables). For instance in the case of @code{API.dll} the @code{EXPORTS}
23868 section of @code{API.def} looks like:
23870 @example
23871 EXPORTS
23872    some_var
23873    get
23874 @end example
23875 @end table
23877 Note that you must specify the correct suffix (@code{@@@var{nn}})
23878 (see @ref{1d6,,Windows Calling Conventions}) for a Stdcall
23879 calling convention function in the exported symbols list.
23881 There can actually be other sections in a definition file, but these
23882 sections are not relevant to the discussion at hand.
23883 @anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{1e7}
23884 @subsubheading Creating a Definition File Automatically
23887 You can automatically create the definition file @code{API.def}
23888 (see @ref{1e1,,The Definition File}) from a DLL.
23889 For that use the @code{dlltool} program as follows:
23891 @quotation
23893 @example
23894 $ dlltool API.dll -z API.def --export-all-symbols
23895 @end example
23897 Note that if some routines in the DLL have the @code{Stdcall} convention
23898 (@ref{1d6,,Windows Calling Conventions}) with stripped @code{@@@var{nn}}
23899 suffix then you’ll have to edit @code{api.def} to add it, and specify
23900 @code{-k} to @code{gnatdll} when creating the import library.
23902 Here are some hints to find the right @code{@@@var{nn}} suffix.
23905 @itemize -
23907 @item 
23908 If you have the Microsoft import library (.lib), it is possible to get
23909 the right symbols by using Microsoft @code{dumpbin} tool (see the
23910 corresponding Microsoft documentation for further details).
23912 @example
23913 $ dumpbin /exports api.lib
23914 @end example
23916 @item 
23917 If you have a message about a missing symbol at link time the compiler
23918 tells you what symbol is expected. You just have to go back to the
23919 definition file and add the right suffix.
23920 @end itemize
23921 @end quotation
23922 @anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{1e8}
23923 @subsubheading GNAT-Style Import Library
23926 To create a static import library from @code{API.dll} with the GNAT tools
23927 you should create the .def file, then use @code{gnatdll} tool
23928 (see @ref{1e9,,Using gnatdll}) as follows:
23930 @quotation
23932 @example
23933 $ gnatdll -e API.def -d API.dll
23934 @end example
23936 @code{gnatdll} takes as input a definition file @code{API.def} and the
23937 name of the DLL containing the services listed in the definition file
23938 @code{API.dll}. The name of the static import library generated is
23939 computed from the name of the definition file as follows: if the
23940 definition file name is @code{xyz.def}, the import library name will
23941 be @code{libxyz.a}. Note that in the previous example option
23942 @code{-e} could have been removed because the name of the definition
23943 file (before the @code{.def} suffix) is the same as the name of the
23944 DLL (@ref{1e9,,Using gnatdll} for more information about @code{gnatdll}).
23945 @end quotation
23946 @anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{1ea}
23947 @subsubheading Microsoft-Style Import Library
23950 A Microsoft import library is needed only if you plan to make an
23951 Ada DLL available to applications developed with Microsoft
23952 tools (@ref{1d2,,Mixed-Language Programming on Windows}).
23954 To create a Microsoft-style import library for @code{API.dll} you
23955 should create the .def file, then build the actual import library using
23956 Microsoft’s @code{lib} utility:
23958 @quotation
23960 @example
23961 $ lib -machine:IX86 -def:API.def -out:API.lib
23962 @end example
23964 If you use the above command the definition file @code{API.def} must
23965 contain a line giving the name of the DLL:
23967 @example
23968 LIBRARY      "API"
23969 @end example
23971 See the Microsoft documentation for further details about the usage of
23972 @code{lib}.
23973 @end quotation
23975 @node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
23976 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{1d4}@anchor{gnat_ugn/platform_specific_information id24}@anchor{1eb}
23977 @subsubsection Building DLLs with GNAT Project files
23980 @geindex DLLs
23981 @geindex building
23983 There is nothing specific to Windows in the build process.
23984 See the `Library Projects' section in the `GNAT Project Manager'
23985 chapter of the `GPRbuild User’s Guide'.
23987 Due to a system limitation, it is not possible under Windows to create threads
23988 when inside the @code{DllMain} routine which is used for auto-initialization
23989 of shared libraries, so it is not possible to have library level tasks in SALs.
23991 @node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
23992 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{1ec}@anchor{gnat_ugn/platform_specific_information id25}@anchor{1ed}
23993 @subsubsection Building DLLs with GNAT
23996 @geindex DLLs
23997 @geindex building
23999 This section explain how to build DLLs using the GNAT built-in DLL
24000 support. With the following procedure it is straight forward to build
24001 and use DLLs with GNAT.
24004 @itemize *
24006 @item 
24007 Building object files.
24008 The first step is to build all objects files that are to be included
24009 into the DLL. This is done by using the standard @code{gnatmake} tool.
24011 @item 
24012 Building the DLL.
24013 To build the DLL you must use the @code{gcc} @code{-shared} and
24014 @code{-shared-libgcc} options. It is quite simple to use this method:
24016 @example
24017 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
24018 @end example
24020 It is important to note that in this case all symbols found in the
24021 object files are automatically exported. It is possible to restrict
24022 the set of symbols to export by passing to @code{gcc} a definition
24023 file (see @ref{1e1,,The Definition File}).
24024 For example:
24026 @example
24027 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
24028 @end example
24030 If you use a definition file you must export the elaboration procedures
24031 for every package that required one. Elaboration procedures are named
24032 using the package name followed by “_E”.
24034 @item 
24035 Preparing DLL to be used.
24036 For the DLL to be used by client programs the bodies must be hidden
24037 from it and the .ali set with read-only attribute. This is very important
24038 otherwise GNAT will recompile all packages and will not actually use
24039 the code in the DLL. For example:
24041 @example
24042 $ mkdir apilib
24043 $ copy *.ads *.ali api.dll apilib
24044 $ attrib +R apilib\\*.ali
24045 @end example
24046 @end itemize
24048 At this point it is possible to use the DLL by directly linking
24049 against it. Note that you must use the GNAT shared runtime when using
24050 GNAT shared libraries. This is achieved by using the @code{-shared} binder
24051 option.
24053 @quotation
24055 @example
24056 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
24057 @end example
24058 @end quotation
24060 @node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
24061 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{1ee}@anchor{gnat_ugn/platform_specific_information id26}@anchor{1ef}
24062 @subsubsection Building DLLs with gnatdll
24065 @geindex DLLs
24066 @geindex building
24068 Note that it is preferred to use GNAT Project files
24069 (@ref{1d4,,Building DLLs with GNAT Project files}) or the built-in GNAT
24070 DLL support (@ref{1ec,,Building DLLs with GNAT}) or to build DLLs.
24072 This section explains how to build DLLs containing Ada code using
24073 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
24074 remainder of this section.
24076 The steps required to build an Ada DLL that is to be used by Ada as well as
24077 non-Ada applications are as follows:
24080 @itemize *
24082 @item 
24083 You need to mark each Ada entity exported by the DLL with a @code{C} or
24084 @code{Stdcall} calling convention to avoid any Ada name mangling for the
24085 entities exported by the DLL
24086 (see @ref{1f0,,Exporting Ada Entities}). You can
24087 skip this step if you plan to use the Ada DLL only from Ada applications.
24089 @item 
24090 Your Ada code must export an initialization routine which calls the routine
24091 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
24092 the Ada code in the DLL (@ref{1f1,,Ada DLLs and Elaboration}). The initialization
24093 routine exported by the Ada DLL must be invoked by the clients of the DLL
24094 to initialize the DLL.
24096 @item 
24097 When useful, the DLL should also export a finalization routine which calls
24098 routine @code{adafinal} generated by @code{gnatbind} to perform the
24099 finalization of the Ada code in the DLL (@ref{1f2,,Ada DLLs and Finalization}).
24100 The finalization routine exported by the Ada DLL must be invoked by the
24101 clients of the DLL when the DLL services are no further needed.
24103 @item 
24104 You must provide a spec for the services exported by the Ada DLL in each
24105 of the programming languages to which you plan to make the DLL available.
24107 @item 
24108 You must provide a definition file listing the exported entities
24109 (@ref{1e1,,The Definition File}).
24111 @item 
24112 Finally you must use @code{gnatdll} to produce the DLL and the import
24113 library (@ref{1e9,,Using gnatdll}).
24114 @end itemize
24116 Note that a relocatable DLL stripped using the @code{strip}
24117 binutils tool will not be relocatable anymore. To build a DLL without
24118 debug information pass @code{-largs -s} to @code{gnatdll}. This
24119 restriction does not apply to a DLL built using a Library Project.
24120 See the `Library Projects' section in the `GNAT Project Manager'
24121 chapter of the `GPRbuild User’s Guide'.
24123 @c Limitations_When_Using_Ada_DLLs_from Ada:
24125 @menu
24126 * Limitations When Using Ada DLLs from Ada:: 
24127 * Exporting Ada Entities:: 
24128 * Ada DLLs and Elaboration:: 
24130 @end menu
24132 @node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
24133 @anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{1f3}
24134 @subsubsection Limitations When Using Ada DLLs from Ada
24137 When using Ada DLLs from Ada applications there is a limitation users
24138 should be aware of. Because on Windows the GNAT run-time is not in a DLL of
24139 its own, each Ada DLL includes a part of the GNAT run-time. Specifically,
24140 each Ada DLL includes the services of the GNAT run-time that are necessary
24141 to the Ada code inside the DLL. As a result, when an Ada program uses an
24142 Ada DLL there are two independent GNAT run-times: one in the Ada DLL and
24143 one in the main program.
24145 It is therefore not possible to exchange GNAT run-time objects between the
24146 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
24147 handles (e.g., @code{Text_IO.File_Type}), tasks types, protected objects
24148 types, etc.
24150 It is completely safe to exchange plain elementary, array or record types,
24151 Windows object handles, etc.
24153 @node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
24154 @anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{1f0}@anchor{gnat_ugn/platform_specific_information id27}@anchor{1f4}
24155 @subsubsection Exporting Ada Entities
24158 @geindex Export table
24160 Building a DLL is a way to encapsulate a set of services usable from any
24161 application. As a result, the Ada entities exported by a DLL should be
24162 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
24163 any Ada name mangling. As an example here is an Ada package
24164 @code{API}, spec and body, exporting two procedures, a function, and a
24165 variable:
24167 @quotation
24169 @example
24170 with Interfaces.C; use Interfaces;
24171 package API is
24172    Count : C.int := 0;
24173    function Factorial (Val : C.int) return C.int;
24175    procedure Initialize_API;
24176    procedure Finalize_API;
24177    --  Initialization & Finalization routines. More in the next section.
24178 private
24179    pragma Export (C, Initialize_API);
24180    pragma Export (C, Finalize_API);
24181    pragma Export (C, Count);
24182    pragma Export (C, Factorial);
24183 end API;
24184 @end example
24186 @example
24187 package body API is
24188    function Factorial (Val : C.int) return C.int is
24189       Fact : C.int := 1;
24190    begin
24191       Count := Count + 1;
24192       for K in 1 .. Val loop
24193          Fact := Fact * K;
24194       end loop;
24195       return Fact;
24196    end Factorial;
24198    procedure Initialize_API is
24199       procedure Adainit;
24200       pragma Import (C, Adainit);
24201    begin
24202       Adainit;
24203    end Initialize_API;
24205    procedure Finalize_API is
24206       procedure Adafinal;
24207       pragma Import (C, Adafinal);
24208    begin
24209       Adafinal;
24210    end Finalize_API;
24211 end API;
24212 @end example
24213 @end quotation
24215 If the Ada DLL you are building will only be used by Ada applications
24216 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
24217 convention. As an example, the previous package could be written as
24218 follows:
24220 @quotation
24222 @example
24223 package API is
24224    Count : Integer := 0;
24225    function Factorial (Val : Integer) return Integer;
24227    procedure Initialize_API;
24228    procedure Finalize_API;
24229    --  Initialization and Finalization routines.
24230 end API;
24231 @end example
24233 @example
24234 package body API is
24235    function Factorial (Val : Integer) return Integer is
24236       Fact : Integer := 1;
24237    begin
24238       Count := Count + 1;
24239       for K in 1 .. Val loop
24240          Fact := Fact * K;
24241       end loop;
24242       return Fact;
24243    end Factorial;
24245    ...
24246    --  The remainder of this package body is unchanged.
24247 end API;
24248 @end example
24249 @end quotation
24251 Note that if you do not export the Ada entities with a @code{C} or
24252 @code{Stdcall} convention you will have to provide the mangled Ada names
24253 in the definition file of the Ada DLL
24254 (@ref{1f5,,Creating the Definition File}).
24256 @node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
24257 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{1f1}@anchor{gnat_ugn/platform_specific_information id28}@anchor{1f6}
24258 @subsubsection Ada DLLs and Elaboration
24261 @geindex DLLs and elaboration
24263 The DLL that you are building contains your Ada code as well as all the
24264 routines in the Ada library that are needed by it. The first thing a
24265 user of your DLL must do is elaborate the Ada code
24266 (@ref{f,,Elaboration Order Handling in GNAT}).
24268 To achieve this you must export an initialization routine
24269 (@code{Initialize_API} in the previous example), which must be invoked
24270 before using any of the DLL services. This elaboration routine must call
24271 the Ada elaboration routine @code{adainit} generated by the GNAT binder
24272 (@ref{7e,,Binding with Non-Ada Main Programs}). See the body of
24273 @code{Initialize_Api} for an example. Note that the GNAT binder is
24274 automatically invoked during the DLL build process by the @code{gnatdll}
24275 tool (@ref{1e9,,Using gnatdll}).
24277 When a DLL is loaded, Windows systematically invokes a routine called
24278 @code{DllMain}. It would therefore be possible to call @code{adainit}
24279 directly from @code{DllMain} without having to provide an explicit
24280 initialization routine. Unfortunately, it is not possible to call
24281 @code{adainit} from the @code{DllMain} if your program has library level
24282 tasks because access to the @code{DllMain} entry point is serialized by
24283 the system (that is, only a single thread can execute ‘through’ it at a
24284 time), which means that the GNAT run-time will deadlock waiting for the
24285 newly created task to complete its initialization.
24287 @node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
24288 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{1f2}@anchor{gnat_ugn/platform_specific_information id29}@anchor{1f7}
24289 @subsubsection Ada DLLs and Finalization
24292 @geindex DLLs and finalization
24294 When the services of an Ada DLL are no longer needed, the client code should
24295 invoke the DLL finalization routine, if available. The DLL finalization
24296 routine is in charge of releasing all resources acquired by the DLL. In the
24297 case of the Ada code contained in the DLL, this is achieved by calling
24298 routine @code{adafinal} generated by the GNAT binder
24299 (@ref{7e,,Binding with Non-Ada Main Programs}).
24300 See the body of @code{Finalize_Api} for an
24301 example. As already pointed out the GNAT binder is automatically invoked
24302 during the DLL build process by the @code{gnatdll} tool
24303 (@ref{1e9,,Using gnatdll}).
24305 @node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
24306 @anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{1f8}@anchor{gnat_ugn/platform_specific_information id30}@anchor{1f9}
24307 @subsubsection Creating a Spec for Ada DLLs
24310 To use the services exported by the Ada DLL from another programming
24311 language (e.g., C), you have to translate the specs of the exported Ada
24312 entities in that language. For instance in the case of @code{API.dll},
24313 the corresponding C header file could look like:
24315 @quotation
24317 @example
24318 extern int *_imp__count;
24319 #define count (*_imp__count)
24320 int factorial (int);
24321 @end example
24322 @end quotation
24324 It is important to understand that when building an Ada DLL to be used by
24325 other Ada applications, you need two different specs for the packages
24326 contained in the DLL: one for building the DLL and the other for using
24327 the DLL. This is because the @code{DLL} calling convention is needed to
24328 use a variable defined in a DLL, but when building the DLL, the variable
24329 must have either the @code{Ada} or @code{C} calling convention. As an
24330 example consider a DLL comprising the following package @code{API}:
24332 @quotation
24334 @example
24335 package API is
24336    Count : Integer := 0;
24337    ...
24338    --  Remainder of the package omitted.
24339 end API;
24340 @end example
24341 @end quotation
24343 After producing a DLL containing package @code{API}, the spec that
24344 must be used to import @code{API.Count} from Ada code outside of the
24345 DLL is:
24347 @quotation
24349 @example
24350 package API is
24351    Count : Integer;
24352    pragma Import (DLL, Count);
24353 end API;
24354 @end example
24355 @end quotation
24357 @menu
24358 * Creating the Definition File:: 
24359 * Using gnatdll:: 
24361 @end menu
24363 @node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
24364 @anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{1f5}@anchor{gnat_ugn/platform_specific_information id31}@anchor{1fa}
24365 @subsubsection Creating the Definition File
24368 The definition file is the last file needed to build the DLL. It lists
24369 the exported symbols. As an example, the definition file for a DLL
24370 containing only package @code{API} (where all the entities are exported
24371 with a @code{C} calling convention) is:
24373 @quotation
24375 @example
24376 EXPORTS
24377     count
24378     factorial
24379     finalize_api
24380     initialize_api
24381 @end example
24382 @end quotation
24384 If the @code{C} calling convention is missing from package @code{API},
24385 then the definition file contains the mangled Ada names of the above
24386 entities, which in this case are:
24388 @quotation
24390 @example
24391 EXPORTS
24392     api__count
24393     api__factorial
24394     api__finalize_api
24395     api__initialize_api
24396 @end example
24397 @end quotation
24399 @node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
24400 @anchor{gnat_ugn/platform_specific_information id32}@anchor{1fb}@anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{1e9}
24401 @subsubsection Using @code{gnatdll}
24404 @geindex gnatdll
24406 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
24407 and non-Ada sources that make up your DLL have been compiled.
24408 @code{gnatdll} is actually in charge of two distinct tasks: build the
24409 static import library for the DLL and the actual DLL. The form of the
24410 @code{gnatdll} command is
24412 @quotation
24414 @example
24415 $ gnatdll [ switches ] list-of-files [ -largs opts ]
24416 @end example
24417 @end quotation
24419 where @code{list-of-files} is a list of ALI and object files. The object
24420 file list must be the exact list of objects corresponding to the non-Ada
24421 sources whose services are to be included in the DLL. The ALI file list
24422 must be the exact list of ALI files for the corresponding Ada sources
24423 whose services are to be included in the DLL. If @code{list-of-files} is
24424 missing, only the static import library is generated.
24426 You may specify any of the following switches to @code{gnatdll}:
24428 @quotation
24430 @geindex -a (gnatdll)
24431 @end quotation
24434 @table @asis
24436 @item @code{-a[`address']}
24438 Build a non-relocatable DLL at @code{address}. If @code{address} is not
24439 specified the default address @code{0x11000000} will be used. By default,
24440 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
24441 advise the reader to build relocatable DLL.
24443 @geindex -b (gnatdll)
24445 @item @code{-b `address'}
24447 Set the relocatable DLL base address. By default the address is
24448 @code{0x11000000}.
24450 @geindex -bargs (gnatdll)
24452 @item @code{-bargs `opts'}
24454 Binder options. Pass @code{opts} to the binder.
24456 @geindex -d (gnatdll)
24458 @item @code{-d `dllfile'}
24460 @code{dllfile} is the name of the DLL. This switch must be present for
24461 @code{gnatdll} to do anything. The name of the generated import library is
24462 obtained algorithmically from @code{dllfile} as shown in the following
24463 example: if @code{dllfile} is @code{xyz.dll}, the import library name is
24464 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
24465 by option @code{-e}) is obtained algorithmically from @code{dllfile}
24466 as shown in the following example:
24467 if @code{dllfile} is @code{xyz.dll}, the definition
24468 file used is @code{xyz.def}.
24470 @geindex -e (gnatdll)
24472 @item @code{-e `deffile'}
24474 @code{deffile} is the name of the definition file.
24476 @geindex -g (gnatdll)
24478 @item @code{-g}
24480 Generate debugging information. This information is stored in the object
24481 file and copied from there to the final DLL file by the linker,
24482 where it can be read by the debugger. You must use the
24483 @code{-g} switch if you plan on using the debugger or the symbolic
24484 stack traceback.
24486 @geindex -h (gnatdll)
24488 @item @code{-h}
24490 Help mode. Displays @code{gnatdll} switch usage information.
24492 @geindex -I (gnatdll)
24494 @item @code{-I`dir'}
24496 Direct @code{gnatdll} to search the @code{dir} directory for source and
24497 object files needed to build the DLL.
24498 (@ref{73,,Search Paths and the Run-Time Library (RTL)}).
24500 @geindex -k (gnatdll)
24502 @item @code{-k}
24504 Removes the @code{@@@var{nn}} suffix from the import library’s exported
24505 names, but keeps them for the link names. You must specify this
24506 option if you want to use a @code{Stdcall} function in a DLL for which
24507 the @code{@@@var{nn}} suffix has been removed. This is the case for most
24508 of the Windows NT DLL for example. This option has no effect when
24509 @code{-n} option is specified.
24511 @geindex -l (gnatdll)
24513 @item @code{-l `file'}
24515 The list of ALI and object files used to build the DLL are listed in
24516 @code{file}, instead of being given in the command line. Each line in
24517 @code{file} contains the name of an ALI or object file.
24519 @geindex -n (gnatdll)
24521 @item @code{-n}
24523 No Import. Do not create the import library.
24525 @geindex -q (gnatdll)
24527 @item @code{-q}
24529 Quiet mode. Do not display unnecessary messages.
24531 @geindex -v (gnatdll)
24533 @item @code{-v}
24535 Verbose mode. Display extra information.
24537 @geindex -largs (gnatdll)
24539 @item @code{-largs `opts'}
24541 Linker options. Pass @code{opts} to the linker.
24542 @end table
24544 @subsubheading @code{gnatdll} Example
24547 As an example the command to build a relocatable DLL from @code{api.adb}
24548 once @code{api.adb} has been compiled and @code{api.def} created is
24550 @quotation
24552 @example
24553 $ gnatdll -d api.dll api.ali
24554 @end example
24555 @end quotation
24557 The above command creates two files: @code{libapi.dll.a} (the import
24558 library) and @code{api.dll} (the actual DLL). If you want to create
24559 only the DLL, just type:
24561 @quotation
24563 @example
24564 $ gnatdll -d api.dll -n api.ali
24565 @end example
24566 @end quotation
24568 Alternatively if you want to create just the import library, type:
24570 @quotation
24572 @example
24573 $ gnatdll -d api.dll
24574 @end example
24575 @end quotation
24577 @subsubheading @code{gnatdll} behind the Scenes
24580 This section details the steps involved in creating a DLL. @code{gnatdll}
24581 does these steps for you. Unless you are interested in understanding what
24582 goes on behind the scenes, you should skip this section.
24584 We use the previous example of a DLL containing the Ada package @code{API},
24585 to illustrate the steps necessary to build a DLL. The starting point is a
24586 set of objects that will make up the DLL and the corresponding ALI
24587 files. In the case of this example this means that @code{api.o} and
24588 @code{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
24589 the following:
24592 @itemize *
24594 @item 
24595 @code{gnatdll} builds the base file (@code{api.base}). A base file gives
24596 the information necessary to generate relocation information for the
24597 DLL.
24599 @example
24600 $ gnatbind -n api
24601 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
24602 @end example
24604 In addition to the base file, the @code{gnatlink} command generates an
24605 output file @code{api.jnk} which can be discarded. The @code{-mdll} switch
24606 asks @code{gnatlink} to generate the routines @code{DllMain} and
24607 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
24608 is loaded into memory.
24610 @item 
24611 @code{gnatdll} uses @code{dlltool} (see @ref{1fc,,Using dlltool}) to build the
24612 export table (@code{api.exp}). The export table contains the relocation
24613 information in a form which can be used during the final link to ensure
24614 that the Windows loader is able to place the DLL anywhere in memory.
24616 @example
24617 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
24618           --output-exp api.exp
24619 @end example
24621 @item 
24622 @code{gnatdll} builds the base file using the new export table. Note that
24623 @code{gnatbind} must be called once again since the binder generated file
24624 has been deleted during the previous call to @code{gnatlink}.
24626 @example
24627 $ gnatbind -n api
24628 $ gnatlink api -o api.jnk api.exp -mdll
24629       -Wl,--base-file,api.base
24630 @end example
24632 @item 
24633 @code{gnatdll} builds the new export table using the new base file and
24634 generates the DLL import library @code{libAPI.dll.a}.
24636 @example
24637 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
24638           --output-exp api.exp --output-lib libAPI.a
24639 @end example
24641 @item 
24642 Finally @code{gnatdll} builds the relocatable DLL using the final export
24643 table.
24645 @example
24646 $ gnatbind -n api
24647 $ gnatlink api api.exp -o api.dll -mdll
24648 @end example
24649 @end itemize
24650 @anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{1fc}
24651 @subsubheading Using @code{dlltool}
24654 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
24655 DLLs and static import libraries. This section summarizes the most
24656 common @code{dlltool} switches. The form of the @code{dlltool} command
24659 @quotation
24661 @example
24662 $ dlltool [`switches`]
24663 @end example
24664 @end quotation
24666 @code{dlltool} switches include:
24668 @geindex --base-file (dlltool)
24671 @table @asis
24673 @item @code{--base-file `basefile'}
24675 Read the base file @code{basefile} generated by the linker. This switch
24676 is used to create a relocatable DLL.
24677 @end table
24679 @geindex --def (dlltool)
24682 @table @asis
24684 @item @code{--def `deffile'}
24686 Read the definition file.
24687 @end table
24689 @geindex --dllname (dlltool)
24692 @table @asis
24694 @item @code{--dllname `name'}
24696 Gives the name of the DLL. This switch is used to embed the name of the
24697 DLL in the static import library generated by @code{dlltool} with switch
24698 @code{--output-lib}.
24699 @end table
24701 @geindex -k (dlltool)
24704 @table @asis
24706 @item @code{-k}
24708 Kill @code{@@@var{nn}} from exported names
24709 (@ref{1d6,,Windows Calling Conventions}
24710 for a discussion about @code{Stdcall}-style symbols).
24711 @end table
24713 @geindex --help (dlltool)
24716 @table @asis
24718 @item @code{--help}
24720 Prints the @code{dlltool} switches with a concise description.
24721 @end table
24723 @geindex --output-exp (dlltool)
24726 @table @asis
24728 @item @code{--output-exp `exportfile'}
24730 Generate an export file @code{exportfile}. The export file contains the
24731 export table (list of symbols in the DLL) and is used to create the DLL.
24732 @end table
24734 @geindex --output-lib (dlltool)
24737 @table @asis
24739 @item @code{--output-lib `libfile'}
24741 Generate a static import library @code{libfile}.
24742 @end table
24744 @geindex -v (dlltool)
24747 @table @asis
24749 @item @code{-v}
24751 Verbose mode.
24752 @end table
24754 @geindex --as (dlltool)
24757 @table @asis
24759 @item @code{--as `assembler-name'}
24761 Use @code{assembler-name} as the assembler. The default is @code{as}.
24762 @end table
24764 @node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
24765 @anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{1fd}@anchor{gnat_ugn/platform_specific_information id33}@anchor{1fe}
24766 @subsubsection GNAT and Windows Resources
24769 @geindex Resources
24770 @geindex windows
24772 Resources are an easy way to add Windows specific objects to your
24773 application. The objects that can be added as resources include:
24776 @itemize *
24778 @item 
24779 menus
24781 @item 
24782 accelerators
24784 @item 
24785 dialog boxes
24787 @item 
24788 string tables
24790 @item 
24791 bitmaps
24793 @item 
24794 cursors
24796 @item 
24797 icons
24799 @item 
24800 fonts
24802 @item 
24803 version information
24804 @end itemize
24806 For example, a version information resource can be defined as follow and
24807 embedded into an executable or DLL:
24809 A version information resource can be used to embed information into an
24810 executable or a DLL. These information can be viewed using the file properties
24811 from the Windows Explorer. Here is an example of a version information
24812 resource:
24814 @quotation
24816 @example
24817 1 VERSIONINFO
24818 FILEVERSION     1,0,0,0
24819 PRODUCTVERSION  1,0,0,0
24820 BEGIN
24821   BLOCK "StringFileInfo"
24822   BEGIN
24823     BLOCK "080904E4"
24824     BEGIN
24825       VALUE "CompanyName", "My Company Name"
24826       VALUE "FileDescription", "My application"
24827       VALUE "FileVersion", "1.0"
24828       VALUE "InternalName", "my_app"
24829       VALUE "LegalCopyright", "My Name"
24830       VALUE "OriginalFilename", "my_app.exe"
24831       VALUE "ProductName", "My App"
24832       VALUE "ProductVersion", "1.0"
24833     END
24834   END
24836   BLOCK "VarFileInfo"
24837   BEGIN
24838     VALUE "Translation", 0x809, 1252
24839   END
24841 @end example
24842 @end quotation
24844 The value @code{0809} (langID) is for the U.K English language and
24845 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
24846 multilingual.
24848 This section explains how to build, compile and use resources. Note that this
24849 section does not cover all resource objects, for a complete description see
24850 the corresponding Microsoft documentation.
24852 @menu
24853 * Building Resources:: 
24854 * Compiling Resources:: 
24855 * Using Resources:: 
24857 @end menu
24859 @node Building Resources,Compiling Resources,,GNAT and Windows Resources
24860 @anchor{gnat_ugn/platform_specific_information building-resources}@anchor{1ff}@anchor{gnat_ugn/platform_specific_information id34}@anchor{200}
24861 @subsubsection Building Resources
24864 @geindex Resources
24865 @geindex building
24867 A resource file is an ASCII file. By convention resource files have an
24868 @code{.rc} extension.
24869 The easiest way to build a resource file is to use Microsoft tools
24870 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
24871 @code{dlgedit.exe} to build dialogs.
24872 It is always possible to build an @code{.rc} file yourself by writing a
24873 resource script.
24875 It is not our objective to explain how to write a resource file. A
24876 complete description of the resource script language can be found in the
24877 Microsoft documentation.
24879 @node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
24880 @anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{201}@anchor{gnat_ugn/platform_specific_information id35}@anchor{202}
24881 @subsubsection Compiling Resources
24884 @geindex rc
24886 @geindex windres
24888 @geindex Resources
24889 @geindex compiling
24891 This section describes how to build a GNAT-compatible (COFF) object file
24892 containing the resources. This is done using the Resource Compiler
24893 @code{windres} as follows:
24895 @quotation
24897 @example
24898 $ windres -i myres.rc -o myres.o
24899 @end example
24900 @end quotation
24902 By default @code{windres} will run @code{gcc} to preprocess the @code{.rc}
24903 file. You can specify an alternate preprocessor (usually named
24904 @code{cpp.exe}) using the @code{windres} @code{--preprocessor}
24905 parameter. A list of all possible options may be obtained by entering
24906 the command @code{windres} @code{--help}.
24908 It is also possible to use the Microsoft resource compiler @code{rc.exe}
24909 to produce a @code{.res} file (binary resource file). See the
24910 corresponding Microsoft documentation for further details. In this case
24911 you need to use @code{windres} to translate the @code{.res} file to a
24912 GNAT-compatible object file as follows:
24914 @quotation
24916 @example
24917 $ windres -i myres.res -o myres.o
24918 @end example
24919 @end quotation
24921 @node Using Resources,,Compiling Resources,GNAT and Windows Resources
24922 @anchor{gnat_ugn/platform_specific_information id36}@anchor{203}@anchor{gnat_ugn/platform_specific_information using-resources}@anchor{204}
24923 @subsubsection Using Resources
24926 @geindex Resources
24927 @geindex using
24929 To include the resource file in your program just add the
24930 GNAT-compatible object file for the resource(s) to the linker
24931 arguments. With @code{gnatmake} this is done by using the @code{-largs}
24932 option:
24934 @quotation
24936 @example
24937 $ gnatmake myprog -largs myres.o
24938 @end example
24939 @end quotation
24941 @node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
24942 @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}
24943 @subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
24946 @geindex Microsoft Visual Studio
24947 @geindex use with GNAT DLLs
24949 This section describes a common case of mixed GNAT/Microsoft Visual Studio
24950 application development, where the main program is developed using MSVS, and
24951 is linked with a DLL developed using GNAT. Such a mixed application should
24952 be developed following the general guidelines outlined above; below is the
24953 cookbook-style sequence of steps to follow:
24956 @enumerate 
24958 @item 
24959 First develop and build the GNAT shared library using a library project
24960 (let’s assume the project is @code{mylib.gpr}, producing the library @code{libmylib.dll}):
24961 @end enumerate
24963 @quotation
24965 @example
24966 $ gprbuild -p mylib.gpr
24967 @end example
24968 @end quotation
24971 @enumerate 2
24973 @item 
24974 Produce a .def file for the symbols you need to interface with, either by
24975 hand or automatically with possibly some manual adjustments
24976 (see @ref{1e7,,Creating Definition File Automatically}):
24977 @end enumerate
24979 @quotation
24981 @example
24982 $ dlltool libmylib.dll -z libmylib.def --export-all-symbols
24983 @end example
24984 @end quotation
24987 @enumerate 3
24989 @item 
24990 Make sure that MSVS command-line tools are accessible on the path.
24992 @item 
24993 Create the Microsoft-style import library (see @ref{1ea,,MSVS-Style Import Library}):
24994 @end enumerate
24996 @quotation
24998 @example
24999 $ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
25000 @end example
25001 @end quotation
25003 If you are using a 64-bit toolchain, the above becomes…
25005 @quotation
25007 @example
25008 $ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
25009 @end example
25010 @end quotation
25013 @enumerate 5
25015 @item 
25016 Build the C main
25017 @end enumerate
25019 @quotation
25021 @example
25022 $ cl /O2 /MD main.c libmylib.lib
25023 @end example
25024 @end quotation
25027 @enumerate 6
25029 @item 
25030 Before running the executable, make sure you have set the PATH to the DLL,
25031 or copy the DLL into into the directory containing the .exe.
25032 @end enumerate
25034 @node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
25035 @anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{207}@anchor{gnat_ugn/platform_specific_information id37}@anchor{208}
25036 @subsubsection Debugging a DLL
25039 @geindex DLL debugging
25041 Debugging a DLL is similar to debugging a standard program. But
25042 we have to deal with two different executable parts: the DLL and the
25043 program that uses it. We have the following four possibilities:
25046 @itemize *
25048 @item 
25049 The program and the DLL are built with GCC/GNAT.
25051 @item 
25052 The program is built with foreign tools and the DLL is built with
25053 GCC/GNAT.
25055 @item 
25056 The program is built with GCC/GNAT and the DLL is built with
25057 foreign tools.
25058 @end itemize
25060 In this section we address only cases one and two above.
25061 There is no point in trying to debug
25062 a DLL with GNU/GDB, if there is no GDB-compatible debugging
25063 information in it. To do so you must use a debugger compatible with the
25064 tools suite used to build the DLL.
25066 @menu
25067 * Program and DLL Both Built with GCC/GNAT:: 
25068 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
25070 @end menu
25072 @node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
25073 @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}
25074 @subsubsection Program and DLL Both Built with GCC/GNAT
25077 This is the simplest case. Both the DLL and the program have @code{GDB}
25078 compatible debugging information. It is then possible to break anywhere in
25079 the process. Let’s suppose here that the main procedure is named
25080 @code{ada_main} and that in the DLL there is an entry point named
25081 @code{ada_dll}.
25083 The DLL (@ref{1e0,,Introduction to Dynamic Link Libraries (DLLs)}) and
25084 program must have been built with the debugging information (see GNAT -g
25085 switch). Here are the step-by-step instructions for debugging it:
25088 @itemize *
25090 @item 
25091 Launch @code{GDB} on the main program.
25093 @example
25094 $ gdb -nw ada_main
25095 @end example
25097 @item 
25098 Start the program and stop at the beginning of the main procedure
25100 @example
25101 (gdb) start
25102 @end example
25104 This step is required to be able to set a breakpoint inside the DLL. As long
25105 as the program is not run, the DLL is not loaded. This has the
25106 consequence that the DLL debugging information is also not loaded, so it is not
25107 possible to set a breakpoint in the DLL.
25109 @item 
25110 Set a breakpoint inside the DLL
25112 @example
25113 (gdb) break ada_dll
25114 (gdb) cont
25115 @end example
25116 @end itemize
25118 At this stage a breakpoint is set inside the DLL. From there on
25119 you can use the standard approach to debug the whole program
25120 (@ref{14f,,Running and Debugging Ada Programs}).
25122 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
25123 @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}
25124 @subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
25127 In this case things are slightly more complex because it is not possible to
25128 start the main program and then break at the beginning to load the DLL and the
25129 associated DLL debugging information. It is not possible to break at the
25130 beginning of the program because there is no @code{GDB} debugging information,
25131 and therefore there is no direct way of getting initial control. This
25132 section addresses this issue by describing some methods that can be used
25133 to break somewhere in the DLL to debug it.
25135 First suppose that the main procedure is named @code{main} (this is for
25136 example some C code built with Microsoft Visual C) and that there is a
25137 DLL named @code{test.dll} containing an Ada entry point named
25138 @code{ada_dll}.
25140 The DLL (see @ref{1e0,,Introduction to Dynamic Link Libraries (DLLs)}) must have
25141 been built with debugging information (see the GNAT @code{-g} option).
25143 @subsubheading Debugging the DLL Directly
25147 @itemize *
25149 @item 
25150 Find out the executable starting address
25152 @example
25153 $ objdump --file-header main.exe
25154 @end example
25156 The starting address is reported on the last line. For example:
25158 @example
25159 main.exe:     file format pei-i386
25160 architecture: i386, flags 0x0000010a:
25161 EXEC_P, HAS_DEBUG, D_PAGED
25162 start address 0x00401010
25163 @end example
25165 @item 
25166 Launch the debugger on the executable.
25168 @example
25169 $ gdb main.exe
25170 @end example
25172 @item 
25173 Set a breakpoint at the starting address, and launch the program.
25175 @example
25176 $ (gdb) break *0x00401010
25177 $ (gdb) run
25178 @end example
25180 The program will stop at the given address.
25182 @item 
25183 Set a breakpoint on a DLL subroutine.
25185 @example
25186 (gdb) break ada_dll.adb:45
25187 @end example
25189 Or if you want to break using a symbol on the DLL, you need first to
25190 select the Ada language (language used by the DLL).
25192 @example
25193 (gdb) set language ada
25194 (gdb) break ada_dll
25195 @end example
25197 @item 
25198 Continue the program.
25200 @example
25201 (gdb) cont
25202 @end example
25204 This will run the program until it reaches the breakpoint that has been
25205 set. From that point you can use the standard way to debug a program
25206 as described in (@ref{14f,,Running and Debugging Ada Programs}).
25207 @end itemize
25209 It is also possible to debug the DLL by attaching to a running process.
25211 @subsubheading Attaching to a Running Process
25214 @geindex DLL debugging
25215 @geindex attach to process
25217 With @code{GDB} it is always possible to debug a running process by
25218 attaching to it. It is possible to debug a DLL this way. The limitation
25219 of this approach is that the DLL must run long enough to perform the
25220 attach operation. It may be useful for instance to insert a time wasting
25221 loop in the code of the DLL to meet this criterion.
25224 @itemize *
25226 @item 
25227 Launch the main program @code{main.exe}.
25229 @example
25230 $ main
25231 @end example
25233 @item 
25234 Use the Windows `Task Manager' to find the process ID. Let’s say
25235 that the process PID for @code{main.exe} is 208.
25237 @item 
25238 Launch gdb.
25240 @example
25241 $ gdb
25242 @end example
25244 @item 
25245 Attach to the running process to be debugged.
25247 @example
25248 (gdb) attach 208
25249 @end example
25251 @item 
25252 Load the process debugging information.
25254 @example
25255 (gdb) symbol-file main.exe
25256 @end example
25258 @item 
25259 Break somewhere in the DLL.
25261 @example
25262 (gdb) break ada_dll
25263 @end example
25265 @item 
25266 Continue process execution.
25268 @example
25269 (gdb) cont
25270 @end example
25271 @end itemize
25273 This last step will resume the process execution, and stop at
25274 the breakpoint we have set. From there you can use the standard
25275 approach to debug a program as described in
25276 @ref{14f,,Running and Debugging Ada Programs}.
25278 @node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
25279 @anchor{gnat_ugn/platform_specific_information id40}@anchor{20d}@anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{129}
25280 @subsubsection Setting Stack Size from @code{gnatlink}
25283 It is possible to specify the program stack size at link time. On modern
25284 versions of Windows, starting with XP, this is mostly useful to set the size of
25285 the main stack (environment task). The other task stacks are set with pragma
25286 Storage_Size or with the `gnatbind -d' command.
25288 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
25289 reserve size of individual tasks, the link-time stack size applies to all
25290 tasks, and pragma Storage_Size has no effect.
25291 In particular, Stack Overflow checks are made against this
25292 link-time specified size.
25294 This setting can be done with @code{gnatlink} using either of the following:
25297 @itemize *
25299 @item 
25300 @code{-Xlinker} linker option
25302 @example
25303 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
25304 @end example
25306 This sets the stack reserve size to 0x10000 bytes and the stack commit
25307 size to 0x1000 bytes.
25309 @item 
25310 @code{-Wl} linker option
25312 @example
25313 $ gnatlink hello -Wl,--stack=0x1000000
25314 @end example
25316 This sets the stack reserve size to 0x1000000 bytes. Note that with
25317 @code{-Wl} option it is not possible to set the stack commit size
25318 because the comma is a separator for this option.
25319 @end itemize
25321 @node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
25322 @anchor{gnat_ugn/platform_specific_information id41}@anchor{20e}@anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{12a}
25323 @subsubsection Setting Heap Size from @code{gnatlink}
25326 Under Windows systems, it is possible to specify the program heap size from
25327 @code{gnatlink} using either of the following:
25330 @itemize *
25332 @item 
25333 @code{-Xlinker} linker option
25335 @example
25336 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
25337 @end example
25339 This sets the heap reserve size to 0x10000 bytes and the heap commit
25340 size to 0x1000 bytes.
25342 @item 
25343 @code{-Wl} linker option
25345 @example
25346 $ gnatlink hello -Wl,--heap=0x1000000
25347 @end example
25349 This sets the heap reserve size to 0x1000000 bytes. Note that with
25350 @code{-Wl} option it is not possible to set the heap commit size
25351 because the comma is a separator for this option.
25352 @end itemize
25354 @node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
25355 @anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{20f}@anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{210}
25356 @subsection Windows Specific Add-Ons
25359 This section describes the Windows specific add-ons.
25361 @menu
25362 * Win32Ada:: 
25363 * wPOSIX:: 
25365 @end menu
25367 @node Win32Ada,wPOSIX,,Windows Specific Add-Ons
25368 @anchor{gnat_ugn/platform_specific_information id42}@anchor{211}@anchor{gnat_ugn/platform_specific_information win32ada}@anchor{212}
25369 @subsubsection Win32Ada
25372 Win32Ada is a binding for the Microsoft Win32 API. This binding can be
25373 easily installed from the provided installer. To use the Win32Ada
25374 binding you need to use a project file, and adding a single with_clause
25375 will give you full access to the Win32Ada binding sources and ensure
25376 that the proper libraries are passed to the linker.
25378 @quotation
25380 @example
25381 with "win32ada";
25382 project P is
25383    for Sources use ...;
25384 end P;
25385 @end example
25386 @end quotation
25388 To build the application you just need to call gprbuild for the
25389 application’s project, here p.gpr:
25391 @quotation
25393 @example
25394 gprbuild p.gpr
25395 @end example
25396 @end quotation
25398 @node wPOSIX,,Win32Ada,Windows Specific Add-Ons
25399 @anchor{gnat_ugn/platform_specific_information id43}@anchor{213}@anchor{gnat_ugn/platform_specific_information wposix}@anchor{214}
25400 @subsubsection wPOSIX
25403 wPOSIX is a minimal POSIX binding whose goal is to help with building
25404 cross-platforms applications. This binding is not complete though, as
25405 the Win32 API does not provide the necessary support for all POSIX APIs.
25407 To use the wPOSIX binding you need to use a project file, and adding
25408 a single with_clause will give you full access to the wPOSIX binding
25409 sources and ensure that the proper libraries are passed to the linker.
25411 @quotation
25413 @example
25414 with "wposix";
25415 project P is
25416    for Sources use ...;
25417 end P;
25418 @end example
25419 @end quotation
25421 To build the application you just need to call gprbuild for the
25422 application’s project, here p.gpr:
25424 @quotation
25426 @example
25427 gprbuild p.gpr
25428 @end example
25429 @end quotation
25431 @node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
25432 @anchor{gnat_ugn/platform_specific_information id44}@anchor{215}@anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{216}
25433 @section Mac OS Topics
25436 @geindex OS X
25438 This section describes topics that are specific to Apple’s OS X
25439 platform.
25441 @menu
25442 * Codesigning the Debugger:: 
25444 @end menu
25446 @node Codesigning the Debugger,,,Mac OS Topics
25447 @anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{217}
25448 @subsection Codesigning the Debugger
25451 The Darwin Kernel requires the debugger to have special permissions
25452 before it is allowed to control other processes. These permissions
25453 are granted by codesigning the GDB executable. Without these
25454 permissions, the debugger will report error messages such as:
25456 @example
25457 Starting program: /x/y/foo
25458 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
25459 (please check gdb is codesigned - see taskgated(8))
25460 @end example
25462 Codesigning requires a certificate.  The following procedure explains
25463 how to create one:
25466 @itemize *
25468 @item 
25469 Start the Keychain Access application (in
25470 /Applications/Utilities/Keychain Access.app)
25472 @item 
25473 Select the Keychain Access -> Certificate Assistant ->
25474 Create a Certificate… menu
25476 @item 
25477 Then:
25480 @itemize *
25482 @item 
25483 Choose a name for the new certificate (this procedure will use
25484 “gdb-cert” as an example)
25486 @item 
25487 Set “Identity Type” to “Self Signed Root”
25489 @item 
25490 Set “Certificate Type” to “Code Signing”
25492 @item 
25493 Activate the “Let me override defaults” option
25494 @end itemize
25496 @item 
25497 Click several times on “Continue” until the “Specify a Location
25498 For The Certificate” screen appears, then set “Keychain” to “System”
25500 @item 
25501 Click on “Continue” until the certificate is created
25503 @item 
25504 Finally, in the view, double-click on the new certificate,
25505 and set “When using this certificate” to “Always Trust”
25507 @item 
25508 Exit the Keychain Access application and restart the computer
25509 (this is unfortunately required)
25510 @end itemize
25512 Once a certificate has been created, the debugger can be codesigned
25513 as follow. In a Terminal, run the following command:
25515 @quotation
25517 @example
25518 $ codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
25519 @end example
25520 @end quotation
25522 where “gdb-cert” should be replaced by the actual certificate
25523 name chosen above, and <gnat_install_prefix> should be replaced by
25524 the location where you installed GNAT.  Also, be sure that users are
25525 in the Unix group @code{_developer}.
25527 @node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
25528 @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}
25529 @chapter Example of Binder Output File
25532 @geindex Binder output (example)
25534 This Appendix displays the source code for the output file
25535 generated by `gnatbind' for a simple ‘Hello World’ program.
25536 Comments have been added for clarification purposes.
25538 @example
25539 --  The package is called Ada_Main unless this name is actually used
25540 --  as a unit name in the partition, in which case some other unique
25541 --  name is used.
25543 pragma Ada_95;
25544 with System;
25545 package ada_main is
25546    pragma Warnings (Off);
25548    --  The main program saves the parameters (argument count,
25549    --  argument values, environment pointer) in global variables
25550    --  for later access by other units including
25551    --  Ada.Command_Line.
25553    gnat_argc : Integer;
25554    gnat_argv : System.Address;
25555    gnat_envp : System.Address;
25557    --  The actual variables are stored in a library routine. This
25558    --  is useful for some shared library situations, where there
25559    --  are problems if variables are not in the library.
25561    pragma Import (C, gnat_argc);
25562    pragma Import (C, gnat_argv);
25563    pragma Import (C, gnat_envp);
25565    --  The exit status is similarly an external location
25567    gnat_exit_status : Integer;
25568    pragma Import (C, gnat_exit_status);
25570    GNAT_Version : constant String :=
25571                     "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
25572    pragma Export (C, GNAT_Version, "__gnat_version");
25574    Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
25575    pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
25577    --  This is the generated adainit routine that performs
25578    --  initialization at the start of execution. In the case
25579    --  where Ada is the main program, this main program makes
25580    --  a call to adainit at program startup.
25582    procedure adainit;
25583    pragma Export (C, adainit, "adainit");
25585    --  This is the generated adafinal routine that performs
25586    --  finalization at the end of execution. In the case where
25587    --  Ada is the main program, this main program makes a call
25588    --  to adafinal at program termination.
25590    procedure adafinal;
25591    pragma Export (C, adafinal, "adafinal");
25593    --  This routine is called at the start of execution. It is
25594    --  a dummy routine that is used by the debugger to breakpoint
25595    --  at the start of execution.
25597    --  This is the actual generated main program (it would be
25598    --  suppressed if the no main program switch were used). As
25599    --  required by standard system conventions, this program has
25600    --  the external name main.
25602    function main
25603      (argc : Integer;
25604       argv : System.Address;
25605       envp : System.Address)
25606       return Integer;
25607    pragma Export (C, main, "main");
25609    --  The following set of constants give the version
25610    --  identification values for every unit in the bound
25611    --  partition. This identification is computed from all
25612    --  dependent semantic units, and corresponds to the
25613    --  string that would be returned by use of the
25614    --  Body_Version or Version attributes.
25616    --  The following Export pragmas export the version numbers
25617    --  with symbolic names ending in B (for body) or S
25618    --  (for spec) so that they can be located in a link. The
25619    --  information provided here is sufficient to track down
25620    --  the exact versions of units used in a given build.
25622    type Version_32 is mod 2 ** 32;
25623    u00001 : constant Version_32 := 16#8ad6e54a#;
25624    pragma Export (C, u00001, "helloB");
25625    u00002 : constant Version_32 := 16#fbff4c67#;
25626    pragma Export (C, u00002, "system__standard_libraryB");
25627    u00003 : constant Version_32 := 16#1ec6fd90#;
25628    pragma Export (C, u00003, "system__standard_libraryS");
25629    u00004 : constant Version_32 := 16#3ffc8e18#;
25630    pragma Export (C, u00004, "adaS");
25631    u00005 : constant Version_32 := 16#28f088c2#;
25632    pragma Export (C, u00005, "ada__text_ioB");
25633    u00006 : constant Version_32 := 16#f372c8ac#;
25634    pragma Export (C, u00006, "ada__text_ioS");
25635    u00007 : constant Version_32 := 16#2c143749#;
25636    pragma Export (C, u00007, "ada__exceptionsB");
25637    u00008 : constant Version_32 := 16#f4f0cce8#;
25638    pragma Export (C, u00008, "ada__exceptionsS");
25639    u00009 : constant Version_32 := 16#a46739c0#;
25640    pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
25641    u00010 : constant Version_32 := 16#3aac8c92#;
25642    pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
25643    u00011 : constant Version_32 := 16#1d274481#;
25644    pragma Export (C, u00011, "systemS");
25645    u00012 : constant Version_32 := 16#a207fefe#;
25646    pragma Export (C, u00012, "system__soft_linksB");
25647    u00013 : constant Version_32 := 16#467d9556#;
25648    pragma Export (C, u00013, "system__soft_linksS");
25649    u00014 : constant Version_32 := 16#b01dad17#;
25650    pragma Export (C, u00014, "system__parametersB");
25651    u00015 : constant Version_32 := 16#630d49fe#;
25652    pragma Export (C, u00015, "system__parametersS");
25653    u00016 : constant Version_32 := 16#b19b6653#;
25654    pragma Export (C, u00016, "system__secondary_stackB");
25655    u00017 : constant Version_32 := 16#b6468be8#;
25656    pragma Export (C, u00017, "system__secondary_stackS");
25657    u00018 : constant Version_32 := 16#39a03df9#;
25658    pragma Export (C, u00018, "system__storage_elementsB");
25659    u00019 : constant Version_32 := 16#30e40e85#;
25660    pragma Export (C, u00019, "system__storage_elementsS");
25661    u00020 : constant Version_32 := 16#41837d1e#;
25662    pragma Export (C, u00020, "system__stack_checkingB");
25663    u00021 : constant Version_32 := 16#93982f69#;
25664    pragma Export (C, u00021, "system__stack_checkingS");
25665    u00022 : constant Version_32 := 16#393398c1#;
25666    pragma Export (C, u00022, "system__exception_tableB");
25667    u00023 : constant Version_32 := 16#b33e2294#;
25668    pragma Export (C, u00023, "system__exception_tableS");
25669    u00024 : constant Version_32 := 16#ce4af020#;
25670    pragma Export (C, u00024, "system__exceptionsB");
25671    u00025 : constant Version_32 := 16#75442977#;
25672    pragma Export (C, u00025, "system__exceptionsS");
25673    u00026 : constant Version_32 := 16#37d758f1#;
25674    pragma Export (C, u00026, "system__exceptions__machineS");
25675    u00027 : constant Version_32 := 16#b895431d#;
25676    pragma Export (C, u00027, "system__exceptions_debugB");
25677    u00028 : constant Version_32 := 16#aec55d3f#;
25678    pragma Export (C, u00028, "system__exceptions_debugS");
25679    u00029 : constant Version_32 := 16#570325c8#;
25680    pragma Export (C, u00029, "system__img_intB");
25681    u00030 : constant Version_32 := 16#1ffca443#;
25682    pragma Export (C, u00030, "system__img_intS");
25683    u00031 : constant Version_32 := 16#b98c3e16#;
25684    pragma Export (C, u00031, "system__tracebackB");
25685    u00032 : constant Version_32 := 16#831a9d5a#;
25686    pragma Export (C, u00032, "system__tracebackS");
25687    u00033 : constant Version_32 := 16#9ed49525#;
25688    pragma Export (C, u00033, "system__traceback_entriesB");
25689    u00034 : constant Version_32 := 16#1d7cb2f1#;
25690    pragma Export (C, u00034, "system__traceback_entriesS");
25691    u00035 : constant Version_32 := 16#8c33a517#;
25692    pragma Export (C, u00035, "system__wch_conB");
25693    u00036 : constant Version_32 := 16#065a6653#;
25694    pragma Export (C, u00036, "system__wch_conS");
25695    u00037 : constant Version_32 := 16#9721e840#;
25696    pragma Export (C, u00037, "system__wch_stwB");
25697    u00038 : constant Version_32 := 16#2b4b4a52#;
25698    pragma Export (C, u00038, "system__wch_stwS");
25699    u00039 : constant Version_32 := 16#92b797cb#;
25700    pragma Export (C, u00039, "system__wch_cnvB");
25701    u00040 : constant Version_32 := 16#09eddca0#;
25702    pragma Export (C, u00040, "system__wch_cnvS");
25703    u00041 : constant Version_32 := 16#6033a23f#;
25704    pragma Export (C, u00041, "interfacesS");
25705    u00042 : constant Version_32 := 16#ece6fdb6#;
25706    pragma Export (C, u00042, "system__wch_jisB");
25707    u00043 : constant Version_32 := 16#899dc581#;
25708    pragma Export (C, u00043, "system__wch_jisS");
25709    u00044 : constant Version_32 := 16#10558b11#;
25710    pragma Export (C, u00044, "ada__streamsB");
25711    u00045 : constant Version_32 := 16#2e6701ab#;
25712    pragma Export (C, u00045, "ada__streamsS");
25713    u00046 : constant Version_32 := 16#db5c917c#;
25714    pragma Export (C, u00046, "ada__io_exceptionsS");
25715    u00047 : constant Version_32 := 16#12c8cd7d#;
25716    pragma Export (C, u00047, "ada__tagsB");
25717    u00048 : constant Version_32 := 16#ce72c228#;
25718    pragma Export (C, u00048, "ada__tagsS");
25719    u00049 : constant Version_32 := 16#c3335bfd#;
25720    pragma Export (C, u00049, "system__htableB");
25721    u00050 : constant Version_32 := 16#99e5f76b#;
25722    pragma Export (C, u00050, "system__htableS");
25723    u00051 : constant Version_32 := 16#089f5cd0#;
25724    pragma Export (C, u00051, "system__string_hashB");
25725    u00052 : constant Version_32 := 16#3bbb9c15#;
25726    pragma Export (C, u00052, "system__string_hashS");
25727    u00053 : constant Version_32 := 16#807fe041#;
25728    pragma Export (C, u00053, "system__unsigned_typesS");
25729    u00054 : constant Version_32 := 16#d27be59e#;
25730    pragma Export (C, u00054, "system__val_lluB");
25731    u00055 : constant Version_32 := 16#fa8db733#;
25732    pragma Export (C, u00055, "system__val_lluS");
25733    u00056 : constant Version_32 := 16#27b600b2#;
25734    pragma Export (C, u00056, "system__val_utilB");
25735    u00057 : constant Version_32 := 16#b187f27f#;
25736    pragma Export (C, u00057, "system__val_utilS");
25737    u00058 : constant Version_32 := 16#d1060688#;
25738    pragma Export (C, u00058, "system__case_utilB");
25739    u00059 : constant Version_32 := 16#392e2d56#;
25740    pragma Export (C, u00059, "system__case_utilS");
25741    u00060 : constant Version_32 := 16#84a27f0d#;
25742    pragma Export (C, u00060, "interfaces__c_streamsB");
25743    u00061 : constant Version_32 := 16#8bb5f2c0#;
25744    pragma Export (C, u00061, "interfaces__c_streamsS");
25745    u00062 : constant Version_32 := 16#6db6928f#;
25746    pragma Export (C, u00062, "system__crtlS");
25747    u00063 : constant Version_32 := 16#4e6a342b#;
25748    pragma Export (C, u00063, "system__file_ioB");
25749    u00064 : constant Version_32 := 16#ba56a5e4#;
25750    pragma Export (C, u00064, "system__file_ioS");
25751    u00065 : constant Version_32 := 16#b7ab275c#;
25752    pragma Export (C, u00065, "ada__finalizationB");
25753    u00066 : constant Version_32 := 16#19f764ca#;
25754    pragma Export (C, u00066, "ada__finalizationS");
25755    u00067 : constant Version_32 := 16#95817ed8#;
25756    pragma Export (C, u00067, "system__finalization_rootB");
25757    u00068 : constant Version_32 := 16#52d53711#;
25758    pragma Export (C, u00068, "system__finalization_rootS");
25759    u00069 : constant Version_32 := 16#769e25e6#;
25760    pragma Export (C, u00069, "interfaces__cB");
25761    u00070 : constant Version_32 := 16#4a38bedb#;
25762    pragma Export (C, u00070, "interfaces__cS");
25763    u00071 : constant Version_32 := 16#07e6ee66#;
25764    pragma Export (C, u00071, "system__os_libB");
25765    u00072 : constant Version_32 := 16#d7b69782#;
25766    pragma Export (C, u00072, "system__os_libS");
25767    u00073 : constant Version_32 := 16#1a817b8e#;
25768    pragma Export (C, u00073, "system__stringsB");
25769    u00074 : constant Version_32 := 16#639855e7#;
25770    pragma Export (C, u00074, "system__stringsS");
25771    u00075 : constant Version_32 := 16#e0b8de29#;
25772    pragma Export (C, u00075, "system__file_control_blockS");
25773    u00076 : constant Version_32 := 16#b5b2aca1#;
25774    pragma Export (C, u00076, "system__finalization_mastersB");
25775    u00077 : constant Version_32 := 16#69316dc1#;
25776    pragma Export (C, u00077, "system__finalization_mastersS");
25777    u00078 : constant Version_32 := 16#57a37a42#;
25778    pragma Export (C, u00078, "system__address_imageB");
25779    u00079 : constant Version_32 := 16#bccbd9bb#;
25780    pragma Export (C, u00079, "system__address_imageS");
25781    u00080 : constant Version_32 := 16#7268f812#;
25782    pragma Export (C, u00080, "system__img_boolB");
25783    u00081 : constant Version_32 := 16#e8fe356a#;
25784    pragma Export (C, u00081, "system__img_boolS");
25785    u00082 : constant Version_32 := 16#d7aac20c#;
25786    pragma Export (C, u00082, "system__ioB");
25787    u00083 : constant Version_32 := 16#8365b3ce#;
25788    pragma Export (C, u00083, "system__ioS");
25789    u00084 : constant Version_32 := 16#6d4d969a#;
25790    pragma Export (C, u00084, "system__storage_poolsB");
25791    u00085 : constant Version_32 := 16#e87cc305#;
25792    pragma Export (C, u00085, "system__storage_poolsS");
25793    u00086 : constant Version_32 := 16#e34550ca#;
25794    pragma Export (C, u00086, "system__pool_globalB");
25795    u00087 : constant Version_32 := 16#c88d2d16#;
25796    pragma Export (C, u00087, "system__pool_globalS");
25797    u00088 : constant Version_32 := 16#9d39c675#;
25798    pragma Export (C, u00088, "system__memoryB");
25799    u00089 : constant Version_32 := 16#445a22b5#;
25800    pragma Export (C, u00089, "system__memoryS");
25801    u00090 : constant Version_32 := 16#6a859064#;
25802    pragma Export (C, u00090, "system__storage_pools__subpoolsB");
25803    u00091 : constant Version_32 := 16#e3b008dc#;
25804    pragma Export (C, u00091, "system__storage_pools__subpoolsS");
25805    u00092 : constant Version_32 := 16#63f11652#;
25806    pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
25807    u00093 : constant Version_32 := 16#fe2f4b3a#;
25808    pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
25810    --  BEGIN ELABORATION ORDER
25811    --  ada%s
25812    --  interfaces%s
25813    --  system%s
25814    --  system.case_util%s
25815    --  system.case_util%b
25816    --  system.htable%s
25817    --  system.img_bool%s
25818    --  system.img_bool%b
25819    --  system.img_int%s
25820    --  system.img_int%b
25821    --  system.io%s
25822    --  system.io%b
25823    --  system.parameters%s
25824    --  system.parameters%b
25825    --  system.crtl%s
25826    --  interfaces.c_streams%s
25827    --  interfaces.c_streams%b
25828    --  system.standard_library%s
25829    --  system.exceptions_debug%s
25830    --  system.exceptions_debug%b
25831    --  system.storage_elements%s
25832    --  system.storage_elements%b
25833    --  system.stack_checking%s
25834    --  system.stack_checking%b
25835    --  system.string_hash%s
25836    --  system.string_hash%b
25837    --  system.htable%b
25838    --  system.strings%s
25839    --  system.strings%b
25840    --  system.os_lib%s
25841    --  system.traceback_entries%s
25842    --  system.traceback_entries%b
25843    --  ada.exceptions%s
25844    --  system.soft_links%s
25845    --  system.unsigned_types%s
25846    --  system.val_llu%s
25847    --  system.val_util%s
25848    --  system.val_util%b
25849    --  system.val_llu%b
25850    --  system.wch_con%s
25851    --  system.wch_con%b
25852    --  system.wch_cnv%s
25853    --  system.wch_jis%s
25854    --  system.wch_jis%b
25855    --  system.wch_cnv%b
25856    --  system.wch_stw%s
25857    --  system.wch_stw%b
25858    --  ada.exceptions.last_chance_handler%s
25859    --  ada.exceptions.last_chance_handler%b
25860    --  system.address_image%s
25861    --  system.exception_table%s
25862    --  system.exception_table%b
25863    --  ada.io_exceptions%s
25864    --  ada.tags%s
25865    --  ada.streams%s
25866    --  ada.streams%b
25867    --  interfaces.c%s
25868    --  system.exceptions%s
25869    --  system.exceptions%b
25870    --  system.exceptions.machine%s
25871    --  system.finalization_root%s
25872    --  system.finalization_root%b
25873    --  ada.finalization%s
25874    --  ada.finalization%b
25875    --  system.storage_pools%s
25876    --  system.storage_pools%b
25877    --  system.finalization_masters%s
25878    --  system.storage_pools.subpools%s
25879    --  system.storage_pools.subpools.finalization%s
25880    --  system.storage_pools.subpools.finalization%b
25881    --  system.memory%s
25882    --  system.memory%b
25883    --  system.standard_library%b
25884    --  system.pool_global%s
25885    --  system.pool_global%b
25886    --  system.file_control_block%s
25887    --  system.file_io%s
25888    --  system.secondary_stack%s
25889    --  system.file_io%b
25890    --  system.storage_pools.subpools%b
25891    --  system.finalization_masters%b
25892    --  interfaces.c%b
25893    --  ada.tags%b
25894    --  system.soft_links%b
25895    --  system.os_lib%b
25896    --  system.secondary_stack%b
25897    --  system.address_image%b
25898    --  system.traceback%s
25899    --  ada.exceptions%b
25900    --  system.traceback%b
25901    --  ada.text_io%s
25902    --  ada.text_io%b
25903    --  hello%b
25904    --  END ELABORATION ORDER
25906 end ada_main;
25907 @end example
25909 @example
25910 pragma Ada_95;
25911 --  The following source file name pragmas allow the generated file
25912 --  names to be unique for different main programs. They are needed
25913 --  since the package name will always be Ada_Main.
25915 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
25916 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
25918 pragma Suppress (Overflow_Check);
25919 with Ada.Exceptions;
25921 --  Generated package body for Ada_Main starts here
25923 package body ada_main is
25924    pragma Warnings (Off);
25926    --  These values are reference counter associated to units which have
25927    --  been elaborated. It is also used to avoid elaborating the
25928    --  same unit twice.
25930    E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
25931    E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
25932    E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
25933    E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
25934    E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
25935    E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
25936    E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
25937    E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
25938    E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
25939    E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
25940    E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
25941    E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
25942    E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
25943    E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
25944    E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
25945    E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
25946    E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
25947    E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
25949    Local_Priority_Specific_Dispatching : constant String := "";
25950    Local_Interrupt_States : constant String := "";
25952    Is_Elaborated : Boolean := False;
25954    procedure finalize_library is
25955    begin
25956       E06 := E06 - 1;
25957       declare
25958          procedure F1;
25959          pragma Import (Ada, F1, "ada__text_io__finalize_spec");
25960       begin
25961          F1;
25962       end;
25963       E77 := E77 - 1;
25964       E91 := E91 - 1;
25965       declare
25966          procedure F2;
25967          pragma Import (Ada, F2, "system__file_io__finalize_body");
25968       begin
25969          E64 := E64 - 1;
25970          F2;
25971       end;
25972       declare
25973          procedure F3;
25974          pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
25975       begin
25976          E75 := E75 - 1;
25977          F3;
25978       end;
25979       E87 := E87 - 1;
25980       declare
25981          procedure F4;
25982          pragma Import (Ada, F4, "system__pool_global__finalize_spec");
25983       begin
25984          F4;
25985       end;
25986       declare
25987          procedure F5;
25988          pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
25989       begin
25990          F5;
25991       end;
25992       declare
25993          procedure F6;
25994          pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
25995       begin
25996          F6;
25997       end;
25998       declare
25999          procedure Reraise_Library_Exception_If_Any;
26000          pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
26001       begin
26002          Reraise_Library_Exception_If_Any;
26003       end;
26004    end finalize_library;
26006    -------------
26007    -- adainit --
26008    -------------
26010    procedure adainit is
26012       Main_Priority : Integer;
26013       pragma Import (C, Main_Priority, "__gl_main_priority");
26014       Time_Slice_Value : Integer;
26015       pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
26016       WC_Encoding : Character;
26017       pragma Import (C, WC_Encoding, "__gl_wc_encoding");
26018       Locking_Policy : Character;
26019       pragma Import (C, Locking_Policy, "__gl_locking_policy");
26020       Queuing_Policy : Character;
26021       pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
26022       Task_Dispatching_Policy : Character;
26023       pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
26024       Priority_Specific_Dispatching : System.Address;
26025       pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
26026       Num_Specific_Dispatching : Integer;
26027       pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
26028       Main_CPU : Integer;
26029       pragma Import (C, Main_CPU, "__gl_main_cpu");
26030       Interrupt_States : System.Address;
26031       pragma Import (C, Interrupt_States, "__gl_interrupt_states");
26032       Num_Interrupt_States : Integer;
26033       pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
26034       Unreserve_All_Interrupts : Integer;
26035       pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
26036       Detect_Blocking : Integer;
26037       pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
26038       Default_Stack_Size : Integer;
26039       pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
26040       Leap_Seconds_Support : Integer;
26041       pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
26043       procedure Runtime_Initialize;
26044       pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
26046       Finalize_Library_Objects : No_Param_Proc;
26047       pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
26049    --  Start of processing for adainit
26051    begin
26053       --  Record various information for this partition.  The values
26054       --  are derived by the binder from information stored in the ali
26055       --  files by the compiler.
26057       if Is_Elaborated then
26058          return;
26059       end if;
26060       Is_Elaborated := True;
26061       Main_Priority := -1;
26062       Time_Slice_Value := -1;
26063       WC_Encoding := 'b';
26064       Locking_Policy := ' ';
26065       Queuing_Policy := ' ';
26066       Task_Dispatching_Policy := ' ';
26067       Priority_Specific_Dispatching :=
26068         Local_Priority_Specific_Dispatching'Address;
26069       Num_Specific_Dispatching := 0;
26070       Main_CPU := -1;
26071       Interrupt_States := Local_Interrupt_States'Address;
26072       Num_Interrupt_States := 0;
26073       Unreserve_All_Interrupts := 0;
26074       Detect_Blocking := 0;
26075       Default_Stack_Size := -1;
26076       Leap_Seconds_Support := 0;
26078       Runtime_Initialize;
26080       Finalize_Library_Objects := finalize_library'access;
26082       --  Now we have the elaboration calls for all units in the partition.
26083       --  The Elab_Spec and Elab_Body attributes generate references to the
26084       --  implicit elaboration procedures generated by the compiler for
26085       --  each unit that requires elaboration. Increment a counter of
26086       --  reference for each unit.
26088       System.Soft_Links'Elab_Spec;
26089       System.Exception_Table'Elab_Body;
26090       E23 := E23 + 1;
26091       Ada.Io_Exceptions'Elab_Spec;
26092       E46 := E46 + 1;
26093       Ada.Tags'Elab_Spec;
26094       Ada.Streams'Elab_Spec;
26095       E45 := E45 + 1;
26096       Interfaces.C'Elab_Spec;
26097       System.Exceptions'Elab_Spec;
26098       E25 := E25 + 1;
26099       System.Finalization_Root'Elab_Spec;
26100       E68 := E68 + 1;
26101       Ada.Finalization'Elab_Spec;
26102       E66 := E66 + 1;
26103       System.Storage_Pools'Elab_Spec;
26104       E85 := E85 + 1;
26105       System.Finalization_Masters'Elab_Spec;
26106       System.Storage_Pools.Subpools'Elab_Spec;
26107       System.Pool_Global'Elab_Spec;
26108       E87 := E87 + 1;
26109       System.File_Control_Block'Elab_Spec;
26110       E75 := E75 + 1;
26111       System.File_Io'Elab_Body;
26112       E64 := E64 + 1;
26113       E91 := E91 + 1;
26114       System.Finalization_Masters'Elab_Body;
26115       E77 := E77 + 1;
26116       E70 := E70 + 1;
26117       Ada.Tags'Elab_Body;
26118       E48 := E48 + 1;
26119       System.Soft_Links'Elab_Body;
26120       E13 := E13 + 1;
26121       System.Os_Lib'Elab_Body;
26122       E72 := E72 + 1;
26123       System.Secondary_Stack'Elab_Body;
26124       E17 := E17 + 1;
26125       Ada.Text_Io'Elab_Spec;
26126       Ada.Text_Io'Elab_Body;
26127       E06 := E06 + 1;
26128    end adainit;
26130    --------------
26131    -- adafinal --
26132    --------------
26134    procedure adafinal is
26135       procedure s_stalib_adafinal;
26136       pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
26138       procedure Runtime_Finalize;
26139       pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
26141    begin
26142       if not Is_Elaborated then
26143          return;
26144       end if;
26145       Is_Elaborated := False;
26146       Runtime_Finalize;
26147       s_stalib_adafinal;
26148    end adafinal;
26150    --  We get to the main program of the partition by using
26151    --  pragma Import because if we try to with the unit and
26152    --  call it Ada style, then not only do we waste time
26153    --  recompiling it, but also, we don't really know the right
26154    --  switches (e.g.@@: identifier character set) to be used
26155    --  to compile it.
26157    procedure Ada_Main_Program;
26158    pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26160    ----------
26161    -- main --
26162    ----------
26164    --  main is actually a function, as in the ANSI C standard,
26165    --  defined to return the exit status. The three parameters
26166    --  are the argument count, argument values and environment
26167    --  pointer.
26169    function main
26170      (argc : Integer;
26171       argv : System.Address;
26172       envp : System.Address)
26173       return Integer
26174    is
26175       --  The initialize routine performs low level system
26176       --  initialization using a standard library routine which
26177       --  sets up signal handling and performs any other
26178       --  required setup. The routine can be found in file
26179       --  a-init.c.
26181       procedure initialize;
26182       pragma Import (C, initialize, "__gnat_initialize");
26184       --  The finalize routine performs low level system
26185       --  finalization using a standard library routine. The
26186       --  routine is found in file a-final.c and in the standard
26187       --  distribution is a dummy routine that does nothing, so
26188       --  really this is a hook for special user finalization.
26190       procedure finalize;
26191       pragma Import (C, finalize, "__gnat_finalize");
26193       --  The following is to initialize the SEH exceptions
26195       SEH : aliased array (1 .. 2) of Integer;
26197       Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
26198       pragma Volatile (Ensure_Reference);
26200    --  Start of processing for main
26202    begin
26203       --  Save global variables
26205       gnat_argc := argc;
26206       gnat_argv := argv;
26207       gnat_envp := envp;
26209       --  Call low level system initialization
26211       Initialize (SEH'Address);
26213       --  Call our generated Ada initialization routine
26215       adainit;
26217       --  Now we call the main program of the partition
26219       Ada_Main_Program;
26221       --  Perform Ada finalization
26223       adafinal;
26225       --  Perform low level system finalization
26227       Finalize;
26229       --  Return the proper exit status
26230       return (gnat_exit_status);
26231    end;
26233 --  This section is entirely comments, so it has no effect on the
26234 --  compilation of the Ada_Main package. It provides the list of
26235 --  object files and linker options, as well as some standard
26236 --  libraries needed for the link. The gnatlink utility parses
26237 --  this b~hello.adb file to read these comment lines to generate
26238 --  the appropriate command line arguments for the call to the
26239 --  system linker. The BEGIN/END lines are used for sentinels for
26240 --  this parsing operation.
26242 --  The exact file names will of course depend on the environment,
26243 --  host/target and location of files on the host system.
26245 -- BEGIN Object file/option list
26246    --   ./hello.o
26247    --   -L./
26248    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
26249    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
26250 -- END Object file/option list
26252 end ada_main;
26253 @end example
26255 The Ada code in the above example is exactly what is generated by the
26256 binder. We have added comments to more clearly indicate the function
26257 of each part of the generated @code{Ada_Main} package.
26259 The code is standard Ada in all respects, and can be processed by any
26260 tools that handle Ada. In particular, it is possible to use the debugger
26261 in Ada mode to debug the generated @code{Ada_Main} package. For example,
26262 suppose that for reasons that you do not understand, your program is crashing
26263 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
26264 you can place a breakpoint on the call:
26266 @quotation
26268 @example
26269 Ada.Text_Io'Elab_Body;
26270 @end example
26271 @end quotation
26273 and trace the elaboration routine for this package to find out where
26274 the problem might be (more usually of course you would be debugging
26275 elaboration code in your own application).
26277 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
26279 @node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
26280 @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}
26281 @chapter Elaboration Order Handling in GNAT
26284 @geindex Order of elaboration
26286 @geindex Elaboration control
26288 This appendix describes the handling of elaboration code in Ada and GNAT, and
26289 discusses how the order of elaboration of program units can be controlled in
26290 GNAT, either automatically or with explicit programming features.
26292 @menu
26293 * Elaboration Code:: 
26294 * Elaboration Order:: 
26295 * Checking the Elaboration Order:: 
26296 * Controlling the Elaboration Order in Ada:: 
26297 * Controlling the Elaboration Order in GNAT:: 
26298 * Mixing Elaboration Models:: 
26299 * ABE Diagnostics:: 
26300 * SPARK Diagnostics:: 
26301 * Elaboration Circularities:: 
26302 * Resolving Elaboration Circularities:: 
26303 * Elaboration-related Compiler Switches:: 
26304 * Summary of Procedures for Elaboration Control:: 
26305 * Inspecting the Chosen Elaboration Order:: 
26307 @end menu
26309 @node Elaboration Code,Elaboration Order,,Elaboration Order Handling in GNAT
26310 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{21c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{21d}
26311 @section Elaboration Code
26314 Ada defines the term `execution' as the process by which a construct achieves
26315 its run-time effect. This process is also referred to as `elaboration' for
26316 declarations and `evaluation' for expressions.
26318 The execution model in Ada allows for certain sections of an Ada program to be
26319 executed prior to execution of the program itself, primarily with the intent of
26320 initializing data. These sections are referred to as `elaboration code'.
26321 Elaboration code is executed as follows:
26324 @itemize *
26326 @item 
26327 All partitions of an Ada program are executed in parallel with one another,
26328 possibly in a separate address space, and possibly on a separate computer.
26330 @item 
26331 The execution of a partition involves running the environment task for that
26332 partition.
26334 @item 
26335 The environment task executes all elaboration code (if available) for all
26336 units within that partition. This code is said to be executed at
26337 `elaboration time'.
26339 @item 
26340 The environment task executes the Ada program (if available) for that
26341 partition.
26342 @end itemize
26344 In addition to the Ada terminology, this appendix defines the following terms:
26347 @itemize *
26349 @item 
26350 `Invocation'
26352 The act of calling a subprogram, instantiating a generic, or activating a
26353 task.
26355 @item 
26356 `Scenario'
26358 A construct that is elaborated or invoked by elaboration code is referred to
26359 as an `elaboration scenario' or simply a `scenario'. GNAT recognizes the
26360 following scenarios:
26363 @itemize -
26365 @item 
26366 @code{'Access} of entries, operators, and subprograms
26368 @item 
26369 Activation of tasks
26371 @item 
26372 Calls to entries, operators, and subprograms
26374 @item 
26375 Instantiations of generic templates
26376 @end itemize
26378 @item 
26379 `Target'
26381 A construct elaborated by a scenario is referred to as `elaboration target'
26382 or simply `target'. GNAT recognizes the following targets:
26385 @itemize -
26387 @item 
26388 For @code{'Access} of entries, operators, and subprograms, the target is the
26389 entry, operator, or subprogram being aliased.
26391 @item 
26392 For activation of tasks, the target is the task body
26394 @item 
26395 For calls to entries, operators, and subprograms, the target is the entry,
26396 operator, or subprogram being invoked.
26398 @item 
26399 For instantiations of generic templates, the target is the generic template
26400 being instantiated.
26401 @end itemize
26402 @end itemize
26404 Elaboration code may appear in two distinct contexts:
26407 @itemize *
26409 @item 
26410 `Library level'
26412 A scenario appears at the library level when it is encapsulated by a package
26413 [body] compilation unit, ignoring any other package [body] declarations in
26414 between.
26416 @example
26417 with Server;
26418 package Client is
26419    procedure Proc;
26421    package Nested is
26422       Val : ... := Server.Func;
26423    end Nested;
26424 end Client;
26425 @end example
26427 In the example above, the call to @code{Server.Func} is an elaboration scenario
26428 because it appears at the library level of package @code{Client}. Note that the
26429 declaration of package @code{Nested} is ignored according to the definition
26430 given above. As a result, the call to @code{Server.Func} will be invoked when
26431 the spec of unit @code{Client} is elaborated.
26433 @item 
26434 `Package body statements'
26436 A scenario appears within the statement sequence of a package body when it is
26437 bounded by the region starting from the @code{begin} keyword of the package body
26438 and ending at the @code{end} keyword of the package body.
26440 @example
26441 package body Client is
26442    procedure Proc is
26443    begin
26444       ...
26445    end Proc;
26446 begin
26447    Proc;
26448 end Client;
26449 @end example
26451 In the example above, the call to @code{Proc} is an elaboration scenario because
26452 it appears within the statement sequence of package body @code{Client}. As a
26453 result, the call to @code{Proc} will be invoked when the body of @code{Client} is
26454 elaborated.
26455 @end itemize
26457 @node Elaboration Order,Checking the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
26458 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order}@anchor{21e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{21f}
26459 @section Elaboration Order
26462 The sequence by which the elaboration code of all units within a partition is
26463 executed is referred to as `elaboration order'.
26465 Within a single unit, elaboration code is executed in sequential order.
26467 @quotation
26469 @example
26470 package body Client is
26471    Result : ... := Server.Func;
26473    procedure Proc is
26474       package Inst is new Server.Gen;
26475    begin
26476       Inst.Eval (Result);
26477    end Proc;
26478 begin
26479    Proc;
26480 end Client;
26481 @end example
26482 @end quotation
26484 In the example above, the elaboration order within package body @code{Client} is
26485 as follows:
26488 @enumerate 
26490 @item 
26491 The object declaration of @code{Result} is elaborated.
26494 @itemize *
26496 @item 
26497 Function @code{Server.Func} is invoked.
26498 @end itemize
26500 @item 
26501 The subprogram body of @code{Proc} is elaborated.
26503 @item 
26504 Procedure @code{Proc} is invoked.
26507 @itemize *
26509 @item 
26510 Generic unit @code{Server.Gen} is instantiated as @code{Inst}.
26512 @item 
26513 Instance @code{Inst} is elaborated.
26515 @item 
26516 Procedure @code{Inst.Eval} is invoked.
26517 @end itemize
26518 @end enumerate
26520 The elaboration order of all units within a partition depends on the following
26521 factors:
26524 @itemize *
26526 @item 
26527 `with'ed units
26529 @item 
26530 parent units
26532 @item 
26533 purity of units
26535 @item 
26536 preelaborability of units
26538 @item 
26539 presence of elaboration-control pragmas
26541 @item 
26542 invocations performed in elaboration code
26543 @end itemize
26545 A program may have several elaboration orders depending on its structure.
26547 @quotation
26549 @example
26550 package Server is
26551    function Func (Index : Integer) return Integer;
26552 end Server;
26553 @end example
26555 @example
26556 package body Server is
26557    Results : array (1 .. 5) of Integer := (1, 2, 3, 4, 5);
26559    function Func (Index : Integer) return Integer is
26560    begin
26561       return Results (Index);
26562    end Func;
26563 end Server;
26564 @end example
26566 @example
26567 with Server;
26568 package Client is
26569    Val : constant Integer := Server.Func (3);
26570 end Client;
26571 @end example
26573 @example
26574 with Client;
26575 procedure Main is begin null; end Main;
26576 @end example
26577 @end quotation
26579 The following elaboration order exhibits a fundamental problem referred to as
26580 `access-before-elaboration' or simply `ABE'.
26582 @quotation
26584 @example
26585 spec of Server
26586 spec of Client
26587 body of Server
26588 body of Main
26589 @end example
26590 @end quotation
26592 The elaboration of @code{Server}’s spec materializes function @code{Func}, making it
26593 callable. The elaboration of @code{Client}’s spec elaborates the declaration of
26594 @code{Val}. This invokes function @code{Server.Func}, however the body of
26595 @code{Server.Func} has not been elaborated yet because @code{Server}’s body comes
26596 after @code{Client}’s spec in the elaboration order. As a result, the value of
26597 constant @code{Val} is now undefined.
26599 Without any guarantees from the language, an undetected ABE problem may hinder
26600 proper initialization of data, which in turn may lead to undefined behavior at
26601 run time. To prevent such ABE problems, Ada employs dynamic checks in the same
26602 vein as index or null exclusion checks. A failed ABE check raises exception
26603 @code{Program_Error}.
26605 The following elaboration order avoids the ABE problem and the program can be
26606 successfully elaborated.
26608 @quotation
26610 @example
26611 spec of Server
26612 body of Server
26613 spec of Client
26614 body of Main
26615 @end example
26616 @end quotation
26618 Ada states that a total elaboration order must exist, but it does not define
26619 what this order is. A compiler is thus tasked with choosing a suitable
26620 elaboration order which satisfies the dependencies imposed by `with' clauses,
26621 unit categorization, elaboration-control pragmas, and invocations performed in
26622 elaboration code. Ideally an order that avoids ABE problems should be chosen,
26623 however a compiler may not always find such an order due to complications with
26624 respect to control and data flow.
26626 @node Checking the Elaboration Order,Controlling the Elaboration Order in Ada,Elaboration Order,Elaboration Order Handling in GNAT
26627 @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}
26628 @section Checking the Elaboration Order
26631 To avoid placing the entire elaboration-order burden on the programmer, Ada
26632 provides three lines of defense:
26635 @itemize *
26637 @item 
26638 `Static semantics'
26640 Static semantic rules restrict the possible choice of elaboration order. For
26641 instance, if unit Client `with's unit Server, then the spec of Server is
26642 always elaborated prior to Client. The same principle applies to child units
26643 - the spec of a parent unit is always elaborated prior to the child unit.
26645 @item 
26646 `Dynamic semantics'
26648 Dynamic checks are performed at run time, to ensure that a target is
26649 elaborated prior to a scenario that invokes it, thus avoiding ABE problems.
26650 A failed run-time check raises exception @code{Program_Error}. The following
26651 restrictions apply:
26654 @itemize -
26656 @item 
26657 `Restrictions on calls'
26659 An entry, operator, or subprogram can be called from elaboration code only
26660 when the corresponding body has been elaborated.
26662 @item 
26663 `Restrictions on instantiations'
26665 A generic unit can be instantiated by elaboration code only when the
26666 corresponding body has been elaborated.
26668 @item 
26669 `Restrictions on task activation'
26671 A task can be activated by elaboration code only when the body of the
26672 associated task type has been elaborated.
26673 @end itemize
26675 The restrictions above can be summarized by the following rule:
26677 `If a target has a body, then this body must be elaborated prior to the
26678 scenario that invokes the target.'
26680 @item 
26681 `Elaboration control'
26683 Pragmas are provided for the programmer to specify the desired elaboration
26684 order.
26685 @end itemize
26687 @node Controlling the Elaboration Order in Ada,Controlling the Elaboration Order in GNAT,Checking the Elaboration Order,Elaboration Order Handling in GNAT
26688 @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}
26689 @section Controlling the Elaboration Order in Ada
26692 Ada provides several idioms and pragmas to aid the programmer with specifying
26693 the desired elaboration order and avoiding ABE problems altogether.
26696 @itemize *
26698 @item 
26699 `Packages without a body'
26701 A library package which does not require a completing body does not suffer
26702 from ABE problems.
26704 @example
26705 package Pack is
26706    generic
26707       type Element is private;
26708    package Containers is
26709       type Element_Array is array (1 .. 10) of Element;
26710    end Containers;
26711 end Pack;
26712 @end example
26714 In the example above, package @code{Pack} does not require a body because it
26715 does not contain any constructs which require completion in a body. As a
26716 result, generic @code{Pack.Containers} can be instantiated without encountering
26717 any ABE problems.
26718 @end itemize
26720 @geindex pragma Pure
26723 @itemize *
26725 @item 
26726 `pragma Pure'
26728 Pragma @code{Pure} places sufficient restrictions on a unit to guarantee that no
26729 scenario within the unit can result in an ABE problem.
26730 @end itemize
26732 @geindex pragma Preelaborate
26735 @itemize *
26737 @item 
26738 `pragma Preelaborate'
26740 Pragma @code{Preelaborate} is slightly less restrictive than pragma @code{Pure},
26741 but still strong enough to prevent ABE problems within a unit.
26742 @end itemize
26744 @geindex pragma Elaborate_Body
26747 @itemize *
26749 @item 
26750 `pragma Elaborate_Body'
26752 Pragma @code{Elaborate_Body} requires that the body of a unit is elaborated
26753 immediately after its spec. This restriction guarantees that no client
26754 scenario can invoke a server target before the target body has been
26755 elaborated because the spec and body are effectively “glued” together.
26757 @example
26758 package Server is
26759    pragma Elaborate_Body;
26761    function Func return Integer;
26762 end Server;
26763 @end example
26765 @example
26766 package body Server is
26767    function Func return Integer is
26768    begin
26769       ...
26770    end Func;
26771 end Server;
26772 @end example
26774 @example
26775 with Server;
26776 package Client is
26777    Val : constant Integer := Server.Func;
26778 end Client;
26779 @end example
26781 In the example above, pragma @code{Elaborate_Body} guarantees the following
26782 elaboration order:
26784 @example
26785 spec of Server
26786 body of Server
26787 spec of Client
26788 @end example
26790 because the spec of @code{Server} must be elaborated prior to @code{Client} by
26791 virtue of the `with' clause, and in addition the body of @code{Server} must be
26792 elaborated immediately after the spec of @code{Server}.
26794 Removing pragma @code{Elaborate_Body} could result in the following incorrect
26795 elaboration order:
26797 @example
26798 spec of Server
26799 spec of Client
26800 body of Server
26801 @end example
26803 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func} has
26804 not been elaborated yet.
26805 @end itemize
26807 The pragmas outlined above allow a server unit to guarantee safe elaboration
26808 use by client units. Thus it is a good rule to mark units as @code{Pure} or
26809 @code{Preelaborate}, and if this is not possible, mark them as @code{Elaborate_Body}.
26811 There are however situations where @code{Pure}, @code{Preelaborate}, and
26812 @code{Elaborate_Body} are not applicable. Ada provides another set of pragmas for
26813 use by client units to help ensure the elaboration safety of server units they
26814 depend on.
26816 @geindex pragma Elaborate (Unit)
26819 @itemize *
26821 @item 
26822 `pragma Elaborate (Unit)'
26824 Pragma @code{Elaborate} can be placed in the context clauses of a unit, after a
26825 `with' clause. It guarantees that both the spec and body of its argument will
26826 be elaborated prior to the unit with the pragma. Note that other unrelated
26827 units may be elaborated in between the spec and the body.
26829 @example
26830 package Server is
26831    function Func return Integer;
26832 end Server;
26833 @end example
26835 @example
26836 package body Server is
26837    function Func return Integer is
26838    begin
26839       ...
26840    end Func;
26841 end Server;
26842 @end example
26844 @example
26845 with Server;
26846 pragma Elaborate (Server);
26847 package Client is
26848    Val : constant Integer := Server.Func;
26849 end Client;
26850 @end example
26852 In the example above, pragma @code{Elaborate} guarantees the following
26853 elaboration order:
26855 @example
26856 spec of Server
26857 body of Server
26858 spec of Client
26859 @end example
26861 Removing pragma @code{Elaborate} could result in the following incorrect
26862 elaboration order:
26864 @example
26865 spec of Server
26866 spec of Client
26867 body of Server
26868 @end example
26870 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func}
26871 has not been elaborated yet.
26872 @end itemize
26874 @geindex pragma Elaborate_All (Unit)
26877 @itemize *
26879 @item 
26880 `pragma Elaborate_All (Unit)'
26882 Pragma @code{Elaborate_All} is placed in the context clauses of a unit, after
26883 a `with' clause. It guarantees that both the spec and body of its argument
26884 will be elaborated prior to the unit with the pragma, as well as all units
26885 `with'ed by the spec and body of the argument, recursively. Note that other
26886 unrelated units may be elaborated in between the spec and the body.
26888 @example
26889 package Math is
26890    function Factorial (Val : Natural) return Natural;
26891 end Math;
26892 @end example
26894 @example
26895 package body Math is
26896    function Factorial (Val : Natural) return Natural is
26897    begin
26898       ...;
26899    end Factorial;
26900 end Math;
26901 @end example
26903 @example
26904 package Computer is
26905    type Operation_Kind is (None, Op_Factorial);
26907    function Compute
26908      (Val : Natural;
26909       Op  : Operation_Kind) return Natural;
26910 end Computer;
26911 @end example
26913 @example
26914 with Math;
26915 package body Computer is
26916    function Compute
26917      (Val : Natural;
26918       Op  : Operation_Kind) return Natural
26919    is
26920       if Op = Op_Factorial then
26921          return Math.Factorial (Val);
26922       end if;
26924       return 0;
26925    end Compute;
26926 end Computer;
26927 @end example
26929 @example
26930 with Computer;
26931 pragma Elaborate_All (Computer);
26932 package Client is
26933    Val : constant Natural :=
26934            Computer.Compute (123, Computer.Op_Factorial);
26935 end Client;
26936 @end example
26938 In the example above, pragma @code{Elaborate_All} can result in the following
26939 elaboration order:
26941 @example
26942 spec of Math
26943 body of Math
26944 spec of Computer
26945 body of Computer
26946 spec of Client
26947 @end example
26949 Note that there are several allowable suborders for the specs and bodies of
26950 @code{Math} and @code{Computer}, but the point is that these specs and bodies will
26951 be elaborated prior to @code{Client}.
26953 Removing pragma @code{Elaborate_All} could result in the following incorrect
26954 elaboration order:
26956 @example
26957 spec of Math
26958 spec of Computer
26959 body of Computer
26960 spec of Client
26961 body of Math
26962 @end example
26964 where @code{Client} invokes @code{Computer.Compute}, which in turn invokes
26965 @code{Math.Factorial}, but the body of @code{Math.Factorial} has not been
26966 elaborated yet.
26967 @end itemize
26969 All pragmas shown above can be summarized by the following rule:
26971 `If a client unit elaborates a server target directly or indirectly, then if
26972 the server unit requires a body and does not have pragma Pure, Preelaborate,
26973 or Elaborate_Body, then the client unit should have pragma Elaborate or
26974 Elaborate_All for the server unit.'
26976 If the rule outlined above is not followed, then a program may fall in one of
26977 the following states:
26980 @itemize *
26982 @item 
26983 `No elaboration order exists'
26985 In this case a compiler must diagnose the situation, and refuse to build an
26986 executable program.
26988 @item 
26989 `One or more incorrect elaboration orders exist'
26991 In this case a compiler can build an executable program, but
26992 @code{Program_Error} will be raised when the program is run.
26994 @item 
26995 `Several elaboration orders exist, some correct, some incorrect'
26997 In this case the programmer has not controlled the elaboration order. As a
26998 result, a compiler may or may not pick one of the correct orders, and the
26999 program may or may not raise @code{Program_Error} when it is run. This is the
27000 worst possible state because the program may fail on another compiler, or
27001 even another version of the same compiler.
27003 @item 
27004 `One or more correct orders exist'
27006 In this case a compiler can build an executable program, and the program is
27007 run successfully. This state may be guaranteed by following the outlined
27008 rules, or may be the result of good program architecture.
27009 @end itemize
27011 Note that one additional advantage of using @code{Elaborate} and @code{Elaborate_All}
27012 is that the program continues to stay in the last state (one or more correct
27013 orders exist) even if maintenance changes the bodies of targets.
27015 @node Controlling the Elaboration Order in GNAT,Mixing Elaboration Models,Controlling the Elaboration Order in Ada,Elaboration Order Handling in GNAT
27016 @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}
27017 @section Controlling the Elaboration Order in GNAT
27020 In addition to Ada semantics and rules synthesized from them, GNAT offers
27021 three elaboration models to aid the programmer with specifying the correct
27022 elaboration order and to diagnose elaboration problems.
27024 @geindex Dynamic elaboration model
27027 @itemize *
27029 @item 
27030 `Dynamic elaboration model'
27032 This is the most permissive of the three elaboration models and emulates the
27033 behavior specified by the Ada Reference Manual. When the dynamic model is in
27034 effect, GNAT makes the following assumptions:
27037 @itemize -
27039 @item 
27040 All code within all units in a partition is considered to be elaboration
27041 code.
27043 @item 
27044 Some of the invocations in elaboration code may not take place at run time
27045 due to conditional execution.
27046 @end itemize
27048 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
27049 that invoke internal targets. In addition, GNAT generates run-time checks for
27050 all external targets and for all scenarios that may exhibit ABE problems.
27052 The elaboration order is obtained by honoring all `with' clauses, purity and
27053 preelaborability of units, and elaboration-control pragmas. The dynamic model
27054 attempts to take all invocations in elaboration code into account. If an
27055 invocation leads to a circularity, GNAT ignores the invocation based on the
27056 assumptions stated above. An order obtained using the dynamic model may fail
27057 an ABE check at run time when GNAT ignored an invocation.
27059 The dynamic model is enabled with compiler switch @code{-gnatE}.
27060 @end itemize
27062 @geindex Static elaboration model
27065 @itemize *
27067 @item 
27068 `Static elaboration model'
27070 This is the middle ground of the three models. When the static model is in
27071 effect, GNAT makes the following assumptions:
27074 @itemize -
27076 @item 
27077 Only code at the library level and in package body statements within all
27078 units in a partition is considered to be elaboration code.
27080 @item 
27081 All invocations in elaboration will take place at run time, regardless of
27082 conditional execution.
27083 @end itemize
27085 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
27086 that invoke internal targets. In addition, GNAT generates run-time checks for
27087 all external targets and for all scenarios that may exhibit ABE problems.
27089 The elaboration order is obtained by honoring all `with' clauses, purity and
27090 preelaborability of units, presence of elaboration-control pragmas, and all
27091 invocations in elaboration code. An order obtained using the static model is
27092 guaranteed to be ABE problem-free, excluding dispatching calls and
27093 access-to-subprogram types.
27095 The static model is the default model in GNAT.
27096 @end itemize
27098 @geindex SPARK elaboration model
27101 @itemize *
27103 @item 
27104 `SPARK elaboration model'
27106 This is the most conservative of the three models and enforces the SPARK
27107 rules of elaboration as defined in the SPARK Reference Manual, section 7.7.
27108 The SPARK model is in effect only when a scenario and a target reside in a
27109 region subject to @code{SPARK_Mode On}, otherwise the dynamic or static model
27110 is in effect.
27112 The SPARK model is enabled with compiler switch @code{-gnatd.v}.
27113 @end itemize
27115 @geindex Legacy elaboration models
27118 @itemize *
27120 @item 
27121 `Legacy elaboration models'
27123 In addition to the three elaboration models outlined above, GNAT provides the
27124 following legacy models:
27127 @itemize -
27129 @item 
27130 @cite{Legacy elaboration-checking model} available in pre-18.x versions of GNAT.
27131 This model is enabled with compiler switch @code{-gnatH}.
27133 @item 
27134 @cite{Legacy elaboration-order model} available in pre-20.x versions of GNAT.
27135 This model is enabled with binder switch @code{-H}.
27136 @end itemize
27137 @end itemize
27139 @geindex Relaxed elaboration mode
27141 The dynamic, legacy, and static models can be relaxed using compiler switch
27142 @code{-gnatJ}, making them more permissive. Note that in this mode, GNAT
27143 may not diagnose certain elaboration issues or install run-time checks.
27145 @node Mixing Elaboration Models,ABE Diagnostics,Controlling the Elaboration Order in GNAT,Elaboration Order Handling in GNAT
27146 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{226}@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{227}
27147 @section Mixing Elaboration Models
27150 It is possible to mix units compiled with a different elaboration model,
27151 however the following rules must be observed:
27154 @itemize *
27156 @item 
27157 A client unit compiled with the dynamic model can only `with' a server unit
27158 that meets at least one of the following criteria:
27161 @itemize -
27163 @item 
27164 The server unit is compiled with the dynamic model.
27166 @item 
27167 The server unit is a GNAT implementation unit from the @code{Ada}, @code{GNAT},
27168 @code{Interfaces}, or @code{System} hierarchies.
27170 @item 
27171 The server unit has pragma @code{Pure} or @code{Preelaborate}.
27173 @item 
27174 The client unit has an explicit @code{Elaborate_All} pragma for the server
27175 unit.
27176 @end itemize
27177 @end itemize
27179 These rules ensure that elaboration checks are not omitted. If the rules are
27180 violated, the binder emits a warning:
27182 @quotation
27184 @example
27185 warning: "x.ads" has dynamic elaboration checks and with's
27186 warning:   "y.ads" which has static elaboration checks
27187 @end example
27188 @end quotation
27190 The warnings can be suppressed by binder switch @code{-ws}.
27192 @node ABE Diagnostics,SPARK Diagnostics,Mixing Elaboration Models,Elaboration Order Handling in GNAT
27193 @anchor{gnat_ugn/elaboration_order_handling_in_gnat abe-diagnostics}@anchor{228}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{229}
27194 @section ABE Diagnostics
27197 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
27198 that invoke internal targets, regardless of whether the dynamic, SPARK, or
27199 static model is in effect.
27201 Note that GNAT emits warnings rather than hard errors whenever it encounters an
27202 elaboration problem. This is because the elaboration model in effect may be too
27203 conservative, or a particular scenario may not be invoked due conditional
27204 execution. The warnings can be suppressed selectively with @code{pragma Warnings
27205 (Off)} or globally with compiler switch @code{-gnatwL}.
27207 A `guaranteed ABE' arises when the body of a target is not elaborated early
27208 enough, and causes `all' scenarios that directly invoke the target to fail.
27210 @quotation
27212 @example
27213 package body Guaranteed_ABE is
27214    function ABE return Integer;
27216    Val : constant Integer := ABE;
27218    function ABE return Integer is
27219    begin
27220      ...
27221    end ABE;
27222 end Guaranteed_ABE;
27223 @end example
27224 @end quotation
27226 In the example above, the elaboration of @code{Guaranteed_ABE}’s body elaborates
27227 the declaration of @code{Val}. This invokes function @code{ABE}, however the body of
27228 @code{ABE} has not been elaborated yet. GNAT emits the following diagnostic:
27230 @quotation
27232 @example
27233 4.    Val : constant Integer := ABE;
27234                                 |
27235    >>> warning: cannot call "ABE" before body seen
27236    >>> warning: Program_Error will be raised at run time
27237 @end example
27238 @end quotation
27240 A `conditional ABE' arises when the body of a target is not elaborated early
27241 enough, and causes `some' scenarios that directly invoke the target to fail.
27243 @quotation
27245 @example
27246  1. package body Conditional_ABE is
27247  2.    procedure Force_Body is null;
27248  3.
27249  4.    generic
27250  5.       with function Func return Integer;
27251  6.    package Gen is
27252  7.       Val : constant Integer := Func;
27253  8.    end Gen;
27254  9.
27255 10.    function ABE return Integer;
27257 12.    function Cause_ABE return Boolean is
27258 13.       package Inst is new Gen (ABE);
27259 14.    begin
27260 15.       ...
27261 16.    end Cause_ABE;
27263 18.    Val : constant Boolean := Cause_ABE;
27265 20.    function ABE return Integer is
27266 21.    begin
27267 22.       ...
27268 23.    end ABE;
27270 25.    Safe : constant Boolean := Cause_ABE;
27271 26. end Conditional_ABE;
27272 @end example
27273 @end quotation
27275 In the example above, the elaboration of package body @code{Conditional_ABE}
27276 elaborates the declaration of @code{Val}. This invokes function @code{Cause_ABE},
27277 which instantiates generic unit @code{Gen} as @code{Inst}. The elaboration of
27278 @code{Inst} invokes function @code{ABE}, however the body of @code{ABE} has not been
27279 elaborated yet. GNAT emits the following diagnostic:
27281 @quotation
27283 @example
27284 13.       package Inst is new Gen (ABE);
27285           |
27286     >>> warning: in instantiation at line 7
27287     >>> warning: cannot call "ABE" before body seen
27288     >>> warning: Program_Error may be raised at run time
27289     >>> warning:   body of unit "Conditional_ABE" elaborated
27290     >>> warning:   function "Cause_ABE" called at line 18
27291     >>> warning:   function "ABE" called at line 7, instance at line 13
27292 @end example
27293 @end quotation
27295 Note that the same ABE problem does not occur with the elaboration of
27296 declaration @code{Safe} because the body of function @code{ABE} has already been
27297 elaborated at that point.
27299 @node SPARK Diagnostics,Elaboration Circularities,ABE Diagnostics,Elaboration Order Handling in GNAT
27300 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{22a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat spark-diagnostics}@anchor{22b}
27301 @section SPARK Diagnostics
27304 GNAT enforces the SPARK rules of elaboration as defined in the SPARK Reference
27305 Manual section 7.7 when compiler switch @code{-gnatd.v} is in effect. Note
27306 that GNAT emits hard errors whenever it encounters a violation of the SPARK
27307 rules.
27309 @quotation
27311 @example
27312 1. with Server;
27313 2. package body SPARK_Diagnostics with SPARK_Mode is
27314 3.    Val : constant Integer := Server.Func;
27315                                       |
27316    >>> call to "Func" during elaboration in SPARK
27317    >>> unit "SPARK_Diagnostics" requires pragma "Elaborate_All" for "Server"
27318    >>>   body of unit "SPARK_Model" elaborated
27319    >>>   function "Func" called at line 3
27321 4. end SPARK_Diagnostics;
27322 @end example
27323 @end quotation
27325 @node Elaboration Circularities,Resolving Elaboration Circularities,SPARK Diagnostics,Elaboration Order Handling in GNAT
27326 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-circularities}@anchor{22c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{22d}
27327 @section Elaboration Circularities
27330 An `elaboration circularity' occurs whenever the elaboration of a set of
27331 units enters a deadlocked state, where each unit is waiting for another unit
27332 to be elaborated. This situation may be the result of improper use of `with'
27333 clauses, elaboration-control pragmas, or invocations in elaboration code.
27335 The following example exhibits an elaboration circularity.
27337 @quotation
27339 @example
27340 with B; pragma Elaborate (B);
27341 package A is
27342 end A;
27343 @end example
27345 @example
27346 package B is
27347    procedure Force_Body;
27348 end B;
27349 @end example
27351 @example
27352 with C;
27353 package body B is
27354    procedure Force_Body is null;
27356    Elab : constant Integer := C.Func;
27357 end B;
27358 @end example
27360 @example
27361 package C is
27362    function Func return Integer;
27363 end C;
27364 @end example
27366 @example
27367 with A;
27368 package body C is
27369    function Func return Integer is
27370    begin
27371       ...
27372    end Func;
27373 end C;
27374 @end example
27375 @end quotation
27377 The binder emits the following diagnostic:
27379 @quotation
27381 @example
27382 error: Elaboration circularity detected
27383 info:
27384 info:    Reason:
27385 info:
27386 info:      unit "a (spec)" depends on its own elaboration
27387 info:
27388 info:    Circularity:
27389 info:
27390 info:      unit "a (spec)" has with clause and pragma Elaborate for unit "b (spec)"
27391 info:      unit "b (body)" is in the closure of pragma Elaborate
27392 info:      unit "b (body)" invokes a construct of unit "c (body)" at elaboration time
27393 info:      unit "c (body)" has with clause for unit "a (spec)"
27394 info:
27395 info:    Suggestions:
27396 info:
27397 info:      remove pragma Elaborate for unit "b (body)" in unit "a (spec)"
27398 info:      use the dynamic elaboration model (compiler switch -gnatE)
27399 @end example
27400 @end quotation
27402 The diagnostic consist of the following sections:
27405 @itemize *
27407 @item 
27408 Reason
27410 This section provides a short explanation describing why the set of units
27411 could not be ordered.
27413 @item 
27414 Circularity
27416 This section enumerates the units comprising the deadlocked set, along with
27417 their interdependencies.
27419 @item 
27420 Suggestions
27422 This section enumerates various tactics for eliminating the circularity.
27423 @end itemize
27425 @node Resolving Elaboration Circularities,Elaboration-related Compiler Switches,Elaboration Circularities,Elaboration Order Handling in GNAT
27426 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{22e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat resolving-elaboration-circularities}@anchor{22f}
27427 @section Resolving Elaboration Circularities
27430 The most desirable option from the point of view of long-term maintenance is to
27431 rearrange the program so that the elaboration problems are avoided. One useful
27432 technique is to place the elaboration code into separate child packages.
27433 Another is to move some of the initialization code to explicitly invoked
27434 subprograms, where the program controls the order of initialization explicitly.
27435 Although this is the most desirable option, it may be impractical and involve
27436 too much modification, especially in the case of complex legacy code.
27438 When faced with an elaboration circularity, the programmer should also consider
27439 the tactics given in the suggestions section of the circularity diagnostic.
27440 Depending on the units involved in the circularity, their `with' clauses,
27441 purity, preelaborability, presence of elaboration-control pragmas and
27442 invocations at elaboration time, the binder may suggest one or more of the
27443 following tactics to eliminate the circularity:
27446 @itemize *
27448 @item 
27449 Pragma Elaborate elimination
27451 @example
27452 remove pragma Elaborate for unit "..." in unit "..."
27453 @end example
27455 This tactic is suggested when the binder has determined that pragma
27456 @code{Elaborate}:
27459 @itemize -
27461 @item 
27462 Prevents a set of units from being elaborated.
27464 @item 
27465 The removal of the pragma will not eliminate the semantic effects of the
27466 pragma. In other words, the argument of the pragma will still be elaborated
27467 prior to the unit containing the pragma.
27469 @item 
27470 The removal of the pragma will enable the successful ordering of the units.
27471 @end itemize
27473 The programmer should remove the pragma as advised, and rebuild the program.
27475 @item 
27476 Pragma Elaborate_All elimination
27478 @example
27479 remove pragma Elaborate_All for unit "..." in unit "..."
27480 @end example
27482 This tactic is suggested when the binder has determined that pragma
27483 @code{Elaborate_All}:
27486 @itemize -
27488 @item 
27489 Prevents a set of units from being elaborated.
27491 @item 
27492 The removal of the pragma will not eliminate the semantic effects of the
27493 pragma. In other words, the argument of the pragma along with its `with'
27494 closure will still be elaborated prior to the unit containing the pragma.
27496 @item 
27497 The removal of the pragma will enable the successful ordering of the units.
27498 @end itemize
27500 The programmer should remove the pragma as advised, and rebuild the program.
27502 @item 
27503 Pragma Elaborate_All downgrade
27505 @example
27506 change pragma Elaborate_All for unit "..." to Elaborate in unit "..."
27507 @end example
27509 This tactic is always suggested with the pragma @code{Elaborate_All} elimination
27510 tactic. It offers a different alternative of guaranteeing that the argument
27511 of the pragma will still be elaborated prior to the unit containing the
27512 pragma.
27514 The programmer should update the pragma as advised, and rebuild the program.
27516 @item 
27517 Pragma Elaborate_Body elimination
27519 @example
27520 remove pragma Elaborate_Body in unit "..."
27521 @end example
27523 This tactic is suggested when the binder has determined that pragma
27524 @code{Elaborate_Body}:
27527 @itemize -
27529 @item 
27530 Prevents a set of units from being elaborated.
27532 @item 
27533 The removal of the pragma will enable the successful ordering of the units.
27534 @end itemize
27536 Note that the binder cannot determine whether the pragma is required for
27537 other purposes, such as guaranteeing the initialization of a variable
27538 declared in the spec by elaboration code in the body.
27540 The programmer should remove the pragma as advised, and rebuild the program.
27542 @item 
27543 Use of pragma Restrictions
27545 @example
27546 use pragma Restrictions (No_Entry_Calls_In_Elaboration_Code)
27547 @end example
27549 This tactic is suggested when the binder has determined that a task
27550 activation at elaboration time:
27553 @itemize -
27555 @item 
27556 Prevents a set of units from being elaborated.
27557 @end itemize
27559 Note that the binder cannot determine with certainty whether the task will
27560 block at elaboration time.
27562 The programmer should create a configuration file, place the pragma within,
27563 update the general compilation arguments, and rebuild the program.
27565 @item 
27566 Use of dynamic elaboration model
27568 @example
27569 use the dynamic elaboration model (compiler switch -gnatE)
27570 @end example
27572 This tactic is suggested when the binder has determined that an invocation at
27573 elaboration time:
27576 @itemize -
27578 @item 
27579 Prevents a set of units from being elaborated.
27581 @item 
27582 The use of the dynamic model will enable the successful ordering of the
27583 units.
27584 @end itemize
27586 The programmer has two options:
27589 @itemize -
27591 @item 
27592 Determine the units involved in the invocation using the detailed
27593 invocation information, and add compiler switch @code{-gnatE} to the
27594 compilation arguments of selected files only. This approach will yield
27595 safer elaboration orders compared to the other option because it will
27596 minimize the opportunities presented to the dynamic model for ignoring
27597 invocations.
27599 @item 
27600 Add compiler switch @code{-gnatE} to the general compilation arguments.
27601 @end itemize
27603 @item 
27604 Use of detailed invocation information
27606 @example
27607 use detailed invocation information (compiler switch -gnatd_F)
27608 @end example
27610 This tactic is always suggested with the use of the dynamic model tactic. It
27611 causes the circularity section of the circularity diagnostic to describe the
27612 flow of elaboration code from a unit to a unit, enumerating all such paths in
27613 the process.
27615 The programmer should analyze this information to determine which units
27616 should be compiled with the dynamic model.
27618 @item 
27619 Forced-dependency elimination
27621 @example
27622 remove the dependency of unit "..." on unit "..." from the argument of switch -f
27623 @end example
27625 This tactic is suggested when the binder has determined that a dependency
27626 present in the forced-elaboration-order file indicated by binder switch
27627 @code{-f}:
27630 @itemize -
27632 @item 
27633 Prevents a set of units from being elaborated.
27635 @item 
27636 The removal of the dependency will enable the successful ordering of the
27637 units.
27638 @end itemize
27640 The programmer should edit the forced-elaboration-order file, remove the
27641 dependency, and rebind the program.
27643 @item 
27644 All forced-dependency elimination
27646 @example
27647 remove switch -f
27648 @end example
27650 This tactic is suggested in case editing the forced-elaboration-order file is
27651 not an option.
27653 The programmer should remove binder switch @code{-f} from the binder
27654 arguments, and rebind.
27656 @item 
27657 Multiple-circularities diagnostic
27659 @example
27660 diagnose all circularities (binder switch -d_C)
27661 @end example
27663 By default, the binder will diagnose only the highest-precedence circularity.
27664 If the program contains multiple circularities, the binder will suggest the
27665 use of binder switch @code{-d_C} in order to obtain the diagnostics of all
27666 circularities.
27668 The programmer should add binder switch @code{-d_C} to the binder
27669 arguments, and rebind.
27670 @end itemize
27672 If none of the tactics suggested by the binder eliminate the elaboration
27673 circularity, the programmer should consider using one of the legacy elaboration
27674 models, in the following order:
27677 @itemize *
27679 @item 
27680 Use the pre-20.x legacy elaboration-order model, with binder switch
27681 @code{-H}.
27683 @item 
27684 Use both pre-18.x and pre-20.x legacy elaboration models, with compiler
27685 switch @code{-gnatH} and binder switch @code{-H}.
27687 @item 
27688 Use the relaxed static-elaboration model, with compiler switches
27689 @code{-gnatH} @code{-gnatJ} and binder switch @code{-H}.
27691 @item 
27692 Use the relaxed dynamic-elaboration model, with compiler switches
27693 @code{-gnatH} @code{-gnatJ} @code{-gnatE} and binder switch
27694 @code{-H}.
27695 @end itemize
27697 @node Elaboration-related Compiler Switches,Summary of Procedures for Elaboration Control,Resolving Elaboration Circularities,Elaboration Order Handling in GNAT
27698 @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}
27699 @section Elaboration-related Compiler Switches
27702 GNAT has several switches that affect the elaboration model and consequently
27703 the elaboration order chosen by the binder.
27705 @geindex -gnatE (gnat)
27708 @table @asis
27710 @item @code{-gnatE}
27712 Dynamic elaboration checking mode enabled
27714 When this switch is in effect, GNAT activates the dynamic model.
27715 @end table
27717 @geindex -gnatel (gnat)
27720 @table @asis
27722 @item @code{-gnatel}
27724 Turn on info messages on generated Elaborate[_All] pragmas
27726 This switch is only applicable to the pre-20.x legacy elaboration models.
27727 The post-20.x elaboration model no longer relies on implicitly generated
27728 @code{Elaborate} and @code{Elaborate_All} pragmas to order units.
27730 When this switch is in effect, GNAT will emit the following supplementary
27731 information depending on the elaboration model in effect.
27734 @itemize -
27736 @item 
27737 `Dynamic model'
27739 GNAT will indicate missing @code{Elaborate} and @code{Elaborate_All} pragmas for
27740 all library-level scenarios within the partition.
27742 @item 
27743 `Static model'
27745 GNAT will indicate all scenarios invoked during elaboration. In addition,
27746 it will provide detailed traceback when an implicit @code{Elaborate} or
27747 @code{Elaborate_All} pragma is generated.
27749 @item 
27750 `SPARK model'
27752 GNAT will indicate how an elaboration requirement is met by the context of
27753 a unit. This diagnostic requires compiler switch @code{-gnatd.v}.
27755 @example
27756 1. with Server; pragma Elaborate_All (Server);
27757 2. package Client with SPARK_Mode is
27758 3.    Val : constant Integer := Server.Func;
27759                                       |
27760    >>> info: call to "Func" during elaboration in SPARK
27761    >>> info: "Elaborate_All" requirement for unit "Server" met by pragma at line 1
27763 4. end Client;
27764 @end example
27765 @end itemize
27766 @end table
27768 @geindex -gnatH (gnat)
27771 @table @asis
27773 @item @code{-gnatH}
27775 Legacy elaboration checking mode enabled
27777 When this switch is in effect, GNAT will utilize the pre-18.x elaboration
27778 model.
27779 @end table
27781 @geindex -gnatJ (gnat)
27784 @table @asis
27786 @item @code{-gnatJ}
27788 Relaxed elaboration checking mode enabled
27790 When this switch is in effect, GNAT will not process certain scenarios,
27791 resulting in a more permissive elaboration model. Note that this may
27792 eliminate some diagnostics and run-time checks.
27793 @end table
27795 @geindex -gnatw.f (gnat)
27798 @table @asis
27800 @item @code{-gnatw.f}
27802 Turn on warnings for suspicious Subp’Access
27804 When this switch is in effect, GNAT will treat @code{'Access} of an entry,
27805 operator, or subprogram as a potential call to the target and issue warnings:
27807 @example
27808  1. package body Attribute_Call is
27809  2.    function Func return Integer;
27810  3.    type Func_Ptr is access function return Integer;
27811  4.
27812  5.    Ptr : constant Func_Ptr := Func'Access;
27813                                       |
27814     >>> warning: "Access" attribute of "Func" before body seen
27815     >>> warning: possible Program_Error on later references
27816     >>> warning:   body of unit "Attribute_Call" elaborated
27817     >>> warning:   "Access" of "Func" taken at line 5
27819  6.
27820  7.    function Func return Integer is
27821  8.    begin
27822  9.       ...
27823 10.    end Func;
27824 11. end Attribute_Call;
27825 @end example
27827 In the example above, the elaboration of declaration @code{Ptr} is assigned
27828 @code{Func'Access} before the body of @code{Func} has been elaborated.
27829 @end table
27831 @geindex -gnatwl (gnat)
27834 @table @asis
27836 @item @code{-gnatwl}
27838 Turn on warnings for elaboration problems
27840 When this switch is in effect, GNAT emits diagnostics in the form of warnings
27841 concerning various elaboration problems. The warnings are enabled by default.
27842 The switch is provided in case all warnings are suppressed, but elaboration
27843 warnings are still desired.
27845 @item @code{-gnatwL}
27847 Turn off warnings for elaboration problems
27849 When this switch is in effect, GNAT no longer emits any diagnostics in the
27850 form of warnings. Selective suppression of elaboration problems is possible
27851 using @code{pragma Warnings (Off)}.
27853 @example
27854  1. package body Selective_Suppression is
27855  2.    function ABE return Integer;
27856  3.
27857  4.    Val_1 : constant Integer := ABE;
27858                                    |
27859     >>> warning: cannot call "ABE" before body seen
27860     >>> warning: Program_Error will be raised at run time
27862  5.
27863  6.    pragma Warnings (Off);
27864  7.    Val_2 : constant Integer := ABE;
27865  8.    pragma Warnings (On);
27866  9.
27867 10.    function ABE return Integer is
27868 11.    begin
27869 12.       ...
27870 13.    end ABE;
27871 14. end Selective_Suppression;
27872 @end example
27874 Note that suppressing elaboration warnings does not eliminate run-time
27875 checks. The example above will still fail at run time with an ABE.
27876 @end table
27878 @node Summary of Procedures for Elaboration Control,Inspecting the Chosen Elaboration Order,Elaboration-related Compiler Switches,Elaboration Order Handling in GNAT
27879 @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}
27880 @section Summary of Procedures for Elaboration Control
27883 A programmer should first compile the program with the default options, using
27884 none of the binder or compiler switches. If the binder succeeds in finding an
27885 elaboration order, then apart from possible cases involving dispatching calls
27886 and access-to-subprogram types, the program is free of elaboration errors.
27888 If it is important for the program to be portable to compilers other than GNAT,
27889 then the programmer should use compiler switch @code{-gnatel} and consider
27890 the messages about missing or implicitly created @code{Elaborate} and
27891 @code{Elaborate_All} pragmas.
27893 If the binder reports an elaboration circularity, the programmer has several
27894 options:
27897 @itemize *
27899 @item 
27900 Ensure that elaboration warnings are enabled. This will allow the static
27901 model to output trace information of elaboration issues. The trace
27902 information could shed light on previously unforeseen dependencies, as well
27903 as their origins. Elaboration warnings are enabled with compiler switch
27904 @code{-gnatwl}.
27906 @item 
27907 Cosider the tactics given in the suggestions section of the circularity
27908 diagnostic.
27910 @item 
27911 If none of the steps outlined above resolve the circularity, use a more
27912 permissive elaboration model, in the following order:
27915 @itemize -
27917 @item 
27918 Use the pre-20.x legacy elaboration-order model, with binder switch
27919 @code{-H}.
27921 @item 
27922 Use both pre-18.x and pre-20.x legacy elaboration models, with compiler
27923 switch @code{-gnatH} and binder switch @code{-H}.
27925 @item 
27926 Use the relaxed static elaboration model, with compiler switches
27927 @code{-gnatH} @code{-gnatJ} and binder switch @code{-H}.
27929 @item 
27930 Use the relaxed dynamic elaboration model, with compiler switches
27931 @code{-gnatH} @code{-gnatJ} @code{-gnatE} and binder switch
27932 @code{-H}.
27933 @end itemize
27934 @end itemize
27936 @node Inspecting the Chosen Elaboration Order,,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
27937 @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}
27938 @section Inspecting the Chosen Elaboration Order
27941 To see the elaboration order chosen by the binder, inspect the contents of file
27942 @cite{b~xxx.adb}. On certain targets, this file appears as @cite{b_xxx.adb}. The
27943 elaboration order appears as a sequence of calls to @code{Elab_Body} and
27944 @code{Elab_Spec}, interspersed with assignments to @cite{Exxx} which indicates that a
27945 particular unit is elaborated. For example:
27947 @quotation
27949 @example
27950 System.Soft_Links'Elab_Body;
27951 E14 := True;
27952 System.Secondary_Stack'Elab_Body;
27953 E18 := True;
27954 System.Exception_Table'Elab_Body;
27955 E24 := True;
27956 Ada.Io_Exceptions'Elab_Spec;
27957 E67 := True;
27958 Ada.Tags'Elab_Spec;
27959 Ada.Streams'Elab_Spec;
27960 E43 := True;
27961 Interfaces.C'Elab_Spec;
27962 E69 := True;
27963 System.Finalization_Root'Elab_Spec;
27964 E60 := True;
27965 System.Os_Lib'Elab_Body;
27966 E71 := True;
27967 System.Finalization_Implementation'Elab_Spec;
27968 System.Finalization_Implementation'Elab_Body;
27969 E62 := True;
27970 Ada.Finalization'Elab_Spec;
27971 E58 := True;
27972 Ada.Finalization.List_Controller'Elab_Spec;
27973 E76 := True;
27974 System.File_Control_Block'Elab_Spec;
27975 E74 := True;
27976 System.File_Io'Elab_Body;
27977 E56 := True;
27978 Ada.Tags'Elab_Body;
27979 E45 := True;
27980 Ada.Text_Io'Elab_Spec;
27981 Ada.Text_Io'Elab_Body;
27982 E07 := True;
27983 @end example
27984 @end quotation
27986 Note also binder switch @code{-l}, which outputs the chosen elaboration
27987 order and provides a more readable form of the above:
27989 @quotation
27991 @example
27992 ada (spec)
27993 interfaces (spec)
27994 system (spec)
27995 system.case_util (spec)
27996 system.case_util (body)
27997 system.concat_2 (spec)
27998 system.concat_2 (body)
27999 system.concat_3 (spec)
28000 system.concat_3 (body)
28001 system.htable (spec)
28002 system.parameters (spec)
28003 system.parameters (body)
28004 system.crtl (spec)
28005 interfaces.c_streams (spec)
28006 interfaces.c_streams (body)
28007 system.restrictions (spec)
28008 system.restrictions (body)
28009 system.standard_library (spec)
28010 system.exceptions (spec)
28011 system.exceptions (body)
28012 system.storage_elements (spec)
28013 system.storage_elements (body)
28014 system.secondary_stack (spec)
28015 system.stack_checking (spec)
28016 system.stack_checking (body)
28017 system.string_hash (spec)
28018 system.string_hash (body)
28019 system.htable (body)
28020 system.strings (spec)
28021 system.strings (body)
28022 system.traceback (spec)
28023 system.traceback (body)
28024 system.traceback_entries (spec)
28025 system.traceback_entries (body)
28026 ada.exceptions (spec)
28027 ada.exceptions.last_chance_handler (spec)
28028 system.soft_links (spec)
28029 system.soft_links (body)
28030 ada.exceptions.last_chance_handler (body)
28031 system.secondary_stack (body)
28032 system.exception_table (spec)
28033 system.exception_table (body)
28034 ada.io_exceptions (spec)
28035 ada.tags (spec)
28036 ada.streams (spec)
28037 interfaces.c (spec)
28038 interfaces.c (body)
28039 system.finalization_root (spec)
28040 system.finalization_root (body)
28041 system.memory (spec)
28042 system.memory (body)
28043 system.standard_library (body)
28044 system.os_lib (spec)
28045 system.os_lib (body)
28046 system.unsigned_types (spec)
28047 system.stream_attributes (spec)
28048 system.stream_attributes (body)
28049 system.finalization_implementation (spec)
28050 system.finalization_implementation (body)
28051 ada.finalization (spec)
28052 ada.finalization (body)
28053 ada.finalization.list_controller (spec)
28054 ada.finalization.list_controller (body)
28055 system.file_control_block (spec)
28056 system.file_io (spec)
28057 system.file_io (body)
28058 system.val_uns (spec)
28059 system.val_util (spec)
28060 system.val_util (body)
28061 system.val_uns (body)
28062 system.wch_con (spec)
28063 system.wch_con (body)
28064 system.wch_cnv (spec)
28065 system.wch_jis (spec)
28066 system.wch_jis (body)
28067 system.wch_cnv (body)
28068 system.wch_stw (spec)
28069 system.wch_stw (body)
28070 ada.tags (body)
28071 ada.exceptions (body)
28072 ada.text_io (spec)
28073 ada.text_io (body)
28074 text_io (spec)
28075 gdbstr (body)
28076 @end example
28077 @end quotation
28079 @node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
28080 @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}
28081 @chapter Inline Assembler
28084 @geindex Inline Assembler
28086 If you need to write low-level software that interacts directly
28087 with the hardware, Ada provides two ways to incorporate assembly
28088 language code into your program.  First, you can import and invoke
28089 external routines written in assembly language, an Ada feature fully
28090 supported by GNAT.  However, for small sections of code it may be simpler
28091 or more efficient to include assembly language statements directly
28092 in your Ada source program, using the facilities of the implementation-defined
28093 package @code{System.Machine_Code}, which incorporates the gcc
28094 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
28095 including the following:
28098 @itemize *
28100 @item 
28101 No need to use non-Ada tools
28103 @item 
28104 Consistent interface over different targets
28106 @item 
28107 Automatic usage of the proper calling conventions
28109 @item 
28110 Access to Ada constants and variables
28112 @item 
28113 Definition of intrinsic routines
28115 @item 
28116 Possibility of inlining a subprogram comprising assembler code
28118 @item 
28119 Code optimizer can take Inline Assembler code into account
28120 @end itemize
28122 This appendix presents a series of examples to show you how to use
28123 the Inline Assembler.  Although it focuses on the Intel x86,
28124 the general approach applies also to other processors.
28125 It is assumed that you are familiar with Ada
28126 and with assembly language programming.
28128 @menu
28129 * Basic Assembler Syntax:: 
28130 * A Simple Example of Inline Assembler:: 
28131 * Output Variables in Inline Assembler:: 
28132 * Input Variables in Inline Assembler:: 
28133 * Inlining Inline Assembler Code:: 
28134 * Other Asm Functionality:: 
28136 @end menu
28138 @node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
28139 @anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{238}@anchor{gnat_ugn/inline_assembler id2}@anchor{239}
28140 @section Basic Assembler Syntax
28143 The assembler used by GNAT and gcc is based not on the Intel assembly
28144 language, but rather on a language that descends from the AT&T Unix
28145 assembler @code{as} (and which is often referred to as ‘AT&T syntax’).
28146 The following table summarizes the main features of @code{as} syntax
28147 and points out the differences from the Intel conventions.
28148 See the gcc @code{as} and @code{gas} (an @code{as} macro
28149 pre-processor) documentation for further information.
28152 @display
28153 `Register names'@w{ }
28154 @display
28155 gcc / @code{as}: Prefix with ‘%’; for example @code{%eax}@w{ }
28156 Intel: No extra punctuation; for example @code{eax}@w{ }
28157 @end display
28158 @end display
28163 @display
28164 `Immediate operand'@w{ }
28165 @display
28166 gcc / @code{as}: Prefix with ‘$’; for example @code{$4}@w{ }
28167 Intel: No extra punctuation; for example @code{4}@w{ }
28168 @end display
28169 @end display
28174 @display
28175 `Address'@w{ }
28176 @display
28177 gcc / @code{as}: Prefix with ‘$’; for example @code{$loc}@w{ }
28178 Intel: No extra punctuation; for example @code{loc}@w{ }
28179 @end display
28180 @end display
28185 @display
28186 `Memory contents'@w{ }
28187 @display
28188 gcc / @code{as}: No extra punctuation; for example @code{loc}@w{ }
28189 Intel: Square brackets; for example @code{[loc]}@w{ }
28190 @end display
28191 @end display
28196 @display
28197 `Register contents'@w{ }
28198 @display
28199 gcc / @code{as}: Parentheses; for example @code{(%eax)}@w{ }
28200 Intel: Square brackets; for example @code{[eax]}@w{ }
28201 @end display
28202 @end display
28207 @display
28208 `Hexadecimal numbers'@w{ }
28209 @display
28210 gcc / @code{as}: Leading ‘0x’ (C language syntax); for example @code{0xA0}@w{ }
28211 Intel: Trailing ‘h’; for example @code{A0h}@w{ }
28212 @end display
28213 @end display
28218 @display
28219 `Operand size'@w{ }
28220 @display
28221 gcc / @code{as}: Explicit in op code; for example @code{movw} to move a 16-bit word@w{ }
28222 Intel: Implicit, deduced by assembler; for example @code{mov}@w{ }
28223 @end display
28224 @end display
28229 @display
28230 `Instruction repetition'@w{ }
28231 @display
28232 gcc / @code{as}: Split into two lines; for example@w{ }
28233 @display
28234 @code{rep}@w{ }
28235 @code{stosl}@w{ }
28236 @end display
28237 Intel: Keep on one line; for example @code{rep stosl}@w{ }
28238 @end display
28239 @end display
28244 @display
28245 `Order of operands'@w{ }
28246 @display
28247 gcc / @code{as}: Source first; for example @code{movw $4, %eax}@w{ }
28248 Intel: Destination first; for example @code{mov eax, 4}@w{ }
28249 @end display
28250 @end display
28254 @node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
28255 @anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{23a}@anchor{gnat_ugn/inline_assembler id3}@anchor{23b}
28256 @section A Simple Example of Inline Assembler
28259 The following example will generate a single assembly language statement,
28260 @code{nop}, which does nothing.  Despite its lack of run-time effect,
28261 the example will be useful in illustrating the basics of
28262 the Inline Assembler facility.
28264 @quotation
28266 @example
28267 with System.Machine_Code; use System.Machine_Code;
28268 procedure Nothing is
28269 begin
28270    Asm ("nop");
28271 end Nothing;
28272 @end example
28273 @end quotation
28275 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
28276 here it takes one parameter, a `template string' that must be a static
28277 expression and that will form the generated instruction.
28278 @code{Asm} may be regarded as a compile-time procedure that parses
28279 the template string and additional parameters (none here),
28280 from which it generates a sequence of assembly language instructions.
28282 The examples in this chapter will illustrate several of the forms
28283 for invoking @code{Asm}; a complete specification of the syntax
28284 is found in the @code{Machine_Code_Insertions} section of the
28285 @cite{GNAT Reference Manual}.
28287 Under the standard GNAT conventions, the @code{Nothing} procedure
28288 should be in a file named @code{nothing.adb}.
28289 You can build the executable in the usual way:
28291 @quotation
28293 @example
28294 $ gnatmake nothing
28295 @end example
28296 @end quotation
28298 However, the interesting aspect of this example is not its run-time behavior
28299 but rather the generated assembly code.
28300 To see this output, invoke the compiler as follows:
28302 @quotation
28304 @example
28305 $ gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
28306 @end example
28307 @end quotation
28309 where the options are:
28312 @itemize *
28314 @item 
28316 @table @asis
28318 @item @code{-c}
28320 compile only (no bind or link)
28321 @end table
28323 @item 
28325 @table @asis
28327 @item @code{-S}
28329 generate assembler listing
28330 @end table
28332 @item 
28334 @table @asis
28336 @item @code{-fomit-frame-pointer}
28338 do not set up separate stack frames
28339 @end table
28341 @item 
28343 @table @asis
28345 @item @code{-gnatp}
28347 do not add runtime checks
28348 @end table
28349 @end itemize
28351 This gives a human-readable assembler version of the code. The resulting
28352 file will have the same name as the Ada source file, but with a @code{.s}
28353 extension. In our example, the file @code{nothing.s} has the following
28354 contents:
28356 @quotation
28358 @example
28359 .file "nothing.adb"
28360 gcc2_compiled.:
28361 ___gnu_compiled_ada:
28362 .text
28363    .align 4
28364 .globl __ada_nothing
28365 __ada_nothing:
28366 #APP
28367    nop
28368 #NO_APP
28369    jmp L1
28370    .align 2,0x90
28372    ret
28373 @end example
28374 @end quotation
28376 The assembly code you included is clearly indicated by
28377 the compiler, between the @code{#APP} and @code{#NO_APP}
28378 delimiters. The character before the ‘APP’ and ‘NOAPP’
28379 can differ on different targets. For example, GNU/Linux uses ‘#APP’ while
28380 on NT you will see ‘/APP’.
28382 If you make a mistake in your assembler code (such as using the
28383 wrong size modifier, or using a wrong operand for the instruction) GNAT
28384 will report this error in a temporary file, which will be deleted when
28385 the compilation is finished.  Generating an assembler file will help
28386 in such cases, since you can assemble this file separately using the
28387 @code{as} assembler that comes with gcc.
28389 Assembling the file using the command
28391 @quotation
28393 @example
28394 $ as nothing.s
28395 @end example
28396 @end quotation
28398 will give you error messages whose lines correspond to the assembler
28399 input file, so you can easily find and correct any mistakes you made.
28400 If there are no errors, @code{as} will generate an object file
28401 @code{nothing.out}.
28403 @node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
28404 @anchor{gnat_ugn/inline_assembler id4}@anchor{23c}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{23d}
28405 @section Output Variables in Inline Assembler
28408 The examples in this section, showing how to access the processor flags,
28409 illustrate how to specify the destination operands for assembly language
28410 statements.
28412 @quotation
28414 @example
28415 with Interfaces; use Interfaces;
28416 with Ada.Text_IO; use Ada.Text_IO;
28417 with System.Machine_Code; use System.Machine_Code;
28418 procedure Get_Flags is
28419    Flags : Unsigned_32;
28420    use ASCII;
28421 begin
28422    Asm ("pushfl"          & LF & HT & -- push flags on stack
28423         "popl %%eax"      & LF & HT & -- load eax with flags
28424         "movl %%eax, %0",             -- store flags in variable
28425         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28426    Put_Line ("Flags register:" & Flags'Img);
28427 end Get_Flags;
28428 @end example
28429 @end quotation
28431 In order to have a nicely aligned assembly listing, we have separated
28432 multiple assembler statements in the Asm template string with linefeed
28433 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28434 The resulting section of the assembly output file is:
28436 @quotation
28438 @example
28439 #APP
28440    pushfl
28441    popl %eax
28442    movl %eax, -40(%ebp)
28443 #NO_APP
28444 @end example
28445 @end quotation
28447 It would have been legal to write the Asm invocation as:
28449 @quotation
28451 @example
28452 Asm ("pushfl popl %%eax movl %%eax, %0")
28453 @end example
28454 @end quotation
28456 but in the generated assembler file, this would come out as:
28458 @quotation
28460 @example
28461 #APP
28462    pushfl popl %eax movl %eax, -40(%ebp)
28463 #NO_APP
28464 @end example
28465 @end quotation
28467 which is not so convenient for the human reader.
28469 We use Ada comments
28470 at the end of each line to explain what the assembler instructions
28471 actually do.  This is a useful convention.
28473 When writing Inline Assembler instructions, you need to precede each register
28474 and variable name with a percent sign.  Since the assembler already requires
28475 a percent sign at the beginning of a register name, you need two consecutive
28476 percent signs for such names in the Asm template string, thus @code{%%eax}.
28477 In the generated assembly code, one of the percent signs will be stripped off.
28479 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28480 variables: operands you later define using @code{Input} or @code{Output}
28481 parameters to @code{Asm}.
28482 An output variable is illustrated in
28483 the third statement in the Asm template string:
28485 @quotation
28487 @example
28488 movl %%eax, %0
28489 @end example
28490 @end quotation
28492 The intent is to store the contents of the eax register in a variable that can
28493 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
28494 necessarily work, since the compiler might optimize by using a register
28495 to hold Flags, and the expansion of the @code{movl} instruction would not be
28496 aware of this optimization.  The solution is not to store the result directly
28497 but rather to advise the compiler to choose the correct operand form;
28498 that is the purpose of the @code{%0} output variable.
28500 Information about the output variable is supplied in the @code{Outputs}
28501 parameter to @code{Asm}:
28503 @quotation
28505 @example
28506 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28507 @end example
28508 @end quotation
28510 The output is defined by the @code{Asm_Output} attribute of the target type;
28511 the general format is
28513 @quotation
28515 @example
28516 Type'Asm_Output (constraint_string, variable_name)
28517 @end example
28518 @end quotation
28520 The constraint string directs the compiler how
28521 to store/access the associated variable.  In the example
28523 @quotation
28525 @example
28526 Unsigned_32'Asm_Output ("=m", Flags);
28527 @end example
28528 @end quotation
28530 the @code{"m"} (memory) constraint tells the compiler that the variable
28531 @code{Flags} should be stored in a memory variable, thus preventing
28532 the optimizer from keeping it in a register.  In contrast,
28534 @quotation
28536 @example
28537 Unsigned_32'Asm_Output ("=r", Flags);
28538 @end example
28539 @end quotation
28541 uses the @code{"r"} (register) constraint, telling the compiler to
28542 store the variable in a register.
28544 If the constraint is preceded by the equal character ‘=’, it tells
28545 the compiler that the variable will be used to store data into it.
28547 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28548 allowing the optimizer to choose whatever it deems best.
28550 There are a fairly large number of constraints, but the ones that are
28551 most useful (for the Intel x86 processor) are the following:
28553 @quotation
28556 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
28557 @item
28561 @tab
28563 output constraint
28565 @item
28569 @tab
28571 global (i.e., can be stored anywhere)
28573 @item
28577 @tab
28579 in memory
28581 @item
28585 @tab
28587 a constant
28589 @item
28593 @tab
28595 use eax
28597 @item
28601 @tab
28603 use ebx
28605 @item
28609 @tab
28611 use ecx
28613 @item
28617 @tab
28619 use edx
28621 @item
28625 @tab
28627 use esi
28629 @item
28633 @tab
28635 use edi
28637 @item
28641 @tab
28643 use one of eax, ebx, ecx or edx
28645 @item
28649 @tab
28651 use one of eax, ebx, ecx, edx, esi or edi
28653 @end multitable
28655 @end quotation
28657 The full set of constraints is described in the gcc and @code{as}
28658 documentation; note that it is possible to combine certain constraints
28659 in one constraint string.
28661 You specify the association of an output variable with an assembler operand
28662 through the @code{%@var{n}} notation, where `n' is a non-negative
28663 integer.  Thus in
28665 @quotation
28667 @example
28668 Asm ("pushfl"          & LF & HT & -- push flags on stack
28669      "popl %%eax"      & LF & HT & -- load eax with flags
28670      "movl %%eax, %0",             -- store flags in variable
28671      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28672 @end example
28673 @end quotation
28675 @code{%0} will be replaced in the expanded code by the appropriate operand,
28676 whatever
28677 the compiler decided for the @code{Flags} variable.
28679 In general, you may have any number of output variables:
28682 @itemize *
28684 @item 
28685 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28687 @item 
28688 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28689 of @code{Asm_Output} attributes
28690 @end itemize
28692 For example:
28694 @quotation
28696 @example
28697 Asm ("movl %%eax, %0" & LF & HT &
28698      "movl %%ebx, %1" & LF & HT &
28699      "movl %%ecx, %2",
28700      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
28701                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
28702                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
28703 @end example
28704 @end quotation
28706 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28707 in the Ada program.
28709 As a variation on the @code{Get_Flags} example, we can use the constraints
28710 string to direct the compiler to store the eax register into the @code{Flags}
28711 variable, instead of including the store instruction explicitly in the
28712 @code{Asm} template string:
28714 @quotation
28716 @example
28717 with Interfaces; use Interfaces;
28718 with Ada.Text_IO; use Ada.Text_IO;
28719 with System.Machine_Code; use System.Machine_Code;
28720 procedure Get_Flags_2 is
28721    Flags : Unsigned_32;
28722    use ASCII;
28723 begin
28724    Asm ("pushfl"      & LF & HT & -- push flags on stack
28725         "popl %%eax",             -- save flags in eax
28726         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28727    Put_Line ("Flags register:" & Flags'Img);
28728 end Get_Flags_2;
28729 @end example
28730 @end quotation
28732 The @code{"a"} constraint tells the compiler that the @code{Flags}
28733 variable will come from the eax register. Here is the resulting code:
28735 @quotation
28737 @example
28738 #APP
28739    pushfl
28740    popl %eax
28741 #NO_APP
28742    movl %eax,-40(%ebp)
28743 @end example
28744 @end quotation
28746 The compiler generated the store of eax into Flags after
28747 expanding the assembler code.
28749 Actually, there was no need to pop the flags into the eax register;
28750 more simply, we could just pop the flags directly into the program variable:
28752 @quotation
28754 @example
28755 with Interfaces; use Interfaces;
28756 with Ada.Text_IO; use Ada.Text_IO;
28757 with System.Machine_Code; use System.Machine_Code;
28758 procedure Get_Flags_3 is
28759    Flags : Unsigned_32;
28760    use ASCII;
28761 begin
28762    Asm ("pushfl"  & LF & HT & -- push flags on stack
28763         "pop %0",             -- save flags in Flags
28764         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28765    Put_Line ("Flags register:" & Flags'Img);
28766 end Get_Flags_3;
28767 @end example
28768 @end quotation
28770 @node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
28771 @anchor{gnat_ugn/inline_assembler id5}@anchor{23e}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{23f}
28772 @section Input Variables in Inline Assembler
28775 The example in this section illustrates how to specify the source operands
28776 for assembly language statements.
28777 The program simply increments its input value by 1:
28779 @quotation
28781 @example
28782 with Interfaces; use Interfaces;
28783 with Ada.Text_IO; use Ada.Text_IO;
28784 with System.Machine_Code; use System.Machine_Code;
28785 procedure Increment is
28787    function Incr (Value : Unsigned_32) return Unsigned_32 is
28788       Result : Unsigned_32;
28789    begin
28790       Asm ("incl %0",
28791            Outputs => Unsigned_32'Asm_Output ("=a", Result),
28792            Inputs  => Unsigned_32'Asm_Input ("a", Value));
28793       return Result;
28794    end Incr;
28796    Value : Unsigned_32;
28798 begin
28799    Value := 5;
28800    Put_Line ("Value before is" & Value'Img);
28801    Value := Incr (Value);
28802   Put_Line ("Value after is" & Value'Img);
28803 end Increment;
28804 @end example
28805 @end quotation
28807 The @code{Outputs} parameter to @code{Asm} specifies
28808 that the result will be in the eax register and that it is to be stored
28809 in the @code{Result} variable.
28811 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28812 but with an @code{Asm_Input} attribute.
28813 The @code{"="} constraint, indicating an output value, is not present.
28815 You can have multiple input variables, in the same way that you can have more
28816 than one output variable.
28818 The parameter count (%0, %1) etc, still starts at the first output statement,
28819 and continues with the input statements.
28821 Just as the @code{Outputs} parameter causes the register to be stored into the
28822 target variable after execution of the assembler statements, so does the
28823 @code{Inputs} parameter cause its variable to be loaded into the register
28824 before execution of the assembler statements.
28826 Thus the effect of the @code{Asm} invocation is:
28829 @itemize *
28831 @item 
28832 load the 32-bit value of @code{Value} into eax
28834 @item 
28835 execute the @code{incl %eax} instruction
28837 @item 
28838 store the contents of eax into the @code{Result} variable
28839 @end itemize
28841 The resulting assembler file (with @code{-O2} optimization) contains:
28843 @quotation
28845 @example
28846 _increment__incr.1:
28847    subl $4,%esp
28848    movl 8(%esp),%eax
28849 #APP
28850    incl %eax
28851 #NO_APP
28852    movl %eax,%edx
28853    movl %ecx,(%esp)
28854    addl $4,%esp
28855    ret
28856 @end example
28857 @end quotation
28859 @node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
28860 @anchor{gnat_ugn/inline_assembler id6}@anchor{240}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{241}
28861 @section Inlining Inline Assembler Code
28864 For a short subprogram such as the @code{Incr} function in the previous
28865 section, the overhead of the call and return (creating / deleting the stack
28866 frame) can be significant, compared to the amount of code in the subprogram
28867 body.  A solution is to apply Ada’s @code{Inline} pragma to the subprogram,
28868 which directs the compiler to expand invocations of the subprogram at the
28869 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28870 Here is the resulting program:
28872 @quotation
28874 @example
28875 with Interfaces; use Interfaces;
28876 with Ada.Text_IO; use Ada.Text_IO;
28877 with System.Machine_Code; use System.Machine_Code;
28878 procedure Increment_2 is
28880    function Incr (Value : Unsigned_32) return Unsigned_32 is
28881       Result : Unsigned_32;
28882    begin
28883       Asm ("incl %0",
28884            Outputs => Unsigned_32'Asm_Output ("=a", Result),
28885            Inputs  => Unsigned_32'Asm_Input ("a", Value));
28886       return Result;
28887    end Incr;
28888    pragma Inline (Increment);
28890    Value : Unsigned_32;
28892 begin
28893    Value := 5;
28894    Put_Line ("Value before is" & Value'Img);
28895    Value := Increment (Value);
28896    Put_Line ("Value after is" & Value'Img);
28897 end Increment_2;
28898 @end example
28899 @end quotation
28901 Compile the program with both optimization (@code{-O2}) and inlining
28902 (@code{-gnatn}) enabled.
28904 The @code{Incr} function is still compiled as usual, but at the
28905 point in @code{Increment} where our function used to be called:
28907 @quotation
28909 @example
28910 pushl %edi
28911 call _increment__incr.1
28912 @end example
28913 @end quotation
28915 the code for the function body directly appears:
28917 @quotation
28919 @example
28920 movl %esi,%eax
28921 #APP
28922    incl %eax
28923 #NO_APP
28924    movl %eax,%edx
28925 @end example
28926 @end quotation
28928 thus saving the overhead of stack frame setup and an out-of-line call.
28930 @node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
28931 @anchor{gnat_ugn/inline_assembler id7}@anchor{242}@anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{243}
28932 @section Other @code{Asm} Functionality
28935 This section describes two important parameters to the @code{Asm}
28936 procedure: @code{Clobber}, which identifies register usage;
28937 and @code{Volatile}, which inhibits unwanted optimizations.
28939 @menu
28940 * The Clobber Parameter:: 
28941 * The Volatile Parameter:: 
28943 @end menu
28945 @node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
28946 @anchor{gnat_ugn/inline_assembler id8}@anchor{244}@anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{245}
28947 @subsection The @code{Clobber} Parameter
28950 One of the dangers of intermixing assembly language and a compiled language
28951 such as Ada is that the compiler needs to be aware of which registers are
28952 being used by the assembly code.  In some cases, such as the earlier examples,
28953 the constraint string is sufficient to indicate register usage (e.g.,
28954 @code{"a"} for
28955 the eax register).  But more generally, the compiler needs an explicit
28956 identification of the registers that are used by the Inline Assembly
28957 statements.
28959 Using a register that the compiler doesn’t know about
28960 could be a side effect of an instruction (like @code{mull}
28961 storing its result in both eax and edx).
28962 It can also arise from explicit register usage in your
28963 assembly code; for example:
28965 @quotation
28967 @example
28968 Asm ("movl %0, %%ebx" & LF & HT &
28969      "movl %%ebx, %1",
28970      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28971      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
28972 @end example
28973 @end quotation
28975 where the compiler (since it does not analyze the @code{Asm} template string)
28976 does not know you are using the ebx register.
28978 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28979 to identify the registers that will be used by your assembly code:
28981 @quotation
28983 @example
28984 Asm ("movl %0, %%ebx" & LF & HT &
28985      "movl %%ebx, %1",
28986      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28987      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
28988      Clobber => "ebx");
28989 @end example
28990 @end quotation
28992 The Clobber parameter is a static string expression specifying the
28993 register(s) you are using.  Note that register names are `not' prefixed
28994 by a percent sign. Also, if more than one register is used then their names
28995 are separated by commas; e.g., @code{"eax, ebx"}
28997 The @code{Clobber} parameter has several additional uses:
29000 @itemize *
29002 @item 
29003 Use ‘register’ name @code{cc} to indicate that flags might have changed
29005 @item 
29006 Use ‘register’ name @code{memory} if you changed a memory location
29007 @end itemize
29009 @node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
29010 @anchor{gnat_ugn/inline_assembler id9}@anchor{246}@anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{247}
29011 @subsection The @code{Volatile} Parameter
29014 @geindex Volatile parameter
29016 Compiler optimizations in the presence of Inline Assembler may sometimes have
29017 unwanted effects.  For example, when an @code{Asm} invocation with an input
29018 variable is inside a loop, the compiler might move the loading of the input
29019 variable outside the loop, regarding it as a one-time initialization.
29021 If this effect is not desired, you can disable such optimizations by setting
29022 the @code{Volatile} parameter to @code{True}; for example:
29024 @quotation
29026 @example
29027 Asm ("movl %0, %%ebx" & LF & HT &
29028      "movl %%ebx, %1",
29029      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
29030      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
29031      Clobber  => "ebx",
29032      Volatile => True);
29033 @end example
29034 @end quotation
29036 By default, @code{Volatile} is set to @code{False} unless there is no
29037 @code{Outputs} parameter.
29039 Although setting @code{Volatile} to @code{True} prevents unwanted
29040 optimizations, it will also disable other optimizations that might be
29041 important for efficiency. In general, you should set @code{Volatile}
29042 to @code{True} only if the compiler’s optimizations have created
29043 problems.
29045 @node GNU Free Documentation License,Index,Inline Assembler,Top
29046 @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}
29047 @chapter GNU Free Documentation License
29050 Version 1.3, 3 November 2008
29052 Copyright  2000, 2001, 2002, 2007, 2008  Free Software Foundation, Inc
29053 @indicateurl{https://fsf.org/}
29055 Everyone is permitted to copy and distribute verbatim copies of this
29056 license document, but changing it is not allowed.
29058 `Preamble'
29060 The purpose of this License is to make a manual, textbook, or other
29061 functional and useful document “free” in the sense of freedom: to
29062 assure everyone the effective freedom to copy and redistribute it,
29063 with or without modifying it, either commercially or noncommercially.
29064 Secondarily, this License preserves for the author and publisher a way
29065 to get credit for their work, while not being considered responsible
29066 for modifications made by others.
29068 This License is a kind of “copyleft”, which means that derivative
29069 works of the document must themselves be free in the same sense.  It
29070 complements the GNU General Public License, which is a copyleft
29071 license designed for free software.
29073 We have designed this License in order to use it for manuals for free
29074 software, because free software needs free documentation: a free
29075 program should come with manuals providing the same freedoms that the
29076 software does.  But this License is not limited to software manuals;
29077 it can be used for any textual work, regardless of subject matter or
29078 whether it is published as a printed book.  We recommend this License
29079 principally for works whose purpose is instruction or reference.
29081 `1. APPLICABILITY AND DEFINITIONS'
29083 This License applies to any manual or other work, in any medium, that
29084 contains a notice placed by the copyright holder saying it can be
29085 distributed under the terms of this License.  Such a notice grants a
29086 world-wide, royalty-free license, unlimited in duration, to use that
29087 work under the conditions stated herein.  The `Document', below,
29088 refers to any such manual or work.  Any member of the public is a
29089 licensee, and is addressed as “`you'”.  You accept the license if you
29090 copy, modify or distribute the work in a way requiring permission
29091 under copyright law.
29093 A “`Modified Version'” of the Document means any work containing the
29094 Document or a portion of it, either copied verbatim, or with
29095 modifications and/or translated into another language.
29097 A “`Secondary Section'” is a named appendix or a front-matter section of
29098 the Document that deals exclusively with the relationship of the
29099 publishers or authors of the Document to the Document’s overall subject
29100 (or to related matters) and contains nothing that could fall directly
29101 within that overall subject.  (Thus, if the Document is in part a
29102 textbook of mathematics, a Secondary Section may not explain any
29103 mathematics.)  The relationship could be a matter of historical
29104 connection with the subject or with related matters, or of legal,
29105 commercial, philosophical, ethical or political position regarding
29106 them.
29108 The “`Invariant Sections'” are certain Secondary Sections whose titles
29109 are designated, as being those of Invariant Sections, in the notice
29110 that says that the Document is released under this License.  If a
29111 section does not fit the above definition of Secondary then it is not
29112 allowed to be designated as Invariant.  The Document may contain zero
29113 Invariant Sections.  If the Document does not identify any Invariant
29114 Sections then there are none.
29116 The “`Cover Texts'” are certain short passages of text that are listed,
29117 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
29118 the Document is released under this License.  A Front-Cover Text may
29119 be at most 5 words, and a Back-Cover Text may be at most 25 words.
29121 A “`Transparent'” copy of the Document means a machine-readable copy,
29122 represented in a format whose specification is available to the
29123 general public, that is suitable for revising the document
29124 straightforwardly with generic text editors or (for images composed of
29125 pixels) generic paint programs or (for drawings) some widely available
29126 drawing editor, and that is suitable for input to text formatters or
29127 for automatic translation to a variety of formats suitable for input
29128 to text formatters.  A copy made in an otherwise Transparent file
29129 format whose markup, or absence of markup, has been arranged to thwart
29130 or discourage subsequent modification by readers is not Transparent.
29131 An image format is not Transparent if used for any substantial amount
29132 of text.  A copy that is not “Transparent” is called `Opaque'.
29134 Examples of suitable formats for Transparent copies include plain
29135 ASCII without markup, Texinfo input format, LaTeX input format, SGML
29136 or XML using a publicly available DTD, and standard-conforming simple
29137 HTML, PostScript or PDF designed for human modification.  Examples of
29138 transparent image formats include PNG, XCF and JPG.  Opaque formats
29139 include proprietary formats that can be read and edited only by
29140 proprietary word processors, SGML or XML for which the DTD and/or
29141 processing tools are not generally available, and the
29142 machine-generated HTML, PostScript or PDF produced by some word
29143 processors for output purposes only.
29145 The “`Title Page'” means, for a printed book, the title page itself,
29146 plus such following pages as are needed to hold, legibly, the material
29147 this License requires to appear in the title page.  For works in
29148 formats which do not have any title page as such, “Title Page” means
29149 the text near the most prominent appearance of the work’s title,
29150 preceding the beginning of the body of the text.
29152 The “`publisher'” means any person or entity that distributes
29153 copies of the Document to the public.
29155 A section “`Entitled XYZ'” means a named subunit of the Document whose
29156 title either is precisely XYZ or contains XYZ in parentheses following
29157 text that translates XYZ in another language.  (Here XYZ stands for a
29158 specific section name mentioned below, such as “`Acknowledgements'”,
29159 “`Dedications'”, “`Endorsements'”, or “`History'”.)
29160 To “`Preserve the Title'”
29161 of such a section when you modify the Document means that it remains a
29162 section “Entitled XYZ” according to this definition.
29164 The Document may include Warranty Disclaimers next to the notice which
29165 states that this License applies to the Document.  These Warranty
29166 Disclaimers are considered to be included by reference in this
29167 License, but only as regards disclaiming warranties: any other
29168 implication that these Warranty Disclaimers may have is void and has
29169 no effect on the meaning of this License.
29171 `2. VERBATIM COPYING'
29173 You may copy and distribute the Document in any medium, either
29174 commercially or noncommercially, provided that this License, the
29175 copyright notices, and the license notice saying this License applies
29176 to the Document are reproduced in all copies, and that you add no other
29177 conditions whatsoever to those of this License.  You may not use
29178 technical measures to obstruct or control the reading or further
29179 copying of the copies you make or distribute.  However, you may accept
29180 compensation in exchange for copies.  If you distribute a large enough
29181 number of copies you must also follow the conditions in section 3.
29183 You may also lend copies, under the same conditions stated above, and
29184 you may publicly display copies.
29186 `3. COPYING IN QUANTITY'
29188 If you publish printed copies (or copies in media that commonly have
29189 printed covers) of the Document, numbering more than 100, and the
29190 Document’s license notice requires Cover Texts, you must enclose the
29191 copies in covers that carry, clearly and legibly, all these Cover
29192 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
29193 the back cover.  Both covers must also clearly and legibly identify
29194 you as the publisher of these copies.  The front cover must present
29195 the full title with all words of the title equally prominent and
29196 visible.  You may add other material on the covers in addition.
29197 Copying with changes limited to the covers, as long as they preserve
29198 the title of the Document and satisfy these conditions, can be treated
29199 as verbatim copying in other respects.
29201 If the required texts for either cover are too voluminous to fit
29202 legibly, you should put the first ones listed (as many as fit
29203 reasonably) on the actual cover, and continue the rest onto adjacent
29204 pages.
29206 If you publish or distribute Opaque copies of the Document numbering
29207 more than 100, you must either include a machine-readable Transparent
29208 copy along with each Opaque copy, or state in or with each Opaque copy
29209 a computer-network location from which the general network-using
29210 public has access to download using public-standard network protocols
29211 a complete Transparent copy of the Document, free of added material.
29212 If you use the latter option, you must take reasonably prudent steps,
29213 when you begin distribution of Opaque copies in quantity, to ensure
29214 that this Transparent copy will remain thus accessible at the stated
29215 location until at least one year after the last time you distribute an
29216 Opaque copy (directly or through your agents or retailers) of that
29217 edition to the public.
29219 It is requested, but not required, that you contact the authors of the
29220 Document well before redistributing any large number of copies, to give
29221 them a chance to provide you with an updated version of the Document.
29223 `4. MODIFICATIONS'
29225 You may copy and distribute a Modified Version of the Document under
29226 the conditions of sections 2 and 3 above, provided that you release
29227 the Modified Version under precisely this License, with the Modified
29228 Version filling the role of the Document, thus licensing distribution
29229 and modification of the Modified Version to whoever possesses a copy
29230 of it.  In addition, you must do these things in the Modified Version:
29233 @enumerate A
29235 @item 
29236 Use in the Title Page (and on the covers, if any) a title distinct
29237 from that of the Document, and from those of previous versions
29238 (which should, if there were any, be listed in the History section
29239 of the Document).  You may use the same title as a previous version
29240 if the original publisher of that version gives permission.
29242 @item 
29243 List on the Title Page, as authors, one or more persons or entities
29244 responsible for authorship of the modifications in the Modified
29245 Version, together with at least five of the principal authors of the
29246 Document (all of its principal authors, if it has fewer than five),
29247 unless they release you from this requirement.
29249 @item 
29250 State on the Title page the name of the publisher of the
29251 Modified Version, as the publisher.
29253 @item 
29254 Preserve all the copyright notices of the Document.
29256 @item 
29257 Add an appropriate copyright notice for your modifications
29258 adjacent to the other copyright notices.
29260 @item 
29261 Include, immediately after the copyright notices, a license notice
29262 giving the public permission to use the Modified Version under the
29263 terms of this License, in the form shown in the Addendum below.
29265 @item 
29266 Preserve in that license notice the full lists of Invariant Sections
29267 and required Cover Texts given in the Document’s license notice.
29269 @item 
29270 Include an unaltered copy of this License.
29272 @item 
29273 Preserve the section Entitled “History”, Preserve its Title, and add
29274 to it an item stating at least the title, year, new authors, and
29275 publisher of the Modified Version as given on the Title Page.  If
29276 there is no section Entitled “History” in the Document, create one
29277 stating the title, year, authors, and publisher of the Document as
29278 given on its Title Page, then add an item describing the Modified
29279 Version as stated in the previous sentence.
29281 @item 
29282 Preserve the network location, if any, given in the Document for
29283 public access to a Transparent copy of the Document, and likewise
29284 the network locations given in the Document for previous versions
29285 it was based on.  These may be placed in the “History” section.
29286 You may omit a network location for a work that was published at
29287 least four years before the Document itself, or if the original
29288 publisher of the version it refers to gives permission.
29290 @item 
29291 For any section Entitled “Acknowledgements” or “Dedications”,
29292 Preserve the Title of the section, and preserve in the section all
29293 the substance and tone of each of the contributor acknowledgements
29294 and/or dedications given therein.
29296 @item 
29297 Preserve all the Invariant Sections of the Document,
29298 unaltered in their text and in their titles.  Section numbers
29299 or the equivalent are not considered part of the section titles.
29301 @item 
29302 Delete any section Entitled “Endorsements”.  Such a section
29303 may not be included in the Modified Version.
29305 @item 
29306 Do not retitle any existing section to be Entitled “Endorsements”
29307 or to conflict in title with any Invariant Section.
29309 @item 
29310 Preserve any Warranty Disclaimers.
29311 @end enumerate
29313 If the Modified Version includes new front-matter sections or
29314 appendices that qualify as Secondary Sections and contain no material
29315 copied from the Document, you may at your option designate some or all
29316 of these sections as invariant.  To do this, add their titles to the
29317 list of Invariant Sections in the Modified Version’s license notice.
29318 These titles must be distinct from any other section titles.
29320 You may add a section Entitled “Endorsements”, provided it contains
29321 nothing but endorsements of your Modified Version by various
29322 parties—for example, statements of peer review or that the text has
29323 been approved by an organization as the authoritative definition of a
29324 standard.
29326 You may add a passage of up to five words as a Front-Cover Text, and a
29327 passage of up to 25 words as a Back-Cover Text, to the end of the list
29328 of Cover Texts in the Modified Version.  Only one passage of
29329 Front-Cover Text and one of Back-Cover Text may be added by (or
29330 through arrangements made by) any one entity.  If the Document already
29331 includes a cover text for the same cover, previously added by you or
29332 by arrangement made by the same entity you are acting on behalf of,
29333 you may not add another; but you may replace the old one, on explicit
29334 permission from the previous publisher that added the old one.
29336 The author(s) and publisher(s) of the Document do not by this License
29337 give permission to use their names for publicity for or to assert or
29338 imply endorsement of any Modified Version.
29340 `5. COMBINING DOCUMENTS'
29342 You may combine the Document with other documents released under this
29343 License, under the terms defined in section 4 above for modified
29344 versions, provided that you include in the combination all of the
29345 Invariant Sections of all of the original documents, unmodified, and
29346 list them all as Invariant Sections of your combined work in its
29347 license notice, and that you preserve all their Warranty Disclaimers.
29349 The combined work need only contain one copy of this License, and
29350 multiple identical Invariant Sections may be replaced with a single
29351 copy.  If there are multiple Invariant Sections with the same name but
29352 different contents, make the title of each such section unique by
29353 adding at the end of it, in parentheses, the name of the original
29354 author or publisher of that section if known, or else a unique number.
29355 Make the same adjustment to the section titles in the list of
29356 Invariant Sections in the license notice of the combined work.
29358 In the combination, you must combine any sections Entitled “History”
29359 in the various original documents, forming one section Entitled
29360 “History”; likewise combine any sections Entitled “Acknowledgements”,
29361 and any sections Entitled “Dedications”.  You must delete all sections
29362 Entitled “Endorsements”.
29364 `6. COLLECTIONS OF DOCUMENTS'
29366 You may make a collection consisting of the Document and other documents
29367 released under this License, and replace the individual copies of this
29368 License in the various documents with a single copy that is included in
29369 the collection, provided that you follow the rules of this License for
29370 verbatim copying of each of the documents in all other respects.
29372 You may extract a single document from such a collection, and distribute
29373 it individually under this License, provided you insert a copy of this
29374 License into the extracted document, and follow this License in all
29375 other respects regarding verbatim copying of that document.
29377 `7. AGGREGATION WITH INDEPENDENT WORKS'
29379 A compilation of the Document or its derivatives with other separate
29380 and independent documents or works, in or on a volume of a storage or
29381 distribution medium, is called an “aggregate” if the copyright
29382 resulting from the compilation is not used to limit the legal rights
29383 of the compilation’s users beyond what the individual works permit.
29384 When the Document is included in an aggregate, this License does not
29385 apply to the other works in the aggregate which are not themselves
29386 derivative works of the Document.
29388 If the Cover Text requirement of section 3 is applicable to these
29389 copies of the Document, then if the Document is less than one half of
29390 the entire aggregate, the Document’s Cover Texts may be placed on
29391 covers that bracket the Document within the aggregate, or the
29392 electronic equivalent of covers if the Document is in electronic form.
29393 Otherwise they must appear on printed covers that bracket the whole
29394 aggregate.
29396 `8. TRANSLATION'
29398 Translation is considered a kind of modification, so you may
29399 distribute translations of the Document under the terms of section 4.
29400 Replacing Invariant Sections with translations requires special
29401 permission from their copyright holders, but you may include
29402 translations of some or all Invariant Sections in addition to the
29403 original versions of these Invariant Sections.  You may include a
29404 translation of this License, and all the license notices in the
29405 Document, and any Warranty Disclaimers, provided that you also include
29406 the original English version of this License and the original versions
29407 of those notices and disclaimers.  In case of a disagreement between
29408 the translation and the original version of this License or a notice
29409 or disclaimer, the original version will prevail.
29411 If a section in the Document is Entitled “Acknowledgements”,
29412 “Dedications”, or “History”, the requirement (section 4) to Preserve
29413 its Title (section 1) will typically require changing the actual
29414 title.
29416 `9. TERMINATION'
29418 You may not copy, modify, sublicense, or distribute the Document
29419 except as expressly provided under this License.  Any attempt
29420 otherwise to copy, modify, sublicense, or distribute it is void, and
29421 will automatically terminate your rights under this License.
29423 However, if you cease all violation of this License, then your license
29424 from a particular copyright holder is reinstated (a) provisionally,
29425 unless and until the copyright holder explicitly and finally
29426 terminates your license, and (b) permanently, if the copyright holder
29427 fails to notify you of the violation by some reasonable means prior to
29428 60 days after the cessation.
29430 Moreover, your license from a particular copyright holder is
29431 reinstated permanently if the copyright holder notifies you of the
29432 violation by some reasonable means, this is the first time you have
29433 received notice of violation of this License (for any work) from that
29434 copyright holder, and you cure the violation prior to 30 days after
29435 your receipt of the notice.
29437 Termination of your rights under this section does not terminate the
29438 licenses of parties who have received copies or rights from you under
29439 this License.  If your rights have been terminated and not permanently
29440 reinstated, receipt of a copy of some or all of the same material does
29441 not give you any rights to use it.
29443 `10. FUTURE REVISIONS OF THIS LICENSE'
29445 The Free Software Foundation may publish new, revised versions
29446 of the GNU Free Documentation License from time to time.  Such new
29447 versions will be similar in spirit to the present version, but may
29448 differ in detail to address new problems or concerns.  See
29449 @indicateurl{https://www.gnu.org/copyleft/}.
29451 Each version of the License is given a distinguishing version number.
29452 If the Document specifies that a particular numbered version of this
29453 License “or any later version” applies to it, you have the option of
29454 following the terms and conditions either of that specified version or
29455 of any later version that has been published (not as a draft) by the
29456 Free Software Foundation.  If the Document does not specify a version
29457 number of this License, you may choose any version ever published (not
29458 as a draft) by the Free Software Foundation.  If the Document
29459 specifies that a proxy can decide which future versions of this
29460 License can be used, that proxy’s public statement of acceptance of a
29461 version permanently authorizes you to choose that version for the
29462 Document.
29464 `11. RELICENSING'
29466 “Massive Multiauthor Collaboration Site” (or “MMC Site”) means any
29467 World Wide Web server that publishes copyrightable works and also
29468 provides prominent facilities for anybody to edit those works.  A
29469 public wiki that anybody can edit is an example of such a server.  A
29470 “Massive Multiauthor Collaboration” (or “MMC”) contained in the
29471 site means any set of copyrightable works thus published on the MMC
29472 site.
29474 “CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0
29475 license published by Creative Commons Corporation, a not-for-profit
29476 corporation with a principal place of business in San Francisco,
29477 California, as well as future copyleft versions of that license
29478 published by that same organization.
29480 “Incorporate” means to publish or republish a Document, in whole or
29481 in part, as part of another Document.
29483 An MMC is “eligible for relicensing” if it is licensed under this
29484 License, and if all works that were first published under this License
29485 somewhere other than this MMC, and subsequently incorporated in whole
29486 or in part into the MMC, (1) had no cover texts or invariant sections,
29487 and (2) were thus incorporated prior to November 1, 2008.
29489 The operator of an MMC Site may republish an MMC contained in the site
29490 under CC-BY-SA on the same site at any time before August 1, 2009,
29491 provided the MMC is eligible for relicensing.
29493 `ADDENDUM: How to use this License for your documents'
29495 To use this License in a document you have written, include a copy of
29496 the License in the document and put the following copyright and
29497 license notices just after the title page:
29499 @quotation
29501 Copyright © YEAR  YOUR NAME.
29502 Permission is granted to copy, distribute and/or modify this document
29503 under the terms of the GNU Free Documentation License, Version 1.3
29504 or any later version published by the Free Software Foundation;
29505 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
29506 A copy of the license is included in the section entitled “GNU
29507 Free Documentation License”.
29508 @end quotation
29510 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
29511 replace the “with … Texts.” line with this:
29513 @quotation
29515 with the Invariant Sections being LIST THEIR TITLES, with the
29516 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
29517 @end quotation
29519 If you have Invariant Sections without Cover Texts, or some other
29520 combination of the three, merge those two alternatives to suit the
29521 situation.
29523 If your document contains nontrivial examples of program code, we
29524 recommend releasing these examples in parallel under your choice of
29525 free software license, such as the GNU General Public License,
29526 to permit their use in free software.
29528 @node Index,,GNU Free Documentation License,Top
29529 @unnumbered Index
29532 @printindex ge
29534 @anchor{d1}@w{                              }
29535 @anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{                              }
29537 @c %**end of body
29538 @bye