libstdc++: Qualify calls in <bits/stl_uninitialized.h> to prevent ADL
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob135a4e13e783154b130703fe31df6ed7bc5d8476
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3 @setfilename gnat_ugn.info
4 @documentencoding UTF-8
5 @ifinfo
6 @*Generated by Sphinx 5.3.0.@*
7 @end ifinfo
8 @settitle GNAT User's Guide for Native Platforms
9 @defindex ge
10 @paragraphindent 0
11 @exampleindent 4
12 @finalout
13 @dircategory GNU Ada Tools 
14 @direntry
15 * gnat_ugn: (gnat_ugn.info). gnat_ugn
16 @end direntry
18 @c %**end of header
20 @copying
21 @quotation
22 GNAT User's Guide for Native Platforms , Jun 14, 2024
24 AdaCore
26 Copyright @copyright{} 2008-2024, Free Software Foundation
27 @end quotation
29 @end copying
31 @titlepage
32 @title GNAT User's Guide for Native Platforms
33 @insertcopying
34 @end titlepage
35 @contents
37 @c %** start of user preamble
39 @c %** end of user preamble
41 @ifnottex
42 @node Top
43 @top GNAT User's Guide for Native Platforms
44 @insertcopying
45 @end ifnottex
47 @c %**start of body
48 @anchor{gnat_ugn doc}@anchor{0}
49 `GNAT, The GNU Ada Development Environment'
52 @include gcc-common.texi
53 GCC version @value{version-GCC}@*
54 AdaCore
56 Permission is granted to copy, distribute and/or modify this document
57 under the terms of the GNU Free Documentation License, Version 1.3 or
58 any later version published by the Free Software Foundation; with no
59 Invariant Sections, with the Front-Cover Texts being
60 “GNAT User’s Guide for Native Platforms”,
61 and with no Back-Cover Texts.  A copy of the license is
62 included in the section entitled @ref{1,,GNU Free Documentation License}.
64 @menu
65 * About This Guide:: 
66 * Getting Started with GNAT:: 
67 * The GNAT Compilation Model:: 
68 * Building Executable Programs with GNAT:: 
69 * GNAT Utility Programs:: 
70 * GNAT and Program Execution:: 
71 * Platform-Specific Information:: 
72 * Example of Binder Output File:: 
73 * Elaboration Order Handling in GNAT:: 
74 * Inline Assembler:: 
75 * GNU Free Documentation License:: 
76 * Index:: 
78 @detailmenu
79  --- The Detailed Node Listing ---
81 About This Guide
83 * What This Guide Contains:: 
84 * What You Should Know before Reading This Guide:: 
85 * Related Information:: 
86 * Conventions:: 
88 Getting Started with GNAT
90 * System Requirements:: 
91 * Running GNAT:: 
92 * Running a Simple Ada Program:: 
93 * Running a Program with Multiple Units:: 
95 The GNAT Compilation Model
97 * Source Representation:: 
98 * Foreign Language Representation:: 
99 * File Naming Topics and Utilities:: 
100 * Configuration Pragmas:: 
101 * Generating Object Files:: 
102 * Source Dependencies:: 
103 * The Ada Library Information Files:: 
104 * Binding an Ada Program:: 
105 * GNAT and Libraries:: 
106 * Conditional Compilation:: 
107 * Mixed Language Programming:: 
108 * GNAT and Other Compilation Models:: 
109 * Using GNAT Files with External Tools:: 
111 Foreign Language Representation
113 * Latin-1:: 
114 * Other 8-Bit Codes:: 
115 * Wide_Character Encodings:: 
116 * Wide_Wide_Character Encodings:: 
118 File Naming Topics and Utilities
120 * File Naming Rules:: 
121 * Using Other File Names:: 
122 * Alternative File Naming Schemes:: 
123 * Handling Arbitrary File Naming Conventions with gnatname:: 
124 * File Name Krunching with gnatkr:: 
125 * Renaming Files with gnatchop:: 
127 Handling Arbitrary File Naming Conventions with gnatname
129 * Arbitrary File Naming Conventions:: 
130 * Running gnatname:: 
131 * Switches for gnatname:: 
132 * Examples of gnatname Usage:: 
134 File Name Krunching with gnatkr
136 * About gnatkr:: 
137 * Using gnatkr:: 
138 * Krunching Method:: 
139 * Examples of gnatkr Usage:: 
141 Renaming Files with gnatchop
143 * Handling Files with Multiple Units:: 
144 * Operating gnatchop in Compilation Mode:: 
145 * Command Line for gnatchop:: 
146 * Switches for gnatchop:: 
147 * Examples of gnatchop Usage:: 
149 Configuration Pragmas
151 * Handling of Configuration Pragmas:: 
152 * The Configuration Pragmas Files:: 
154 GNAT and Libraries
156 * Introduction to Libraries in GNAT:: 
157 * General Ada Libraries:: 
158 * Stand-alone Ada Libraries:: 
159 * Rebuilding the GNAT Run-Time Library:: 
161 General Ada Libraries
163 * Building a library:: 
164 * Installing a library:: 
165 * Using a library:: 
167 Stand-alone Ada Libraries
169 * Introduction to Stand-alone Libraries:: 
170 * Building a Stand-alone Library:: 
171 * Creating a Stand-alone Library to be used in a non-Ada context:: 
172 * Restrictions in Stand-alone Libraries:: 
174 Conditional Compilation
176 * Modeling Conditional Compilation in Ada:: 
177 * Preprocessing with gnatprep:: 
178 * Integrated Preprocessing:: 
180 Modeling Conditional Compilation in Ada
182 * Use of Boolean Constants:: 
183 * Debugging - A Special Case:: 
184 * Conditionalizing Declarations:: 
185 * Use of Alternative Implementations:: 
186 * Preprocessing:: 
188 Preprocessing with gnatprep
190 * Preprocessing Symbols:: 
191 * Using gnatprep:: 
192 * Switches for gnatprep:: 
193 * Form of Definitions File:: 
194 * Form of Input Text for gnatprep:: 
196 Mixed Language Programming
198 * Interfacing to C:: 
199 * Calling Conventions:: 
200 * Building Mixed Ada and C++ Programs:: 
201 * Partition-Wide Settings:: 
202 * Generating Ada Bindings for C and C++ headers:: 
203 * Generating C Headers for Ada Specifications:: 
205 Building Mixed Ada and C++ Programs
207 * Interfacing to C++:: 
208 * Linking a Mixed C++ & Ada Program:: 
209 * A Simple Example:: 
210 * Interfacing with C++ constructors:: 
211 * Interfacing with C++ at the Class Level:: 
213 Generating Ada Bindings for C and C++ headers
215 * Running the Binding Generator:: 
216 * Generating Bindings for C++ Headers:: 
217 * Switches:: 
219 Generating C Headers for Ada Specifications
221 * Running the C Header Generator:: 
223 GNAT and Other Compilation Models
225 * Comparison between GNAT and C/C++ Compilation Models:: 
226 * Comparison between GNAT and Conventional Ada Library Models:: 
228 Using GNAT Files with External Tools
230 * Using Other Utility Programs with GNAT:: 
231 * The External Symbol Naming Scheme of GNAT:: 
233 Building Executable Programs with GNAT
235 * Building with gnatmake:: 
236 * Compiling with gcc:: 
237 * Compiler Switches:: 
238 * Linker Switches:: 
239 * Binding with gnatbind:: 
240 * Linking with gnatlink:: 
241 * Using the GNU make Utility:: 
243 Building with gnatmake
245 * Running gnatmake:: 
246 * Switches for gnatmake:: 
247 * Mode Switches for gnatmake:: 
248 * Notes on the Command Line:: 
249 * How gnatmake Works:: 
250 * Examples of gnatmake Usage:: 
252 Compiling with gcc
254 * Compiling Programs:: 
255 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
256 * Order of Compilation Issues:: 
257 * Examples:: 
259 Compiler Switches
261 * Alphabetical List of All Switches:: 
262 * Output and Error Message Control:: 
263 * Warning Message Control:: 
264 * Info message Control:: 
265 * Debugging and Assertion Control:: 
266 * Validity Checking:: 
267 * Style Checking:: 
268 * Run-Time Checks:: 
269 * Using gcc for Syntax Checking:: 
270 * Using gcc for Semantic Checking:: 
271 * Compiling Different Versions of Ada:: 
272 * Character Set Control:: 
273 * File Naming Control:: 
274 * Subprogram Inlining Control:: 
275 * Auxiliary Output Control:: 
276 * Debugging Control:: 
277 * Exception Handling Control:: 
278 * Units to Sources Mapping Files:: 
279 * Code Generation Control:: 
281 Binding with gnatbind
283 * Running gnatbind:: 
284 * Switches for gnatbind:: 
285 * Command-Line Access:: 
286 * Search Paths for gnatbind:: 
287 * Examples of gnatbind Usage:: 
289 Switches for gnatbind
291 * Consistency-Checking Modes:: 
292 * Binder Error Message Control:: 
293 * Elaboration Control:: 
294 * Output Control:: 
295 * Dynamic Allocation Control:: 
296 * Binding with Non-Ada Main Programs:: 
297 * Binding Programs with No Main Subprogram:: 
299 Linking with gnatlink
301 * Running gnatlink:: 
302 * Switches for gnatlink:: 
304 Using the GNU make Utility
306 * Using gnatmake in a Makefile:: 
307 * Automatically Creating a List of Directories:: 
308 * Generating the Command Line Switches:: 
309 * Overcoming Command Line Length Limits:: 
311 GNAT Utility Programs
313 * The File Cleanup Utility gnatclean:: 
314 * The GNAT Library Browser gnatls:: 
316 The File Cleanup Utility gnatclean
318 * Running gnatclean:: 
319 * Switches for gnatclean:: 
321 The GNAT Library Browser gnatls
323 * Running gnatls:: 
324 * Switches for gnatls:: 
325 * Example of gnatls Usage:: 
327 GNAT and Program Execution
329 * Running and Debugging Ada Programs:: 
330 * Profiling:: 
331 * Improving Performance:: 
332 * Overflow Check Handling in GNAT:: 
333 * Performing Dimensionality Analysis in GNAT:: 
334 * Stack Related Facilities:: 
335 * Memory Management Issues:: 
337 Running and Debugging Ada Programs
339 * The GNAT Debugger GDB:: 
340 * Running GDB:: 
341 * Introduction to GDB Commands:: 
342 * Using Ada Expressions:: 
343 * Calling User-Defined Subprograms:: 
344 * Using the next Command in a Function:: 
345 * Stopping When Ada Exceptions Are Raised:: 
346 * Ada Tasks:: 
347 * Debugging Generic Units:: 
348 * Remote Debugging with gdbserver:: 
349 * GNAT Abnormal Termination or Failure to Terminate:: 
350 * Naming Conventions for GNAT Source Files:: 
351 * Getting Internal Debugging Information:: 
352 * Stack Traceback:: 
353 * Pretty-Printers for the GNAT runtime:: 
355 Stack Traceback
357 * Non-Symbolic Traceback:: 
358 * Symbolic Traceback:: 
360 Profiling
362 * Profiling an Ada Program with gprof:: 
364 Profiling an Ada Program with gprof
366 * Compilation for profiling:: 
367 * Program execution:: 
368 * Running gprof:: 
369 * Interpretation of profiling results:: 
371 Improving Performance
373 * Performance Considerations:: 
374 * Text_IO Suggestions:: 
375 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
377 Performance Considerations
379 * Controlling Run-Time Checks:: 
380 * Use of Restrictions:: 
381 * Optimization Levels:: 
382 * Debugging Optimized Code:: 
383 * Inlining of Subprograms:: 
384 * Floating Point Operations:: 
385 * Vectorization of loops:: 
386 * Other Optimization Switches:: 
387 * Optimization and Strict Aliasing:: 
388 * Aliased Variables and Optimization:: 
389 * Atomic Variables and Optimization:: 
390 * Passive Task Optimization:: 
392 Reducing Size of Executables with Unused Subprogram/Data Elimination
394 * About unused subprogram/data elimination:: 
395 * Compilation options:: 
396 * Example of unused subprogram/data elimination:: 
398 Overflow Check Handling in GNAT
400 * Background:: 
401 * Management of Overflows in GNAT:: 
402 * Specifying the Desired Mode:: 
403 * Default Settings:: 
404 * Implementation Notes:: 
406 Stack Related Facilities
408 * Stack Overflow Checking:: 
409 * Static Stack Usage Analysis:: 
410 * Dynamic Stack Usage Analysis:: 
412 Memory Management Issues
414 * Some Useful Memory Pools:: 
415 * The GNAT Debug Pool Facility:: 
417 Platform-Specific Information
419 * Run-Time Libraries:: 
420 * Specifying a Run-Time Library:: 
421 * GNU/Linux Topics:: 
422 * Microsoft Windows Topics:: 
423 * Mac OS Topics:: 
425 Run-Time Libraries
427 * Summary of Run-Time Configurations:: 
429 GNU/Linux Topics
431 * Required Packages on GNU/Linux:: 
432 * Position Independent Executable (PIE) Enabled by Default on Linux: Position Independent Executable PIE Enabled by Default on Linux. 
433 * Choosing the Scheduling Policy with GNU/Linux:: 
434 * A GNU/Linux Debug Quirk:: 
436 Microsoft Windows Topics
438 * Using GNAT on Windows:: 
439 * Using a network installation of GNAT:: 
440 * CONSOLE and WINDOWS subsystems:: 
441 * Temporary Files:: 
442 * Disabling Command Line Argument Expansion:: 
443 * Choosing the Scheduling Policy with Windows:: 
444 * Windows Socket Timeouts:: 
445 * Mixed-Language Programming on Windows:: 
446 * Windows Specific Add-Ons:: 
448 Mixed-Language Programming on Windows
450 * Windows Calling Conventions:: 
451 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
452 * Using DLLs with GNAT:: 
453 * Building DLLs with GNAT Project files:: 
454 * Building DLLs with GNAT:: 
455 * Building DLLs with gnatdll:: 
456 * Ada DLLs and Finalization:: 
457 * Creating a Spec for Ada DLLs:: 
458 * GNAT and Windows Resources:: 
459 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
460 * Debugging a DLL:: 
461 * Setting Stack Size from gnatlink:: 
462 * Setting Heap Size from gnatlink:: 
464 Windows Calling Conventions
466 * C Calling Convention:: 
467 * Stdcall Calling Convention:: 
468 * Win32 Calling Convention:: 
469 * DLL Calling Convention:: 
471 Using DLLs with GNAT
473 * Creating an Ada Spec for the DLL Services:: 
474 * Creating an Import Library:: 
476 Building DLLs with gnatdll
478 * Limitations When Using Ada DLLs from Ada:: 
479 * Exporting Ada Entities:: 
480 * Ada DLLs and Elaboration:: 
482 Creating a Spec for Ada DLLs
484 * Creating the Definition File:: 
485 * Using gnatdll:: 
487 GNAT and Windows Resources
489 * Building Resources:: 
490 * Compiling Resources:: 
491 * Using Resources:: 
493 Debugging a DLL
495 * Program and DLL Both Built with GCC/GNAT:: 
496 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
498 Windows Specific Add-Ons
500 * Win32Ada:: 
501 * wPOSIX:: 
503 Mac OS Topics
505 * Codesigning the Debugger:: 
507 Elaboration Order Handling in GNAT
509 * Elaboration Code:: 
510 * Elaboration Order:: 
511 * Checking the Elaboration Order:: 
512 * Controlling the Elaboration Order in Ada:: 
513 * Controlling the Elaboration Order in GNAT:: 
514 * Mixing Elaboration Models:: 
515 * ABE Diagnostics:: 
516 * SPARK Diagnostics:: 
517 * Elaboration Circularities:: 
518 * Resolving Elaboration Circularities:: 
519 * Elaboration-related Compiler Switches:: 
520 * Summary of Procedures for Elaboration Control:: 
521 * Inspecting the Chosen Elaboration Order:: 
523 Inline Assembler
525 * Basic Assembler Syntax:: 
526 * A Simple Example of Inline Assembler:: 
527 * Output Variables in Inline Assembler:: 
528 * Input Variables in Inline Assembler:: 
529 * Inlining Inline Assembler Code:: 
530 * Other Asm Functionality:: 
532 Other Asm Functionality
534 * The Clobber Parameter:: 
535 * The Volatile Parameter:: 
537 @end detailmenu
538 @end menu
540 @node About This Guide,Getting Started with GNAT,Top,Top
541 @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}
542 @chapter About This Guide
546 This guide describes the use of GNAT,
547 a compiler and software development
548 toolset for the full Ada programming language.
549 It documents the features of the compiler and tools, and explains
550 how to use them to build Ada applications.
552 GNAT implements Ada 95, Ada 2005, Ada 2012, and Ada 202x, and it may also be
553 invoked in Ada 83 compatibility mode.
554 By default, GNAT assumes Ada 2012, but you can override with a
555 compiler switch (@ref{6,,Compiling Different Versions of Ada})
556 to explicitly specify the language version.
557 Throughout this manual, references to ‘Ada’ without a year suffix
558 apply to all Ada versions of the language, starting with Ada 95.
560 @menu
561 * What This Guide Contains:: 
562 * What You Should Know before Reading This Guide:: 
563 * Related Information:: 
564 * Conventions:: 
566 @end menu
568 @node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
569 @anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
570 @section What This Guide Contains
573 This guide contains the following chapters:
576 @itemize *
578 @item 
579 @ref{8,,Getting Started with GNAT} describes how to get started compiling
580 and running Ada programs with the GNAT Ada programming environment.
582 @item 
583 @ref{9,,The GNAT Compilation Model} describes the compilation model used
584 by GNAT.
586 @item 
587 @ref{a,,Building Executable Programs with GNAT} describes how to use the
588 main GNAT tools to build executable programs, and it also gives examples of
589 using the GNU make utility with GNAT.
591 @item 
592 @ref{b,,GNAT Utility Programs} explains the various utility programs that
593 are included in the GNAT environment.
595 @item 
596 @ref{c,,GNAT and Program Execution} covers a number of topics related to
597 running, debugging, and tuning the performance of programs developed
598 with GNAT.
599 @end itemize
601 Appendices cover several additional topics:
604 @itemize *
606 @item 
607 @ref{d,,Platform-Specific Information} describes the different run-time
608 library implementations and also presents information on how to use
609 GNAT on several specific platforms.
611 @item 
612 @ref{e,,Example of Binder Output File} shows the source code for the binder
613 output file for a sample program.
615 @item 
616 @ref{f,,Elaboration Order Handling in GNAT} describes how GNAT helps
617 you deal with elaboration order issues.
619 @item 
620 @ref{10,,Inline Assembler} shows how to use the inline assembly facility
621 in an Ada program.
622 @end itemize
624 @node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
625 @anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{11}
626 @section What You Should Know before Reading This Guide
629 @geindex Ada 95 Language Reference Manual
631 @geindex Ada 2005 Language Reference Manual
633 This guide assumes a basic familiarity with the Ada 95 language, as
634 described in the International Standard ANSI/ISO/IEC-8652:1995, January
635 1995.
636 Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
637 the GNAT documentation package.
639 @node Related Information,Conventions,What You Should Know before Reading This Guide,About This Guide
640 @anchor{gnat_ugn/about_this_guide related-information}@anchor{12}
641 @section Related Information
644 For further information about Ada and related tools, please refer to the
645 following documents:
648 @itemize *
650 @item 
651 @cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
652 @cite{Ada 2012 Reference Manual}, which contain reference
653 material for the several revisions of the Ada language standard.
655 @item 
656 @cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
657 implementation of Ada.
659 @item 
660 @cite{Using GNAT Studio}, which describes the GNAT Studio
661 Integrated Development Environment.
663 @item 
664 @cite{GNAT Studio Tutorial}, which introduces the
665 main GNAT Studio features through examples.
667 @item 
668 @cite{Debugging with GDB},
669 for all details on the use of the GNU source-level debugger.
671 @item 
672 @cite{GNU Emacs Manual},
673 for full information on the extensible editor and programming
674 environment Emacs.
675 @end itemize
677 @node Conventions,,Related Information,About This Guide
678 @anchor{gnat_ugn/about_this_guide conventions}@anchor{13}
679 @section Conventions
682 @geindex Conventions
683 @geindex typographical
685 @geindex Typographical conventions
687 Following are examples of the typographical and graphic conventions used
688 in this guide:
691 @itemize *
693 @item 
694 @code{Functions}, @code{utility program names}, @code{standard names},
695 and @code{classes}.
697 @item 
698 @code{Option flags}
700 @item 
701 @code{File names}
703 @item 
704 @code{Variables}
706 @item 
707 `Emphasis'
709 @item 
710 [optional information or parameters]
712 @item 
713 Examples are described by text
715 @example
716 and then shown this way.
717 @end example
719 @item 
720 Commands that are entered by the user are shown as preceded by a prompt string
721 comprising the @code{$} character followed by a space.
723 @item 
724 Full file names are shown with the ‘/’ character
725 as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
726 If you are using GNAT on a Windows platform, please note that
727 the ‘\’ character should be used instead.
728 @end itemize
730 @node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
731 @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}
732 @chapter Getting Started with GNAT
735 This chapter describes how to use GNAT’s command line interface to build
736 executable Ada programs.
737 On most platforms a visually oriented Integrated Development Environment
738 is also available: GNAT Studio.
739 GNAT Studio offers a graphical “look and feel”, support for development in
740 other programming languages, comprehensive browsing features, and
741 many other capabilities.
742 For information on GNAT Studio please refer to the
743 @cite{GNAT Studio documentation}.
745 @menu
746 * System Requirements:: 
747 * Running GNAT:: 
748 * Running a Simple Ada Program:: 
749 * Running a Program with Multiple Units:: 
751 @end menu
753 @node System Requirements,Running GNAT,,Getting Started with GNAT
754 @anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{16}@anchor{gnat_ugn/getting_started_with_gnat system-requirements}@anchor{17}
755 @section System Requirements
758 Even though any machine can run the GNAT toolset and GNAT Studio IDE, in order
759 to get the best experience, we recommend using a machine with as many cores
760 as possible since all individual compilations can run in parallel.
761 A comfortable setup for a compiler server is a machine with 24 physical cores
762 or more, with at least 48 GB of memory (2 GB per core).
764 For a desktop machine, a minimum of 4 cores is recommended (8 preferred),
765 with at least 2GB per core (so 8 to 16GB).
767 In addition, for running and navigating sources in GNAT Studio smoothly, we
768 recommend at least 1.5 GB plus 3 GB of RAM per 1 million source line of code.
769 In other words, we recommend at least 3 GB for for 500K lines of code and
770 7.5 GB for 2 million lines of code.
772 Note that using local and fast drives will also make a difference in terms of
773 build and link time. Network drives such as NFS, SMB, or worse, configuration
774 management filesystems (such as ClearCase dynamic views) should be avoided as
775 much as possible and will produce very degraded performance (typically 2 to 3
776 times slower than on local fast drives). If such slow drives cannot be avoided
777 for accessing the source code, then you should at least configure your project
778 file so that the result of the compilation is stored on a drive local to the
779 machine performing the run. This can be achieved by setting the @code{Object_Dir}
780 project file attribute.
782 @node Running GNAT,Running a Simple Ada Program,System Requirements,Getting Started with GNAT
783 @anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{18}@anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{19}
784 @section Running GNAT
787 Three steps are needed to create an executable file from an Ada source
788 file:
791 @itemize *
793 @item 
794 The source file(s) must be compiled.
796 @item 
797 The file(s) must be bound using the GNAT binder.
799 @item 
800 All appropriate object files must be linked to produce an executable.
801 @end itemize
803 All three steps are most commonly handled by using the @code{gnatmake}
804 utility program that, given the name of the main program, automatically
805 performs the necessary compilation, binding and linking steps.
807 @node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
808 @anchor{gnat_ugn/getting_started_with_gnat id4}@anchor{1a}@anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{1b}
809 @section Running a Simple Ada Program
812 Any text editor may be used to prepare an Ada program.
813 (If Emacs is used, the optional Ada mode may be helpful in laying out the
814 program.)
815 The program text is a normal text file. We will assume in our initial
816 example that you have used your editor to prepare the following
817 standard format text file:
819 @example
820 with Ada.Text_IO; use Ada.Text_IO;
821 procedure Hello is
822 begin
823    Put_Line ("Hello WORLD!");
824 end Hello;
825 @end example
827 This file should be named @code{hello.adb}.
828 With the normal default file naming conventions, GNAT requires
829 that each file
830 contain a single compilation unit whose file name is the
831 unit name,
832 with periods replaced by hyphens; the
833 extension is @code{ads} for a
834 spec and @code{adb} for a body.
835 You can override this default file naming convention by use of the
836 special pragma @code{Source_File_Name} (for further information please
837 see @ref{1c,,Using Other File Names}).
838 Alternatively, if you want to rename your files according to this default
839 convention, which is probably more convenient if you will be using GNAT
840 for all your compilations, then the @code{gnatchop} utility
841 can be used to generate correctly-named source files
842 (see @ref{1d,,Renaming Files with gnatchop}).
844 You can compile the program using the following command (@code{$} is used
845 as the command prompt in the examples in this document):
847 @example
848 $ gcc -c hello.adb
849 @end example
851 @code{gcc} is the command used to run the compiler. This compiler is
852 capable of compiling programs in several languages, including Ada and
853 C. It assumes that you have given it an Ada program if the file extension is
854 either @code{.ads} or @code{.adb}, and it will then call
855 the GNAT compiler to compile the specified file.
857 The @code{-c} switch is required. It tells @code{gcc} to only do a
858 compilation. (For C programs, @code{gcc} can also do linking, but this
859 capability is not used directly for Ada programs, so the @code{-c}
860 switch must always be present.)
862 This compile command generates a file
863 @code{hello.o}, which is the object
864 file corresponding to your Ada program. It also generates
865 an ‘Ada Library Information’ file @code{hello.ali},
866 which contains additional information used to check
867 that an Ada program is consistent.
869 To build an executable file, use either @code{gnatmake} or gprbuild with
870 the name of the main file: these tools are builders that will take care of
871 all the necessary build steps in the correct order.
872 In particular, these builders automatically recompile any sources that have
873 been modified since they were last compiled, or sources that depend
874 on such modified sources, so that ‘version skew’ is avoided.
876 @geindex Version skew (avoided by `@w{`}gnatmake`@w{`})
878 @example
879 $ gnatmake hello.adb
880 @end example
882 The result is an executable program called @code{hello}, which can be
883 run by entering:
885 @example
886 $ hello
887 @end example
889 assuming that the current directory is on the search path
890 for executable programs.
892 and, if all has gone well, you will see:
894 @example
895 Hello WORLD!
896 @end example
898 appear in response to this command.
900 @node Running a Program with Multiple Units,,Running a Simple Ada Program,Getting Started with GNAT
901 @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}
902 @section Running a Program with Multiple Units
905 Consider a slightly more complicated example that has three files: a
906 main program, and the spec and body of a package:
908 @example
909 package Greetings is
910    procedure Hello;
911    procedure Goodbye;
912 end Greetings;
914 with Ada.Text_IO; use Ada.Text_IO;
915 package body Greetings is
916    procedure Hello is
917    begin
918       Put_Line ("Hello WORLD!");
919    end Hello;
921    procedure Goodbye is
922    begin
923       Put_Line ("Goodbye WORLD!");
924    end Goodbye;
925 end Greetings;
927 with Greetings;
928 procedure Gmain is
929 begin
930    Greetings.Hello;
931    Greetings.Goodbye;
932 end Gmain;
933 @end example
935 Following the one-unit-per-file rule, place this program in the
936 following three separate files:
939 @table @asis
941 @item `greetings.ads'
943 spec of package @code{Greetings}
945 @item `greetings.adb'
947 body of package @code{Greetings}
949 @item `gmain.adb'
951 body of main program
952 @end table
954 Note that there is no required order of compilation when using GNAT.
955 In particular it is perfectly fine to compile the main program first.
956 Also, it is not necessary to compile package specs in the case where
957 there is an accompanying body; you only need to compile the body. If you want
958 to submit these files to the compiler for semantic checking and not code
959 generation, then use the @code{-gnatc} switch:
961 @example
962 $ gcc -c greetings.ads -gnatc
963 @end example
965 Although the compilation can be done in separate steps, in practice it is
966 almost always more convenient to use the @code{gnatmake} or @code{gprbuild} tools:
968 @example
969 $ gnatmake gmain.adb
970 @end example
972 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
974 @node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
975 @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}
976 @chapter The GNAT Compilation Model
979 @geindex GNAT compilation model
981 @geindex Compilation model
983 This chapter describes the compilation model used by GNAT. Although
984 similar to that used by other languages such as C and C++, this model
985 is substantially different from the traditional Ada compilation models,
986 which are based on a centralized program library. The chapter covers
987 the following material:
990 @itemize *
992 @item 
993 Topics related to source file makeup and naming
996 @itemize *
998 @item 
999 @ref{22,,Source Representation}
1001 @item 
1002 @ref{23,,Foreign Language Representation}
1004 @item 
1005 @ref{24,,File Naming Topics and Utilities}
1006 @end itemize
1008 @item 
1009 @ref{25,,Configuration Pragmas}
1011 @item 
1012 @ref{26,,Generating Object Files}
1014 @item 
1015 @ref{27,,Source Dependencies}
1017 @item 
1018 @ref{28,,The Ada Library Information Files}
1020 @item 
1021 @ref{29,,Binding an Ada Program}
1023 @item 
1024 @ref{2a,,GNAT and Libraries}
1026 @item 
1027 @ref{2b,,Conditional Compilation}
1029 @item 
1030 @ref{2c,,Mixed Language Programming}
1032 @item 
1033 @ref{2d,,GNAT and Other Compilation Models}
1035 @item 
1036 @ref{2e,,Using GNAT Files with External Tools}
1037 @end itemize
1039 @menu
1040 * Source Representation:: 
1041 * Foreign Language Representation:: 
1042 * File Naming Topics and Utilities:: 
1043 * Configuration Pragmas:: 
1044 * Generating Object Files:: 
1045 * Source Dependencies:: 
1046 * The Ada Library Information Files:: 
1047 * Binding an Ada Program:: 
1048 * GNAT and Libraries:: 
1049 * Conditional Compilation:: 
1050 * Mixed Language Programming:: 
1051 * GNAT and Other Compilation Models:: 
1052 * Using GNAT Files with External Tools:: 
1054 @end menu
1056 @node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1057 @anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{2f}@anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{22}
1058 @section Source Representation
1061 @geindex Latin-1
1063 @geindex VT
1064 @geindex HT
1065 @geindex CR
1066 @geindex LF
1067 @geindex FF
1069 Ada source programs are represented in standard text files, using
1070 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1071 7-bit ASCII set, plus additional characters used for
1072 representing foreign languages (see @ref{23,,Foreign Language Representation}
1073 for support of non-USA character sets). The format effector characters
1074 are represented using their standard ASCII encodings, as follows:
1076 @quotation
1079 @multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxx} 
1080 @item
1082 Character
1084 @tab
1086 Effect
1088 @tab
1090 Code
1092 @item
1094 @code{VT}
1096 @tab
1098 Vertical tab
1100 @tab
1102 @code{16#0B#}
1104 @item
1106 @code{HT}
1108 @tab
1110 Horizontal tab
1112 @tab
1114 @code{16#09#}
1116 @item
1118 @code{CR}
1120 @tab
1122 Carriage return
1124 @tab
1126 @code{16#0D#}
1128 @item
1130 @code{LF}
1132 @tab
1134 Line feed
1136 @tab
1138 @code{16#0A#}
1140 @item
1142 @code{FF}
1144 @tab
1146 Form feed
1148 @tab
1150 @code{16#0C#}
1152 @end multitable
1154 @end quotation
1156 Source files are in standard text file format. In addition, GNAT will
1157 recognize a wide variety of stream formats, in which the end of
1158 physical lines is marked by any of the following sequences:
1159 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1160 in accommodating files that are imported from other operating systems.
1162 @geindex End of source file; Source file@comma{} end
1164 @geindex SUB (control character)
1166 The end of a source file is normally represented by the physical end of
1167 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1168 recognized as signalling the end of the source file. Again, this is
1169 provided for compatibility with other operating systems where this
1170 code is used to represent the end of file.
1172 @geindex spec (definition)
1173 @geindex compilation (definition)
1175 Each file contains a single Ada compilation unit, including any pragmas
1176 associated with the unit. For example, this means you must place a
1177 package declaration (a package `spec') and the corresponding body in
1178 separate files. An Ada `compilation' (which is a sequence of
1179 compilation units) is represented using a sequence of files. Similarly,
1180 you will place each subunit or child unit in a separate file.
1182 @node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1183 @anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{23}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{30}
1184 @section Foreign Language Representation
1187 GNAT supports the standard character sets defined in Ada as well as
1188 several other non-standard character sets for use in localized versions
1189 of the compiler (@ref{31,,Character Set Control}).
1191 @menu
1192 * Latin-1:: 
1193 * Other 8-Bit Codes:: 
1194 * Wide_Character Encodings:: 
1195 * Wide_Wide_Character Encodings:: 
1197 @end menu
1199 @node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1200 @anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{32}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{33}
1201 @subsection Latin-1
1204 @geindex Latin-1
1206 The basic character set is Latin-1. This character set is defined by ISO
1207 standard 8859, part 1. The lower half (character codes @code{16#00#}
1208 … @code{16#7F#)} is identical to standard ASCII coding, but the upper
1209 half is used to represent additional characters. These include extended letters
1210 used by European languages, such as French accents, the vowels with umlauts
1211 used in German, and the extra letter A-ring used in Swedish.
1213 @geindex Ada.Characters.Latin_1
1215 For a complete list of Latin-1 codes and their encodings, see the source
1216 file of library unit @code{Ada.Characters.Latin_1} in file
1217 @code{a-chlat1.ads}.
1218 You may use any of these extended characters freely in character or
1219 string literals. In addition, the extended characters that represent
1220 letters can be used in identifiers.
1222 @node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1223 @anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{34}@anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{35}
1224 @subsection Other 8-Bit Codes
1227 GNAT also supports several other 8-bit coding schemes:
1229 @geindex Latin-2
1231 @geindex ISO 8859-2
1234 @table @asis
1236 @item `ISO 8859-2 (Latin-2)'
1238 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1239 equivalence.
1240 @end table
1242 @geindex Latin-3
1244 @geindex ISO 8859-3
1247 @table @asis
1249 @item `ISO 8859-3 (Latin-3)'
1251 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1252 equivalence.
1253 @end table
1255 @geindex Latin-4
1257 @geindex ISO 8859-4
1260 @table @asis
1262 @item `ISO 8859-4 (Latin-4)'
1264 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1265 equivalence.
1266 @end table
1268 @geindex ISO 8859-5
1270 @geindex Cyrillic
1273 @table @asis
1275 @item `ISO 8859-5 (Cyrillic)'
1277 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1278 lowercase equivalence.
1279 @end table
1281 @geindex ISO 8859-15
1283 @geindex Latin-9
1286 @table @asis
1288 @item `ISO 8859-15 (Latin-9)'
1290 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1291 lowercase equivalence.
1292 @end table
1294 @geindex code page 437 (IBM PC)
1297 @table @asis
1299 @item `IBM PC (code page 437)'
1301 This code page is the normal default for PCs in the U.S. It corresponds
1302 to the original IBM PC character set. This set has some, but not all, of
1303 the extended Latin-1 letters, but these letters do not have the same
1304 encoding as Latin-1. In this mode, these letters are allowed in
1305 identifiers with uppercase and lowercase equivalence.
1306 @end table
1308 @geindex code page 850 (IBM PC)
1311 @table @asis
1313 @item `IBM PC (code page 850)'
1315 This code page is a modification of 437 extended to include all the
1316 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1317 mode, all these letters are allowed in identifiers with uppercase and
1318 lowercase equivalence.
1320 @item `Full Upper 8-bit'
1322 Any character in the range 80-FF allowed in identifiers, and all are
1323 considered distinct. In other words, there are no uppercase and lowercase
1324 equivalences in this range. This is useful in conjunction with
1325 certain encoding schemes used for some foreign character sets (e.g.,
1326 the typical method of representing Chinese characters on the PC).
1328 @item `No Upper-Half'
1330 No upper-half characters in the range 80-FF are allowed in identifiers.
1331 This gives Ada 83 compatibility for identifier names.
1332 @end table
1334 For precise data on the encodings permitted, and the uppercase and lowercase
1335 equivalences that are recognized, see the file @code{csets.adb} in
1336 the GNAT compiler sources. You will need to obtain a full source release
1337 of GNAT to obtain this file.
1339 @node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1340 @anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{36}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{37}
1341 @subsection Wide_Character Encodings
1344 GNAT allows wide character codes to appear in character and string
1345 literals, and also optionally in identifiers, by means of the following
1346 possible encoding schemes:
1349 @table @asis
1351 @item `Hex Coding'
1353 In this encoding, a wide character is represented by the following five
1354 character sequence:
1356 @example
1357 ESC a b c d
1358 @end example
1360 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1361 characters (using uppercase letters) of the wide character code. For
1362 example, ESC A345 is used to represent the wide character with code
1363 @code{16#A345#}.
1364 This scheme is compatible with use of the full Wide_Character set.
1365 @end table
1367 @geindex Upper-Half Coding
1370 @table @asis
1372 @item `Upper-Half Coding'
1374 The wide character with encoding @code{16#abcd#} where the upper bit is on
1375 (in other words, ‘a’ is in the range 8-F) is represented as two bytes,
1376 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1377 character, but is not required to be in the upper half. This method can
1378 be also used for shift-JIS or EUC, where the internal coding matches the
1379 external coding.
1380 @end table
1382 @geindex Shift JIS Coding
1385 @table @asis
1387 @item `Shift JIS Coding'
1389 A wide character is represented by a two-character sequence,
1390 @code{16#ab#} and
1391 @code{16#cd#}, with the restrictions described for upper-half encoding as
1392 described above. The internal character code is the corresponding JIS
1393 character according to the standard algorithm for Shift-JIS
1394 conversion. Only characters defined in the JIS code set table can be
1395 used with this encoding method.
1396 @end table
1398 @geindex EUC Coding
1401 @table @asis
1403 @item `EUC Coding'
1405 A wide character is represented by a two-character sequence
1406 @code{16#ab#} and
1407 @code{16#cd#}, with both characters being in the upper half. The internal
1408 character code is the corresponding JIS character according to the EUC
1409 encoding algorithm. Only characters defined in the JIS code set table
1410 can be used with this encoding method.
1412 @item `UTF-8 Coding'
1414 A wide character is represented using
1415 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1416 10646-1/Am.2. Depending on the character value, the representation
1417 is a one, two, or three byte sequence:
1419 @example
1420 16#0000#-16#007f#: 2#0xxxxxxx#
1421 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1422 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1423 @end example
1425 where the @code{xxx} bits correspond to the left-padded bits of the
1426 16-bit character value. Note that all lower half ASCII characters
1427 are represented as ASCII bytes and all upper half characters and
1428 other wide characters are represented as sequences of upper-half
1429 (The full UTF-8 scheme allows for encoding 31-bit characters as
1430 6-byte sequences, and in the following section on wide wide
1431 characters, the use of these sequences is documented).
1433 @item `Brackets Coding'
1435 In this encoding, a wide character is represented by the following eight
1436 character sequence:
1438 @example
1439 [ " a b c d " ]
1440 @end example
1442 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1443 characters (using uppercase letters) of the wide character code. For
1444 example, [‘A345’] is used to represent the wide character with code
1445 @code{16#A345#}. It is also possible (though not required) to use the
1446 Brackets coding for upper half characters. For example, the code
1447 @code{16#A3#} can be represented as @code{['A3']}.
1449 This scheme is compatible with use of the full Wide_Character set,
1450 and is also the method used for wide character encoding in some standard
1451 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1452 @end table
1454 @cartouche
1455 @quotation Note 
1456 Some of these coding schemes do not permit the full use of the
1457 Ada character set. For example, neither Shift JIS nor EUC allow the
1458 use of the upper half of the Latin-1 set.
1459 @end quotation
1460 @end cartouche
1462 @node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1463 @anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{38}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{39}
1464 @subsection Wide_Wide_Character Encodings
1467 GNAT allows wide wide character codes to appear in character and string
1468 literals, and also optionally in identifiers, by means of the following
1469 possible encoding schemes:
1472 @table @asis
1474 @item `UTF-8 Coding'
1476 A wide character is represented using
1477 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1478 10646-1/Am.2. Depending on the character value, the representation
1479 of character codes with values greater than 16#FFFF# is a
1480 is a four, five, or six byte sequence:
1482 @example
1483 16#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1484                              10xxxxxx
1485 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1486                              10xxxxxx 10xxxxxx
1487 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1488                              10xxxxxx 10xxxxxx 10xxxxxx
1489 @end example
1491 where the @code{xxx} bits correspond to the left-padded bits of the
1492 32-bit character value.
1494 @item `Brackets Coding'
1496 In this encoding, a wide wide character is represented by the following ten or
1497 twelve byte character sequence:
1499 @example
1500 [ " a b c d e f " ]
1501 [ " a b c d e f g h " ]
1502 @end example
1504 where @code{a-h} are the six or eight hexadecimal
1505 characters (using uppercase letters) of the wide wide character code. For
1506 example, [“1F4567”] is used to represent the wide wide character with code
1507 @code{16#001F_4567#}.
1509 This scheme is compatible with use of the full Wide_Wide_Character set,
1510 and is also the method used for wide wide character encoding in some standard
1511 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1512 @end table
1514 @node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1515 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{24}@anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{3a}
1516 @section File Naming Topics and Utilities
1519 GNAT has a default file naming scheme and also provides the user with
1520 a high degree of control over how the names and extensions of the
1521 source files correspond to the Ada compilation units that they contain.
1523 @menu
1524 * File Naming Rules:: 
1525 * Using Other File Names:: 
1526 * Alternative File Naming Schemes:: 
1527 * Handling Arbitrary File Naming Conventions with gnatname:: 
1528 * File Name Krunching with gnatkr:: 
1529 * Renaming Files with gnatchop:: 
1531 @end menu
1533 @node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1534 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{3b}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{3c}
1535 @subsection File Naming Rules
1538 The default file name is determined by the name of the unit that the
1539 file contains. The name is formed by taking the full expanded name of
1540 the unit and replacing the separating dots with hyphens and using
1541 lowercase for all letters.
1543 An exception arises if the file name generated by the above rules starts
1544 with one of the characters
1545 @code{a}, @code{g}, @code{i}, or @code{s}, and the second character is a
1546 minus. In this case, the character tilde is used in place
1547 of the minus. The reason for this special rule is to avoid clashes with
1548 the standard names for child units of the packages System, Ada,
1549 Interfaces, and GNAT, which use the prefixes
1550 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
1551 respectively.
1553 The file extension is @code{.ads} for a spec and
1554 @code{.adb} for a body. The following table shows some
1555 examples of these rules.
1557 @quotation
1560 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
1561 @item
1563 Source File
1565 @tab
1567 Ada Compilation Unit
1569 @item
1571 @code{main.ads}
1573 @tab
1575 Main (spec)
1577 @item
1579 @code{main.adb}
1581 @tab
1583 Main (body)
1585 @item
1587 @code{arith_functions.ads}
1589 @tab
1591 Arith_Functions (package spec)
1593 @item
1595 @code{arith_functions.adb}
1597 @tab
1599 Arith_Functions (package body)
1601 @item
1603 @code{func-spec.ads}
1605 @tab
1607 Func.Spec (child package spec)
1609 @item
1611 @code{func-spec.adb}
1613 @tab
1615 Func.Spec (child package body)
1617 @item
1619 @code{main-sub.adb}
1621 @tab
1623 Sub (subunit of Main)
1625 @item
1627 @code{a~bad.adb}
1629 @tab
1631 A.Bad (child package body)
1633 @end multitable
1635 @end quotation
1637 Following these rules can result in excessively long
1638 file names if corresponding
1639 unit names are long (for example, if child units or subunits are
1640 heavily nested). An option is available to shorten such long file names
1641 (called file name ‘krunching’). This may be particularly useful when
1642 programs being developed with GNAT are to be used on operating systems
1643 with limited file name lengths. @ref{3d,,Using gnatkr}.
1645 Of course, no file shortening algorithm can guarantee uniqueness over
1646 all possible unit names; if file name krunching is used, it is your
1647 responsibility to ensure no name clashes occur. Alternatively you
1648 can specify the exact file names that you want used, as described
1649 in the next section. Finally, if your Ada programs are migrating from a
1650 compiler with a different naming convention, you can use the gnatchop
1651 utility to produce source files that follow the GNAT naming conventions.
1652 (For details see @ref{1d,,Renaming Files with gnatchop}.)
1654 Note: in the case of Windows or Mac OS operating systems, case is not
1655 significant. So for example on Windows if the canonical name is
1656 @code{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1657 However, case is significant for other operating systems, so for example,
1658 if you want to use other than canonically cased file names on a Unix system,
1659 you need to follow the procedures described in the next section.
1661 @node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1662 @anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{3e}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{1c}
1663 @subsection Using Other File Names
1666 @geindex File names
1668 In the previous section, we have described the default rules used by
1669 GNAT to determine the file name in which a given unit resides. It is
1670 often convenient to follow these default rules, and if you follow them,
1671 the compiler knows without being explicitly told where to find all
1672 the files it needs.
1674 @geindex Source_File_Name pragma
1676 However, in some cases, particularly when a program is imported from
1677 another Ada compiler environment, it may be more convenient for the
1678 programmer to specify which file names contain which units. GNAT allows
1679 arbitrary file names to be used by means of the Source_File_Name pragma.
1680 The form of this pragma is as shown in the following examples:
1682 @example
1683 pragma Source_File_Name (My_Utilities.Stacks,
1684   Spec_File_Name => "myutilst_a.ada");
1685 pragma Source_File_name (My_Utilities.Stacks,
1686   Body_File_Name => "myutilst.ada");
1687 @end example
1689 As shown in this example, the first argument for the pragma is the unit
1690 name (in this example a child unit). The second argument has the form
1691 of a named association. The identifier
1692 indicates whether the file name is for a spec or a body;
1693 the file name itself is given by a string literal.
1695 The source file name pragma is a configuration pragma, which means that
1696 normally it will be placed in the @code{gnat.adc}
1697 file used to hold configuration
1698 pragmas that apply to a complete compilation environment.
1699 For more details on how the @code{gnat.adc} file is created and used
1700 see @ref{3f,,Handling of Configuration Pragmas}.
1702 @geindex gnat.adc
1704 GNAT allows completely arbitrary file names to be specified using the
1705 source file name pragma. However, if the file name specified has an
1706 extension other than @code{.ads} or @code{.adb} it is necessary to use
1707 a special syntax when compiling the file. The name in this case must be
1708 preceded by the special sequence @code{-x} followed by a space and the name
1709 of the language, here @code{ada}, as in:
1711 @example
1712 $ gcc -c -x ada peculiar_file_name.sim
1713 @end example
1715 @code{gnatmake} handles non-standard file names in the usual manner (the
1716 non-standard file name for the main program is simply used as the
1717 argument to gnatmake). Note that if the extension is also non-standard,
1718 then it must be included in the @code{gnatmake} command, it may not
1719 be omitted.
1721 @node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
1722 @anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{41}
1723 @subsection Alternative File Naming Schemes
1726 @geindex File naming schemes
1727 @geindex alternative
1729 @geindex File names
1731 The previous section described the use of the @code{Source_File_Name}
1732 pragma to allow arbitrary names to be assigned to individual source files.
1733 However, this approach requires one pragma for each file, and especially in
1734 large systems can result in very long @code{gnat.adc} files, and also create
1735 a maintenance problem.
1737 @geindex Source_File_Name pragma
1739 GNAT also provides a facility for specifying systematic file naming schemes
1740 other than the standard default naming scheme previously described. An
1741 alternative scheme for naming is specified by the use of
1742 @code{Source_File_Name} pragmas having the following format:
1744 @example
1745 pragma Source_File_Name (
1746    Spec_File_Name  => FILE_NAME_PATTERN
1747  [ , Casing          => CASING_SPEC]
1748  [ , Dot_Replacement => STRING_LITERAL ] );
1750 pragma Source_File_Name (
1751    Body_File_Name  => FILE_NAME_PATTERN
1752  [ , Casing          => CASING_SPEC ]
1753  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1755 pragma Source_File_Name (
1756    Subunit_File_Name  => FILE_NAME_PATTERN
1757  [ , Casing          => CASING_SPEC ]
1758  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1760 FILE_NAME_PATTERN ::= STRING_LITERAL
1761 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1762 @end example
1764 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1765 It contains a single asterisk character, and the unit name is substituted
1766 systematically for this asterisk. The optional parameter
1767 @code{Casing} indicates
1768 whether the unit name is to be all upper-case letters, all lower-case letters,
1769 or mixed-case. If no
1770 @code{Casing} parameter is used, then the default is all
1771 lower-case.
1773 The optional @code{Dot_Replacement} string is used to replace any periods
1774 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1775 argument is used then separating dots appear unchanged in the resulting
1776 file name.
1777 Although the above syntax indicates that the
1778 @code{Casing} argument must appear
1779 before the @code{Dot_Replacement} argument, but it
1780 is also permissible to write these arguments in the opposite order.
1782 As indicated, it is possible to specify different naming schemes for
1783 bodies, specs, and subunits. Quite often the rule for subunits is the
1784 same as the rule for bodies, in which case, there is no need to give
1785 a separate @code{Subunit_File_Name} rule, and in this case the
1786 @code{Body_File_name} rule is used for subunits as well.
1788 The separate rule for subunits can also be used to implement the rather
1789 unusual case of a compilation environment (e.g., a single directory) which
1790 contains a subunit and a child unit with the same unit name. Although
1791 both units cannot appear in the same partition, the Ada Reference Manual
1792 allows (but does not require) the possibility of the two units coexisting
1793 in the same environment.
1795 The file name translation works in the following steps:
1798 @itemize *
1800 @item 
1801 If there is a specific @code{Source_File_Name} pragma for the given unit,
1802 then this is always used, and any general pattern rules are ignored.
1804 @item 
1805 If there is a pattern type @code{Source_File_Name} pragma that applies to
1806 the unit, then the resulting file name will be used if the file exists. If
1807 more than one pattern matches, the latest one will be tried first, and the
1808 first attempt resulting in a reference to a file that exists will be used.
1810 @item 
1811 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1812 for which the corresponding file exists, then the standard GNAT default
1813 naming rules are used.
1814 @end itemize
1816 As an example of the use of this mechanism, consider a commonly used scheme
1817 in which file names are all lower case, with separating periods copied
1818 unchanged to the resulting file name, and specs end with @code{.1.ada}, and
1819 bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
1820 two pragmas appear:
1822 @example
1823 pragma Source_File_Name
1824   (Spec_File_Name => ".1.ada");
1825 pragma Source_File_Name
1826   (Body_File_Name => ".2.ada");
1827 @end example
1829 The default GNAT scheme is actually implemented by providing the following
1830 default pragmas internally:
1832 @example
1833 pragma Source_File_Name
1834   (Spec_File_Name => ".ads", Dot_Replacement => "-");
1835 pragma Source_File_Name
1836   (Body_File_Name => ".adb", Dot_Replacement => "-");
1837 @end example
1839 Our final example implements a scheme typically used with one of the
1840 Ada 83 compilers, where the separator character for subunits was ‘__’
1841 (two underscores), specs were identified by adding @code{_.ADA}, bodies
1842 by adding @code{.ADA}, and subunits by
1843 adding @code{.SEP}. All file names were
1844 upper case. Child units were not present of course since this was an
1845 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1846 the same double underscore separator for child units.
1848 @example
1849 pragma Source_File_Name
1850   (Spec_File_Name => "_.ADA",
1851    Dot_Replacement => "__",
1852    Casing = Uppercase);
1853 pragma Source_File_Name
1854   (Body_File_Name => ".ADA",
1855    Dot_Replacement => "__",
1856    Casing = Uppercase);
1857 pragma Source_File_Name
1858   (Subunit_File_Name => ".SEP",
1859    Dot_Replacement => "__",
1860    Casing = Uppercase);
1861 @end example
1863 @geindex gnatname
1865 @node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
1866 @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}
1867 @subsection Handling Arbitrary File Naming Conventions with @code{gnatname}
1870 @geindex File Naming Conventions
1872 @menu
1873 * Arbitrary File Naming Conventions:: 
1874 * Running gnatname:: 
1875 * Switches for gnatname:: 
1876 * Examples of gnatname Usage:: 
1878 @end menu
1880 @node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
1881 @anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{44}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{45}
1882 @subsubsection Arbitrary File Naming Conventions
1885 The GNAT compiler must be able to know the source file name of a compilation
1886 unit.  When using the standard GNAT default file naming conventions
1887 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
1888 does not need additional information.
1890 When the source file names do not follow the standard GNAT default file naming
1891 conventions, the GNAT compiler must be given additional information through
1892 a configuration pragmas file (@ref{25,,Configuration Pragmas})
1893 or a project file.
1894 When the non-standard file naming conventions are well-defined,
1895 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
1896 (@ref{40,,Alternative File Naming Schemes}) may be sufficient. However,
1897 if the file naming conventions are irregular or arbitrary, a number
1898 of pragma @code{Source_File_Name} for individual compilation units
1899 must be defined.
1900 To help maintain the correspondence between compilation unit names and
1901 source file names within the compiler,
1902 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
1903 set of files.
1905 @node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
1906 @anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{46}@anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{47}
1907 @subsubsection Running @code{gnatname}
1910 The usual form of the @code{gnatname} command is:
1912 @example
1913 $ gnatname [ switches ]  naming_pattern  [ naming_patterns ]
1914     [--and [ switches ]  naming_pattern  [ naming_patterns ]]
1915 @end example
1917 All of the arguments are optional. If invoked without any argument,
1918 @code{gnatname} will display its usage.
1920 When used with at least one naming pattern, @code{gnatname} will attempt to
1921 find all the compilation units in files that follow at least one of the
1922 naming patterns. To find these compilation units,
1923 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
1924 regular files.
1926 One or several Naming Patterns may be given as arguments to @code{gnatname}.
1927 Each Naming Pattern is enclosed between double quotes (or single
1928 quotes on Windows).
1929 A Naming Pattern is a regular expression similar to the wildcard patterns
1930 used in file names by the Unix shells or the DOS prompt.
1932 @code{gnatname} may be called with several sections of directories/patterns.
1933 Sections are separated by the switch @code{--and}. In each section, there must be
1934 at least one pattern. If no directory is specified in a section, the current
1935 directory (or the project directory if @code{-P} is used) is implied.
1936 The options other that the directory switches and the patterns apply globally
1937 even if they are in different sections.
1939 Examples of Naming Patterns are:
1941 @example
1942 "*.[12].ada"
1943 "*.ad[sb]*"
1944 "body_*"    "spec_*"
1945 @end example
1947 For a more complete description of the syntax of Naming Patterns,
1948 see the second kind of regular expressions described in @code{g-regexp.ads}
1949 (the ‘Glob’ regular expressions).
1951 When invoked without the switch @code{-P}, @code{gnatname} will create a
1952 configuration pragmas file @code{gnat.adc} in the current working directory,
1953 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
1954 unit.
1956 @node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
1957 @anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{48}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{49}
1958 @subsubsection Switches for @code{gnatname}
1961 Switches for @code{gnatname} must precede any specified Naming Pattern.
1963 You may specify any of the following switches to @code{gnatname}:
1965 @geindex --version (gnatname)
1968 @table @asis
1970 @item @code{--version}
1972 Display Copyright and version, then exit disregarding all other options.
1973 @end table
1975 @geindex --help (gnatname)
1978 @table @asis
1980 @item @code{--help}
1982 If @code{--version} was not used, display usage, then exit disregarding
1983 all other options.
1985 @item @code{--subdirs=`dir'}
1987 Real object, library or exec directories are subdirectories <dir> of the
1988 specified ones.
1990 @item @code{--no-backup}
1992 Do not create a backup copy of an existing project file.
1994 @item @code{--and}
1996 Start another section of directories/patterns.
1997 @end table
1999 @geindex -c (gnatname)
2002 @table @asis
2004 @item @code{-c`filename'}
2006 Create a configuration pragmas file @code{filename} (instead of the default
2007 @code{gnat.adc}).
2008 There may be zero, one or more space between @code{-c} and
2009 @code{filename}.
2010 @code{filename} may include directory information. @code{filename} must be
2011 writable. There may be only one switch @code{-c}.
2012 When a switch @code{-c} is
2013 specified, no switch @code{-P} may be specified (see below).
2014 @end table
2016 @geindex -d (gnatname)
2019 @table @asis
2021 @item @code{-d`dir'}
2023 Look for source files in directory @code{dir}. There may be zero, one or more
2024 spaces between @code{-d} and @code{dir}.
2025 @code{dir} may end with @code{/**}, that is it may be of the form
2026 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
2027 subdirectories, recursively, have to be searched for sources.
2028 When a switch @code{-d}
2029 is specified, the current working directory will not be searched for source
2030 files, unless it is explicitly specified with a @code{-d}
2031 or @code{-D} switch.
2032 Several switches @code{-d} may be specified.
2033 If @code{dir} is a relative path, it is relative to the directory of
2034 the configuration pragmas file specified with switch
2035 @code{-c},
2036 or to the directory of the project file specified with switch
2037 @code{-P} or,
2038 if neither switch @code{-c}
2039 nor switch @code{-P} are specified, it is relative to the
2040 current working directory. The directory
2041 specified with switch @code{-d} must exist and be readable.
2042 @end table
2044 @geindex -D (gnatname)
2047 @table @asis
2049 @item @code{-D`filename'}
2051 Look for source files in all directories listed in text file @code{filename}.
2052 There may be zero, one or more spaces between @code{-D}
2053 and @code{filename}.
2054 @code{filename} must be an existing, readable text file.
2055 Each nonempty line in @code{filename} must be a directory.
2056 Specifying switch @code{-D} is equivalent to specifying as many
2057 switches @code{-d} as there are nonempty lines in
2058 @code{file}.
2060 @item @code{-eL}
2062 Follow symbolic links when processing project files.
2064 @geindex -f (gnatname)
2066 @item @code{-f`pattern'}
2068 Foreign patterns. Using this switch, it is possible to add sources of languages
2069 other than Ada to the list of sources of a project file.
2070 It is only useful if a -P switch is used.
2071 For example,
2073 @example
2074 gnatname -Pprj -f"*.c" "*.ada"
2075 @end example
2077 will look for Ada units in all files with the @code{.ada} extension,
2078 and will add to the list of file for project @code{prj.gpr} the C files
2079 with extension @code{.c}.
2081 @geindex -h (gnatname)
2083 @item @code{-h}
2085 Output usage (help) information. The output is written to @code{stdout}.
2087 @geindex -P (gnatname)
2089 @item @code{-P`proj'}
2091 Create or update project file @code{proj}. There may be zero, one or more space
2092 between @code{-P} and @code{proj}. @code{proj} may include directory
2093 information. @code{proj} must be writable.
2094 There may be only one switch @code{-P}.
2095 When a switch @code{-P} is specified,
2096 no switch @code{-c} may be specified.
2097 On all platforms, except on VMS, when @code{gnatname} is invoked for an
2098 existing project file <proj>.gpr, a backup copy of the project file is created
2099 in the project directory with file name <proj>.gpr.saved_x. ‘x’ is the first
2100 non negative number that makes this backup copy a new file.
2102 @geindex -v (gnatname)
2104 @item @code{-v}
2106 Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2107 This includes name of the file written, the name of the directories to search
2108 and, for each file in those directories whose name matches at least one of
2109 the Naming Patterns, an indication of whether the file contains a unit,
2110 and if so the name of the unit.
2111 @end table
2113 @geindex -v -v (gnatname)
2116 @table @asis
2118 @item @code{-v -v}
2120 Very Verbose mode. In addition to the output produced in verbose mode,
2121 for each file in the searched directories whose name matches none of
2122 the Naming Patterns, an indication is given that there is no match.
2124 @geindex -x (gnatname)
2126 @item @code{-x`pattern'}
2128 Excluded patterns. Using this switch, it is possible to exclude some files
2129 that would match the name patterns. For example,
2131 @example
2132 gnatname -x "*_nt.ada" "*.ada"
2133 @end example
2135 will look for Ada units in all files with the @code{.ada} extension,
2136 except those whose names end with @code{_nt.ada}.
2137 @end table
2139 @node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2140 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{4a}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{4b}
2141 @subsubsection Examples of @code{gnatname} Usage
2144 @example
2145 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2146 @end example
2148 In this example, the directory @code{/home/me} must already exist
2149 and be writable. In addition, the directory
2150 @code{/home/me/sources} (specified by
2151 @code{-d sources}) must exist and be readable.
2153 Note the optional spaces after @code{-c} and @code{-d}.
2155 @example
2156 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
2157 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2158 @end example
2160 Note that several switches @code{-d} may be used,
2161 even in conjunction with one or several switches
2162 @code{-D}. Several Naming Patterns and one excluded pattern
2163 are used in this example.
2165 @node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2166 @anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{4c}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{4d}
2167 @subsection File Name Krunching with @code{gnatkr}
2170 @geindex gnatkr
2172 This section discusses the method used by the compiler to shorten
2173 the default file names chosen for Ada units so that they do not
2174 exceed the maximum length permitted. It also describes the
2175 @code{gnatkr} utility that can be used to determine the result of
2176 applying this shortening.
2178 @menu
2179 * About gnatkr:: 
2180 * Using gnatkr:: 
2181 * Krunching Method:: 
2182 * Examples of gnatkr Usage:: 
2184 @end menu
2186 @node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2187 @anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{4e}@anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{4f}
2188 @subsubsection About @code{gnatkr}
2191 The default file naming rule in GNAT
2192 is that the file name must be derived from
2193 the unit name. The exact default rule is as follows:
2196 @itemize *
2198 @item 
2199 Take the unit name and replace all dots by hyphens.
2201 @item 
2202 If such a replacement occurs in the
2203 second character position of a name, and the first character is
2204 @code{a}, @code{g}, @code{s}, or @code{i},
2205 then replace the dot by the character
2206 @code{~} (tilde)
2207 instead of a minus.
2209 The reason for this exception is to avoid clashes
2210 with the standard names for children of System, Ada, Interfaces,
2211 and GNAT, which use the prefixes
2212 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
2213 respectively.
2214 @end itemize
2216 The @code{-gnatk`nn'}
2217 switch of the compiler activates a ‘krunching’
2218 circuit that limits file names to nn characters (where nn is a decimal
2219 integer).
2221 The @code{gnatkr} utility can be used to determine the krunched name for
2222 a given file, when krunched to a specified maximum length.
2224 @node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2225 @anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{50}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{3d}
2226 @subsubsection Using @code{gnatkr}
2229 The @code{gnatkr} command has the form:
2231 @example
2232 $ gnatkr name [ length ]
2233 @end example
2235 @code{name} is the uncrunched file name, derived from the name of the unit
2236 in the standard manner described in the previous section (i.e., in particular
2237 all dots are replaced by hyphens). The file name may or may not have an
2238 extension (defined as a suffix of the form period followed by arbitrary
2239 characters other than period). If an extension is present then it will
2240 be preserved in the output. For example, when krunching @code{hellofile.ads}
2241 to eight characters, the result will be hellofil.ads.
2243 Note: for compatibility with previous versions of @code{gnatkr} dots may
2244 appear in the name instead of hyphens, but the last dot will always be
2245 taken as the start of an extension. So if @code{gnatkr} is given an argument
2246 such as @code{Hello.World.adb} it will be treated exactly as if the first
2247 period had been a hyphen, and for example krunching to eight characters
2248 gives the result @code{hellworl.adb}.
2250 Note that the result is always all lower case.
2251 Characters of the other case are folded as required.
2253 @code{length} represents the length of the krunched name. The default
2254 when no argument is given is 8 characters. A length of zero stands for
2255 unlimited, in other words do not chop except for system files where the
2256 implied crunching length is always eight characters.
2258 The output is the krunched name. The output has an extension only if the
2259 original argument was a file name with an extension.
2261 @node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2262 @anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{52}
2263 @subsubsection Krunching Method
2266 The initial file name is determined by the name of the unit that the file
2267 contains. The name is formed by taking the full expanded name of the
2268 unit and replacing the separating dots with hyphens and
2269 using lowercase
2270 for all letters, except that a hyphen in the second character position is
2271 replaced by a tilde if the first character is
2272 @code{a}, @code{i}, @code{g}, or @code{s}.
2273 The extension is @code{.ads} for a
2274 spec and @code{.adb} for a body.
2275 Krunching does not affect the extension, but the file name is shortened to
2276 the specified length by following these rules:
2279 @itemize *
2281 @item 
2282 The name is divided into segments separated by hyphens, tildes or
2283 underscores and all hyphens, tildes, and underscores are
2284 eliminated. If this leaves the name short enough, we are done.
2286 @item 
2287 If the name is too long, the longest segment is located (left-most
2288 if there are two of equal length), and shortened by dropping
2289 its last character. This is repeated until the name is short enough.
2291 As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2292 to fit the name into 8 characters as required by some operating systems:
2294 @example
2295 our-strings-wide_fixed 22
2296 our strings wide fixed 19
2297 our string  wide fixed 18
2298 our strin   wide fixed 17
2299 our stri    wide fixed 16
2300 our stri    wide fixe  15
2301 our str     wide fixe  14
2302 our str     wid  fixe  13
2303 our str     wid  fix   12
2304 ou  str     wid  fix   11
2305 ou  st      wid  fix   10
2306 ou  st      wi   fix   9
2307 ou  st      wi   fi    8
2308 Final file name: oustwifi.adb
2309 @end example
2311 @item 
2312 The file names for all predefined units are always krunched to eight
2313 characters. The krunching of these predefined units uses the following
2314 special prefix replacements:
2317 @multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
2318 @item
2320 Prefix
2322 @tab
2324 Replacement
2326 @item
2328 @code{ada-}
2330 @tab
2332 @code{a-}
2334 @item
2336 @code{gnat-}
2338 @tab
2340 @code{g-}
2342 @item
2344 @code{interfac es-}
2346 @tab
2348 @code{i-}
2350 @item
2352 @code{system-}
2354 @tab
2356 @code{s-}
2358 @end multitable
2361 These system files have a hyphen in the second character position. That
2362 is why normal user files replace such a character with a
2363 tilde, to avoid confusion with system file names.
2365 As an example of this special rule, consider
2366 @code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2368 @example
2369 ada-strings-wide_fixed 22
2370 a-  strings wide fixed 18
2371 a-  string  wide fixed 17
2372 a-  strin   wide fixed 16
2373 a-  stri    wide fixed 15
2374 a-  stri    wide fixe  14
2375 a-  str     wide fixe  13
2376 a-  str     wid  fixe  12
2377 a-  str     wid  fix   11
2378 a-  st      wid  fix   10
2379 a-  st      wi   fix   9
2380 a-  st      wi   fi    8
2381 Final file name: a-stwifi.adb
2382 @end example
2383 @end itemize
2385 Of course no file shortening algorithm can guarantee uniqueness over all
2386 possible unit names, and if file name krunching is used then it is your
2387 responsibility to ensure that no name clashes occur. The utility
2388 program @code{gnatkr} is supplied for conveniently determining the
2389 krunched name of a file.
2391 @node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2392 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{53}@anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{54}
2393 @subsubsection Examples of @code{gnatkr} Usage
2396 @example
2397 $ gnatkr very_long_unit_name.ads      --> velounna.ads
2398 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
2399 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2400 $ gnatkr grandparent-parent-child     --> grparchi
2401 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2402 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2403 @end example
2405 @node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2406 @anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{55}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{1d}
2407 @subsection Renaming Files with @code{gnatchop}
2410 @geindex gnatchop
2412 This section discusses how to handle files with multiple units by using
2413 the @code{gnatchop} utility. This utility is also useful in renaming
2414 files to meet the standard GNAT default file naming conventions.
2416 @menu
2417 * Handling Files with Multiple Units:: 
2418 * Operating gnatchop in Compilation Mode:: 
2419 * Command Line for gnatchop:: 
2420 * Switches for gnatchop:: 
2421 * Examples of gnatchop Usage:: 
2423 @end menu
2425 @node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2426 @anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{56}@anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{57}
2427 @subsubsection Handling Files with Multiple Units
2430 The basic compilation model of GNAT requires that a file submitted to the
2431 compiler have only one unit and there be a strict correspondence
2432 between the file name and the unit name.
2434 If you want to keep your files with multiple units,
2435 perhaps to maintain compatibility with some other Ada compilation system,
2436 you can use @code{gnatname} to generate or update your project files.
2437 Generated or modified project files can be processed by GNAT.
2439 See @ref{42,,Handling Arbitrary File Naming Conventions with gnatname}
2440 for more details on how to use @cite{gnatname}.
2442 Alternatively, if you want to permanently restructure a set of ‘foreign’
2443 files so that they match the GNAT rules, and do the remaining development
2444 using the GNAT structure, you can simply use @code{gnatchop} once, generate the
2445 new set of files and work with them from that point on.
2447 Note that if your file containing multiple units starts with a byte order
2448 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2449 will each start with a copy of this BOM, meaning that they can be compiled
2450 automatically in UTF-8 mode without needing to specify an explicit encoding.
2452 @node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2453 @anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{58}@anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{59}
2454 @subsubsection Operating gnatchop in Compilation Mode
2457 The basic function of @code{gnatchop} is to take a file with multiple units
2458 and split it into separate files. The boundary between files is reasonably
2459 clear, except for the issue of comments and pragmas. In default mode, the
2460 rule is that any pragmas between units belong to the previous unit, except
2461 that configuration pragmas always belong to the following unit. Any comments
2462 belong to the following unit. These rules
2463 almost always result in the right choice of
2464 the split point without needing to mark it explicitly and most users will
2465 find this default to be what they want. In this default mode it is incorrect to
2466 submit a file containing only configuration pragmas, or one that ends in
2467 configuration pragmas, to @code{gnatchop}.
2469 However, using a special option to activate ‘compilation mode’,
2470 @code{gnatchop}
2471 can perform another function, which is to provide exactly the semantics
2472 required by the RM for handling of configuration pragmas in a compilation.
2473 In the absence of configuration pragmas (at the main file level), this
2474 option has no effect, but it causes such configuration pragmas to be handled
2475 in a quite different manner.
2477 First, in compilation mode, if @code{gnatchop} is given a file that consists of
2478 only configuration pragmas, then this file is appended to the
2479 @code{gnat.adc} file in the current directory. This behavior provides
2480 the required behavior described in the RM for the actions to be taken
2481 on submitting such a file to the compiler, namely that these pragmas
2482 should apply to all subsequent compilations in the same compilation
2483 environment. Using GNAT, the current directory, possibly containing a
2484 @code{gnat.adc} file is the representation
2485 of a compilation environment. For more information on the
2486 @code{gnat.adc} file, see @ref{3f,,Handling of Configuration Pragmas}.
2488 Second, in compilation mode, if @code{gnatchop}
2489 is given a file that starts with
2490 configuration pragmas, and contains one or more units, then these
2491 configuration pragmas are prepended to each of the chopped files. This
2492 behavior provides the required behavior described in the RM for the
2493 actions to be taken on compiling such a file, namely that the pragmas
2494 apply to all units in the compilation, but not to subsequently compiled
2495 units.
2497 Finally, if configuration pragmas appear between units, they are appended
2498 to the previous unit. This results in the previous unit being illegal,
2499 since the compiler does not accept configuration pragmas that follow
2500 a unit. This provides the required RM behavior that forbids configuration
2501 pragmas other than those preceding the first compilation unit of a
2502 compilation.
2504 For most purposes, @code{gnatchop} will be used in default mode. The
2505 compilation mode described above is used only if you need exactly
2506 accurate behavior with respect to compilations, and you have files
2507 that contain multiple units and configuration pragmas. In this
2508 circumstance the use of @code{gnatchop} with the compilation mode
2509 switch provides the required behavior, and is for example the mode
2510 in which GNAT processes the ACVC tests.
2512 @node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2513 @anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{5a}@anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{5b}
2514 @subsubsection Command Line for @code{gnatchop}
2517 The @code{gnatchop} command has the form:
2519 @example
2520 $ gnatchop switches file_name [file_name ...]
2521       [directory]
2522 @end example
2524 The only required argument is the file name of the file to be chopped.
2525 There are no restrictions on the form of this file name. The file itself
2526 contains one or more Ada units, in normal GNAT format, concatenated
2527 together. As shown, more than one file may be presented to be chopped.
2529 When run in default mode, @code{gnatchop} generates one output file in
2530 the current directory for each unit in each of the files.
2532 @code{directory}, if specified, gives the name of the directory to which
2533 the output files will be written. If it is not specified, all files are
2534 written to the current directory.
2536 For example, given a
2537 file called @code{hellofiles} containing
2539 @example
2540 procedure Hello;
2542 with Ada.Text_IO; use Ada.Text_IO;
2543 procedure Hello is
2544 begin
2545    Put_Line ("Hello");
2546 end Hello;
2547 @end example
2549 the command
2551 @example
2552 $ gnatchop hellofiles
2553 @end example
2555 generates two files in the current directory, one called
2556 @code{hello.ads} containing the single line that is the procedure spec,
2557 and the other called @code{hello.adb} containing the remaining text. The
2558 original file is not affected. The generated files can be compiled in
2559 the normal manner.
2561 When gnatchop is invoked on a file that is empty or that contains only empty
2562 lines and/or comments, gnatchop will not fail, but will not produce any
2563 new sources.
2565 For example, given a
2566 file called @code{toto.txt} containing
2568 @example
2569 --  Just a comment
2570 @end example
2572 the command
2574 @example
2575 $ gnatchop toto.txt
2576 @end example
2578 will not produce any new file and will result in the following warnings:
2580 @example
2581 toto.txt:1:01: warning: empty file, contains no compilation units
2582 no compilation units found
2583 no source files written
2584 @end example
2586 @node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2587 @anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{5c}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{5d}
2588 @subsubsection Switches for @code{gnatchop}
2591 @code{gnatchop} recognizes the following switches:
2593 @geindex --version (gnatchop)
2596 @table @asis
2598 @item @code{--version}
2600 Display Copyright and version, then exit disregarding all other options.
2601 @end table
2603 @geindex --help (gnatchop)
2606 @table @asis
2608 @item @code{--help}
2610 If @code{--version} was not used, display usage, then exit disregarding
2611 all other options.
2612 @end table
2614 @geindex -c (gnatchop)
2617 @table @asis
2619 @item @code{-c}
2621 Causes @code{gnatchop} to operate in compilation mode, in which
2622 configuration pragmas are handled according to strict RM rules. See
2623 previous section for a full description of this mode.
2625 @item @code{-gnat`xxx'}
2627 This passes the given @code{-gnat`xxx'} switch to @code{gnat} which is
2628 used to parse the given file. Not all `xxx' options make sense,
2629 but for example, the use of @code{-gnati2} allows @code{gnatchop} to
2630 process a source file that uses Latin-2 coding for identifiers.
2632 @item @code{-h}
2634 Causes @code{gnatchop} to generate a brief help summary to the standard
2635 output file showing usage information.
2636 @end table
2638 @geindex -k (gnatchop)
2641 @table @asis
2643 @item @code{-k`mm'}
2645 Limit generated file names to the specified number @code{mm}
2646 of characters.
2647 This is useful if the
2648 resulting set of files is required to be interoperable with systems
2649 which limit the length of file names.
2650 No space is allowed between the @code{-k} and the numeric value. The numeric
2651 value may be omitted in which case a default of @code{-k8},
2652 suitable for use
2653 with DOS-like file systems, is used. If no @code{-k} switch
2654 is present then
2655 there is no limit on the length of file names.
2656 @end table
2658 @geindex -p (gnatchop)
2661 @table @asis
2663 @item @code{-p}
2665 Causes the file modification time stamp of the input file to be
2666 preserved and used for the time stamp of the output file(s). This may be
2667 useful for preserving coherency of time stamps in an environment where
2668 @code{gnatchop} is used as part of a standard build process.
2669 @end table
2671 @geindex -q (gnatchop)
2674 @table @asis
2676 @item @code{-q}
2678 Causes output of informational messages indicating the set of generated
2679 files to be suppressed. Warnings and error messages are unaffected.
2680 @end table
2682 @geindex -r (gnatchop)
2684 @geindex Source_Reference pragmas
2687 @table @asis
2689 @item @code{-r}
2691 Generate @code{Source_Reference} pragmas. Use this switch if the output
2692 files are regarded as temporary and development is to be done in terms
2693 of the original unchopped file. This switch causes
2694 @code{Source_Reference} pragmas to be inserted into each of the
2695 generated files to refers back to the original file name and line number.
2696 The result is that all error messages refer back to the original
2697 unchopped file.
2698 In addition, the debugging information placed into the object file (when
2699 the @code{-g} switch of @code{gcc} or @code{gnatmake} is
2700 specified)
2701 also refers back to this original file so that tools like profilers and
2702 debuggers will give information in terms of the original unchopped file.
2704 If the original file to be chopped itself contains
2705 a @code{Source_Reference}
2706 pragma referencing a third file, then gnatchop respects
2707 this pragma, and the generated @code{Source_Reference} pragmas
2708 in the chopped file refer to the original file, with appropriate
2709 line numbers. This is particularly useful when @code{gnatchop}
2710 is used in conjunction with @code{gnatprep} to compile files that
2711 contain preprocessing statements and multiple units.
2712 @end table
2714 @geindex -v (gnatchop)
2717 @table @asis
2719 @item @code{-v}
2721 Causes @code{gnatchop} to operate in verbose mode. The version
2722 number and copyright notice are output, as well as exact copies of
2723 the gnat1 commands spawned to obtain the chop control information.
2724 @end table
2726 @geindex -w (gnatchop)
2729 @table @asis
2731 @item @code{-w}
2733 Overwrite existing file names. Normally @code{gnatchop} regards it as a
2734 fatal error if there is already a file with the same name as a
2735 file it would otherwise output, in other words if the files to be
2736 chopped contain duplicated units. This switch bypasses this
2737 check, and causes all but the last instance of such duplicated
2738 units to be skipped.
2739 @end table
2741 @geindex --GCC= (gnatchop)
2744 @table @asis
2746 @item @code{--GCC=`xxxx'}
2748 Specify the path of the GNAT parser to be used. When this switch is used,
2749 no attempt is made to add the prefix to the GNAT parser executable.
2750 @end table
2752 @node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
2753 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{5e}@anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{5f}
2754 @subsubsection Examples of @code{gnatchop} Usage
2757 @example
2758 $ gnatchop -w hello_s.ada prerelease/files
2759 @end example
2761 Chops the source file @code{hello_s.ada}. The output files will be
2762 placed in the directory @code{prerelease/files},
2763 overwriting any
2764 files with matching names in that directory (no files in the current
2765 directory are modified).
2767 @example
2768 $ gnatchop archive
2769 @end example
2771 Chops the source file @code{archive}
2772 into the current directory. One
2773 useful application of @code{gnatchop} is in sending sets of sources
2774 around, for example in email messages. The required sources are simply
2775 concatenated (for example, using a Unix @code{cat}
2776 command), and then
2777 @code{gnatchop} is used at the other end to reconstitute the original
2778 file names.
2780 @example
2781 $ gnatchop file1 file2 file3 direc
2782 @end example
2784 Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
2785 the resulting files in the directory @code{direc}. Note that if any units
2786 occur more than once anywhere within this set of files, an error message
2787 is generated, and no files are written. To override this check, use the
2788 @code{-w} switch,
2789 in which case the last occurrence in the last file will
2790 be the one that is output, and earlier duplicate occurrences for a given
2791 unit will be skipped.
2793 @node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
2794 @anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{25}@anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{60}
2795 @section Configuration Pragmas
2798 @geindex Configuration pragmas
2800 @geindex Pragmas
2801 @geindex configuration
2803 Configuration pragmas include those pragmas described as
2804 such in the Ada Reference Manual, as well as
2805 implementation-dependent pragmas that are configuration pragmas.
2806 See the @code{Implementation_Defined_Pragmas} chapter in the
2807 @cite{GNAT_Reference_Manual} for details on these
2808 additional GNAT-specific configuration pragmas.
2809 Most notably, the pragma @code{Source_File_Name}, which allows
2810 specifying non-default names for source files, is a configuration
2811 pragma. The following is a complete list of configuration pragmas
2812 recognized by GNAT:
2814 @example
2815 Ada_83
2816 Ada_95
2817 Ada_05
2818 Ada_2005
2819 Ada_12
2820 Ada_2012
2821 Ada_2022
2822 Aggregate_Individually_Assign
2823 Allow_Integer_Address
2824 Annotate
2825 Assertion_Policy
2826 Assume_No_Invalid_Values
2827 C_Pass_By_Copy
2828 Check_Float_Overflow
2829 Check_Name
2830 Check_Policy
2831 Component_Alignment
2832 Convention_Identifier
2833 Debug_Policy
2834 Default_Scalar_Storage_Order
2835 Default_Storage_Pool
2836 Detect_Blocking
2837 Disable_Atomic_Synchronization
2838 Discard_Names
2839 Elaboration_Checks
2840 Eliminate
2841 Enable_Atomic_Synchronization
2842 Extend_System
2843 Extensions_Allowed
2844 External_Name_Casing
2845 Fast_Math
2846 Favor_Top_Level
2847 Ignore_Pragma
2848 Implicit_Packing
2849 Initialize_Scalars
2850 Interrupt_State
2851 Interrupts_System_By_Default
2852 License
2853 Locking_Policy
2854 No_Component_Reordering
2855 No_Heap_Finalization
2856 No_Strict_Aliasing
2857 Normalize_Scalars
2858 Optimize_Alignment
2859 Overflow_Mode
2860 Overriding_Renamings
2861 Partition_Elaboration_Policy
2862 Persistent_BSS
2863 Prefix_Exception_Messages
2864 Priority_Specific_Dispatching
2865 Profile
2866 Profile_Warnings
2867 Queuing_Policy
2868 Rename_Pragma
2869 Restrictions
2870 Restriction_Warnings
2871 Reviewable
2872 Short_Circuit_And_Or
2873 Source_File_Name
2874 Source_File_Name_Project
2875 SPARK_Mode
2876 Style_Checks
2877 Suppress
2878 Suppress_Exception_Locations
2879 Task_Dispatching_Policy
2880 Unevaluated_Use_Of_Old
2881 Unsuppress
2882 Use_VADS_Size
2883 User_Aspect_Definition
2884 Validity_Checks
2885 Warning_As_Error
2886 Warnings
2887 Wide_Character_Encoding
2888 @end example
2890 @menu
2891 * Handling of Configuration Pragmas:: 
2892 * The Configuration Pragmas Files:: 
2894 @end menu
2896 @node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
2897 @anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{3f}@anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{61}
2898 @subsection Handling of Configuration Pragmas
2901 Configuration pragmas may either appear at the start of a compilation
2902 unit, or they can appear in a configuration pragma file to apply to
2903 all compilations performed in a given compilation environment.
2905 GNAT also provides the @code{gnatchop} utility to provide an automatic
2906 way to handle configuration pragmas following the semantics for
2907 compilations (that is, files with multiple units), described in the RM.
2908 See @ref{59,,Operating gnatchop in Compilation Mode} for details.
2909 However, for most purposes, it will be more convenient to edit the
2910 @code{gnat.adc} file that contains configuration pragmas directly,
2911 as described in the following section.
2913 In the case of @code{Restrictions} pragmas appearing as configuration
2914 pragmas in individual compilation units, the exact handling depends on
2915 the type of restriction.
2917 Restrictions that require partition-wide consistency (like
2918 @code{No_Tasking}) are
2919 recognized wherever they appear
2920 and can be freely inherited, e.g. from a `with'ed unit to the `with'ing
2921 unit. This makes sense since the binder will in any case insist on seeing
2922 consistent use, so any unit not conforming to any restrictions that are
2923 anywhere in the partition will be rejected, and you might as well find
2924 that out at compile time rather than at bind time.
2926 For restrictions that do not require partition-wide consistency, e.g.
2927 SPARK or No_Implementation_Attributes, in general the restriction applies
2928 only to the unit in which the pragma appears, and not to any other units.
2930 The exception is No_Elaboration_Code which always applies to the entire
2931 object file from a compilation, i.e. to the body, spec, and all subunits.
2932 This restriction can be specified in a configuration pragma file, or it
2933 can be on the body and/or the spec (in either case it applies to all the
2934 relevant units). It can appear on a subunit only if it has previously
2935 appeared in the body of spec.
2937 @node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
2938 @anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{62}@anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{63}
2939 @subsection The Configuration Pragmas Files
2942 @geindex gnat.adc
2944 In GNAT a compilation environment is defined by the current
2945 directory at the time that a compile command is given. This current
2946 directory is searched for a file whose name is @code{gnat.adc}. If
2947 this file is present, it is expected to contain one or more
2948 configuration pragmas that will be applied to the current compilation.
2949 However, if the switch @code{-gnatA} is used, @code{gnat.adc} is not
2950 considered. When taken into account, @code{gnat.adc} is added to the
2951 dependencies, so that if @code{gnat.adc} is modified later, an invocation of
2952 @code{gnatmake} will recompile the source.
2954 Configuration pragmas may be entered into the @code{gnat.adc} file
2955 either by running @code{gnatchop} on a source file that consists only of
2956 configuration pragmas, or more conveniently by direct editing of the
2957 @code{gnat.adc} file, which is a standard format source file.
2959 Besides @code{gnat.adc}, additional files containing configuration
2960 pragmas may be applied to the current compilation using the switch
2961 @code{-gnatec=`path'} where @code{path} must designate an existing file that
2962 contains only configuration pragmas. These configuration pragmas are
2963 in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
2964 is present and switch @code{-gnatA} is not used).
2966 It is allowable to specify several switches @code{-gnatec=}, all of which
2967 will be taken into account.
2969 Files containing configuration pragmas specified with switches
2970 @code{-gnatec=} are added to the dependencies, unless they are
2971 temporary files. A file is considered temporary if its name ends in
2972 @code{.tmp} or @code{.TMP}. Certain tools follow this naming
2973 convention because they pass information to @code{gcc} via
2974 temporary files that are immediately deleted; it doesn’t make sense to
2975 depend on a file that no longer exists. Such tools include
2976 @code{gprbuild}, @code{gnatmake}, and @code{gnatcheck}.
2978 By default, configuration pragma files are stored by their absolute paths in
2979 ALI files. You can use the @code{-gnateb} switch in order to store them by
2980 their basename instead.
2982 If you are using project file, a separate mechanism is provided using
2983 project attributes.
2985 @c --Comment
2986 @c See :ref:`Specifying_Configuration_Pragmas` for more details.
2988 @node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
2989 @anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{26}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{64}
2990 @section Generating Object Files
2993 An Ada program consists of a set of source files, and the first step in
2994 compiling the program is to generate the corresponding object files.
2995 These are generated by compiling a subset of these source files.
2996 The files you need to compile are the following:
2999 @itemize *
3001 @item 
3002 If a package spec has no body, compile the package spec to produce the
3003 object file for the package.
3005 @item 
3006 If a package has both a spec and a body, compile the body to produce the
3007 object file for the package. The source file for the package spec need
3008 not be compiled in this case because there is only one object file, which
3009 contains the code for both the spec and body of the package.
3011 @item 
3012 For a subprogram, compile the subprogram body to produce the object file
3013 for the subprogram. The spec, if one is present, is as usual in a
3014 separate file, and need not be compiled.
3015 @end itemize
3017 @geindex Subunits
3020 @itemize *
3022 @item 
3023 In the case of subunits, only compile the parent unit. A single object
3024 file is generated for the entire subunit tree, which includes all the
3025 subunits.
3027 @item 
3028 Compile child units independently of their parent units
3029 (though, of course, the spec of all the ancestor unit must be present in order
3030 to compile a child unit).
3032 @geindex Generics
3034 @item 
3035 Compile generic units in the same manner as any other units. The object
3036 files in this case are small dummy files that contain at most the
3037 flag used for elaboration checking. This is because GNAT always handles generic
3038 instantiation by means of macro expansion. However, it is still necessary to
3039 compile generic units, for dependency checking and elaboration purposes.
3040 @end itemize
3042 The preceding rules describe the set of files that must be compiled to
3043 generate the object files for a program. Each object file has the same
3044 name as the corresponding source file, except that the extension is
3045 @code{.o} as usual.
3047 You may wish to compile other files for the purpose of checking their
3048 syntactic and semantic correctness. For example, in the case where a
3049 package has a separate spec and body, you would not normally compile the
3050 spec. However, it is convenient in practice to compile the spec to make
3051 sure it is error-free before compiling clients of this spec, because such
3052 compilations will fail if there is an error in the spec.
3054 GNAT provides an option for compiling such files purely for the
3055 purposes of checking correctness; such compilations are not required as
3056 part of the process of building a program. To compile a file in this
3057 checking mode, use the @code{-gnatc} switch.
3059 @node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3060 @anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{27}
3061 @section Source Dependencies
3064 A given object file clearly depends on the source file which is compiled
3065 to produce it. Here we are using “depends” in the sense of a typical
3066 @code{make} utility; in other words, an object file depends on a source
3067 file if changes to the source file require the object file to be
3068 recompiled.
3069 In addition to this basic dependency, a given object may depend on
3070 additional source files as follows:
3073 @itemize *
3075 @item 
3076 If a file being compiled `with's a unit @code{X}, the object file
3077 depends on the file containing the spec of unit @code{X}. This includes
3078 files that are `with'ed implicitly either because they are parents
3079 of `with'ed child units or they are run-time units required by the
3080 language constructs used in a particular unit.
3082 @item 
3083 If a file being compiled instantiates a library level generic unit, the
3084 object file depends on both the spec and body files for this generic
3085 unit.
3087 @item 
3088 If a file being compiled instantiates a generic unit defined within a
3089 package, the object file depends on the body file for the package as
3090 well as the spec file.
3091 @end itemize
3093 @geindex Inline
3095 @geindex -gnatn switch
3098 @itemize *
3100 @item 
3101 If a file being compiled contains a call to a subprogram for which
3102 pragma @code{Inline} applies and inlining is activated with the
3103 @code{-gnatn} switch, the object file depends on the file containing the
3104 body of this subprogram as well as on the file containing the spec. Note
3105 that for inlining to actually occur as a result of the use of this switch,
3106 it is necessary to compile in optimizing mode.
3108 @geindex -gnatN switch
3110 The use of @code{-gnatN} activates  inlining optimization
3111 that is performed by the front end of the compiler. This inlining does
3112 not require that the code generation be optimized. Like @code{-gnatn},
3113 the use of this switch generates additional dependencies.
3115 When using a gcc-based back end, then the use of
3116 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
3117 Historically front end inlining was more extensive than the gcc back end
3118 inlining, but that is no longer the case.
3120 @item 
3121 If an object file @code{O} depends on the proper body of a subunit through
3122 inlining or instantiation, it depends on the parent unit of the subunit.
3123 This means that any modification of the parent unit or one of its subunits
3124 affects the compilation of @code{O}.
3126 @item 
3127 The object file for a parent unit depends on all its subunit body files.
3129 @item 
3130 The previous two rules meant that for purposes of computing dependencies and
3131 recompilation, a body and all its subunits are treated as an indivisible whole.
3133 These rules are applied transitively: if unit @code{A} `with's
3134 unit @code{B}, whose elaboration calls an inlined procedure in package
3135 @code{C}, the object file for unit @code{A} will depend on the body of
3136 @code{C}, in file @code{c.adb}.
3138 The set of dependent files described by these rules includes all the
3139 files on which the unit is semantically dependent, as dictated by the
3140 Ada language standard. However, it is a superset of what the
3141 standard describes, because it includes generic, inline, and subunit
3142 dependencies.
3144 An object file must be recreated by recompiling the corresponding source
3145 file if any of the source files on which it depends are modified. For
3146 example, if the @code{make} utility is used to control compilation,
3147 the rule for an Ada object file must mention all the source files on
3148 which the object file depends, according to the above definition.
3149 The determination of the necessary
3150 recompilations is done automatically when one uses @code{gnatmake}.
3151 @end itemize
3153 @node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3154 @anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{66}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{28}
3155 @section The Ada Library Information Files
3158 @geindex Ada Library Information files
3160 @geindex ALI files
3162 Each compilation actually generates two output files. The first of these
3163 is the normal object file that has a @code{.o} extension. The second is a
3164 text file containing full dependency information. It has the same
3165 name as the source file, but an @code{.ali} extension.
3166 This file is known as the Ada Library Information (@code{ALI}) file.
3167 The following information is contained in the @code{ALI} file.
3170 @itemize *
3172 @item 
3173 Version information (indicates which version of GNAT was used to compile
3174 the unit(s) in question)
3176 @item 
3177 Main program information (including priority and time slice settings,
3178 as well as the wide character encoding used during compilation).
3180 @item 
3181 List of arguments used in the @code{gcc} command for the compilation
3183 @item 
3184 Attributes of the unit, including configuration pragmas used, an indication
3185 of whether the compilation was successful, exception model used etc.
3187 @item 
3188 A list of relevant restrictions applying to the unit (used for consistency)
3189 checking.
3191 @item 
3192 Categorization information (e.g., use of pragma @code{Pure}).
3194 @item 
3195 Information on all `with'ed units, including presence of
3196 @code{Elaborate} or @code{Elaborate_All} pragmas.
3198 @item 
3199 Information from any @code{Linker_Options} pragmas used in the unit
3201 @item 
3202 Information on the use of @code{Body_Version} or @code{Version}
3203 attributes in the unit.
3205 @item 
3206 Dependency information. This is a list of files, together with
3207 time stamp and checksum information. These are files on which
3208 the unit depends in the sense that recompilation is required
3209 if any of these units are modified.
3211 @item 
3212 Cross-reference data. Contains information on all entities referenced
3213 in the unit. Used by some tools to provide cross-reference information.
3214 @end itemize
3216 For a full detailed description of the format of the @code{ALI} file,
3217 see the source of the body of unit @code{Lib.Writ}, contained in file
3218 @code{lib-writ.adb} in the GNAT compiler sources.
3220 @node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3221 @anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{29}@anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{67}
3222 @section Binding an Ada Program
3225 When using languages such as C and C++, once the source files have been
3226 compiled the only remaining step in building an executable program
3227 is linking the object modules together. This means that it is possible to
3228 link an inconsistent version of a program, in which two units have
3229 included different versions of the same header.
3231 The rules of Ada do not permit such an inconsistent program to be built.
3232 For example, if two clients have different versions of the same package,
3233 it is illegal to build a program containing these two clients.
3234 These rules are enforced by the GNAT binder, which also determines an
3235 elaboration order consistent with the Ada rules.
3237 The GNAT binder is run after all the object files for a program have
3238 been created. It is given the name of the main program unit, and from
3239 this it determines the set of units required by the program, by reading the
3240 corresponding ALI files. It generates error messages if the program is
3241 inconsistent or if no valid order of elaboration exists.
3243 If no errors are detected, the binder produces a main program, in Ada by
3244 default, that contains calls to the elaboration procedures of those
3245 compilation unit that require them, followed by
3246 a call to the main program. This Ada program is compiled to generate the
3247 object file for the main program. The name of
3248 the Ada file is @code{b~xxx.adb} (with the corresponding spec
3249 @code{b~xxx.ads}) where @code{xxx} is the name of the
3250 main program unit.
3252 Finally, the linker is used to build the resulting executable program,
3253 using the object from the main program from the bind step as well as the
3254 object files for the Ada units of the program.
3256 @node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3257 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{2a}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{68}
3258 @section GNAT and Libraries
3261 @geindex Library building and using
3263 This section describes how to build and use libraries with GNAT, and also shows
3264 how to recompile the GNAT run-time library. You should be familiar with the
3265 Project Manager facility (see the `GNAT_Project_Manager' chapter of the
3266 `GPRbuild User’s Guide') before reading this chapter.
3268 @menu
3269 * Introduction to Libraries in GNAT:: 
3270 * General Ada Libraries:: 
3271 * Stand-alone Ada Libraries:: 
3272 * Rebuilding the GNAT Run-Time Library:: 
3274 @end menu
3276 @node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3277 @anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{69}@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{6a}
3278 @subsection Introduction to Libraries in GNAT
3281 A library is, conceptually, a collection of objects which does not have its
3282 own main thread of execution, but rather provides certain services to the
3283 applications that use it. A library can be either statically linked with the
3284 application, in which case its code is directly included in the application,
3285 or, on platforms that support it, be dynamically linked, in which case
3286 its code is shared by all applications making use of this library.
3288 GNAT supports both types of libraries.
3289 In the static case, the compiled code can be provided in different ways. The
3290 simplest approach is to provide directly the set of objects resulting from
3291 compilation of the library source files. Alternatively, you can group the
3292 objects into an archive using whatever commands are provided by the operating
3293 system. For the latter case, the objects are grouped into a shared library.
3295 In the GNAT environment, a library has three types of components:
3298 @itemize *
3300 @item 
3301 Source files,
3303 @item 
3304 @code{ALI} files (see @ref{28,,The Ada Library Information Files}), and
3306 @item 
3307 Object files, an archive or a shared library.
3308 @end itemize
3310 A GNAT library may expose all its source files, which is useful for
3311 documentation purposes. Alternatively, it may expose only the units needed by
3312 an external user to make use of the library. That is to say, the specs
3313 reflecting the library services along with all the units needed to compile
3314 those specs, which can include generic bodies or any body implementing an
3315 inlined routine. In the case of `stand-alone libraries' those exposed
3316 units are called `interface units' (@ref{6b,,Stand-alone Ada Libraries}).
3318 All compilation units comprising an application, including those in a library,
3319 need to be elaborated in an order partially defined by Ada’s semantics. GNAT
3320 computes the elaboration order from the @code{ALI} files and this is why they
3321 constitute a mandatory part of GNAT libraries.
3322 `Stand-alone libraries' are the exception to this rule because a specific
3323 library elaboration routine is produced independently of the application(s)
3324 using the library.
3326 @node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3327 @anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{6d}
3328 @subsection General Ada Libraries
3331 @menu
3332 * Building a library:: 
3333 * Installing a library:: 
3334 * Using a library:: 
3336 @end menu
3338 @node Building a library,Installing a library,,General Ada Libraries
3339 @anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{6e}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{6f}
3340 @subsubsection Building a library
3343 The easiest way to build a library is to use the Project Manager,
3344 which supports a special type of project called a `Library Project'
3345 (see the `Library Projects' section in the `GNAT Project Manager'
3346 chapter of the `GPRbuild User’s Guide').
3348 A project is considered a library project, when two project-level attributes
3349 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
3350 control different aspects of library configuration, additional optional
3351 project-level attributes can be specified:
3354 @itemize *
3356 @item 
3358 @table @asis
3360 @item @code{Library_Kind}
3362 This attribute controls whether the library is to be static or dynamic
3363 @end table
3365 @item 
3367 @table @asis
3369 @item @code{Library_Version}
3371 This attribute specifies the library version; this value is used
3372 during dynamic linking of shared libraries to determine if the currently
3373 installed versions of the binaries are compatible.
3374 @end table
3376 @item 
3377 @code{Library_Options}
3379 @item 
3381 @table @asis
3383 @item @code{Library_GCC}
3385 These attributes specify additional low-level options to be used during
3386 library generation, and redefine the actual application used to generate
3387 library.
3388 @end table
3389 @end itemize
3391 The GNAT Project Manager takes full care of the library maintenance task,
3392 including recompilation of the source files for which objects do not exist
3393 or are not up to date, assembly of the library archive, and installation of
3394 the library (i.e., copying associated source, object and @code{ALI} files
3395 to the specified location).
3397 Here is a simple library project file:
3399 @example
3400 project My_Lib is
3401   for Source_Dirs use ("src1", "src2");
3402   for Object_Dir use "obj";
3403   for Library_Name use "mylib";
3404   for Library_Dir use "lib";
3405   for Library_Kind use "dynamic";
3406 end My_lib;
3407 @end example
3409 and the compilation command to build and install the library:
3411 @example
3412 $ gnatmake -Pmy_lib
3413 @end example
3415 It is not entirely trivial to perform manually all the steps required to
3416 produce a library. We recommend that you use the GNAT Project Manager
3417 for this task. In special cases where this is not desired, the necessary
3418 steps are discussed below.
3420 There are various possibilities for compiling the units that make up the
3421 library: for example with a Makefile (@ref{70,,Using the GNU make Utility}) or
3422 with a conventional script. For simple libraries, it is also possible to create
3423 a dummy main program which depends upon all the packages that comprise the
3424 interface of the library. This dummy main program can then be given to
3425 @code{gnatmake}, which will ensure that all necessary objects are built.
3427 After this task is accomplished, you should follow the standard procedure
3428 of the underlying operating system to produce the static or shared library.
3430 Here is an example of such a dummy program:
3432 @example
3433 with My_Lib.Service1;
3434 with My_Lib.Service2;
3435 with My_Lib.Service3;
3436 procedure My_Lib_Dummy is
3437 begin
3438    null;
3439 end;
3440 @end example
3442 Here are the generic commands that will build an archive or a shared library.
3444 @example
3445 # compiling the library
3446 $ gnatmake -c my_lib_dummy.adb
3448 # we don't need the dummy object itself
3449 $ rm my_lib_dummy.o my_lib_dummy.ali
3451 # create an archive with the remaining objects
3452 $ ar rc libmy_lib.a *.o
3453 # some systems may require "ranlib" to be run as well
3455 # or create a shared library
3456 $ gcc -shared -o libmy_lib.so *.o
3457 # some systems may require the code to have been compiled with -fPIC
3459 # remove the object files that are now in the library
3460 $ rm *.o
3462 # Make the ALI files read-only so that gnatmake will not try to
3463 # regenerate the objects that are in the library
3464 $ chmod -w *.ali
3465 @end example
3467 Please note that the library must have a name of the form @code{lib`xxx'.a}
3468 or @code{lib`xxx'.so} (or @code{lib`xxx'.dll} on Windows) in order to
3469 be accessed by the directive @code{-l`xxx'} at link time.
3471 @node Installing a library,Using a library,Building a library,General Ada Libraries
3472 @anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{72}
3473 @subsubsection Installing a library
3476 @geindex ADA_PROJECT_PATH
3478 @geindex GPR_PROJECT_PATH
3480 If you use project files, library installation is part of the library build
3481 process (see the `Installing a Library with Project Files' section of the
3482 `GNAT Project Manager' chapter of the `GPRbuild User’s Guide').
3484 When project files are not an option, it is also possible, but not recommended,
3485 to install the library so that the sources needed to use the library are on the
3486 Ada source path and the ALI files & libraries be on the Ada Object path (see
3487 @ref{73,,Search Paths and the Run-Time Library (RTL)}). Alternatively, the system
3488 administrator can place general-purpose libraries in the default compiler
3489 paths, by specifying the libraries’ location in the configuration files
3490 @code{ada_source_path} and @code{ada_object_path}. These configuration files
3491 must be located in the GNAT installation tree at the same place as the gcc spec
3492 file. The location of the gcc spec file can be determined as follows:
3494 @example
3495 $ gcc -v
3496 @end example
3498 The configuration files mentioned above have a simple format: each line
3499 must contain one unique directory name.
3500 Those names are added to the corresponding path
3501 in their order of appearance in the file. The names can be either absolute
3502 or relative; in the latter case, they are relative to where theses files
3503 are located.
3505 The files @code{ada_source_path} and @code{ada_object_path} might not be
3506 present in a
3507 GNAT installation, in which case, GNAT will look for its run-time library in
3508 the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3509 objects and @code{ALI} files). When the files exist, the compiler does not
3510 look in @code{adainclude} and @code{adalib}, and thus the
3511 @code{ada_source_path} file
3512 must contain the location for the GNAT run-time sources (which can simply
3513 be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3514 contain the location for the GNAT run-time objects (which can simply
3515 be @code{adalib}).
3517 You can also specify a new default path to the run-time library at compilation
3518 time with the switch @code{--RTS=rts-path}. You can thus choose / change
3519 the run-time library you want your program to be compiled with. This switch is
3520 recognized by @code{gcc}, @code{gnatmake}, @code{gnatbind}, @code{gnatls}, and all
3521 project aware tools.
3523 It is possible to install a library before or after the standard GNAT
3524 library, by reordering the lines in the configuration files. In general, a
3525 library must be installed before the GNAT library if it redefines
3526 any part of it.
3528 @node Using a library,,Installing a library,General Ada Libraries
3529 @anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{74}@anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{75}
3530 @subsubsection Using a library
3533 Once again, the project facility greatly simplifies the use of
3534 libraries. In this context, using a library is just a matter of adding a
3535 `with' clause in the user project. For instance, to make use of the
3536 library @code{My_Lib} shown in examples in earlier sections, you can
3537 write:
3539 @example
3540 with "my_lib";
3541 project My_Proj is
3542   ...
3543 end My_Proj;
3544 @end example
3546 Even if you have a third-party, non-Ada library, you can still use GNAT’s
3547 Project Manager facility to provide a wrapper for it. For example, the
3548 following project, when `with'ed by your main project, will link with the
3549 third-party library @code{liba.a}:
3551 @example
3552 project Liba is
3553    for Externally_Built use "true";
3554    for Source_Files use ();
3555    for Library_Dir use "lib";
3556    for Library_Name use "a";
3557    for Library_Kind use "static";
3558 end Liba;
3559 @end example
3561 This is an alternative to the use of @code{pragma Linker_Options}. It is
3562 especially interesting in the context of systems with several interdependent
3563 static libraries where finding a proper linker order is not easy and best be
3564 left to the tools having visibility over project dependence information.
3566 In order to use an Ada library manually, you need to make sure that this
3567 library is on both your source and object path
3568 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}
3569 and @ref{76,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3570 in an archive or a shared library, you need to specify the desired
3571 library at link time.
3573 For example, you can use the library @code{mylib} installed in
3574 @code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3576 @example
3577 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3578   -largs -lmy_lib
3579 @end example
3581 This can be expressed more simply:
3583 @example
3584 $ gnatmake my_appl
3585 @end example
3587 when the following conditions are met:
3590 @itemize *
3592 @item 
3593 @code{/dir/my_lib_src} has been added by the user to the environment
3594 variable 
3595 @geindex ADA_INCLUDE_PATH
3596 @geindex environment variable; ADA_INCLUDE_PATH
3597 @code{ADA_INCLUDE_PATH}, or by the administrator to the file
3598 @code{ada_source_path}
3600 @item 
3601 @code{/dir/my_lib_obj} has been added by the user to the environment
3602 variable 
3603 @geindex ADA_OBJECTS_PATH
3604 @geindex environment variable; ADA_OBJECTS_PATH
3605 @code{ADA_OBJECTS_PATH}, or by the administrator to the file
3606 @code{ada_object_path}
3608 @item 
3609 a pragma @code{Linker_Options} has been added to one of the sources.
3610 For example:
3612 @example
3613 pragma Linker_Options ("-lmy_lib");
3614 @end example
3615 @end itemize
3617 Note that you may also load a library dynamically at
3618 run time given its filename, as illustrated in the GNAT @code{plugins} example
3619 in the directory @code{share/examples/gnat/plugins} within the GNAT
3620 install area.
3622 @node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3623 @anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{6b}
3624 @subsection Stand-alone Ada Libraries
3627 @geindex Stand-alone libraries
3629 @menu
3630 * Introduction to Stand-alone Libraries:: 
3631 * Building a Stand-alone Library:: 
3632 * Creating a Stand-alone Library to be used in a non-Ada context:: 
3633 * Restrictions in Stand-alone Libraries:: 
3635 @end menu
3637 @node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3638 @anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{78}@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{79}
3639 @subsubsection Introduction to Stand-alone Libraries
3642 A Stand-alone Library (abbreviated ‘SAL’) is a library that contains the
3643 necessary code to
3644 elaborate the Ada units that are included in the library. In contrast with
3645 an ordinary library, which consists of all sources, objects and @code{ALI}
3646 files of the
3647 library, a SAL may specify a restricted subset of compilation units
3648 to serve as a library interface. In this case, the fully
3649 self-sufficient set of files will normally consist of an objects
3650 archive, the sources of interface units’ specs, and the @code{ALI}
3651 files of interface units.
3652 If an interface spec contains a generic unit or an inlined subprogram,
3653 the body’s
3654 source must also be provided; if the units that must be provided in the source
3655 form depend on other units, the source and @code{ALI} files of those must
3656 also be provided.
3658 The main purpose of a SAL is to minimize the recompilation overhead of client
3659 applications when a new version of the library is installed. Specifically,
3660 if the interface sources have not changed, client applications do not need to
3661 be recompiled. If, furthermore, a SAL is provided in the shared form and its
3662 version, controlled by @code{Library_Version} attribute, is not changed,
3663 then the clients do not need to be relinked.
3665 SALs also allow the library providers to minimize the amount of library source
3666 text exposed to the clients.  Such ‘information hiding’ might be useful or
3667 necessary for various reasons.
3669 Stand-alone libraries are also well suited to be used in an executable whose
3670 main routine is not written in Ada.
3672 @node Building a Stand-alone Library,Creating a Stand-alone Library to be used in a non-Ada context,Introduction to Stand-alone Libraries,Stand-alone Ada Libraries
3673 @anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{7a}@anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{7b}
3674 @subsubsection Building a Stand-alone Library
3677 GNAT’s Project facility provides a simple way of building and installing
3678 stand-alone libraries; see the `Stand-alone Library Projects' section
3679 in the `GNAT Project Manager' chapter of the `GPRbuild User’s Guide'.
3680 To be a Stand-alone Library Project, in addition to the two attributes
3681 that make a project a Library Project (@code{Library_Name} and
3682 @code{Library_Dir}; see the `Library Projects' section in the
3683 `GNAT Project Manager' chapter of the `GPRbuild User’s Guide'),
3684 the attribute @code{Library_Interface} must be defined.  For example:
3686 @example
3687 for Library_Dir use "lib_dir";
3688 for Library_Name use "dummy";
3689 for Library_Interface use ("int1", "int1.child");
3690 @end example
3692 Attribute @code{Library_Interface} has a non-empty string list value,
3693 each string in the list designating a unit contained in an immediate source
3694 of the project file.
3696 When a Stand-alone Library is built, first the binder is invoked to build
3697 a package whose name depends on the library name
3698 (@code{b~dummy.ads/b} in the example above).
3699 This binder-generated package includes initialization and
3700 finalization procedures whose
3701 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
3702 in the example
3703 above). The object corresponding to this package is included in the library.
3705 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3706 calling of these procedures if a static SAL is built, or if a shared SAL
3707 is built
3708 with the project-level attribute @code{Library_Auto_Init} set to
3709 @code{"false"}.
3711 For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
3712 (those that are listed in attribute @code{Library_Interface}) are copied to
3713 the Library Directory. As a consequence, only the Interface Units may be
3714 imported from Ada units outside of the library. If other units are imported,
3715 the binding phase will fail.
3717 It is also possible to build an encapsulated library where not only
3718 the code to elaborate and finalize the library is embedded but also
3719 ensuring that the library is linked only against static
3720 libraries. So an encapsulated library only depends on system
3721 libraries, all other code, including the GNAT runtime, is embedded. To
3722 build an encapsulated library the attribute
3723 @code{Library_Standalone} must be set to @code{encapsulated}:
3725 @example
3726 for Library_Dir use "lib_dir";
3727 for Library_Name use "dummy";
3728 for Library_Kind use "dynamic";
3729 for Library_Interface use ("int1", "int1.child");
3730 for Library_Standalone use "encapsulated";
3731 @end example
3733 The default value for this attribute is @code{standard} in which case
3734 a stand-alone library is built.
3736 The attribute @code{Library_Src_Dir} may be specified for a
3737 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
3738 single string value. Its value must be the path (absolute or relative to the
3739 project directory) of an existing directory. This directory cannot be the
3740 object directory or one of the source directories, but it can be the same as
3741 the library directory. The sources of the Interface
3742 Units of the library that are needed by an Ada client of the library will be
3743 copied to the designated directory, called the Interface Copy directory.
3744 These sources include the specs of the Interface Units, but they may also
3745 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
3746 are used, or when there is a generic unit in the spec. Before the sources
3747 are copied to the Interface Copy directory, an attempt is made to delete all
3748 files in the Interface Copy directory.
3750 Building stand-alone libraries by hand is somewhat tedious, but for those
3751 occasions when it is necessary here are the steps that you need to perform:
3754 @itemize *
3756 @item 
3757 Compile all library sources.
3759 @item 
3760 Invoke the binder with the switch @code{-n} (No Ada main program),
3761 with all the @code{ALI} files of the interfaces, and
3762 with the switch @code{-L} to give specific names to the @code{init}
3763 and @code{final} procedures.  For example:
3765 @example
3766 $ gnatbind -n int1.ali int2.ali -Lsal1
3767 @end example
3769 @item 
3770 Compile the binder generated file:
3772 @example
3773 $ gcc -c b~int2.adb
3774 @end example
3776 @item 
3777 Link the dynamic library with all the necessary object files,
3778 indicating to the linker the names of the @code{init} (and possibly
3779 @code{final}) procedures for automatic initialization (and finalization).
3780 The built library should be placed in a directory different from
3781 the object directory.
3783 @item 
3784 Copy the @code{ALI} files of the interface to the library directory,
3785 add in this copy an indication that it is an interface to a SAL
3786 (i.e., add a word @code{SL} on the line in the @code{ALI} file that starts
3787 with letter ‘P’) and make the modified copy of the @code{ALI} file
3788 read-only.
3789 @end itemize
3791 Using SALs is not different from using other libraries
3792 (see @ref{75,,Using a library}).
3794 @node Creating a Stand-alone Library to be used in a non-Ada context,Restrictions in Stand-alone Libraries,Building a Stand-alone Library,Stand-alone Ada Libraries
3795 @anchor{gnat_ugn/the_gnat_compilation_model creating-a-stand-alone-library-to-be-used-in-a-non-ada-context}@anchor{7c}@anchor{gnat_ugn/the_gnat_compilation_model id44}@anchor{7d}
3796 @subsubsection Creating a Stand-alone Library to be used in a non-Ada context
3799 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
3800 a non-Ada context.
3802 The only extra step required is to ensure that library interface subprograms
3803 are compatible with the main program, by means of @code{pragma Export}
3804 or @code{pragma Convention}.
3806 Here is an example of simple library interface for use with C main program:
3808 @example
3809 package My_Package is
3811    procedure Do_Something;
3812    pragma Export (C, Do_Something, "do_something");
3814    procedure Do_Something_Else;
3815    pragma Export (C, Do_Something_Else, "do_something_else");
3817 end My_Package;
3818 @end example
3820 On the foreign language side, you must provide a ‘foreign’ view of the
3821 library interface; remember that it should contain elaboration routines in
3822 addition to interface subprograms.
3824 The example below shows the content of @code{mylib_interface.h} (note
3825 that there is no rule for the naming of this file, any name can be used)
3827 @example
3828 /* the library elaboration procedure */
3829 extern void mylibinit (void);
3831 /* the library finalization procedure */
3832 extern void mylibfinal (void);
3834 /* the interface exported by the library */
3835 extern void do_something (void);
3836 extern void do_something_else (void);
3837 @end example
3839 Libraries built as explained above can be used from any program, provided
3840 that the elaboration procedures (named @code{mylibinit} in the previous
3841 example) are called before the library services are used. Any number of
3842 libraries can be used simultaneously, as long as the elaboration
3843 procedure of each library is called.
3845 Below is an example of a C program that uses the @code{mylib} library.
3847 @example
3848 #include "mylib_interface.h"
3851 main (void)
3853    /* First, elaborate the library before using it */
3854    mylibinit ();
3856    /* Main program, using the library exported entities */
3857    do_something ();
3858    do_something_else ();
3860    /* Library finalization at the end of the program */
3861    mylibfinal ();
3862    return 0;
3864 @end example
3866 Note that invoking any library finalization procedure generated by
3867 @code{gnatbind} shuts down the Ada run-time environment.
3868 Consequently, the
3869 finalization of all Ada libraries must be performed at the end of the program.
3870 No call to these libraries or to the Ada run-time library should be made
3871 after the finalization phase.
3873 Information on limitations of binding Ada code in non-Ada contexts can be
3874 found under @ref{7e,,Binding with Non-Ada Main Programs}.
3876 Note also that special care must be taken with multi-tasks
3877 applications. The initialization and finalization routines are not
3878 protected against concurrent access. If such requirement is needed it
3879 must be ensured at the application level using a specific operating
3880 system services like a mutex or a critical-section.
3882 @node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
3883 @anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{7f}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{80}
3884 @subsubsection Restrictions in Stand-alone Libraries
3887 The pragmas listed below should be used with caution inside libraries,
3888 as they can create incompatibilities with other Ada libraries:
3891 @itemize *
3893 @item 
3894 pragma @code{Locking_Policy}
3896 @item 
3897 pragma @code{Partition_Elaboration_Policy}
3899 @item 
3900 pragma @code{Queuing_Policy}
3902 @item 
3903 pragma @code{Task_Dispatching_Policy}
3905 @item 
3906 pragma @code{Unreserve_All_Interrupts}
3907 @end itemize
3909 When using a library that contains such pragmas, the user must make sure
3910 that all libraries use the same pragmas with the same values. Otherwise,
3911 @code{Program_Error} will
3912 be raised during the elaboration of the conflicting
3913 libraries. The usage of these pragmas and its consequences for the user
3914 should therefore be well documented.
3916 Similarly, the traceback in the exception occurrence mechanism should be
3917 enabled or disabled in a consistent manner across all libraries.
3918 Otherwise, Program_Error will be raised during the elaboration of the
3919 conflicting libraries.
3921 If the @code{Version} or @code{Body_Version}
3922 attributes are used inside a library, then you need to
3923 perform a @code{gnatbind} step that specifies all @code{ALI} files in all
3924 libraries, so that version identifiers can be properly computed.
3925 In practice these attributes are rarely used, so this is unlikely
3926 to be a consideration.
3928 @node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
3929 @anchor{gnat_ugn/the_gnat_compilation_model id46}@anchor{81}@anchor{gnat_ugn/the_gnat_compilation_model rebuilding-the-gnat-run-time-library}@anchor{82}
3930 @subsection Rebuilding the GNAT Run-Time Library
3933 @geindex GNAT Run-Time Library
3934 @geindex rebuilding
3936 @geindex Building the GNAT Run-Time Library
3938 @geindex Rebuilding the GNAT Run-Time Library
3940 @geindex Run-Time Library
3941 @geindex rebuilding
3943 It may be useful to recompile the GNAT library in various debugging or
3944 experimentation contexts. A project file called
3945 @code{libada.gpr} is provided to that effect and can be found in
3946 the directory containing the GNAT library. The location of this
3947 directory depends on the way the GNAT environment has been installed and can
3948 be determined by means of the command:
3950 @example
3951 $ gnatls -v
3952 @end example
3954 The last entry in the source search path usually contains the
3955 gnat library (the @code{adainclude} directory). This project file contains its
3956 own documentation and in particular the set of instructions needed to rebuild a
3957 new library and to use it.
3959 Note that rebuilding the GNAT Run-Time is only recommended for temporary
3960 experiments or debugging, and is not supported.
3962 @geindex Conditional compilation
3964 @node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
3965 @anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{2b}@anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{83}
3966 @section Conditional Compilation
3969 This section presents some guidelines for modeling conditional compilation in Ada and describes the
3970 gnatprep preprocessor utility.
3972 @geindex Conditional compilation
3974 @menu
3975 * Modeling Conditional Compilation in Ada:: 
3976 * Preprocessing with gnatprep:: 
3977 * Integrated Preprocessing:: 
3979 @end menu
3981 @node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
3982 @anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{84}@anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{85}
3983 @subsection Modeling Conditional Compilation in Ada
3986 It is often necessary to arrange for a single source program
3987 to serve multiple purposes, where it is compiled in different
3988 ways to achieve these different goals. Some examples of the
3989 need for this feature are
3992 @itemize *
3994 @item 
3995 Adapting a program to a different hardware environment
3997 @item 
3998 Adapting a program to a different target architecture
4000 @item 
4001 Turning debugging features on and off
4003 @item 
4004 Arranging for a program to compile with different compilers
4005 @end itemize
4007 In C, or C++, the typical approach would be to use the preprocessor
4008 that is defined as part of the language. The Ada language does not
4009 contain such a feature. This is not an oversight, but rather a very
4010 deliberate design decision, based on the experience that overuse of
4011 the preprocessing features in C and C++ can result in programs that
4012 are extremely difficult to maintain. For example, if we have ten
4013 switches that can be on or off, this means that there are a thousand
4014 separate programs, any one of which might not even be syntactically
4015 correct, and even if syntactically correct, the resulting program
4016 might not work correctly. Testing all combinations can quickly become
4017 impossible.
4019 Nevertheless, the need to tailor programs certainly exists, and in
4020 this section we will discuss how this can
4021 be achieved using Ada in general, and GNAT in particular.
4023 @menu
4024 * Use of Boolean Constants:: 
4025 * Debugging - A Special Case:: 
4026 * Conditionalizing Declarations:: 
4027 * Use of Alternative Implementations:: 
4028 * Preprocessing:: 
4030 @end menu
4032 @node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4033 @anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{86}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{87}
4034 @subsubsection Use of Boolean Constants
4037 In the case where the difference is simply which code
4038 sequence is executed, the cleanest solution is to use Boolean
4039 constants to control which code is executed.
4041 @example
4042 FP_Initialize_Required : constant Boolean := True;
4044 if FP_Initialize_Required then
4046 end if;
4047 @end example
4049 Not only will the code inside the @code{if} statement not be executed if
4050 the constant Boolean is @code{False}, but it will also be completely
4051 deleted from the program.
4052 However, the code is only deleted after the @code{if} statement
4053 has been checked for syntactic and semantic correctness.
4054 (In contrast, with preprocessors the code is deleted before the
4055 compiler ever gets to see it, so it is not checked until the switch
4056 is turned on.)
4058 @geindex Preprocessors (contrasted with conditional compilation)
4060 Typically the Boolean constants will be in a separate package,
4061 something like:
4063 @example
4064 package Config is
4065    FP_Initialize_Required : constant Boolean := True;
4066    Reset_Available        : constant Boolean := False;
4067    ...
4068 end Config;
4069 @end example
4071 The @code{Config} package exists in multiple forms for the various targets,
4072 with an appropriate script selecting the version of @code{Config} needed.
4073 Then any other unit requiring conditional compilation can do a `with'
4074 of @code{Config} to make the constants visible.
4076 @node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4077 @anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{88}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{89}
4078 @subsubsection Debugging - A Special Case
4081 A common use of conditional code is to execute statements (for example
4082 dynamic checks, or output of intermediate results) under control of a
4083 debug switch, so that the debugging behavior can be turned on and off.
4084 This can be done using a Boolean constant to control whether the code
4085 is active:
4087 @example
4088 if Debugging then
4089    Put_Line ("got to the first stage!");
4090 end if;
4091 @end example
4095 @example
4096 if Debugging and then Temperature > 999.0 then
4097    raise Temperature_Crazy;
4098 end if;
4099 @end example
4101 @geindex pragma Assert
4103 Since this is a common case, there are special features to deal with
4104 this in a convenient manner. For the case of tests, Ada 2005 has added
4105 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
4106 on the @code{Assert} pragma that has always been available in GNAT, so this
4107 feature may be used with GNAT even if you are not using Ada 2005 features.
4108 The use of pragma @code{Assert} is described in the
4109 @cite{GNAT_Reference_Manual}, but as an
4110 example, the last test could be written:
4112 @example
4113 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4114 @end example
4116 or simply
4118 @example
4119 pragma Assert (Temperature <= 999.0);
4120 @end example
4122 In both cases, if assertions are active and the temperature is excessive,
4123 the exception @code{Assert_Failure} will be raised, with the given string in
4124 the first case or a string indicating the location of the pragma in the second
4125 case used as the exception message.
4127 @geindex pragma Assertion_Policy
4129 You can turn assertions on and off by using the @code{Assertion_Policy}
4130 pragma.
4132 @geindex -gnata switch
4134 This is an Ada 2005 pragma which is implemented in all modes by
4135 GNAT. Alternatively, you can use the @code{-gnata} switch
4136 to enable assertions from the command line, which applies to
4137 all versions of Ada.
4139 @geindex pragma Debug
4141 For the example above with the @code{Put_Line}, the GNAT-specific pragma
4142 @code{Debug} can be used:
4144 @example
4145 pragma Debug (Put_Line ("got to the first stage!"));
4146 @end example
4148 If debug pragmas are enabled, the argument, which must be of the form of
4149 a procedure call, is executed (in this case, @code{Put_Line} will be called).
4150 Only one call can be present, but of course a special debugging procedure
4151 containing any code you like can be included in the program and then
4152 called in a pragma @code{Debug} argument as needed.
4154 One advantage of pragma @code{Debug} over the @code{if Debugging then}
4155 construct is that pragma @code{Debug} can appear in declarative contexts,
4156 such as at the very beginning of a procedure, before local declarations have
4157 been elaborated.
4159 @geindex pragma Debug_Policy
4161 Debug pragmas are enabled using either the @code{-gnata} switch that also
4162 controls assertions, or with a separate Debug_Policy pragma.
4164 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4165 in Ada 95 and Ada 83 programs as well), and is analogous to
4166 pragma @code{Assertion_Policy} to control assertions.
4168 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
4169 and thus they can appear in @code{gnat.adc} if you are not using a
4170 project file, or in the file designated to contain configuration pragmas
4171 in a project file.
4172 They then apply to all subsequent compilations. In practice the use of
4173 the @code{-gnata} switch is often the most convenient method of controlling
4174 the status of these pragmas.
4176 Note that a pragma is not a statement, so in contexts where a statement
4177 sequence is required, you can’t just write a pragma on its own. You have
4178 to add a @code{null} statement.
4180 @example
4181 if ... then
4182    ... -- some statements
4183 else
4184    pragma Assert (Num_Cases < 10);
4185    null;
4186 end if;
4187 @end example
4189 @node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4190 @anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{8a}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{8b}
4191 @subsubsection Conditionalizing Declarations
4194 In some cases it may be necessary to conditionalize declarations to meet
4195 different requirements. For example we might want a bit string whose length
4196 is set to meet some hardware message requirement.
4198 This may be possible using declare blocks controlled
4199 by conditional constants:
4201 @example
4202 if Small_Machine then
4203    declare
4204       X : Bit_String (1 .. 10);
4205    begin
4206       ...
4207    end;
4208 else
4209    declare
4210       X : Large_Bit_String (1 .. 1000);
4211    begin
4212       ...
4213    end;
4214 end if;
4215 @end example
4217 Note that in this approach, both declarations are analyzed by the
4218 compiler so this can only be used where both declarations are legal,
4219 even though one of them will not be used.
4221 Another approach is to define integer constants, e.g., @code{Bits_Per_Word},
4222 or Boolean constants, e.g., @code{Little_Endian}, and then write declarations
4223 that are parameterized by these constants. For example
4225 @example
4226 for Rec use
4227   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4228 end record;
4229 @end example
4231 If @code{Bits_Per_Word} is set to 32, this generates either
4233 @example
4234 for Rec use
4235   Field1 at 0 range 0 .. 32;
4236 end record;
4237 @end example
4239 for the big endian case, or
4241 @example
4242 for Rec use record
4243     Field1 at 0 range 10 .. 32;
4244 end record;
4245 @end example
4247 for the little endian case. Since a powerful subset of Ada expression
4248 notation is usable for creating static constants, clever use of this
4249 feature can often solve quite difficult problems in conditionalizing
4250 compilation (note incidentally that in Ada 95, the little endian
4251 constant was introduced as @code{System.Default_Bit_Order}, so you do not
4252 need to define this one yourself).
4254 @node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4255 @anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{8c}@anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{8d}
4256 @subsubsection Use of Alternative Implementations
4259 In some cases, none of the approaches described above are adequate. This
4260 can occur for example if the set of declarations required is radically
4261 different for two different configurations.
4263 In this situation, the official Ada way of dealing with conditionalizing
4264 such code is to write separate units for the different cases. As long as
4265 this does not result in excessive duplication of code, this can be done
4266 without creating maintenance problems. The approach is to share common
4267 code as far as possible, and then isolate the code and declarations
4268 that are different. Subunits are often a convenient method for breaking
4269 out a piece of a unit that is to be conditionalized, with separate files
4270 for different versions of the subunit for different targets, where the
4271 build script selects the right one to give to the compiler.
4273 @geindex Subunits (and conditional compilation)
4275 As an example, consider a situation where a new feature in Ada 2005
4276 allows something to be done in a really nice way. But your code must be able
4277 to compile with an Ada 95 compiler. Conceptually you want to say:
4279 @example
4280 if Ada_2005 then
4281    ... neat Ada 2005 code
4282 else
4283    ... not quite as neat Ada 95 code
4284 end if;
4285 @end example
4287 where @code{Ada_2005} is a Boolean constant.
4289 But this won’t work when @code{Ada_2005} is set to @code{False},
4290 since the @code{then} clause will be illegal for an Ada 95 compiler.
4291 (Recall that although such unreachable code would eventually be deleted
4292 by the compiler, it still needs to be legal.  If it uses features
4293 introduced in Ada 2005, it will be illegal in Ada 95.)
4295 So instead we write
4297 @example
4298 procedure Insert is separate;
4299 @end example
4301 Then we have two files for the subunit @code{Insert}, with the two sets of
4302 code.
4303 If the package containing this is called @code{File_Queries}, then we might
4304 have two files
4307 @itemize *
4309 @item 
4310 @code{file_queries-insert-2005.adb}
4312 @item 
4313 @code{file_queries-insert-95.adb}
4314 @end itemize
4316 and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4318 This can also be done with project files’ naming schemes. For example:
4320 @example
4321 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4322 @end example
4324 Note also that with project files it is desirable to use a different extension
4325 than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4326 conflict may arise through another commonly used feature: to declare as part
4327 of the project a set of directories containing all the sources obeying the
4328 default naming scheme.
4330 The use of alternative units is certainly feasible in all situations,
4331 and for example the Ada part of the GNAT run-time is conditionalized
4332 based on the target architecture using this approach. As a specific example,
4333 consider the implementation of the AST feature in VMS. There is one
4334 spec: @code{s-asthan.ads} which is the same for all architectures, and three
4335 bodies:
4338 @itemize *
4340 @item 
4342 @table @asis
4344 @item @code{s-asthan.adb}
4346 used for all non-VMS operating systems
4347 @end table
4349 @item 
4351 @table @asis
4353 @item @code{s-asthan-vms-alpha.adb}
4355 used for VMS on the Alpha
4356 @end table
4358 @item 
4360 @table @asis
4362 @item @code{s-asthan-vms-ia64.adb}
4364 used for VMS on the ia64
4365 @end table
4366 @end itemize
4368 The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4369 this operating system feature is not available, and the two remaining
4370 versions interface with the corresponding versions of VMS to provide
4371 VMS-compatible AST handling. The GNAT build script knows the architecture
4372 and operating system, and automatically selects the right version,
4373 renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4375 Another style for arranging alternative implementations is through Ada’s
4376 access-to-subprogram facility.
4377 In case some functionality is to be conditionally included,
4378 you can declare an access-to-procedure variable @code{Ref} that is initialized
4379 to designate a ‘do nothing’ procedure, and then invoke @code{Ref.all}
4380 when appropriate.
4381 In some library package, set @code{Ref} to @code{Proc'Access} for some
4382 procedure @code{Proc} that performs the relevant processing.
4383 The initialization only occurs if the library package is included in the
4384 program.
4385 The same idea can also be implemented using tagged types and dispatching
4386 calls.
4388 @node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4389 @anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{8e}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{8f}
4390 @subsubsection Preprocessing
4393 @geindex Preprocessing
4395 Although it is quite possible to conditionalize code without the use of
4396 C-style preprocessing, as described earlier in this section, it is
4397 nevertheless convenient in some cases to use the C approach. Moreover,
4398 older Ada compilers have often provided some preprocessing capability,
4399 so legacy code may depend on this approach, even though it is not
4400 standard.
4402 To accommodate such use, GNAT provides a preprocessor (modeled to a large
4403 extent on the various preprocessors that have been used
4404 with legacy code on other compilers, to enable easier transition).
4406 @geindex gnatprep
4408 The preprocessor may be used in two separate modes. It can be used quite
4409 separately from the compiler, to generate a separate output source file
4410 that is then fed to the compiler as a separate step. This is the
4411 @code{gnatprep} utility, whose use is fully described in
4412 @ref{90,,Preprocessing with gnatprep}.
4414 The preprocessing language allows such constructs as
4416 @example
4417 #if DEBUG or else (PRIORITY > 4) then
4418    sequence of declarations
4419 #else
4420    completely different sequence of declarations
4421 #end if;
4422 @end example
4424 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
4425 defined either on the command line or in a separate file.
4427 The other way of running the preprocessor is even closer to the C style and
4428 often more convenient. In this approach the preprocessing is integrated into
4429 the compilation process. The compiler is given the preprocessor input which
4430 includes @code{#if} lines etc, and then the compiler carries out the
4431 preprocessing internally and processes the resulting output.
4432 For more details on this approach, see @ref{91,,Integrated Preprocessing}.
4434 @node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4435 @anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{92}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{90}
4436 @subsection Preprocessing with @code{gnatprep}
4439 @geindex gnatprep
4441 @geindex Preprocessing (gnatprep)
4443 This section discusses how to use GNAT’s @code{gnatprep} utility for simple
4444 preprocessing.
4445 Although designed for use with GNAT, @code{gnatprep} does not depend on any
4446 special GNAT features.
4447 For further discussion of conditional compilation in general, see
4448 @ref{2b,,Conditional Compilation}.
4450 @menu
4451 * Preprocessing Symbols:: 
4452 * Using gnatprep:: 
4453 * Switches for gnatprep:: 
4454 * Form of Definitions File:: 
4455 * Form of Input Text for gnatprep:: 
4457 @end menu
4459 @node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4460 @anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{93}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{94}
4461 @subsubsection Preprocessing Symbols
4464 Preprocessing symbols are defined in `definition files' and referenced in the
4465 sources to be preprocessed. A preprocessing symbol is an identifier, following
4466 normal Ada (case-insensitive) rules for its syntax, with the restriction that
4467 all characters need to be in the ASCII set (no accented letters).
4469 @node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4470 @anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{95}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{96}
4471 @subsubsection Using @code{gnatprep}
4474 To call @code{gnatprep} use:
4476 @example
4477 $ gnatprep [ switches ] infile outfile [ deffile ]
4478 @end example
4480 where
4483 @itemize *
4485 @item 
4487 @table @asis
4489 @item `switches'
4491 is an optional sequence of switches as described in the next section.
4492 @end table
4494 @item 
4496 @table @asis
4498 @item `infile'
4500 is the full name of the input file, which is an Ada source
4501 file containing preprocessor directives.
4502 @end table
4504 @item 
4506 @table @asis
4508 @item `outfile'
4510 is the full name of the output file, which is an Ada source
4511 in standard Ada form. When used with GNAT, this file name will
4512 normally have an @code{ads} or @code{adb} suffix.
4513 @end table
4515 @item 
4517 @table @asis
4519 @item @code{deffile}
4521 is the full name of a text file containing definitions of
4522 preprocessing symbols to be referenced by the preprocessor. This argument is
4523 optional, and can be replaced by the use of the @code{-D} switch.
4524 @end table
4525 @end itemize
4527 @node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4528 @anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{97}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{98}
4529 @subsubsection Switches for @code{gnatprep}
4532 @geindex --version (gnatprep)
4535 @table @asis
4537 @item @code{--version}
4539 Display Copyright and version, then exit disregarding all other options.
4540 @end table
4542 @geindex --help (gnatprep)
4545 @table @asis
4547 @item @code{--help}
4549 If @code{--version} was not used, display usage and then exit disregarding
4550 all other options.
4551 @end table
4553 @geindex -b (gnatprep)
4556 @table @asis
4558 @item @code{-b}
4560 Causes both preprocessor lines and the lines deleted by
4561 preprocessing to be replaced by blank lines in the output source file,
4562 preserving line numbers in the output file.
4563 @end table
4565 @geindex -c (gnatprep)
4568 @table @asis
4570 @item @code{-c}
4572 Causes both preprocessor lines and the lines deleted
4573 by preprocessing to be retained in the output source as comments marked
4574 with the special string @code{"--! "}. This option will result in line numbers
4575 being preserved in the output file.
4576 @end table
4578 @geindex -C (gnatprep)
4581 @table @asis
4583 @item @code{-C}
4585 Causes comments to be scanned. Normally comments are ignored by gnatprep.
4586 If this option is specified, then comments are scanned and any $symbol
4587 substitutions performed as in program text. This is particularly useful
4588 when structured comments are used (e.g., for programs written in a
4589 pre-2014 version of the SPARK Ada subset). Note that this switch is not
4590 available when  doing integrated preprocessing (it would be useless in
4591 this context since comments are ignored by the compiler in any case).
4592 @end table
4594 @geindex -D (gnatprep)
4597 @table @asis
4599 @item @code{-D`symbol'[=`value']}
4601 Defines a new preprocessing symbol with the specified value. If no value is given
4602 on the command line, then symbol is considered to be @code{True}. This switch
4603 can be used in place of a definition file.
4604 @end table
4606 @geindex -r (gnatprep)
4609 @table @asis
4611 @item @code{-r}
4613 Causes a @code{Source_Reference} pragma to be generated that
4614 references the original input file, so that error messages will use
4615 the file name of this original file. The use of this switch implies
4616 that preprocessor lines are not to be removed from the file, so its
4617 use will force @code{-b} mode if @code{-c}
4618 has not been specified explicitly.
4620 Note that if the file to be preprocessed contains multiple units, then
4621 it will be necessary to @code{gnatchop} the output file from
4622 @code{gnatprep}. If a @code{Source_Reference} pragma is present
4623 in the preprocessed file, it will be respected by
4624 @code{gnatchop -r}
4625 so that the final chopped files will correctly refer to the original
4626 input source file for @code{gnatprep}.
4627 @end table
4629 @geindex -s (gnatprep)
4632 @table @asis
4634 @item @code{-s}
4636 Causes a sorted list of symbol names and values to be
4637 listed on the standard output file.
4638 @end table
4640 @geindex -T (gnatprep)
4643 @table @asis
4645 @item @code{-T}
4647 Use LF as line terminators when writing files. By default the line terminator
4648 of the host (LF under unix, CR/LF under Windows) is used.
4649 @end table
4651 @geindex -u (gnatprep)
4654 @table @asis
4656 @item @code{-u}
4658 Causes undefined symbols to be treated as having the value FALSE in the context
4659 of a preprocessor test. In the absence of this option, an undefined symbol in
4660 a @code{#if} or @code{#elsif} test will be treated as an error.
4661 @end table
4663 @geindex -v (gnatprep)
4666 @table @asis
4668 @item @code{-v}
4670 Verbose mode: generates more output about work done.
4671 @end table
4673 Note: if neither @code{-b} nor @code{-c} is present,
4674 then preprocessor lines and
4675 deleted lines are completely removed from the output, unless -r is
4676 specified, in which case -b is assumed.
4678 @node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4679 @anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{99}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{9a}
4680 @subsubsection Form of Definitions File
4683 The definitions file contains lines of the form:
4685 @example
4686 symbol := value
4687 @end example
4689 where @code{symbol} is a preprocessing symbol, and @code{value} is one of the following:
4692 @itemize *
4694 @item 
4695 Empty, corresponding to a null substitution,
4697 @item 
4698 A string literal using normal Ada syntax, or
4700 @item 
4701 Any sequence of characters from the set @{letters, digits, period, underline@}.
4702 @end itemize
4704 Comment lines may also appear in the definitions file, starting with
4705 the usual @code{--},
4706 and comments may be added to the definitions lines.
4708 @node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4709 @anchor{gnat_ugn/the_gnat_compilation_model form-of-input-text-for-gnatprep}@anchor{9b}@anchor{gnat_ugn/the_gnat_compilation_model id59}@anchor{9c}
4710 @subsubsection Form of Input Text for @code{gnatprep}
4713 The input text may contain preprocessor conditional inclusion lines,
4714 as well as general symbol substitution sequences.
4716 The preprocessor conditional inclusion commands have the form:
4718 @example
4719 #if <expression> [then]
4720    lines
4721 #elsif <expression> [then]
4722    lines
4723 #elsif <expression> [then]
4724    lines
4726 #else
4727    lines
4728 #end if;
4729 @end example
4731 In this example, <expression> is defined by the following grammar:
4733 @example
4734 <expression> ::=  <symbol>
4735 <expression> ::=  <symbol> = "<value>"
4736 <expression> ::=  <symbol> = <symbol>
4737 <expression> ::=  <symbol> = <integer>
4738 <expression> ::=  <symbol> > <integer>
4739 <expression> ::=  <symbol> >= <integer>
4740 <expression> ::=  <symbol> < <integer>
4741 <expression> ::=  <symbol> <= <integer>
4742 <expression> ::=  <symbol> 'Defined
4743 <expression> ::=  not <expression>
4744 <expression> ::=  <expression> and <expression>
4745 <expression> ::=  <expression> or <expression>
4746 <expression> ::=  <expression> and then <expression>
4747 <expression> ::=  <expression> or else <expression>
4748 <expression> ::=  ( <expression> )
4749 @end example
4751 Note the following restriction: it is not allowed to have “and” or “or”
4752 following “not” in the same expression without parentheses. For example, this
4753 is not allowed:
4755 @example
4756 not X or Y
4757 @end example
4759 This can be expressed instead as one of the following forms:
4761 @example
4762 (not X) or Y
4763 not (X or Y)
4764 @end example
4766 For the first test (<expression> ::= <symbol>) the symbol must have
4767 either the value true or false, that is to say the right-hand of the
4768 symbol definition must be one of the (case-insensitive) literals
4769 @code{True} or @code{False}. If the value is true, then the
4770 corresponding lines are included, and if the value is false, they are
4771 excluded.
4773 When comparing a symbol to an integer, the integer is any non negative
4774 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
4775 2#11#. The symbol value must also be a non negative integer. Integer values
4776 in the range 0 .. 2**31-1 are supported.
4778 The test (<expression> ::= <symbol>’Defined) is true only if
4779 the symbol has been defined in the definition file or by a @code{-D}
4780 switch on the command line. Otherwise, the test is false.
4782 The equality tests are case insensitive, as are all the preprocessor lines.
4784 If the symbol referenced is not defined in the symbol definitions file,
4785 then the effect depends on whether or not switch @code{-u}
4786 is specified. If so, then the symbol is treated as if it had the value
4787 false and the test fails. If this switch is not specified, then
4788 it is an error to reference an undefined symbol. It is also an error to
4789 reference a symbol that is defined with a value other than @code{True}
4790 or @code{False}.
4792 The use of the @code{not} operator inverts the sense of this logical test.
4793 The @code{not} operator cannot be combined with the @code{or} or @code{and}
4794 operators, without parentheses. For example, “if not X or Y then” is not
4795 allowed, but “if (not X) or Y then” and “if not (X or Y) then” are.
4797 The @code{then} keyword is optional as shown
4799 The @code{#} must be the first non-blank character on a line, but
4800 otherwise the format is free form. Spaces or tabs may appear between
4801 the @code{#} and the keyword. The keywords and the symbols are case
4802 insensitive as in normal Ada code. Comments may be used on a
4803 preprocessor line, but other than that, no other tokens may appear on a
4804 preprocessor line. Any number of @code{elsif} clauses can be present,
4805 including none at all. The @code{else} is optional, as in Ada.
4807 The @code{#} marking the start of a preprocessor line must be the first
4808 non-blank character on the line, i.e., it must be preceded only by
4809 spaces or horizontal tabs.
4811 Symbol substitution outside of preprocessor lines is obtained by using
4812 the sequence:
4814 @example
4815 $symbol
4816 @end example
4818 anywhere within a source line, except in a comment or within a
4819 string literal. The identifier
4820 following the @code{$} must match one of the symbols defined in the symbol
4821 definition file, and the result is to substitute the value of the
4822 symbol in place of @code{$symbol} in the output file.
4824 Note that although the substitution of strings within a string literal
4825 is not possible, it is possible to have a symbol whose defined value is
4826 a string literal. So instead of setting XYZ to @code{hello} and writing:
4828 @example
4829 Header : String := "$XYZ";
4830 @end example
4832 you should set XYZ to @code{"hello"} and write:
4834 @example
4835 Header : String := $XYZ;
4836 @end example
4838 and then the substitution will occur as desired.
4840 @node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
4841 @anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{9d}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{91}
4842 @subsection Integrated Preprocessing
4845 As noted above, a file to be preprocessed consists of Ada source code
4846 in which preprocessing lines have been inserted. However,
4847 instead of using @code{gnatprep} to explicitly preprocess a file as a separate
4848 step before compilation, you can carry out the preprocessing implicitly
4849 as part of compilation. Such `integrated preprocessing', which is the common
4850 style with C, is performed when either or both of the following switches
4851 are passed to the compiler:
4853 @quotation
4856 @itemize *
4858 @item 
4859 @code{-gnatep}, which specifies the `preprocessor data file'.
4860 This file dictates how the source files will be preprocessed (e.g., which
4861 symbol definition files apply to which sources).
4863 @item 
4864 @code{-gnateD}, which defines values for preprocessing symbols.
4865 @end itemize
4866 @end quotation
4868 Integrated preprocessing applies only to Ada source files, it is
4869 not available for configuration pragma files.
4871 With integrated preprocessing, the output from the preprocessor is not,
4872 by default, written to any external file. Instead it is passed
4873 internally to the compiler. To preserve the result of
4874 preprocessing in a file, either run @code{gnatprep}
4875 in standalone mode or else supply the @code{-gnateG} switch
4876 (described below) to the compiler.
4878 When using project files:
4880 @quotation
4883 @itemize *
4885 @item 
4886 the builder switch @code{-x} should be used if any Ada source is
4887 compiled with @code{gnatep=}, so that the compiler finds the
4888 `preprocessor data file'.
4890 @item 
4891 the preprocessing data file and the symbol definition files should be
4892 located in the source directories of the project.
4893 @end itemize
4894 @end quotation
4896 Note that the @code{gnatmake} switch @code{-m} will almost
4897 always trigger recompilation for sources that are preprocessed,
4898 because @code{gnatmake} cannot compute the checksum of the source after
4899 preprocessing.
4901 The actual preprocessing function is described in detail in
4902 @ref{90,,Preprocessing with gnatprep}. This section explains the switches
4903 that relate to integrated preprocessing.
4905 @geindex -gnatep (gcc)
4908 @table @asis
4910 @item @code{-gnatep=`preprocessor_data_file'}
4912 This switch specifies the file name (without directory
4913 information) of the preprocessor data file. Either place this file
4914 in one of the source directories, or, when using project
4915 files, reference the project file’s directory via the
4916 @code{project_name'Project_Dir} project attribute; e.g:
4918 @quotation
4920 @example
4921 project Prj is
4922    package Compiler is
4923       for Switches ("Ada") use
4924         ("-gnatep=" & Prj'Project_Dir & "prep.def");
4925    end Compiler;
4926 end Prj;
4927 @end example
4928 @end quotation
4930 A preprocessor data file is a text file that contains `preprocessor
4931 control lines'.  A preprocessor control line directs the preprocessing of
4932 either a particular source file, or, analogous to @code{others} in Ada,
4933 all sources not specified elsewhere in  the preprocessor data file.
4934 A preprocessor control line
4935 can optionally identify a `definition file' that assigns values to
4936 preprocessor symbols, as well as a list of switches that relate to
4937 preprocessing.
4938 Empty lines and comments (using Ada syntax) are also permitted, with no
4939 semantic effect.
4941 Here’s an example of a preprocessor data file:
4943 @quotation
4945 @example
4946 "toto.adb"  "prep.def" -u
4947 --  Preprocess toto.adb, using definition file prep.def
4948 --  Undefined symbols are treated as False
4950 * -c -DVERSION=V101
4951 --  Preprocess all other sources without using a definition file
4952 --  Suppressed lined are commented
4953 --  Symbol VERSION has the value V101
4955 "tata.adb" "prep2.def" -s
4956 --  Preprocess tata.adb, using definition file prep2.def
4957 --  List all symbols with their values
4958 @end example
4959 @end quotation
4961 A preprocessor control line has the following syntax:
4963 @quotation
4965 @example
4966 <preprocessor_control_line> ::=
4967    <preprocessor_input> [ <definition_file_name> ] @{ <switch> @}
4969 <preprocessor_input> ::= <source_file_name> | '*'
4971 <definition_file_name> ::= <string_literal>
4973 <source_file_name> := <string_literal>
4975 <switch> := (See below for list)
4976 @end example
4977 @end quotation
4979 Thus  each preprocessor control line starts with either a literal string or
4980 the character ‘*’:
4983 @itemize *
4985 @item 
4986 A literal string is the file name (without directory information) of the source
4987 file that will be input to the preprocessor.
4989 @item 
4990 The character ‘*’ is a wild-card indicator; the additional parameters on the line
4991 indicate the preprocessing for all the sources
4992 that are not specified explicitly on other lines (the order of the lines is not
4993 significant).
4994 @end itemize
4996 It is an error to have two lines with the same file name or two
4997 lines starting with the character ‘*’.
4999 After the file name or ‘*’, an optional literal string specifies the name of
5000 the definition file to be used for preprocessing
5001 (@ref{99,,Form of Definitions File}). The definition files are found by the
5002 compiler in one of the source directories. In some cases, when compiling
5003 a source in a directory other than the current directory, if the definition
5004 file is in the current directory, it may be necessary to add the current
5005 directory as a source directory through the @code{-I} switch; otherwise
5006 the compiler would not find the definition file.
5008 Finally, switches similar to those of @code{gnatprep} may optionally appear:
5011 @table @asis
5013 @item @code{-b}
5015 Causes both preprocessor lines and the lines deleted by
5016 preprocessing to be replaced by blank lines, preserving the line number.
5017 This switch is always implied; however, if specified after @code{-c}
5018 it cancels the effect of @code{-c}.
5020 @item @code{-c}
5022 Causes both preprocessor lines and the lines deleted
5023 by preprocessing to be retained as comments marked
5024 with the special string ‘@cite{–!}’.
5026 @item @code{-D`symbol'=`new_value'}
5028 Define or redefine @code{symbol} to have @code{new_value} as its value.
5029 The permitted form for @code{symbol} is either an Ada identifier, or any Ada reserved word
5030 aside from @code{if},
5031 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5032 The permitted form for @code{new_value} is a literal string, an Ada identifier or any Ada reserved
5033 word. A symbol declared with this switch replaces a symbol with the
5034 same name defined in a definition file.
5036 @item @code{-s}
5038 Causes a sorted list of symbol names and values to be
5039 listed on the standard output file.
5041 @item @code{-u}
5043 Causes undefined symbols to be treated as having the value @code{FALSE}
5044 in the context
5045 of a preprocessor test. In the absence of this option, an undefined symbol in
5046 a @code{#if} or @code{#elsif} test will be treated as an error.
5047 @end table
5048 @end table
5050 @geindex -gnateD (gcc)
5053 @table @asis
5055 @item @code{-gnateD`symbol'[=`new_value']}
5057 Define or redefine @code{symbol} to have @code{new_value} as its value. If no value
5058 is supplied, then the value of @code{symbol} is @code{True}.
5059 The form of @code{symbol} is an identifier, following normal Ada (case-insensitive)
5060 rules for its syntax, and @code{new_value} is either an arbitrary string between double
5061 quotes or any sequence (including an empty sequence) of characters from the
5062 set (letters, digits, period, underline).
5063 Ada reserved words may be used as symbols, with the exceptions of @code{if},
5064 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5066 Examples:
5068 @quotation
5070 @example
5071 -gnateDToto=Tata
5072 -gnateDFoo
5073 -gnateDFoo=\"Foo-Bar\"
5074 @end example
5075 @end quotation
5077 A symbol declared with this switch on the command line replaces a
5078 symbol with the same name either in a definition file or specified with a
5079 switch @code{-D} in the preprocessor data file.
5081 This switch is similar to switch @code{-D} of @code{gnatprep}.
5083 @item @code{-gnateG}
5085 When integrated preprocessing is performed on source file @code{filename.extension},
5086 create or overwrite @code{filename.extension.prep} to contain
5087 the result of the preprocessing.
5088 For example if the source file is @code{foo.adb} then
5089 the output file will be @code{foo.adb.prep}.
5090 @end table
5092 @node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5093 @anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{9e}@anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{2c}
5094 @section Mixed Language Programming
5097 @geindex Mixed Language Programming
5099 This section describes how to develop a mixed-language program,
5100 with a focus on combining Ada with C or C++.
5102 @menu
5103 * Interfacing to C:: 
5104 * Calling Conventions:: 
5105 * Building Mixed Ada and C++ Programs:: 
5106 * Partition-Wide Settings:: 
5107 * Generating Ada Bindings for C and C++ headers:: 
5108 * Generating C Headers for Ada Specifications:: 
5110 @end menu
5112 @node Interfacing to C,Calling Conventions,,Mixed Language Programming
5113 @anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{a0}
5114 @subsection Interfacing to C
5117 Interfacing Ada with a foreign language such as C involves using
5118 compiler directives to import and/or export entity definitions in each
5119 language – using @code{extern} statements in C, for instance, and the
5120 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
5121 A full treatment of these topics is provided in Appendix B, section 1
5122 of the Ada Reference Manual.
5124 There are two ways to build a program using GNAT that contains some Ada
5125 sources and some foreign language sources, depending on whether or not
5126 the main subprogram is written in Ada.  Here is a source example with
5127 the main subprogram in Ada:
5129 @example
5130 /* file1.c */
5131 #include <stdio.h>
5133 void print_num (int num)
5135   printf ("num is %d.\\n", num);
5136   return;
5138 @end example
5140 @example
5141 /* file2.c */
5143 /* num_from_Ada is declared in my_main.adb */
5144 extern int num_from_Ada;
5146 int get_num (void)
5148   return num_from_Ada;
5150 @end example
5152 @example
5153 --  my_main.adb
5154 procedure My_Main is
5156    --  Declare then export an Integer entity called num_from_Ada
5157    My_Num : Integer := 10;
5158    pragma Export (C, My_Num, "num_from_Ada");
5160    --  Declare an Ada function spec for Get_Num, then use
5161    --  C function get_num for the implementation.
5162    function Get_Num return Integer;
5163    pragma Import (C, Get_Num, "get_num");
5165    --  Declare an Ada procedure spec for Print_Num, then use
5166    --  C function print_num for the implementation.
5167    procedure Print_Num (Num : Integer);
5168    pragma Import (C, Print_Num, "print_num");
5170 begin
5171    Print_Num (Get_Num);
5172 end My_Main;
5173 @end example
5175 To build this example:
5178 @itemize *
5180 @item 
5181 First compile the foreign language files to
5182 generate object files:
5184 @example
5185 $ gcc -c file1.c
5186 $ gcc -c file2.c
5187 @end example
5189 @item 
5190 Then, compile the Ada units to produce a set of object files and ALI
5191 files:
5193 @example
5194 $ gnatmake -c my_main.adb
5195 @end example
5197 @item 
5198 Run the Ada binder on the Ada main program:
5200 @example
5201 $ gnatbind my_main.ali
5202 @end example
5204 @item 
5205 Link the Ada main program, the Ada objects and the other language
5206 objects:
5208 @example
5209 $ gnatlink my_main.ali file1.o file2.o
5210 @end example
5211 @end itemize
5213 The last three steps can be grouped in a single command:
5215 @example
5216 $ gnatmake my_main.adb -largs file1.o file2.o
5217 @end example
5219 @geindex Binder output file
5221 If the main program is in a language other than Ada, then you may have
5222 more than one entry point into the Ada subsystem. You must use a special
5223 binder option to generate callable routines that initialize and
5224 finalize the Ada units (@ref{7e,,Binding with Non-Ada Main Programs}).
5225 Calls to the initialization and finalization routines must be inserted
5226 in the main program, or some other appropriate point in the code. The
5227 call to initialize the Ada units must occur before the first Ada
5228 subprogram is called, and the call to finalize the Ada units must occur
5229 after the last Ada subprogram returns. The binder will place the
5230 initialization and finalization subprograms into the
5231 @code{b~xxx.adb} file where they can be accessed by your C
5232 sources.  To illustrate, we have the following example:
5234 @example
5235 /* main.c */
5236 extern void adainit (void);
5237 extern void adafinal (void);
5238 extern int add (int, int);
5239 extern int sub (int, int);
5241 int main (int argc, char *argv[])
5243    int a = 21, b = 7;
5245    adainit();
5247    /* Should print "21 + 7 = 28" */
5248    printf ("%d + %d = %d\\n", a, b, add (a, b));
5250    /* Should print "21 - 7 = 14" */
5251    printf ("%d - %d = %d\\n", a, b, sub (a, b));
5253    adafinal();
5255 @end example
5257 @example
5258 --  unit1.ads
5259 package Unit1 is
5260    function Add (A, B : Integer) return Integer;
5261    pragma Export (C, Add, "add");
5262 end Unit1;
5263 @end example
5265 @example
5266 --  unit1.adb
5267 package body Unit1 is
5268    function Add (A, B : Integer) return Integer is
5269    begin
5270       return A + B;
5271    end Add;
5272 end Unit1;
5273 @end example
5275 @example
5276 --  unit2.ads
5277 package Unit2 is
5278    function Sub (A, B : Integer) return Integer;
5279    pragma Export (C, Sub, "sub");
5280 end Unit2;
5281 @end example
5283 @example
5284 --  unit2.adb
5285 package body Unit2 is
5286    function Sub (A, B : Integer) return Integer is
5287    begin
5288       return A - B;
5289    end Sub;
5290 end Unit2;
5291 @end example
5293 The build procedure for this application is similar to the last
5294 example’s:
5297 @itemize *
5299 @item 
5300 First, compile the foreign language files to generate object files:
5302 @example
5303 $ gcc -c main.c
5304 @end example
5306 @item 
5307 Next, compile the Ada units to produce a set of object files and ALI
5308 files:
5310 @example
5311 $ gnatmake -c unit1.adb
5312 $ gnatmake -c unit2.adb
5313 @end example
5315 @item 
5316 Run the Ada binder on every generated ALI file.  Make sure to use the
5317 @code{-n} option to specify a foreign main program:
5319 @example
5320 $ gnatbind -n unit1.ali unit2.ali
5321 @end example
5323 @item 
5324 Link the Ada main program, the Ada objects and the foreign language
5325 objects. You need only list the last ALI file here:
5327 @example
5328 $ gnatlink unit2.ali main.o -o exec_file
5329 @end example
5331 This procedure yields a binary executable called @code{exec_file}.
5332 @end itemize
5334 Depending on the circumstances (for example when your non-Ada main object
5335 does not provide symbol @code{main}), you may also need to instruct the
5336 GNAT linker not to include the standard startup objects by passing the
5337 @code{-nostartfiles} switch to @code{gnatlink}.
5339 @node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5340 @anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{a2}
5341 @subsection Calling Conventions
5344 @geindex Foreign Languages
5346 @geindex Calling Conventions
5348 GNAT follows standard calling sequence conventions and will thus interface
5349 to any other language that also follows these conventions. The following
5350 Convention identifiers are recognized by GNAT:
5352 @geindex Interfacing to Ada
5354 @geindex Other Ada compilers
5356 @geindex Convention Ada
5359 @table @asis
5361 @item @code{Ada}
5363 This indicates that the standard Ada calling sequence will be
5364 used and all Ada data items may be passed without any limitations in the
5365 case where GNAT is used to generate both the caller and callee. It is also
5366 possible to mix GNAT generated code and code generated by another Ada
5367 compiler. In this case, the data types should be restricted to simple
5368 cases, including primitive types. Whether complex data types can be passed
5369 depends on the situation. Probably it is safe to pass simple arrays, such
5370 as arrays of integers or floats. Records may or may not work, depending
5371 on whether both compilers lay them out identically. Complex structures
5372 involving variant records, access parameters, tasks, or protected types,
5373 are unlikely to be able to be passed.
5375 Note that in the case of GNAT running
5376 on a platform that supports HP Ada 83, a higher degree of compatibility
5377 can be guaranteed, and in particular records are laid out in an identical
5378 manner in the two compilers. Note also that if output from two different
5379 compilers is mixed, the program is responsible for dealing with elaboration
5380 issues. Probably the safest approach is to write the main program in the
5381 version of Ada other than GNAT, so that it takes care of its own elaboration
5382 requirements, and then call the GNAT-generated adainit procedure to ensure
5383 elaboration of the GNAT components. Consult the documentation of the other
5384 Ada compiler for further details on elaboration.
5386 However, it is not possible to mix the tasking run time of GNAT and
5387 HP Ada 83, all the tasking operations must either be entirely within
5388 GNAT compiled sections of the program, or entirely within HP Ada 83
5389 compiled sections of the program.
5390 @end table
5392 @geindex Interfacing to Assembly
5394 @geindex Convention Assembler
5397 @table @asis
5399 @item @code{Assembler}
5401 Specifies assembler as the convention. In practice this has the
5402 same effect as convention Ada (but is not equivalent in the sense of being
5403 considered the same convention).
5404 @end table
5406 @geindex Convention Asm
5408 @geindex Asm
5411 @table @asis
5413 @item @code{Asm}
5415 Equivalent to Assembler.
5417 @geindex Interfacing to COBOL
5419 @geindex Convention COBOL
5420 @end table
5422 @geindex COBOL
5425 @table @asis
5427 @item @code{COBOL}
5429 Data will be passed according to the conventions described
5430 in section B.4 of the Ada Reference Manual.
5431 @end table
5433 @geindex C
5435 @geindex Interfacing to C
5437 @geindex Convention C
5440 @table @asis
5442 @item @code{C}
5444 Data will be passed according to the conventions described
5445 in section B.3 of the Ada Reference Manual.
5447 A note on interfacing to a C ‘varargs’ function:
5449 @quotation
5451 @geindex C varargs function
5453 @geindex Interfacing to C varargs function
5455 @geindex varargs function interfaces
5457 In C, @code{varargs} allows a function to take a variable number of
5458 arguments. There is no direct equivalent in this to Ada. One
5459 approach that can be used is to create a C wrapper for each
5460 different profile and then interface to this C wrapper. For
5461 example, to print an @code{int} value using @code{printf},
5462 create a C function @code{printfi} that takes two arguments, a
5463 pointer to a string and an int, and calls @code{printf}.
5464 Then in the Ada program, use pragma @code{Import} to
5465 interface to @code{printfi}.
5467 It may work on some platforms to directly interface to
5468 a @code{varargs} function by providing a specific Ada profile
5469 for a particular call. However, this does not work on
5470 all platforms, since there is no guarantee that the
5471 calling sequence for a two argument normal C function
5472 is the same as for calling a @code{varargs} C function with
5473 the same two arguments.
5474 @end quotation
5475 @end table
5477 @geindex Convention Default
5479 @geindex Default
5482 @table @asis
5484 @item @code{Default}
5486 Equivalent to C.
5487 @end table
5489 @geindex Convention External
5491 @geindex External
5494 @table @asis
5496 @item @code{External}
5498 Equivalent to C.
5499 @end table
5501 @geindex C++
5503 @geindex Interfacing to C++
5505 @geindex Convention C++
5508 @table @asis
5510 @item @code{C_Plus_Plus} (or @code{CPP})
5512 This stands for C++. For most purposes this is identical to C.
5513 See the separate description of the specialized GNAT pragmas relating to
5514 C++ interfacing for further details.
5515 @end table
5517 @geindex Fortran
5519 @geindex Interfacing to Fortran
5521 @geindex Convention Fortran
5524 @table @asis
5526 @item @code{Fortran}
5528 Data will be passed according to the conventions described
5529 in section B.5 of the Ada Reference Manual.
5531 @item @code{Intrinsic}
5533 This applies to an intrinsic operation, as defined in the Ada
5534 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5535 this means that the body of the subprogram is provided by the compiler itself,
5536 usually by means of an efficient code sequence, and that the user does not
5537 supply an explicit body for it. In an application program, the pragma may
5538 be applied to the following sets of names:
5541 @itemize *
5543 @item 
5544 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5545 The corresponding subprogram declaration must have
5546 two formal parameters. The
5547 first one must be a signed integer type or a modular type with a binary
5548 modulus, and the second parameter must be of type Natural.
5549 The return type must be the same as the type of the first argument. The size
5550 of this type can only be 8, 16, 32, or 64.
5552 @item 
5553 Binary arithmetic operators: ‘+’, ‘-’, ‘*’, ‘/’.
5554 The corresponding operator declaration must have parameters and result type
5555 that have the same root numeric type (for example, all three are long_float
5556 types). This simplifies the definition of operations that use type checking
5557 to perform dimensional checks:
5559 @example
5560 type Distance is new Long_Float;
5561 type Time     is new Long_Float;
5562 type Velocity is new Long_Float;
5563 function "/" (D : Distance; T : Time)
5564   return Velocity;
5565 pragma Import (Intrinsic, "/");
5566 @end example
5568 This common idiom is often programmed with a generic definition and an
5569 explicit body. The pragma makes it simpler to introduce such declarations.
5570 It incurs no overhead in compilation time or code size, because it is
5571 implemented as a single machine instruction.
5573 @item 
5574 General subprogram entities. This is used  to bind an Ada subprogram
5575 declaration to
5576 a compiler builtin by name with back-ends where such interfaces are
5577 available. A typical example is the set of @code{__builtin} functions
5578 exposed by the GCC back-end, as in the following example:
5580 @example
5581 function builtin_sqrt (F : Float) return Float;
5582 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5583 @end example
5585 Most of the GCC builtins are accessible this way, and as for other
5586 import conventions (e.g. C), it is the user’s responsibility to ensure
5587 that the Ada subprogram profile matches the underlying builtin
5588 expectations.
5589 @end itemize
5590 @end table
5592 @geindex Stdcall
5594 @geindex Convention Stdcall
5597 @table @asis
5599 @item @code{Stdcall}
5601 This is relevant only to Windows implementations of GNAT,
5602 and specifies that the @code{Stdcall} calling sequence will be used,
5603 as defined by the NT API. Nevertheless, to ease building
5604 cross-platform bindings this convention will be handled as a @code{C} calling
5605 convention on non-Windows platforms.
5606 @end table
5608 @geindex DLL
5610 @geindex Convention DLL
5613 @table @asis
5615 @item @code{DLL}
5617 This is equivalent to @code{Stdcall}.
5618 @end table
5620 @geindex Win32
5622 @geindex Convention Win32
5625 @table @asis
5627 @item @code{Win32}
5629 This is equivalent to @code{Stdcall}.
5630 @end table
5632 @geindex Stubbed
5634 @geindex Convention Stubbed
5637 @table @asis
5639 @item @code{Stubbed}
5641 This is a special convention that indicates that the compiler
5642 should provide a stub body that raises @code{Program_Error}.
5643 @end table
5645 GNAT additionally provides a useful pragma @code{Convention_Identifier}
5646 that can be used to parameterize conventions and allow additional synonyms
5647 to be specified. For example if you have legacy code in which the convention
5648 identifier Fortran77 was used for Fortran, you can use the configuration
5649 pragma:
5651 @example
5652 pragma Convention_Identifier (Fortran77, Fortran);
5653 @end example
5655 And from now on the identifier Fortran77 may be used as a convention
5656 identifier (for example in an @code{Import} pragma) with the same
5657 meaning as Fortran.
5659 @node Building Mixed Ada and C++ Programs,Partition-Wide Settings,Calling Conventions,Mixed Language Programming
5660 @anchor{gnat_ugn/the_gnat_compilation_model building-mixed-ada-and-c-programs}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id64}@anchor{a4}
5661 @subsection Building Mixed Ada and C++ Programs
5664 A programmer inexperienced with mixed-language development may find that
5665 building an application containing both Ada and C++ code can be a
5666 challenge.  This section gives a few hints that should make this task easier.
5668 @menu
5669 * Interfacing to C++:: 
5670 * Linking a Mixed C++ & Ada Program:: 
5671 * A Simple Example:: 
5672 * Interfacing with C++ constructors:: 
5673 * Interfacing with C++ at the Class Level:: 
5675 @end menu
5677 @node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5678 @anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{a6}
5679 @subsubsection Interfacing to C++
5682 GNAT supports interfacing with the G++ compiler (or any C++ compiler
5683 generating code that is compatible with the G++ Application Binary
5684 Interface —see @indicateurl{http://itanium-cxx-abi.github.io/cxx-abi/abi.html}).
5686 Interfacing can be done at 3 levels: simple data, subprograms, and
5687 classes. In the first two cases, GNAT offers a specific @code{Convention C_Plus_Plus}
5688 (or @code{CPP}) that behaves exactly like @code{Convention C}.
5689 Usually, C++ mangles the names of subprograms. To generate proper mangled
5690 names automatically, see @ref{a7,,Generating Ada Bindings for C and C++ headers}).
5691 This problem can also be addressed manually in two ways:
5694 @itemize *
5696 @item 
5697 by modifying the C++ code in order to force a C convention using
5698 the @code{extern "C"} syntax.
5700 @item 
5701 by figuring out the mangled name (using e.g. @code{nm}) and using it as the
5702 Link_Name argument of the pragma import.
5703 @end itemize
5705 Interfacing at the class level can be achieved by using the GNAT specific
5706 pragmas such as @code{CPP_Constructor}.  See the @cite{GNAT_Reference_Manual} for additional information.
5708 @node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5709 @anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-ada-program}@anchor{a8}@anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-and-ada-program}@anchor{a9}
5710 @subsubsection Linking a Mixed C++ & Ada Program
5713 Usually the linker of the C++ development system must be used to link
5714 mixed applications because most C++ systems will resolve elaboration
5715 issues (such as calling constructors on global class instances)
5716 transparently during the link phase. GNAT has been adapted to ease the
5717 use of a foreign linker for the last phase. Three cases can be
5718 considered:
5721 @itemize *
5723 @item 
5724 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5725 The C++ linker can simply be called by using the C++ specific driver
5726 called @code{g++}.
5728 Note that if the C++ code uses inline functions, you will need to
5729 compile your C++ code with the @code{-fkeep-inline-functions} switch in
5730 order to provide an existing function implementation that the Ada code can
5731 link with.
5733 @example
5734 $ g++ -c -fkeep-inline-functions file1.C
5735 $ g++ -c -fkeep-inline-functions file2.C
5736 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5737 @end example
5739 @item 
5740 Using GNAT and G++ from two different GCC installations: If both
5741 compilers are on the 
5742 @geindex PATH
5743 @geindex environment variable; PATH
5744 @code{PATH}, the previous method may be used. It is
5745 important to note that environment variables such as
5746 @geindex C_INCLUDE_PATH
5747 @geindex environment variable; C_INCLUDE_PATH
5748 @code{C_INCLUDE_PATH}, 
5749 @geindex GCC_EXEC_PREFIX
5750 @geindex environment variable; GCC_EXEC_PREFIX
5751 @code{GCC_EXEC_PREFIX},
5752 @geindex BINUTILS_ROOT
5753 @geindex environment variable; BINUTILS_ROOT
5754 @code{BINUTILS_ROOT}, and
5755 @geindex GCC_ROOT
5756 @geindex environment variable; GCC_ROOT
5757 @code{GCC_ROOT} will affect both compilers
5758 at the same time and may make one of the two compilers operate
5759 improperly if set during invocation of the wrong compiler.  It is also
5760 very important that the linker uses the proper @code{libgcc.a} GCC
5761 library – that is, the one from the C++ compiler installation. The
5762 implicit link command as suggested in the @code{gnatmake} command
5763 from the former example can be replaced by an explicit link command with
5764 the full-verbosity option in order to verify which library is used:
5766 @example
5767 $ gnatbind ada_unit
5768 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5769 @end example
5771 If there is a problem due to interfering environment variables, it can
5772 be worked around by using an intermediate script. The following example
5773 shows the proper script to use when GNAT has not been installed at its
5774 default location and g++ has been installed at its default location:
5776 @example
5777 $ cat ./my_script
5778 #!/bin/sh
5779 unset BINUTILS_ROOT
5780 unset GCC_ROOT
5781 c++ $*
5782 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5783 @end example
5785 @item 
5786 Using a non-GNU C++ compiler: The commands previously described can be
5787 used to insure that the C++ linker is used. Nonetheless, you need to add
5788 a few more parameters to the link command line, depending on the exception
5789 mechanism used.
5791 If the @code{setjmp} / @code{longjmp} exception mechanism is used, only the paths
5792 to the @code{libgcc} libraries are required:
5794 @example
5795 $ cat ./my_script
5796 #!/bin/sh
5797 CC $* gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a
5798 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5799 @end example
5801 where CC is the name of the non-GNU C++ compiler.
5803 If the “zero cost” exception mechanism is used, and the platform
5804 supports automatic registration of exception tables (e.g., Solaris),
5805 paths to more objects are required:
5807 @example
5808 $ cat ./my_script
5809 #!/bin/sh
5810 CC gcc -print-file-name=crtbegin.o $* \\
5811 gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a \\
5812 gcc -print-file-name=crtend.o
5813 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5814 @end example
5816 If the “zero cost exception” mechanism is used, and the platform
5817 doesn’t support automatic registration of exception tables (e.g., HP-UX
5818 or AIX), the simple approach described above will not work and
5819 a pre-linking phase using GNAT will be necessary.
5820 @end itemize
5822 Another alternative is to use the @code{gprbuild} multi-language builder
5823 which has a large knowledge base and knows how to link Ada and C++ code
5824 together automatically in most cases.
5826 @node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
5827 @anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{aa}@anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{ab}
5828 @subsubsection A Simple Example
5831 The following example, provided as part of the GNAT examples, shows how
5832 to achieve procedural interfacing between Ada and C++ in both
5833 directions. The C++ class A has two methods. The first method is exported
5834 to Ada by the means of an extern C wrapper function. The second method
5835 calls an Ada subprogram. On the Ada side, the C++ calls are modelled by
5836 a limited record with a layout comparable to the C++ class. The Ada
5837 subprogram, in turn, calls the C++ method. So, starting from the C++
5838 main program, the process passes back and forth between the two
5839 languages.
5841 Here are the compilation commands:
5843 @example
5844 $ gnatmake -c simple_cpp_interface
5845 $ g++ -c cpp_main.C
5846 $ g++ -c ex7.C
5847 $ gnatbind -n simple_cpp_interface
5848 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
5849 @end example
5851 Here are the corresponding sources:
5853 @example
5854 //cpp_main.C
5856 #include "ex7.h"
5858 extern "C" @{
5859   void adainit (void);
5860   void adafinal (void);
5861   void method1 (A *t);
5864 void method1 (A *t)
5866   t->method1 ();
5869 int main ()
5871   A obj;
5872   adainit ();
5873   obj.method2 (3030);
5874   adafinal ();
5876 @end example
5878 @example
5879 //ex7.h
5881 class Origin @{
5882  public:
5883   int o_value;
5885 class A : public Origin @{
5886  public:
5887   void method1 (void);
5888   void method2 (int v);
5889   A();
5890   int   a_value;
5892 @end example
5894 @example
5895 //ex7.C
5897 #include "ex7.h"
5898 #include <stdio.h>
5900 extern "C" @{ void ada_method2 (A *t, int v);@}
5902 void A::method1 (void)
5904   a_value = 2020;
5905   printf ("in A::method1, a_value = %d \\n",a_value);
5908 void A::method2 (int v)
5910    ada_method2 (this, v);
5911    printf ("in A::method2, a_value = %d \\n",a_value);
5914 A::A(void)
5916    a_value = 1010;
5917   printf ("in A::A, a_value = %d \\n",a_value);
5919 @end example
5921 @example
5922 -- simple_cpp_interface.ads
5923 with System;
5924 package Simple_Cpp_Interface is
5925    type A is limited
5926       record
5927          Vptr    : System.Address;
5928          O_Value : Integer;
5929          A_Value : Integer;
5930       end record;
5931    pragma Convention (C, A);
5933    procedure Method1 (This : in out A);
5934    pragma Import (C, Method1);
5936    procedure Ada_Method2 (This : in out A; V : Integer);
5937    pragma Export (C, Ada_Method2);
5939 end Simple_Cpp_Interface;
5940 @end example
5942 @example
5943 -- simple_cpp_interface.adb
5944 package body Simple_Cpp_Interface is
5946    procedure Ada_Method2 (This : in out A; V : Integer) is
5947    begin
5948       Method1 (This);
5949       This.A_Value := V;
5950    end Ada_Method2;
5952 end Simple_Cpp_Interface;
5953 @end example
5955 @node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
5956 @anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{ad}
5957 @subsubsection Interfacing with C++ constructors
5960 In order to interface with C++ constructors GNAT provides the
5961 @code{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
5962 for additional information).
5963 In this section we present some common uses of C++ constructors
5964 in mixed-languages programs in GNAT.
5966 Let us assume that we need to interface with the following
5967 C++ class:
5969 @example
5970 class Root @{
5971 public:
5972   int  a_value;
5973   int  b_value;
5974   virtual int Get_Value ();
5975   Root();              // Default constructor
5976   Root(int v);         // 1st non-default constructor
5977   Root(int v, int w);  // 2nd non-default constructor
5979 @end example
5981 For this purpose we can write the following package spec (further
5982 information on how to build this spec is available in
5983 @ref{ae,,Interfacing with C++ at the Class Level} and
5984 @ref{a7,,Generating Ada Bindings for C and C++ headers}).
5986 @example
5987 with Interfaces.C; use Interfaces.C;
5988 package Pkg_Root is
5989   type Root is tagged limited record
5990      A_Value : int;
5991      B_Value : int;
5992   end record;
5993   pragma Import (CPP, Root);
5995   function Get_Value (Obj : Root) return int;
5996   pragma Import (CPP, Get_Value);
5998   function Constructor return Root;
5999   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
6001   function Constructor (v : Integer) return Root;
6002   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
6004   function Constructor (v, w : Integer) return Root;
6005   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
6006 end Pkg_Root;
6007 @end example
6009 On the Ada side the constructor is represented by a function (whose
6010 name is arbitrary) that returns the classwide type corresponding to
6011 the imported C++ class. Although the constructor is described as a
6012 function, it is typically a procedure with an extra implicit argument
6013 (the object being initialized) at the implementation level. GNAT
6014 issues the appropriate call, whatever it is, to get the object
6015 properly initialized.
6017 Constructors can only appear in the following contexts:
6020 @itemize *
6022 @item 
6023 On the right side of an initialization of an object of type @code{T}.
6025 @item 
6026 On the right side of an initialization of a record component of type @code{T}.
6028 @item 
6029 In an Ada 2005 limited aggregate.
6031 @item 
6032 In an Ada 2005 nested limited aggregate.
6034 @item 
6035 In an Ada 2005 limited aggregate that initializes an object built in
6036 place by an extended return statement.
6037 @end itemize
6039 In a declaration of an object whose type is a class imported from C++,
6040 either the default C++ constructor is implicitly called by GNAT, or
6041 else the required C++ constructor must be explicitly called in the
6042 expression that initializes the object. For example:
6044 @example
6045 Obj1 : Root;
6046 Obj2 : Root := Constructor;
6047 Obj3 : Root := Constructor (v => 10);
6048 Obj4 : Root := Constructor (30, 40);
6049 @end example
6051 The first two declarations are equivalent: in both cases the default C++
6052 constructor is invoked (in the former case the call to the constructor is
6053 implicit, and in the latter case the call is explicit in the object
6054 declaration). @code{Obj3} is initialized by the C++ non-default constructor
6055 that takes an integer argument, and @code{Obj4} is initialized by the
6056 non-default C++ constructor that takes two integers.
6058 Let us derive the imported C++ class in the Ada side. For example:
6060 @example
6061 type DT is new Root with record
6062    C_Value : Natural := 2009;
6063 end record;
6064 @end example
6066 In this case the components DT inherited from the C++ side must be
6067 initialized by a C++ constructor, and the additional Ada components
6068 of type DT are initialized by GNAT. The initialization of such an
6069 object is done either by default, or by means of a function returning
6070 an aggregate of type DT, or by means of an extension aggregate.
6072 @example
6073 Obj5 : DT;
6074 Obj6 : DT := Function_Returning_DT (50);
6075 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6076 @end example
6078 The declaration of @code{Obj5} invokes the default constructors: the
6079 C++ default constructor of the parent type takes care of the initialization
6080 of the components inherited from Root, and GNAT takes care of the default
6081 initialization of the additional Ada components of type DT (that is,
6082 @code{C_Value} is initialized to value 2009). The order of invocation of
6083 the constructors is consistent with the order of elaboration required by
6084 Ada and C++. That is, the constructor of the parent type is always called
6085 before the constructor of the derived type.
6087 Let us now consider a record that has components whose type is imported
6088 from C++. For example:
6090 @example
6091 type Rec1 is limited record
6092    Data1 : Root := Constructor (10);
6093    Value : Natural := 1000;
6094 end record;
6096 type Rec2 (D : Integer := 20) is limited record
6097    Rec   : Rec1;
6098    Data2 : Root := Constructor (D, 30);
6099 end record;
6100 @end example
6102 The initialization of an object of type @code{Rec2} will call the
6103 non-default C++ constructors specified for the imported components.
6104 For example:
6106 @example
6107 Obj8 : Rec2 (40);
6108 @end example
6110 Using Ada 2005 we can use limited aggregates to initialize an object
6111 invoking C++ constructors that differ from those specified in the type
6112 declarations. For example:
6114 @example
6115 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6116                         others => <>),
6117                 others => <>);
6118 @end example
6120 The above declaration uses an Ada 2005 limited aggregate to
6121 initialize @code{Obj9}, and the C++ constructor that has two integer
6122 arguments is invoked to initialize the @code{Data1} component instead
6123 of the constructor specified in the declaration of type @code{Rec1}. In
6124 Ada 2005 the box in the aggregate indicates that unspecified components
6125 are initialized using the expression (if any) available in the component
6126 declaration. That is, in this case discriminant @code{D} is initialized
6127 to value @code{20}, @code{Value} is initialized to value 1000, and the
6128 non-default C++ constructor that handles two integers takes care of
6129 initializing component @code{Data2} with values @code{20,30}.
6131 In Ada 2005 we can use the extended return statement to build the Ada
6132 equivalent to C++ non-default constructors. For example:
6134 @example
6135 function Constructor (V : Integer) return Rec2 is
6136 begin
6137    return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
6138                                  others => <>),
6139                          others => <>) do
6140       --  Further actions required for construction of
6141       --  objects of type Rec2
6142       ...
6143    end record;
6144 end Constructor;
6145 @end example
6147 In this example the extended return statement construct is used to
6148 build in place the returned object whose components are initialized
6149 by means of a limited aggregate. Any further action associated with
6150 the constructor can be placed inside the construct.
6152 @node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6153 @anchor{gnat_ugn/the_gnat_compilation_model id69}@anchor{af}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-at-the-class-level}@anchor{ae}
6154 @subsubsection Interfacing with C++ at the Class Level
6157 In this section we demonstrate the GNAT features for interfacing with
6158 C++ by means of an example making use of Ada 2005 abstract interface
6159 types. This example consists of a classification of animals; classes
6160 have been used to model our main classification of animals, and
6161 interfaces provide support for the management of secondary
6162 classifications. We first demonstrate a case in which the types and
6163 constructors are defined on the C++ side and imported from the Ada
6164 side, and latter the reverse case.
6166 The root of our derivation will be the @code{Animal} class, with a
6167 single private attribute (the @code{Age} of the animal), a constructor,
6168 and two public primitives to set and get the value of this attribute.
6170 @example
6171 class Animal @{
6172  public:
6173    virtual void Set_Age (int New_Age);
6174    virtual int Age ();
6175    Animal() @{Age_Count = 0;@};
6176  private:
6177    int Age_Count;
6179 @end example
6181 Abstract interface types are defined in C++ by means of classes with pure
6182 virtual functions and no data members. In our example we will use two
6183 interfaces that provide support for the common management of @code{Carnivore}
6184 and @code{Domestic} animals:
6186 @example
6187 class Carnivore @{
6188 public:
6189    virtual int Number_Of_Teeth () = 0;
6192 class Domestic @{
6193 public:
6194    virtual void Set_Owner (char* Name) = 0;
6196 @end example
6198 Using these declarations, we can now say that a @code{Dog} is an animal that is
6199 both Carnivore and Domestic, that is:
6201 @example
6202 class Dog : Animal, Carnivore, Domestic @{
6203  public:
6204    virtual int  Number_Of_Teeth ();
6205    virtual void Set_Owner (char* Name);
6207    Dog(); // Constructor
6208  private:
6209    int  Tooth_Count;
6210    char *Owner;
6212 @end example
6214 In the following examples we will assume that the previous declarations are
6215 located in a file named @code{animals.h}. The following package demonstrates
6216 how to import these C++ declarations from the Ada side:
6218 @example
6219 with Interfaces.C.Strings; use Interfaces.C.Strings;
6220 package Animals is
6221   type Carnivore is limited interface;
6222   pragma Convention (C_Plus_Plus, Carnivore);
6223   function Number_Of_Teeth (X : Carnivore)
6224      return Natural is abstract;
6226   type Domestic is limited interface;
6227   pragma Convention (C_Plus_Plus, Domestic);
6228   procedure Set_Owner
6229     (X    : in out Domestic;
6230      Name : Chars_Ptr) is abstract;
6232   type Animal is tagged limited record
6233     Age : Natural;
6234   end record;
6235   pragma Import (C_Plus_Plus, Animal);
6237   procedure Set_Age (X : in out Animal; Age : Integer);
6238   pragma Import (C_Plus_Plus, Set_Age);
6240   function Age (X : Animal) return Integer;
6241   pragma Import (C_Plus_Plus, Age);
6243   function New_Animal return Animal;
6244   pragma CPP_Constructor (New_Animal);
6245   pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6247   type Dog is new Animal and Carnivore and Domestic with record
6248     Tooth_Count : Natural;
6249     Owner       : Chars_Ptr;
6250   end record;
6251   pragma Import (C_Plus_Plus, Dog);
6253   function Number_Of_Teeth (A : Dog) return Natural;
6254   pragma Import (C_Plus_Plus, Number_Of_Teeth);
6256   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6257   pragma Import (C_Plus_Plus, Set_Owner);
6259   function New_Dog return Dog;
6260   pragma CPP_Constructor (New_Dog);
6261   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6262 end Animals;
6263 @end example
6265 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6266 interfacing with these C++ classes is easy. The only requirement is that all
6267 the primitives and components must be declared exactly in the same order in
6268 the two languages.
6270 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6271 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
6272 the arguments to the called primitives will be the same as for C++. For the
6273 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
6274 to indicate that they have been defined on the C++ side; this is required
6275 because the dispatch table associated with these tagged types will be built
6276 in the C++ side and therefore will not contain the predefined Ada primitives
6277 which Ada would otherwise expect.
6279 As the reader can see there is no need to indicate the C++ mangled names
6280 associated with each subprogram because it is assumed that all the calls to
6281 these primitives will be dispatching calls. The only exception is the
6282 constructor, which must be registered with the compiler by means of
6283 @code{pragma CPP_Constructor} and needs to provide its associated C++
6284 mangled name because the Ada compiler generates direct calls to it.
6286 With the above packages we can now declare objects of type Dog on the Ada side
6287 and dispatch calls to the corresponding subprograms on the C++ side. We can
6288 also extend the tagged type Dog with further fields and primitives, and
6289 override some of its C++ primitives on the Ada side. For example, here we have
6290 a type derivation defined on the Ada side that inherits all the dispatching
6291 primitives of the ancestor from the C++ side.
6293 @example
6294 with Animals; use Animals;
6295 package Vaccinated_Animals is
6296   type Vaccinated_Dog is new Dog with null record;
6297   function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6298 end Vaccinated_Animals;
6299 @end example
6301 It is important to note that, because of the ABI compatibility, the programmer
6302 does not need to add any further information to indicate either the object
6303 layout or the dispatch table entry associated with each dispatching operation.
6305 Now let us define all the types and constructors on the Ada side and export
6306 them to C++, using the same hierarchy of our previous example:
6308 @example
6309 with Interfaces.C.Strings;
6310 use Interfaces.C.Strings;
6311 package Animals is
6312   type Carnivore is limited interface;
6313   pragma Convention (C_Plus_Plus, Carnivore);
6314   function Number_Of_Teeth (X : Carnivore)
6315      return Natural is abstract;
6317   type Domestic is limited interface;
6318   pragma Convention (C_Plus_Plus, Domestic);
6319   procedure Set_Owner
6320     (X    : in out Domestic;
6321      Name : Chars_Ptr) is abstract;
6323   type Animal is tagged record
6324     Age : Natural;
6325   end record;
6326   pragma Convention (C_Plus_Plus, Animal);
6328   procedure Set_Age (X : in out Animal; Age : Integer);
6329   pragma Export (C_Plus_Plus, Set_Age);
6331   function Age (X : Animal) return Integer;
6332   pragma Export (C_Plus_Plus, Age);
6334   function New_Animal return Animal'Class;
6335   pragma Export (C_Plus_Plus, New_Animal);
6337   type Dog is new Animal and Carnivore and Domestic with record
6338     Tooth_Count : Natural;
6339     Owner       : String (1 .. 30);
6340   end record;
6341   pragma Convention (C_Plus_Plus, Dog);
6343   function Number_Of_Teeth (A : Dog) return Natural;
6344   pragma Export (C_Plus_Plus, Number_Of_Teeth);
6346   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6347   pragma Export (C_Plus_Plus, Set_Owner);
6349   function New_Dog return Dog'Class;
6350   pragma Export (C_Plus_Plus, New_Dog);
6351 end Animals;
6352 @end example
6354 Compared with our previous example the only differences are the use of
6355 @code{pragma Convention} (instead of @code{pragma Import}), and the use of
6356 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
6357 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6358 nothing else to be done; as explained above, the only requirement is that all
6359 the primitives and components are declared in exactly the same order.
6361 For completeness, let us see a brief C++ main program that uses the
6362 declarations available in @code{animals.h} (presented in our first example) to
6363 import and use the declarations from the Ada side, properly initializing and
6364 finalizing the Ada run-time system along the way:
6366 @example
6367 #include "animals.h"
6368 #include <iostream>
6369 using namespace std;
6371 void Check_Carnivore (Carnivore *obj) @{...@}
6372 void Check_Domestic (Domestic *obj)   @{...@}
6373 void Check_Animal (Animal *obj)       @{...@}
6374 void Check_Dog (Dog *obj)             @{...@}
6376 extern "C" @{
6377   void adainit (void);
6378   void adafinal (void);
6379   Dog* new_dog ();
6382 void test ()
6384   Dog *obj = new_dog();  // Ada constructor
6385   Check_Carnivore (obj); // Check secondary DT
6386   Check_Domestic (obj);  // Check secondary DT
6387   Check_Animal (obj);    // Check primary DT
6388   Check_Dog (obj);       // Check primary DT
6391 int main ()
6393   adainit ();  test();  adafinal ();
6394   return 0;
6396 @end example
6398 @node Partition-Wide Settings,Generating Ada Bindings for C and C++ headers,Building Mixed Ada and C++ Programs,Mixed Language Programming
6399 @anchor{gnat_ugn/the_gnat_compilation_model id70}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model partition-wide-settings}@anchor{b1}
6400 @subsection Partition-Wide Settings
6403 When building a mixed-language application it is important to be aware that
6404 Ada enforces some partition-wide settings that may implicitly impact the
6405 behavior of the other languages.
6407 This is the case of certain signals that are reserved to the
6408 implementation to implement proper Ada semantics (such as the behavior
6409 of @code{abort} statements).
6411 It means that the Ada part of the application may override signal handlers
6412 that were previously installed by either the system or by other user code.
6414 If your application requires that either system or user signals be preserved
6415 then you need to instruct the Ada part not to install its own signal handler.
6416 This is done using @code{pragma Interrupt_State} that provides a general
6417 mechanism for overriding such uses of interrupts.
6419 Additionally, @code{pragma Interrupts_System_By_Default} can be used to default
6420 all interrupts to System.
6422 The set of interrupts for which the Ada run-time library sets a specific signal
6423 handler is the following:
6426 @itemize *
6428 @item 
6429 Ada.Interrupts.Names.SIGSEGV
6431 @item 
6432 Ada.Interrupts.Names.SIGBUS
6434 @item 
6435 Ada.Interrupts.Names.SIGFPE
6437 @item 
6438 Ada.Interrupts.Names.SIGILL
6440 @item 
6441 Ada.Interrupts.Names.SIGABRT
6442 @end itemize
6444 The run-time library can be instructed not to install its signal handler for a
6445 particular signal by using the configuration pragma @code{Interrupt_State} in the
6446 Ada code. For example:
6448 @example
6449 pragma Interrupt_State (Ada.Interrupts.Names.SIGSEGV, System);
6450 pragma Interrupt_State (Ada.Interrupts.Names.SIGBUS,  System);
6451 pragma Interrupt_State (Ada.Interrupts.Names.SIGFPE,  System);
6452 pragma Interrupt_State (Ada.Interrupts.Names.SIGILL,  System);
6453 pragma Interrupt_State (Ada.Interrupts.Names.SIGABRT, System);
6454 @end example
6456 Obviously, if the Ada run-time system cannot set these handlers it comes with the
6457 drawback of not fully preserving Ada semantics. @code{SIGSEGV}, @code{SIGBUS}, @code{SIGFPE}
6458 and @code{SIGILL} are used to raise corresponding Ada exceptions in the application,
6459 while @code{SIGABRT} is used to asynchronously abort an action or a task.
6461 @node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Partition-Wide Settings,Mixed Language Programming
6462 @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}
6463 @subsection Generating Ada Bindings for C and C++ headers
6466 @geindex Binding generation (for C and C++ headers)
6468 @geindex C headers (binding generation)
6470 @geindex C++ headers (binding generation)
6472 GNAT includes a binding generator for C and C++ headers which is
6473 intended to do 95% of the tedious work of generating Ada specs from C
6474 or C++ header files.
6476 Note that this capability is not intended to generate 100% correct Ada specs,
6477 and will is some cases require manual adjustments, although it can often
6478 be used out of the box in practice.
6480 Some of the known limitations include:
6483 @itemize *
6485 @item 
6486 only very simple character constant macros are translated into Ada
6487 constants. Function macros (macros with arguments) are partially translated
6488 as comments, to be completed manually if needed.
6490 @item 
6491 some extensions (e.g. vector types) are not supported
6493 @item 
6494 pointers to pointers are mapped to System.Address
6496 @item 
6497 identifiers with identical name (except casing) may generate compilation
6498 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
6499 @end itemize
6501 The code is generated using Ada 2012 syntax, which makes it easier to interface
6502 with other languages. In most cases you can still use the generated binding
6503 even if your code is compiled using earlier versions of Ada (e.g. @code{-gnat95}).
6505 @menu
6506 * Running the Binding Generator:: 
6507 * Generating Bindings for C++ Headers:: 
6508 * Switches:: 
6510 @end menu
6512 @node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6513 @anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{b3}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{b4}
6514 @subsubsection Running the Binding Generator
6517 The binding generator is part of the @code{gcc} compiler and can be
6518 invoked via the @code{-fdump-ada-spec} switch, which will generate Ada
6519 spec files for the header files specified on the command line, and all
6520 header files needed by these files transitively. For example:
6522 @example
6523 $ gcc -c -fdump-ada-spec -C /usr/include/time.h
6524 $ gcc -c *.ads
6525 @end example
6527 will generate, under GNU/Linux, the following files: @code{time_h.ads},
6528 @code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6529 correspond to the files @code{/usr/include/time.h},
6530 @code{/usr/include/bits/time.h}, etc…, and then compile these Ada specs.
6531 That is to say, the name of the Ada specs is in keeping with the relative path
6532 under @code{/usr/include/} of the header files. This behavior is specific to
6533 paths ending with @code{/include/}; in all the other cases, the name of the
6534 Ada specs is derived from the simple name of the header files instead.
6536 The @code{-C} switch tells @code{gcc} to extract comments from headers,
6537 and will attempt to generate corresponding Ada comments.
6539 If you want to generate a single Ada file and not the transitive closure, you
6540 can use instead the @code{-fdump-ada-spec-slim} switch.
6542 You can optionally specify a parent unit, of which all generated units will
6543 be children, using @code{-fada-spec-parent=`unit'}.
6545 The simple @code{gcc}-based command works only for C headers. For C++ headers
6546 you need to use either the @code{g++} command or the combination @code{gcc -x c++}.
6548 In some cases, the generated bindings will be more complete or more meaningful
6549 when defining some macros, which you can do via the @code{-D} switch. This
6550 is for example the case with @code{Xlib.h} under GNU/Linux:
6552 @example
6553 $ gcc -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6554 @end example
6556 The above will generate more complete bindings than a straight call without
6557 the @code{-DXLIB_ILLEGAL_ACCESS} switch.
6559 In other cases, it is not possible to parse a header file in a stand-alone
6560 manner, because other include files need to be included first. In this
6561 case, the solution is to create a small header file including the needed
6562 @code{#include} and possible @code{#define} directives. For example, to
6563 generate Ada bindings for @code{readline/readline.h}, you need to first
6564 include @code{stdio.h}, so you can create a file with the following two
6565 lines in e.g. @code{readline1.h}:
6567 @example
6568 #include <stdio.h>
6569 #include <readline/readline.h>
6570 @end example
6572 and then generate Ada bindings from this file:
6574 @example
6575 $ gcc -c -fdump-ada-spec readline1.h
6576 @end example
6578 @node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6579 @anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{b5}@anchor{gnat_ugn/the_gnat_compilation_model id73}@anchor{b6}
6580 @subsubsection Generating Bindings for C++ Headers
6583 Generating bindings for C++ headers is done using the same options, always
6584 with the `g++' compiler. Note that generating Ada spec from C++ headers is a
6585 much more complex job and support for C++ headers is much more limited that
6586 support for C headers. As a result, you will need to modify the resulting
6587 bindings by hand more extensively when using C++ headers.
6589 In this mode, C++ classes will be mapped to Ada tagged types, constructors
6590 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
6591 multiple inheritance of abstract classes will be mapped to Ada interfaces
6592 (see the `Interfacing to C++' section in the @cite{GNAT Reference Manual}
6593 for additional information on interfacing to C++).
6595 For example, given the following C++ header file:
6597 @example
6598 class Carnivore @{
6599 public:
6600    virtual int Number_Of_Teeth () = 0;
6603 class Domestic @{
6604 public:
6605    virtual void Set_Owner (char* Name) = 0;
6608 class Animal @{
6609 public:
6610   int Age_Count;
6611   virtual void Set_Age (int New_Age);
6614 class Dog : Animal, Carnivore, Domestic @{
6615  public:
6616   int  Tooth_Count;
6617   char *Owner;
6619   virtual int  Number_Of_Teeth ();
6620   virtual void Set_Owner (char* Name);
6622   Dog();
6624 @end example
6626 The corresponding Ada code is generated:
6628 @example
6629 package Class_Carnivore is
6630   type Carnivore is limited interface;
6631   pragma Import (CPP, Carnivore);
6633   function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6634 end;
6635 use Class_Carnivore;
6637 package Class_Domestic is
6638   type Domestic is limited interface;
6639   pragma Import (CPP, Domestic);
6641   procedure Set_Owner
6642     (this : access Domestic;
6643      Name : Interfaces.C.Strings.chars_ptr) is abstract;
6644 end;
6645 use Class_Domestic;
6647 package Class_Animal is
6648   type Animal is tagged limited record
6649     Age_Count : aliased int;
6650   end record;
6651   pragma Import (CPP, Animal);
6653   procedure Set_Age (this : access Animal; New_Age : int);
6654   pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6655 end;
6656 use Class_Animal;
6658 package Class_Dog is
6659   type Dog is new Animal and Carnivore and Domestic with record
6660     Tooth_Count : aliased int;
6661     Owner : Interfaces.C.Strings.chars_ptr;
6662   end record;
6663   pragma Import (CPP, Dog);
6665   function Number_Of_Teeth (this : access Dog) return int;
6666   pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6668   procedure Set_Owner
6669     (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6670   pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6672   function New_Dog return Dog;
6673   pragma CPP_Constructor (New_Dog);
6674   pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6675 end;
6676 use Class_Dog;
6677 @end example
6679 @node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6680 @anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{b7}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{b8}
6681 @subsubsection Switches
6684 @geindex -fdump-ada-spec (gcc)
6687 @table @asis
6689 @item @code{-fdump-ada-spec}
6691 Generate Ada spec files for the given header files transitively (including
6692 all header files that these headers depend upon).
6693 @end table
6695 @geindex -fdump-ada-spec-slim (gcc)
6698 @table @asis
6700 @item @code{-fdump-ada-spec-slim}
6702 Generate Ada spec files for the header files specified on the command line
6703 only.
6704 @end table
6706 @geindex -fada-spec-parent (gcc)
6709 @table @asis
6711 @item @code{-fada-spec-parent=`unit'}
6713 Specifies that all files generated by @code{-fdump-ada-spec} are
6714 to be child units of the specified parent unit.
6715 @end table
6717 @geindex -C (gcc)
6720 @table @asis
6722 @item @code{-C}
6724 Extract comments from headers and generate Ada comments in the Ada spec files.
6725 @end table
6727 @node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6728 @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}
6729 @subsection Generating C Headers for Ada Specifications
6732 @geindex Binding generation (for Ada specs)
6734 @geindex C headers (binding generation)
6736 GNAT includes a C header generator for Ada specifications which supports
6737 Ada types that have a direct mapping to C types. This includes in particular
6738 support for:
6741 @itemize *
6743 @item 
6744 Scalar types
6746 @item 
6747 Constrained arrays
6749 @item 
6750 Records (untagged)
6752 @item 
6753 Composition of the above types
6755 @item 
6756 Constant declarations
6758 @item 
6759 Object declarations
6761 @item 
6762 Subprogram declarations
6763 @end itemize
6765 @menu
6766 * Running the C Header Generator:: 
6768 @end menu
6770 @node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6771 @anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{bb}
6772 @subsubsection Running the C Header Generator
6775 The C header generator is part of the GNAT compiler and can be invoked via
6776 the @code{-gnatceg} combination of switches, which will generate a @code{.h}
6777 file corresponding to the given input file (Ada spec or body). Note that
6778 only spec files are processed in any case, so giving a spec or a body file
6779 as input is equivalent. For example:
6781 @example
6782 $ gcc -c -gnatceg pack1.ads
6783 @end example
6785 will generate a self-contained file called @code{pack1.h} including
6786 common definitions from the Ada Standard package, followed by the
6787 definitions included in @code{pack1.ads}, as well as all the other units
6788 withed by this file.
6790 For instance, given the following Ada files:
6792 @example
6793 package Pack2 is
6794    type Int is range 1 .. 10;
6795 end Pack2;
6796 @end example
6798 @example
6799 with Pack2;
6801 package Pack1 is
6802    type Rec is record
6803       Field1, Field2 : Pack2.Int;
6804    end record;
6806    Global : Rec := (1, 2);
6808    procedure Proc1 (R : Rec);
6809    procedure Proc2 (R : in out Rec);
6810 end Pack1;
6811 @end example
6813 The above @code{gcc} command will generate the following @code{pack1.h} file:
6815 @example
6816 /* Standard definitions skipped */
6817 #ifndef PACK2_ADS
6818 #define PACK2_ADS
6819 typedef short_short_integer pack2__TintB;
6820 typedef pack2__TintB pack2__int;
6821 #endif /* PACK2_ADS */
6823 #ifndef PACK1_ADS
6824 #define PACK1_ADS
6825 typedef struct _pack1__rec @{
6826   pack2__int field1;
6827   pack2__int field2;
6828 @} pack1__rec;
6829 extern pack1__rec pack1__global;
6830 extern void pack1__proc1(const pack1__rec r);
6831 extern void pack1__proc2(pack1__rec *r);
6832 #endif /* PACK1_ADS */
6833 @end example
6835 You can then @code{include} @code{pack1.h} from a C source file and use the types,
6836 call subprograms, reference objects, and constants.
6838 @node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
6839 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{2d}@anchor{gnat_ugn/the_gnat_compilation_model id75}@anchor{bc}
6840 @section GNAT and Other Compilation Models
6843 This section compares the GNAT model with the approaches taken in
6844 other environments, first the C/C++ model and then the mechanism that
6845 has been used in other Ada systems, in particular those traditionally
6846 used for Ada 83.
6848 @menu
6849 * Comparison between GNAT and C/C++ Compilation Models:: 
6850 * Comparison between GNAT and Conventional Ada Library Models:: 
6852 @end menu
6854 @node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
6855 @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}
6856 @subsection Comparison between GNAT and C/C++ Compilation Models
6859 The GNAT model of compilation is close to the C and C++ models. You can
6860 think of Ada specs as corresponding to header files in C. As in C, you
6861 don’t need to compile specs; they are compiled when they are used. The
6862 Ada `with' is similar in effect to the @code{#include} of a C
6863 header.
6865 One notable difference is that, in Ada, you may compile specs separately
6866 to check them for semantic and syntactic accuracy. This is not always
6867 possible with C headers because they are fragments of programs that have
6868 less specific syntactic or semantic rules.
6870 The other major difference is the requirement for running the binder,
6871 which performs two important functions. First, it checks for
6872 consistency. In C or C++, the only defense against assembling
6873 inconsistent programs lies outside the compiler, in a makefile, for
6874 example. The binder satisfies the Ada requirement that it be impossible
6875 to construct an inconsistent program when the compiler is used in normal
6876 mode.
6878 @geindex Elaboration order control
6880 The other important function of the binder is to deal with elaboration
6881 issues. There are also elaboration issues in C++ that are handled
6882 automatically. This automatic handling has the advantage of being
6883 simpler to use, but the C++ programmer has no control over elaboration.
6884 Where @code{gnatbind} might complain there was no valid order of
6885 elaboration, a C++ compiler would simply construct a program that
6886 malfunctioned at run time.
6888 @node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
6889 @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}
6890 @subsection Comparison between GNAT and Conventional Ada Library Models
6893 This section is intended for Ada programmers who have
6894 used an Ada compiler implementing the traditional Ada library
6895 model, as described in the Ada Reference Manual.
6897 @geindex GNAT library
6899 In GNAT, there is no ‘library’ in the normal sense. Instead, the set of
6900 source files themselves acts as the library. Compiling Ada programs does
6901 not generate any centralized information, but rather an object file and
6902 a ALI file, which are of interest only to the binder and linker.
6903 In a traditional system, the compiler reads information not only from
6904 the source file being compiled, but also from the centralized library.
6905 This means that the effect of a compilation depends on what has been
6906 previously compiled. In particular:
6909 @itemize *
6911 @item 
6912 When a unit is `with'ed, the unit seen by the compiler corresponds
6913 to the version of the unit most recently compiled into the library.
6915 @item 
6916 Inlining is effective only if the necessary body has already been
6917 compiled into the library.
6919 @item 
6920 Compiling a unit may obsolete other units in the library.
6921 @end itemize
6923 In GNAT, compiling one unit never affects the compilation of any other
6924 units because the compiler reads only source files. Only changes to source
6925 files can affect the results of a compilation. In particular:
6928 @itemize *
6930 @item 
6931 When a unit is `with'ed, the unit seen by the compiler corresponds
6932 to the source version of the unit that is currently accessible to the
6933 compiler.
6935 @geindex Inlining
6937 @item 
6938 Inlining requires the appropriate source files for the package or
6939 subprogram bodies to be available to the compiler. Inlining is always
6940 effective, independent of the order in which units are compiled.
6942 @item 
6943 Compiling a unit never affects any other compilations. The editing of
6944 sources may cause previous compilations to be out of date if they
6945 depended on the source file being modified.
6946 @end itemize
6948 The most important result of these differences is that order of compilation
6949 is never significant in GNAT. There is no situation in which one is
6950 required to do one compilation before another. What shows up as order of
6951 compilation requirements in the traditional Ada library becomes, in
6952 GNAT, simple source dependencies; in other words, there is only a set
6953 of rules saying what source files must be present when a file is
6954 compiled.
6956 @node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
6957 @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}
6958 @section Using GNAT Files with External Tools
6961 This section explains how files that are produced by GNAT may be
6962 used with tools designed for other languages.
6964 @menu
6965 * Using Other Utility Programs with GNAT:: 
6966 * The External Symbol Naming Scheme of GNAT:: 
6968 @end menu
6970 @node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
6971 @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}
6972 @subsection Using Other Utility Programs with GNAT
6975 The object files generated by GNAT are in standard system format and in
6976 particular the debugging information uses this format. This means
6977 programs generated by GNAT can be used with existing utilities that
6978 depend on these formats.
6980 In general, any utility program that works with C will also often work with
6981 Ada programs generated by GNAT. This includes software utilities such as
6982 gprof (a profiling program), gdb (the FSF debugger), and utilities such
6983 as Purify.
6985 @node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
6986 @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}
6987 @subsection The External Symbol Naming Scheme of GNAT
6990 In order to interpret the output from GNAT, when using tools that are
6991 originally intended for use with other languages, it is useful to
6992 understand the conventions used to generate link names from the Ada
6993 entity names.
6995 All link names are in all lowercase letters. With the exception of library
6996 procedure names, the mechanism used is simply to use the full expanded
6997 Ada name with dots replaced by double underscores. For example, suppose
6998 we have the following package spec:
7000 @example
7001 package QRS is
7002    MN : Integer;
7003 end QRS;
7004 @end example
7006 @geindex pragma Export
7008 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
7009 the corresponding link name is @code{qrs__mn}.
7010 Of course if a @code{pragma Export} is used this may be overridden:
7012 @example
7013 package Exports is
7014    Var1 : Integer;
7015    pragma Export (Var1, C, External_Name => "var1_name");
7016    Var2 : Integer;
7017    pragma Export (Var2, C, Link_Name => "var2_link_name");
7018 end Exports;
7019 @end example
7021 In this case, the link name for @code{Var1} is whatever link name the
7022 C compiler would assign for the C function @code{var1_name}. This typically
7023 would be either @code{var1_name} or @code{_var1_name}, depending on operating
7024 system conventions, but other possibilities exist. The link name for
7025 @code{Var2} is @code{var2_link_name}, and this is not operating system
7026 dependent.
7028 One exception occurs for library level procedures. A potential ambiguity
7029 arises between the required name @code{_main} for the C main program,
7030 and the name we would otherwise assign to an Ada library level procedure
7031 called @code{Main} (which might well not be the main program).
7033 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
7034 names. So if we have a library level procedure such as:
7036 @example
7037 procedure Hello (S : String);
7038 @end example
7040 the external name of this procedure will be @code{_ada_hello}.
7042 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7044 @node Building Executable Programs with GNAT,GNAT Utility Programs,The GNAT Compilation Model,Top
7045 @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}
7046 @chapter Building Executable Programs with GNAT
7049 This chapter describes first the gnatmake tool
7050 (@ref{c8,,Building with gnatmake}),
7051 which automatically determines the set of sources
7052 needed by an Ada compilation unit and executes the necessary
7053 (re)compilations, binding and linking.
7054 It also explains how to use each tool individually: the
7055 compiler (gcc, see @ref{c9,,Compiling with gcc}),
7056 binder (gnatbind, see @ref{ca,,Binding with gnatbind}),
7057 and linker (gnatlink, see @ref{cb,,Linking with gnatlink})
7058 to build executable programs.
7059 Finally, this chapter provides examples of
7060 how to make use of the general GNU make mechanism
7061 in a GNAT context (see @ref{70,,Using the GNU make Utility}).
7064 @menu
7065 * Building with gnatmake:: 
7066 * Compiling with gcc:: 
7067 * Compiler Switches:: 
7068 * Linker Switches:: 
7069 * Binding with gnatbind:: 
7070 * Linking with gnatlink:: 
7071 * Using the GNU make Utility:: 
7073 @end menu
7075 @node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7076 @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}
7077 @section Building with @code{gnatmake}
7080 @geindex gnatmake
7082 A typical development cycle when working on an Ada program consists of
7083 the following steps:
7086 @enumerate 
7088 @item 
7089 Edit some sources to fix bugs;
7091 @item 
7092 Add enhancements;
7094 @item 
7095 Compile all sources affected;
7097 @item 
7098 Rebind and relink; and
7100 @item 
7101 Test.
7102 @end enumerate
7104 @geindex Dependency rules (compilation)
7106 The third step in particular can be tricky, because not only do the modified
7107 files have to be compiled, but any files depending on these files must also be
7108 recompiled. The dependency rules in Ada can be quite complex, especially
7109 in the presence of overloading, @code{use} clauses, generics and inlined
7110 subprograms.
7112 @code{gnatmake} automatically takes care of the third and fourth steps
7113 of this process. It determines which sources need to be compiled,
7114 compiles them, and binds and links the resulting object files.
7116 Unlike some other Ada make programs, the dependencies are always
7117 accurately recomputed from the new sources. The source based approach of
7118 the GNAT compilation model makes this possible. This means that if
7119 changes to the source program cause corresponding changes in
7120 dependencies, they will always be tracked exactly correctly by
7121 @code{gnatmake}.
7123 Note that for advanced forms of project structure, we recommend creating
7124 a project file as explained in the `GNAT_Project_Manager' chapter in the
7125 `GPRbuild User’s Guide', and using the
7126 @code{gprbuild} tool which supports building with project files and works similarly
7127 to @code{gnatmake}.
7129 @menu
7130 * Running gnatmake:: 
7131 * Switches for gnatmake:: 
7132 * Mode Switches for gnatmake:: 
7133 * Notes on the Command Line:: 
7134 * How gnatmake Works:: 
7135 * Examples of gnatmake Usage:: 
7137 @end menu
7139 @node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7140 @anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{cd}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{ce}
7141 @subsection Running @code{gnatmake}
7144 The usual form of the @code{gnatmake} command is
7146 @example
7147 $ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7148 @end example
7150 The only required argument is one @code{file_name}, which specifies
7151 a compilation unit that is a main program. Several @code{file_names} can be
7152 specified: this will result in several executables being built.
7153 If @code{switches} are present, they can be placed before the first
7154 @code{file_name}, between @code{file_names} or after the last @code{file_name}.
7155 If @code{mode_switches} are present, they must always be placed after
7156 the last @code{file_name} and all @code{switches}.
7158 If you are using standard file extensions (@code{.adb} and
7159 @code{.ads}), then the
7160 extension may be omitted from the @code{file_name} arguments. However, if
7161 you are using non-standard extensions, then it is required that the
7162 extension be given. A relative or absolute directory path can be
7163 specified in a @code{file_name}, in which case, the input source file will
7164 be searched for in the specified directory only. Otherwise, the input
7165 source file will first be searched in the directory where
7166 @code{gnatmake} was invoked and if it is not found, it will be search on
7167 the source path of the compiler as described in
7168 @ref{73,,Search Paths and the Run-Time Library (RTL)}.
7170 All @code{gnatmake} output (except when you specify @code{-M}) is sent to
7171 @code{stderr}. The output produced by the
7172 @code{-M} switch is sent to @code{stdout}.
7174 @node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7175 @anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{cf}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{d0}
7176 @subsection Switches for @code{gnatmake}
7179 You may specify any of the following switches to @code{gnatmake}:
7181 @geindex --version (gnatmake)
7184 @table @asis
7186 @item @code{--version}
7188 Display Copyright and version, then exit disregarding all other options.
7189 @end table
7191 @geindex --help (gnatmake)
7194 @table @asis
7196 @item @code{--help}
7198 If @code{--version} was not used, display usage, then exit disregarding
7199 all other options.
7200 @end table
7202 @geindex -P (gnatmake)
7205 @table @asis
7207 @item @code{-P`project'}
7209 Build GNAT project file @code{project} using GPRbuild. When this switch is
7210 present, all other command-line switches are treated as GPRbuild switches
7211 and not @code{gnatmake} switches.
7212 @end table
7214 @c -- Comment:
7215 @c :ref:`gnatmake_and_Project_Files`.
7217 @geindex --GCC=compiler_name (gnatmake)
7220 @table @asis
7222 @item @code{--GCC=`compiler_name'}
7224 Program used for compiling. The default is @code{gcc}. You need to use
7225 quotes around @code{compiler_name} if @code{compiler_name} contains
7226 spaces or other separator characters.
7227 As an example @code{--GCC="foo -x  -y"}
7228 will instruct @code{gnatmake} to use @code{foo -x -y} as your
7229 compiler. A limitation of this syntax is that the name and path name of
7230 the executable itself must not include any embedded spaces. Note that
7231 switch @code{-c} is always inserted after your command name. Thus in the
7232 above example the compiler command that will be used by @code{gnatmake}
7233 will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7234 used, only the last @code{compiler_name} is taken into account. However,
7235 all the additional switches are also taken into account. Thus,
7236 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7237 @code{--GCC="bar -x -y -z -t"}.
7238 @end table
7240 @geindex --GNATBIND=binder_name (gnatmake)
7243 @table @asis
7245 @item @code{--GNATBIND=`binder_name'}
7247 Program used for binding. The default is @code{gnatbind}. You need to
7248 use quotes around @code{binder_name} if @code{binder_name} contains spaces
7249 or other separator characters.
7250 As an example @code{--GNATBIND="bar -x  -y"}
7251 will instruct @code{gnatmake} to use @code{bar -x -y} as your
7252 binder. Binder switches that are normally appended by @code{gnatmake}
7253 to @code{gnatbind} are now appended to the end of @code{bar -x -y}.
7254 A limitation of this syntax is that the name and path name of the executable
7255 itself must not include any embedded spaces.
7256 @end table
7258 @geindex --GNATLINK=linker_name (gnatmake)
7261 @table @asis
7263 @item @code{--GNATLINK=`linker_name'}
7265 Program used for linking. The default is @code{gnatlink}. You need to
7266 use quotes around @code{linker_name} if @code{linker_name} contains spaces
7267 or other separator characters.
7268 As an example @code{--GNATLINK="lan -x  -y"}
7269 will instruct @code{gnatmake} to use @code{lan -x -y} as your
7270 linker. Linker switches that are normally appended by @code{gnatmake} to
7271 @code{gnatlink} are now appended to the end of @code{lan -x -y}.
7272 A limitation of this syntax is that the name and path name of the executable
7273 itself must not include any embedded spaces.
7275 @item @code{--create-map-file}
7277 When linking an executable, create a map file. The name of the map file
7278 has the same name as the executable with extension “.map”.
7280 @item @code{--create-map-file=`mapfile'}
7282 When linking an executable, create a map file with the specified name.
7283 @end table
7285 @geindex --create-missing-dirs (gnatmake)
7288 @table @asis
7290 @item @code{--create-missing-dirs}
7292 When using project files (@code{-P`project'}), automatically create
7293 missing object directories, library directories and exec
7294 directories.
7296 @item @code{--single-compile-per-obj-dir}
7298 Disallow simultaneous compilations in the same object directory when
7299 project files are used.
7301 @item @code{--subdirs=`subdir'}
7303 Actual object directory of each project file is the subdirectory subdir of the
7304 object directory specified or defaulted in the project file.
7306 @item @code{--unchecked-shared-lib-imports}
7308 By default, shared library projects are not allowed to import static library
7309 projects. When this switch is used on the command line, this restriction is
7310 relaxed.
7312 @item @code{--source-info=`source info file'}
7314 Specify a source info file. This switch is active only when project files
7315 are used. If the source info file is specified as a relative path, then it is
7316 relative to the object directory of the main project. If the source info file
7317 does not exist, then after the Project Manager has successfully parsed and
7318 processed the project files and found the sources, it creates the source info
7319 file. If the source info file already exists and can be read successfully,
7320 then the Project Manager will get all the needed information about the sources
7321 from the source info file and will not look for them. This reduces the time
7322 to process the project files, especially when looking for sources that take a
7323 long time. If the source info file exists but cannot be parsed successfully,
7324 the Project Manager will attempt to recreate it. If the Project Manager fails
7325 to create the source info file, a message is issued, but gnatmake does not
7326 fail. @code{gnatmake} “trusts” the source info file. This means that
7327 if the source files have changed (addition, deletion, moving to a different
7328 source directory), then the source info file need to be deleted and recreated.
7329 @end table
7331 @geindex -a (gnatmake)
7334 @table @asis
7336 @item @code{-a}
7338 Consider all files in the make process, even the GNAT internal system
7339 files (for example, the predefined Ada library files), as well as any
7340 locked files. Locked files are files whose ALI file is write-protected.
7341 By default,
7342 @code{gnatmake} does not check these files,
7343 because the assumption is that the GNAT internal files are properly up
7344 to date, and also that any write protected ALI files have been properly
7345 installed. Note that if there is an installation problem, such that one
7346 of these files is not up to date, it will be properly caught by the
7347 binder.
7348 You may have to specify this switch if you are working on GNAT
7349 itself. The switch @code{-a} is also useful
7350 in conjunction with @code{-f}
7351 if you need to recompile an entire application,
7352 including run-time files, using special configuration pragmas,
7353 such as a @code{Normalize_Scalars} pragma.
7355 By default
7356 @code{gnatmake -a} compiles all GNAT
7357 internal files with
7358 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7359 @end table
7361 @geindex -b (gnatmake)
7364 @table @asis
7366 @item @code{-b}
7368 Bind only. Can be combined with @code{-c} to do
7369 compilation and binding, but no link.
7370 Can be combined with @code{-l}
7371 to do binding and linking. When not combined with
7372 @code{-c}
7373 all the units in the closure of the main program must have been previously
7374 compiled and must be up to date. The root unit specified by @code{file_name}
7375 may be given without extension, with the source extension or, if no GNAT
7376 Project File is specified, with the ALI file extension.
7377 @end table
7379 @geindex -c (gnatmake)
7382 @table @asis
7384 @item @code{-c}
7386 Compile only. Do not perform binding, except when @code{-b}
7387 is also specified. Do not perform linking, except if both
7388 @code{-b} and
7389 @code{-l} are also specified.
7390 If the root unit specified by @code{file_name} is not a main unit, this is the
7391 default. Otherwise @code{gnatmake} will attempt binding and linking
7392 unless all objects are up to date and the executable is more recent than
7393 the objects.
7394 @end table
7396 @geindex -C (gnatmake)
7399 @table @asis
7401 @item @code{-C}
7403 Use a temporary mapping file. A mapping file is a way to communicate
7404 to the compiler two mappings: from unit names to file names (without
7405 any directory information) and from file names to path names (with
7406 full directory information). A mapping file can make the compiler’s
7407 file searches faster, especially if there are many source directories,
7408 or the sources are read over a slow network connection. If
7409 @code{-P} is used, a mapping file is always used, so
7410 @code{-C} is unnecessary; in this case the mapping file
7411 is initially populated based on the project file. If
7412 @code{-C} is used without
7413 @code{-P},
7414 the mapping file is initially empty. Each invocation of the compiler
7415 will add any newly accessed sources to the mapping file.
7416 @end table
7418 @geindex -C= (gnatmake)
7421 @table @asis
7423 @item @code{-C=`file'}
7425 Use a specific mapping file. The file, specified as a path name (absolute or
7426 relative) by this switch, should already exist, otherwise the switch is
7427 ineffective. The specified mapping file will be communicated to the compiler.
7428 This switch is not compatible with a project file
7429 (-P`file`) or with multiple compiling processes
7430 (-jnnn, when nnn is greater than 1).
7431 @end table
7433 @geindex -d (gnatmake)
7436 @table @asis
7438 @item @code{-d}
7440 Display progress for each source, up to date or not, as a single line:
7442 @example
7443 completed x out of y (zz%)
7444 @end example
7446 If the file needs to be compiled this is displayed after the invocation of
7447 the compiler. These lines are displayed even in quiet output mode.
7448 @end table
7450 @geindex -D (gnatmake)
7453 @table @asis
7455 @item @code{-D `dir'}
7457 Put all object files and ALI file in directory @code{dir}.
7458 If the @code{-D} switch is not used, all object files
7459 and ALI files go in the current working directory.
7461 This switch cannot be used when using a project file.
7462 @end table
7464 @geindex -eI (gnatmake)
7467 @table @asis
7469 @item @code{-eI`nnn'}
7471 Indicates that the main source is a multi-unit source and the rank of the unit
7472 in the source file is nnn. nnn needs to be a positive number and a valid
7473 index in the source. This switch cannot be used when @code{gnatmake} is
7474 invoked for several mains.
7475 @end table
7477 @geindex -eL (gnatmake)
7479 @geindex symbolic links
7482 @table @asis
7484 @item @code{-eL}
7486 Follow all symbolic links when processing project files.
7487 This should be used if your project uses symbolic links for files or
7488 directories, but is not needed in other cases.
7490 @geindex naming scheme
7492 This also assumes that no directory matches the naming scheme for files (for
7493 instance that you do not have a directory called “sources.ads” when using the
7494 default GNAT naming scheme).
7496 When you do not have to use this switch (i.e., by default), gnatmake is able to
7497 save a lot of system calls (several per source file and object file), which
7498 can result in a significant speed up to load and manipulate a project file,
7499 especially when using source files from a remote system.
7500 @end table
7502 @geindex -eS (gnatmake)
7505 @table @asis
7507 @item @code{-eS}
7509 Output the commands for the compiler, the binder and the linker
7510 on standard output,
7511 instead of standard error.
7512 @end table
7514 @geindex -f (gnatmake)
7517 @table @asis
7519 @item @code{-f}
7521 Force recompilations. Recompile all sources, even though some object
7522 files may be up to date, but don’t recompile predefined or GNAT internal
7523 files or locked files (files with a write-protected ALI file),
7524 unless the @code{-a} switch is also specified.
7525 @end table
7527 @geindex -F (gnatmake)
7530 @table @asis
7532 @item @code{-F}
7534 When using project files, if some errors or warnings are detected during
7535 parsing and verbose mode is not in effect (no use of switch
7536 -v), then error lines start with the full path name of the project
7537 file, rather than its simple file name.
7538 @end table
7540 @geindex -g (gnatmake)
7543 @table @asis
7545 @item @code{-g}
7547 Enable debugging. This switch is simply passed to the compiler and to the
7548 linker.
7549 @end table
7551 @geindex -i (gnatmake)
7554 @table @asis
7556 @item @code{-i}
7558 In normal mode, @code{gnatmake} compiles all object files and ALI files
7559 into the current directory. If the @code{-i} switch is used,
7560 then instead object files and ALI files that already exist are overwritten
7561 in place. This means that once a large project is organized into separate
7562 directories in the desired manner, then @code{gnatmake} will automatically
7563 maintain and update this organization. If no ALI files are found on the
7564 Ada object path (see @ref{73,,Search Paths and the Run-Time Library (RTL)}),
7565 the new object and ALI files are created in the
7566 directory containing the source being compiled. If another organization
7567 is desired, where objects and sources are kept in different directories,
7568 a useful technique is to create dummy ALI files in the desired directories.
7569 When detecting such a dummy file, @code{gnatmake} will be forced to
7570 recompile the corresponding source file, and it will be put the resulting
7571 object and ALI files in the directory where it found the dummy file.
7572 @end table
7574 @geindex -j (gnatmake)
7576 @geindex Parallel make
7579 @table @asis
7581 @item @code{-j`n'}
7583 Use @code{n} processes to carry out the (re)compilations. On a multiprocessor
7584 machine compilations will occur in parallel. If @code{n} is 0, then the
7585 maximum number of parallel compilations is the number of core processors
7586 on the platform. In the event of compilation errors, messages from various
7587 compilations might get interspersed (but @code{gnatmake} will give you the
7588 full ordered list of failing compiles at the end). If this is problematic,
7589 rerun the make process with n set to 1 to get a clean list of messages.
7590 @end table
7592 @geindex -k (gnatmake)
7595 @table @asis
7597 @item @code{-k}
7599 Keep going. Continue as much as possible after a compilation error. To
7600 ease the programmer’s task in case of compilation errors, the list of
7601 sources for which the compile fails is given when @code{gnatmake}
7602 terminates.
7604 If @code{gnatmake} is invoked with several @code{file_names} and with this
7605 switch, if there are compilation errors when building an executable,
7606 @code{gnatmake} will not attempt to build the following executables.
7607 @end table
7609 @geindex -l (gnatmake)
7612 @table @asis
7614 @item @code{-l}
7616 Link only. Can be combined with @code{-b} to binding
7617 and linking. Linking will not be performed if combined with
7618 @code{-c}
7619 but not with @code{-b}.
7620 When not combined with @code{-b}
7621 all the units in the closure of the main program must have been previously
7622 compiled and must be up to date, and the main program needs to have been bound.
7623 The root unit specified by @code{file_name}
7624 may be given without extension, with the source extension or, if no GNAT
7625 Project File is specified, with the ALI file extension.
7626 @end table
7628 @geindex -m (gnatmake)
7631 @table @asis
7633 @item @code{-m}
7635 Specify that the minimum necessary amount of recompilations
7636 be performed. In this mode @code{gnatmake} ignores time
7637 stamp differences when the only
7638 modifications to a source file consist in adding/removing comments,
7639 empty lines, spaces or tabs. This means that if you have changed the
7640 comments in a source file or have simply reformatted it, using this
7641 switch will tell @code{gnatmake} not to recompile files that depend on it
7642 (provided other sources on which these files depend have undergone no
7643 semantic modifications). Note that the debugging information may be
7644 out of date with respect to the sources if the @code{-m} switch causes
7645 a compilation to be switched, so the use of this switch represents a
7646 trade-off between compilation time and accurate debugging information.
7647 @end table
7649 @geindex Dependencies
7650 @geindex producing list
7652 @geindex -M (gnatmake)
7655 @table @asis
7657 @item @code{-M}
7659 Check if all objects are up to date. If they are, output the object
7660 dependences to @code{stdout} in a form that can be directly exploited in
7661 a @code{Makefile}. By default, each source file is prefixed with its
7662 (relative or absolute) directory name. This name is whatever you
7663 specified in the various @code{-aI}
7664 and @code{-I} switches. If you use
7665 @code{gnatmake -M}  @code{-q}
7666 (see below), only the source file names,
7667 without relative paths, are output. If you just specify the  @code{-M}
7668 switch, dependencies of the GNAT internal system files are omitted. This
7669 is typically what you want. If you also specify
7670 the @code{-a} switch,
7671 dependencies of the GNAT internal files are also listed. Note that
7672 dependencies of the objects in external Ada libraries (see
7673 switch  @code{-aL`dir'} in the following list)
7674 are never reported.
7675 @end table
7677 @geindex -n (gnatmake)
7680 @table @asis
7682 @item @code{-n}
7684 Don’t compile, bind, or link. Checks if all objects are up to date.
7685 If they are not, the full name of the first file that needs to be
7686 recompiled is printed.
7687 Repeated use of this option, followed by compiling the indicated source
7688 file, will eventually result in recompiling all required units.
7689 @end table
7691 @geindex -o (gnatmake)
7694 @table @asis
7696 @item @code{-o `exec_name'}
7698 Output executable name. The name of the final executable program will be
7699 @code{exec_name}. If the @code{-o} switch is omitted the default
7700 name for the executable will be the name of the input file in appropriate form
7701 for an executable file on the host system.
7703 This switch cannot be used when invoking @code{gnatmake} with several
7704 @code{file_names}.
7705 @end table
7707 @geindex -p (gnatmake)
7710 @table @asis
7712 @item @code{-p}
7714 Same as @code{--create-missing-dirs}
7715 @end table
7717 @geindex -q (gnatmake)
7720 @table @asis
7722 @item @code{-q}
7724 Quiet. When this flag is not set, the commands carried out by
7725 @code{gnatmake} are displayed.
7726 @end table
7728 @geindex -s (gnatmake)
7731 @table @asis
7733 @item @code{-s}
7735 Recompile if compiler switches have changed since last compilation.
7736 All compiler switches but -I and -o are taken into account in the
7737 following way:
7738 orders between different ‘first letter’ switches are ignored, but
7739 orders between same switches are taken into account. For example,
7740 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O}
7741 is equivalent to @code{-O -g}.
7743 This switch is recommended when Integrated Preprocessing is used.
7744 @end table
7746 @geindex -u (gnatmake)
7749 @table @asis
7751 @item @code{-u}
7753 Unique. Recompile at most the main files. It implies -c. Combined with
7754 -f, it is equivalent to calling the compiler directly. Note that using
7755 -u with a project file and no main has a special meaning.
7756 @end table
7758 @c --Comment
7759 @c (See :ref:`Project_Files_and_Main_Subprograms`.)
7761 @geindex -U (gnatmake)
7764 @table @asis
7766 @item @code{-U}
7768 When used without a project file or with one or several mains on the command
7769 line, is equivalent to -u. When used with a project file and no main
7770 on the command line, all sources of all project files are checked and compiled
7771 if not up to date, and libraries are rebuilt, if necessary.
7772 @end table
7774 @geindex -v (gnatmake)
7777 @table @asis
7779 @item @code{-v}
7781 Verbose. Display the reason for all recompilations @code{gnatmake}
7782 decides are necessary, with the highest verbosity level.
7783 @end table
7785 @geindex -vl (gnatmake)
7788 @table @asis
7790 @item @code{-vl}
7792 Verbosity level Low. Display fewer lines than in verbosity Medium.
7793 @end table
7795 @geindex -vm (gnatmake)
7798 @table @asis
7800 @item @code{-vm}
7802 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7803 @end table
7805 @geindex -vm (gnatmake)
7808 @table @asis
7810 @item @code{-vh}
7812 Verbosity level High. Equivalent to -v.
7814 @item @code{-vP`x'}
7816 Indicate the verbosity of the parsing of GNAT project files.
7817 See @ref{d1,,Switches Related to Project Files}.
7818 @end table
7820 @geindex -x (gnatmake)
7823 @table @asis
7825 @item @code{-x}
7827 Indicate that sources that are not part of any Project File may be compiled.
7828 Normally, when using Project Files, only sources that are part of a Project
7829 File may be compile. When this switch is used, a source outside of all Project
7830 Files may be compiled. The ALI file and the object file will be put in the
7831 object directory of the main Project. The compilation switches used will only
7832 be those specified on the command line. Even when
7833 @code{-x} is used, mains specified on the
7834 command line need to be sources of a project file.
7836 @item @code{-X`name'=`value'}
7838 Indicate that external variable @code{name} has the value @code{value}.
7839 The Project Manager will use this value for occurrences of
7840 @code{external(name)} when parsing the project file.
7841 @ref{d1,,Switches Related to Project Files}.
7842 @end table
7844 @geindex -z (gnatmake)
7847 @table @asis
7849 @item @code{-z}
7851 No main subprogram. Bind and link the program even if the unit name
7852 given on the command line is a package name. The resulting executable
7853 will execute the elaboration routines of the package and its closure,
7854 then the finalization routines.
7855 @end table
7857 @subsubheading GCC switches
7860 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
7861 is passed to @code{gcc} (e.g., @code{-O}, @code{-gnato,} etc.)
7863 @subsubheading Source and library search path switches
7866 @geindex -aI (gnatmake)
7869 @table @asis
7871 @item @code{-aI`dir'}
7873 When looking for source files also look in directory @code{dir}.
7874 The order in which source files search is undertaken is
7875 described in @ref{73,,Search Paths and the Run-Time Library (RTL)}.
7876 @end table
7878 @geindex -aL (gnatmake)
7881 @table @asis
7883 @item @code{-aL`dir'}
7885 Consider @code{dir} as being an externally provided Ada library.
7886 Instructs @code{gnatmake} to skip compilation units whose @code{.ALI}
7887 files have been located in directory @code{dir}. This allows you to have
7888 missing bodies for the units in @code{dir} and to ignore out of date bodies
7889 for the same units. You still need to specify
7890 the location of the specs for these units by using the switches
7891 @code{-aI`dir'}  or @code{-I`dir'}.
7892 Note: this switch is provided for compatibility with previous versions
7893 of @code{gnatmake}. The easier method of causing standard libraries
7894 to be excluded from consideration is to write-protect the corresponding
7895 ALI files.
7896 @end table
7898 @geindex -aO (gnatmake)
7901 @table @asis
7903 @item @code{-aO`dir'}
7905 When searching for library and object files, look in directory
7906 @code{dir}. The order in which library files are searched is described in
7907 @ref{76,,Search Paths for gnatbind}.
7908 @end table
7910 @geindex Search paths
7911 @geindex for gnatmake
7913 @geindex -A (gnatmake)
7916 @table @asis
7918 @item @code{-A`dir'}
7920 Equivalent to @code{-aL`dir'} @code{-aI`dir'}.
7922 @geindex -I (gnatmake)
7924 @item @code{-I`dir'}
7926 Equivalent to @code{-aO`dir' -aI`dir'}.
7927 @end table
7929 @geindex -I- (gnatmake)
7931 @geindex Source files
7932 @geindex suppressing search
7935 @table @asis
7937 @item @code{-I-}
7939 Do not look for source files in the directory containing the source
7940 file named in the command line.
7941 Do not look for ALI or object files in the directory
7942 where @code{gnatmake} was invoked.
7943 @end table
7945 @geindex -L (gnatmake)
7947 @geindex Linker libraries
7950 @table @asis
7952 @item @code{-L`dir'}
7954 Add directory @code{dir} to the list of directories in which the linker
7955 will search for libraries. This is equivalent to
7956 @code{-largs} @code{-L`dir'}.
7957 Furthermore, under Windows, the sources pointed to by the libraries path
7958 set in the registry are not searched for.
7959 @end table
7961 @geindex -nostdinc (gnatmake)
7964 @table @asis
7966 @item @code{-nostdinc}
7968 Do not look for source files in the system default directory.
7969 @end table
7971 @geindex -nostdlib (gnatmake)
7974 @table @asis
7976 @item @code{-nostdlib}
7978 Do not look for library files in the system default directory.
7979 @end table
7981 @geindex --RTS (gnatmake)
7984 @table @asis
7986 @item @code{--RTS=`rts-path'}
7988 Specifies the default location of the run-time library. GNAT looks for the
7989 run-time
7990 in the following directories, and stops as soon as a valid run-time is found
7991 (@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
7992 @code{ada_object_path} present):
7995 @itemize *
7997 @item 
7998 `<current directory>/$rts_path'
8000 @item 
8001 `<default-search-dir>/$rts_path'
8003 @item 
8004 `<default-search-dir>/rts-$rts_path'
8006 @item 
8007 The selected path is handled like a normal RTS path.
8008 @end itemize
8009 @end table
8011 @node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
8012 @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}
8013 @subsection Mode Switches for @code{gnatmake}
8016 The mode switches (referred to as @code{mode_switches}) allow the
8017 inclusion of switches that are to be passed to the compiler itself, the
8018 binder or the linker. The effect of a mode switch is to cause all
8019 subsequent switches up to the end of the switch list, or up to the next
8020 mode switch, to be interpreted as switches to be passed on to the
8021 designated component of GNAT.
8023 @geindex -cargs (gnatmake)
8026 @table @asis
8028 @item @code{-cargs `switches'}
8030 Compiler switches. Here @code{switches} is a list of switches
8031 that are valid switches for @code{gcc}. They will be passed on to
8032 all compile steps performed by @code{gnatmake}.
8033 @end table
8035 @geindex -bargs (gnatmake)
8038 @table @asis
8040 @item @code{-bargs `switches'}
8042 Binder switches. Here @code{switches} is a list of switches
8043 that are valid switches for @code{gnatbind}. They will be passed on to
8044 all bind steps performed by @code{gnatmake}.
8045 @end table
8047 @geindex -largs (gnatmake)
8050 @table @asis
8052 @item @code{-largs `switches'}
8054 Linker switches. Here @code{switches} is a list of switches
8055 that are valid switches for @code{gnatlink}. They will be passed on to
8056 all link steps performed by @code{gnatmake}.
8057 @end table
8059 @geindex -margs (gnatmake)
8062 @table @asis
8064 @item @code{-margs `switches'}
8066 Make switches. The switches are directly interpreted by @code{gnatmake},
8067 regardless of any previous occurrence of @code{-cargs}, @code{-bargs}
8068 or @code{-largs}.
8069 @end table
8071 @node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8072 @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}
8073 @subsection Notes on the Command Line
8076 This section contains some additional useful notes on the operation
8077 of the @code{gnatmake} command.
8079 @geindex Recompilation (by gnatmake)
8082 @itemize *
8084 @item 
8085 If @code{gnatmake} finds no ALI files, it recompiles the main program
8086 and all other units required by the main program.
8087 This means that @code{gnatmake}
8088 can be used for the initial compile, as well as during subsequent steps of
8089 the development cycle.
8091 @item 
8092 If you enter @code{gnatmake foo.adb}, where @code{foo}
8093 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8094 @code{foo.adb} (because it finds no ALI) and stops, issuing a
8095 warning.
8097 @item 
8098 In @code{gnatmake} the switch @code{-I}
8099 is used to specify both source and
8100 library file paths. Use @code{-aI}
8101 instead if you just want to specify
8102 source paths only and @code{-aO}
8103 if you want to specify library paths
8104 only.
8106 @item 
8107 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8108 This may conveniently be used to exclude standard libraries from
8109 consideration and in particular it means that the use of the
8110 @code{-f} switch will not recompile these files
8111 unless @code{-a} is also specified.
8113 @item 
8114 @code{gnatmake} has been designed to make the use of Ada libraries
8115 particularly convenient. Assume you have an Ada library organized
8116 as follows: `obj-dir' contains the objects and ALI files for
8117 of your Ada compilation units,
8118 whereas `include-dir' contains the
8119 specs of these units, but no bodies. Then to compile a unit
8120 stored in @code{main.adb}, which uses this Ada library you would just type:
8122 @example
8123 $ gnatmake -aI`include-dir`  -aL`obj-dir`  main
8124 @end example
8126 @item 
8127 Using @code{gnatmake} along with the @code{-m (minimal recompilation)}
8128 switch provides a mechanism for avoiding unnecessary recompilations. Using
8129 this switch,
8130 you can update the comments/format of your
8131 source files without having to recompile everything. Note, however, that
8132 adding or deleting lines in a source files may render its debugging
8133 info obsolete. If the file in question is a spec, the impact is rather
8134 limited, as that debugging info will only be useful during the
8135 elaboration phase of your program. For bodies the impact can be more
8136 significant. In all events, your debugger will warn you if a source file
8137 is more recent than the corresponding object, and alert you to the fact
8138 that the debugging information may be out of date.
8139 @end itemize
8141 @node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8142 @anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{d6}@anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{d7}
8143 @subsection How @code{gnatmake} Works
8146 Generally @code{gnatmake} automatically performs all necessary
8147 recompilations and you don’t need to worry about how it works. However,
8148 it may be useful to have some basic understanding of the @code{gnatmake}
8149 approach and in particular to understand how it uses the results of
8150 previous compilations without incorrectly depending on them.
8152 First a definition: an object file is considered `up to date' if the
8153 corresponding ALI file exists and if all the source files listed in the
8154 dependency section of this ALI file have time stamps matching those in
8155 the ALI file. This means that neither the source file itself nor any
8156 files that it depends on have been modified, and hence there is no need
8157 to recompile this file.
8159 @code{gnatmake} works by first checking if the specified main unit is up
8160 to date. If so, no compilations are required for the main unit. If not,
8161 @code{gnatmake} compiles the main program to build a new ALI file that
8162 reflects the latest sources. Then the ALI file of the main unit is
8163 examined to find all the source files on which the main program depends,
8164 and @code{gnatmake} recursively applies the above procedure on all these
8165 files.
8167 This process ensures that @code{gnatmake} only trusts the dependencies
8168 in an existing ALI file if they are known to be correct. Otherwise it
8169 always recompiles to determine a new, guaranteed accurate set of
8170 dependencies. As a result the program is compiled ‘upside down’ from what may
8171 be more familiar as the required order of compilation in some other Ada
8172 systems. In particular, clients are compiled before the units on which
8173 they depend. The ability of GNAT to compile in any order is critical in
8174 allowing an order of compilation to be chosen that guarantees that
8175 @code{gnatmake} will recompute a correct set of new dependencies if
8176 necessary.
8178 When invoking @code{gnatmake} with several @code{file_names}, if a unit is
8179 imported by several of the executables, it will be recompiled at most once.
8181 Note: when using non-standard naming conventions
8182 (@ref{1c,,Using Other File Names}), changing through a configuration pragmas
8183 file the version of a source and invoking @code{gnatmake} to recompile may
8184 have no effect, if the previous version of the source is still accessible
8185 by @code{gnatmake}. It may be necessary to use the switch
8188 @node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8189 @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}
8190 @subsection Examples of @code{gnatmake} Usage
8194 @table @asis
8196 @item @code{gnatmake hello.adb}
8198 Compile all files necessary to bind and link the main program
8199 @code{hello.adb} (containing unit @code{Hello}) and bind and link the
8200 resulting object files to generate an executable file @code{hello}.
8202 @item @code{gnatmake main1 main2 main3}
8204 Compile all files necessary to bind and link the main programs
8205 @code{main1.adb} (containing unit @code{Main1}), @code{main2.adb}
8206 (containing unit @code{Main2}) and @code{main3.adb}
8207 (containing unit @code{Main3}) and bind and link the resulting object files
8208 to generate three executable files @code{main1},
8209 @code{main2}  and @code{main3}.
8211 @item @code{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8213 Compile all files necessary to bind and link the main program unit
8214 @code{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8215 be done with optimization level 2 and the order of elaboration will be
8216 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8217 displaying commands it is executing.
8218 @end table
8220 @node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8221 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{c9}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{da}
8222 @section Compiling with @code{gcc}
8225 This section discusses how to compile Ada programs using the @code{gcc}
8226 command. It also describes the set of switches
8227 that can be used to control the behavior of the compiler.
8229 @menu
8230 * Compiling Programs:: 
8231 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
8232 * Order of Compilation Issues:: 
8233 * Examples:: 
8235 @end menu
8237 @node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8238 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{db}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{dc}
8239 @subsection Compiling Programs
8242 The first step in creating an executable program is to compile the units
8243 of the program using the @code{gcc} command. You must compile the
8244 following files:
8247 @itemize *
8249 @item 
8250 the body file (@code{.adb}) for a library level subprogram or generic
8251 subprogram
8253 @item 
8254 the spec file (@code{.ads}) for a library level package or generic
8255 package that has no body
8257 @item 
8258 the body file (@code{.adb}) for a library level package
8259 or generic package that has a body
8260 @end itemize
8262 You need `not' compile the following files
8265 @itemize *
8267 @item 
8268 the spec of a library unit which has a body
8270 @item 
8271 subunits
8272 @end itemize
8274 because they are compiled as part of compiling related units. GNAT compiles
8275 package specs
8276 when the corresponding body is compiled, and subunits when the parent is
8277 compiled.
8279 @geindex cannot generate code
8281 If you attempt to compile any of these files, you will get one of the
8282 following error messages (where @code{fff} is the name of the file you
8283 compiled):
8285 @quotation
8287 @example
8288 cannot generate code for file `@w{`}fff`@w{`} (package spec)
8289 to check package spec, use -gnatc
8291 cannot generate code for file `@w{`}fff`@w{`} (missing subunits)
8292 to check parent unit, use -gnatc
8294 cannot generate code for file `@w{`}fff`@w{`} (subprogram spec)
8295 to check subprogram spec, use -gnatc
8297 cannot generate code for file `@w{`}fff`@w{`} (subunit)
8298 to check subunit, use -gnatc
8299 @end example
8300 @end quotation
8302 As indicated by the above error messages, if you want to submit
8303 one of these files to the compiler to check for correct semantics
8304 without generating code, then use the @code{-gnatc} switch.
8306 The basic command for compiling a file containing an Ada unit is:
8308 @example
8309 $ gcc -c [switches] <file name>
8310 @end example
8312 where @code{file name} is the name of the Ada file (usually
8313 having an extension @code{.ads} for a spec or @code{.adb} for a body).
8314 You specify the
8315 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
8316 The result of a successful compilation is an object file, which has the
8317 same name as the source file but an extension of @code{.o} and an Ada
8318 Library Information (ALI) file, which also has the same name as the
8319 source file, but with @code{.ali} as the extension. GNAT creates these
8320 two output files in the current directory, but you may specify a source
8321 file in any directory using an absolute or relative path specification
8322 containing the directory information.
8324 @geindex gnat1
8326 @code{gcc} is actually a driver program that looks at the extensions of
8327 the file arguments and loads the appropriate compiler. For example, the
8328 GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8329 These programs are in directories known to the driver program (in some
8330 configurations via environment variables you set), but need not be in
8331 your path. The @code{gcc} driver also calls the assembler and any other
8332 utilities needed to complete the generation of the required object
8333 files.
8335 It is possible to supply several file names on the same @code{gcc}
8336 command. This causes @code{gcc} to call the appropriate compiler for
8337 each file. For example, the following command lists two separate
8338 files to be compiled:
8340 @example
8341 $ gcc -c x.adb y.adb
8342 @end example
8344 calls @code{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8345 @code{y.adb}.
8346 The compiler generates two object files @code{x.o} and @code{y.o}
8347 and the two ALI files @code{x.ali} and @code{y.ali}.
8349 Any switches apply to all the files listed, see @ref{dd,,Compiler Switches} for a
8350 list of available @code{gcc} switches.
8352 @node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8353 @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}
8354 @subsection Search Paths and the Run-Time Library (RTL)
8357 With the GNAT source-based library system, the compiler must be able to
8358 find source files for units that are needed by the unit being compiled.
8359 Search paths are used to guide this process.
8361 The compiler compiles one source file whose name must be given
8362 explicitly on the command line. In other words, no searching is done
8363 for this file. To find all other source files that are needed (the most
8364 common being the specs of units), the compiler examines the following
8365 directories, in the following order:
8368 @itemize *
8370 @item 
8371 The directory containing the source file of the main unit being compiled
8372 (the file name on the command line).
8374 @item 
8375 Each directory named by an @code{-I} switch given on the @code{gcc}
8376 command line, in the order given.
8378 @geindex ADA_PRJ_INCLUDE_FILE
8380 @item 
8381 Each of the directories listed in the text file whose name is given
8382 by the 
8383 @geindex ADA_PRJ_INCLUDE_FILE
8384 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8385 @code{ADA_PRJ_INCLUDE_FILE} environment variable.
8386 @geindex ADA_PRJ_INCLUDE_FILE
8387 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8388 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8389 driver when project files are used. It should not normally be set
8390 by other means.
8392 @geindex ADA_INCLUDE_PATH
8394 @item 
8395 Each of the directories listed in the value of the
8396 @geindex ADA_INCLUDE_PATH
8397 @geindex environment variable; ADA_INCLUDE_PATH
8398 @code{ADA_INCLUDE_PATH} environment variable.
8399 Construct this value
8400 exactly as the 
8401 @geindex PATH
8402 @geindex environment variable; PATH
8403 @code{PATH} environment variable: a list of directory
8404 names separated by colons (semicolons when working with the NT version).
8406 @item 
8407 The content of the @code{ada_source_path} file which is part of the GNAT
8408 installation tree and is used to store standard libraries such as the
8409 GNAT Run Time Library (RTL) source files.
8410 See also @ref{72,,Installing a library}.
8411 @end itemize
8413 Specifying the switch @code{-I-}
8414 inhibits the use of the directory
8415 containing the source file named in the command line. You can still
8416 have this directory on your search path, but in this case it must be
8417 explicitly requested with a @code{-I} switch.
8419 Specifying the switch @code{-nostdinc}
8420 inhibits the search of the default location for the GNAT Run Time
8421 Library (RTL) source files.
8423 The compiler outputs its object files and ALI files in the current
8424 working directory.
8425 Caution: The object file can be redirected with the @code{-o} switch;
8426 however, @code{gcc} and @code{gnat1} have not been coordinated on this
8427 so the @code{ALI} file will not go to the right place. Therefore, you should
8428 avoid using the @code{-o} switch.
8430 @geindex System.IO
8432 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8433 children make up the GNAT RTL, together with the simple @code{System.IO}
8434 package used in the @code{"Hello World"} example. The sources for these units
8435 are needed by the compiler and are kept together in one directory. Not
8436 all of the bodies are needed, but all of the sources are kept together
8437 anyway. In a normal installation, you need not specify these directory
8438 names when compiling or binding. Either the environment variables or
8439 the built-in defaults cause these files to be found.
8441 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8442 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8443 consisting of child units of @code{GNAT}. This is a collection of generally
8444 useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8445 for further details.
8447 Besides simplifying access to the RTL, a major use of search paths is
8448 in compiling sources from multiple directories. This can make
8449 development environments much more flexible.
8451 @node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8452 @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}
8453 @subsection Order of Compilation Issues
8456 If, in our earlier example, there was a spec for the @code{hello}
8457 procedure, it would be contained in the file @code{hello.ads}; yet this
8458 file would not have to be explicitly compiled. This is the result of the
8459 model we chose to implement library management. Some of the consequences
8460 of this model are as follows:
8463 @itemize *
8465 @item 
8466 There is no point in compiling specs (except for package
8467 specs with no bodies) because these are compiled as needed by clients. If
8468 you attempt a useless compilation, you will receive an error message.
8469 It is also useless to compile subunits because they are compiled as needed
8470 by the parent.
8472 @item 
8473 There are no order of compilation requirements: performing a
8474 compilation never obsoletes anything. The only way you can obsolete
8475 something and require recompilations is to modify one of the
8476 source files on which it depends.
8478 @item 
8479 There is no library as such, apart from the ALI files
8480 (@ref{28,,The Ada Library Information Files}, for information on the format
8481 of these files). For now we find it convenient to create separate ALI files,
8482 but eventually the information therein may be incorporated into the object
8483 file directly.
8485 @item 
8486 When you compile a unit, the source files for the specs of all units
8487 that it `with's, all its subunits, and the bodies of any generics it
8488 instantiates must be available (reachable by the search-paths mechanism
8489 described above), or you will receive a fatal error message.
8490 @end itemize
8492 @node Examples,,Order of Compilation Issues,Compiling with gcc
8493 @anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{e1}@anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{e2}
8494 @subsection Examples
8497 The following are some typical Ada compilation command line examples:
8499 @example
8500 $ gcc -c xyz.adb
8501 @end example
8503 Compile body in file @code{xyz.adb} with all default options.
8505 @example
8506 $ gcc -c -O2 -gnata xyz-def.adb
8507 @end example
8509 Compile the child unit package in file @code{xyz-def.adb} with extensive
8510 optimizations, and pragma @code{Assert}/@code{Debug} statements
8511 enabled.
8513 @example
8514 $ gcc -c -gnatc abc-def.adb
8515 @end example
8517 Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8518 mode.
8520 @node Compiler Switches,Linker Switches,Compiling with gcc,Building Executable Programs with GNAT
8521 @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}
8522 @section Compiler Switches
8525 The @code{gcc} command accepts switches that control the
8526 compilation process. These switches are fully described in this section:
8527 first an alphabetical listing of all switches with a brief description,
8528 and then functionally grouped sets of switches with more detailed
8529 information.
8531 More switches exist for GCC than those documented here, especially
8532 for specific targets. However, their use is not recommended as
8533 they may change code generation in ways that are incompatible with
8534 the Ada run-time library, or can cause inconsistencies between
8535 compilation units.
8537 @menu
8538 * Alphabetical List of All Switches:: 
8539 * Output and Error Message Control:: 
8540 * Warning Message Control:: 
8541 * Info message Control:: 
8542 * Debugging and Assertion Control:: 
8543 * Validity Checking:: 
8544 * Style Checking:: 
8545 * Run-Time Checks:: 
8546 * Using gcc for Syntax Checking:: 
8547 * Using gcc for Semantic Checking:: 
8548 * Compiling Different Versions of Ada:: 
8549 * Character Set Control:: 
8550 * File Naming Control:: 
8551 * Subprogram Inlining Control:: 
8552 * Auxiliary Output Control:: 
8553 * Debugging Control:: 
8554 * Exception Handling Control:: 
8555 * Units to Sources Mapping Files:: 
8556 * Code Generation Control:: 
8558 @end menu
8560 @node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8561 @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}
8562 @subsection Alphabetical List of All Switches
8565 @geindex -b (gcc)
8568 @table @asis
8570 @item @code{-b `target'}
8572 Compile your program to run on @code{target}, which is the name of a
8573 system configuration. You must have a GNAT cross-compiler built if
8574 @code{target} is not the same as your host system.
8575 @end table
8577 @geindex -B (gcc)
8580 @table @asis
8582 @item @code{-B`dir'}
8584 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8585 from @code{dir} instead of the default location. Only use this switch
8586 when multiple versions of the GNAT compiler are available.
8587 See the “Options for Directory Search” section in the
8588 @cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8589 You would normally use the @code{-b} or @code{-V} switch instead.
8590 @end table
8592 @geindex -c (gcc)
8595 @table @asis
8597 @item @code{-c}
8599 Compile. Always use this switch when compiling Ada programs.
8601 Note: for some other languages when using @code{gcc}, notably in
8602 the case of C and C++, it is possible to use
8603 use @code{gcc} without a @code{-c} switch to
8604 compile and link in one step. In the case of GNAT, you
8605 cannot use this approach, because the binder must be run
8606 and @code{gcc} cannot be used to run the GNAT binder.
8607 @end table
8609 @geindex -fcallgraph-info (gcc)
8612 @table @asis
8614 @item @code{-fcallgraph-info[=su,da]}
8616 Makes the compiler output callgraph information for the program, on a
8617 per-file basis. The information is generated in the VCG format.  It can
8618 be decorated with additional, per-node and/or per-edge information, if a
8619 list of comma-separated markers is additionally specified. When the
8620 @code{su} marker is specified, the callgraph is decorated with stack usage
8621 information; it is equivalent to @code{-fstack-usage}. When the @code{da}
8622 marker is specified, the callgraph is decorated with information about
8623 dynamically allocated objects.
8624 @end table
8626 @geindex -fdiagnostics-format (gcc)
8629 @table @asis
8631 @item @code{-fdiagnostics-format=json}
8633 Makes GNAT emit warning and error messages as JSON. Inhibits printing of
8634 text warning and errors messages except if @code{-gnatv} or
8635 @code{-gnatl} are present. Uses absolute file paths when used along
8636 @code{-gnatef}.
8637 @end table
8639 @geindex -fdump-scos (gcc)
8642 @table @asis
8644 @item @code{-fdump-scos}
8646 Generates SCO (Source Coverage Obligation) information in the ALI file.
8647 This information is used by advanced coverage tools. See unit @code{SCOs}
8648 in the compiler sources for details in files @code{scos.ads} and
8649 @code{scos.adb}.
8650 @end table
8652 @geindex -fgnat-encodings (gcc)
8655 @table @asis
8657 @item @code{-fgnat-encodings=[all|gdb|minimal]}
8659 This switch controls the balance between GNAT encodings and standard DWARF
8660 emitted in the debug information.
8661 @end table
8663 @geindex -flto (gcc)
8666 @table @asis
8668 @item @code{-flto[=`n']}
8670 Enables Link Time Optimization. This switch must be used in conjunction
8671 with the @code{-Ox} switches (but not with the @code{-gnatn} switch
8672 since it is a full replacement for the latter) and instructs the compiler
8673 to defer most optimizations until the link stage. The advantage of this
8674 approach is that the compiler can do a whole-program analysis and choose
8675 the best interprocedural optimization strategy based on a complete view
8676 of the program, instead of a fragmentary view with the usual approach.
8677 This can also speed up the compilation of big programs and reduce the
8678 size of the executable, compared with a traditional per-unit compilation
8679 with inlining across units enabled by the @code{-gnatn} switch.
8680 The drawback of this approach is that it may require more memory and that
8681 the debugging information generated by @code{-g} with it might be hardly usable.
8682 The switch, as well as the accompanying @code{-Ox} switches, must be
8683 specified both for the compilation and the link phases.
8684 If the @code{n} parameter is specified, the optimization and final code
8685 generation at link time are executed using @code{n} parallel jobs by
8686 means of an installed @code{make} program.
8687 @end table
8689 @geindex -fno-inline (gcc)
8692 @table @asis
8694 @item @code{-fno-inline}
8696 Suppresses all inlining, unless requested with pragma @code{Inline_Always}. The
8697 effect is enforced regardless of other optimization or inlining switches.
8698 Note that inlining can also be suppressed on a finer-grained basis with
8699 pragma @code{No_Inline}.
8700 @end table
8702 @geindex -fno-inline-functions (gcc)
8705 @table @asis
8707 @item @code{-fno-inline-functions}
8709 Suppresses automatic inlining of subprograms, which is enabled
8710 if @code{-O3} is used.
8711 @end table
8713 @geindex -fno-inline-small-functions (gcc)
8716 @table @asis
8718 @item @code{-fno-inline-small-functions}
8720 Suppresses automatic inlining of small subprograms, which is enabled
8721 if @code{-O2} is used.
8722 @end table
8724 @geindex -fno-inline-functions-called-once (gcc)
8727 @table @asis
8729 @item @code{-fno-inline-functions-called-once}
8731 Suppresses inlining of subprograms local to the unit and called once
8732 from within it, which is enabled if @code{-O1} is used.
8733 @end table
8735 @geindex -fno-ivopts (gcc)
8738 @table @asis
8740 @item @code{-fno-ivopts}
8742 Suppresses high-level loop induction variable optimizations, which are
8743 enabled if @code{-O1} is used. These optimizations are generally
8744 profitable but, for some specific cases of loops with numerous uses
8745 of the iteration variable that follow a common pattern, they may end
8746 up destroying the regularity that could be exploited at a lower level
8747 and thus producing inferior code.
8748 @end table
8750 @geindex -fno-strict-aliasing (gcc)
8753 @table @asis
8755 @item @code{-fno-strict-aliasing}
8757 Causes the compiler to avoid assumptions regarding non-aliasing
8758 of objects of different types. See
8759 @ref{e6,,Optimization and Strict Aliasing} for details.
8760 @end table
8762 @geindex -fno-strict-overflow (gcc)
8765 @table @asis
8767 @item @code{-fno-strict-overflow}
8769 Causes the compiler to avoid assumptions regarding the rules of signed
8770 integer overflow. These rules specify that signed integer overflow will
8771 result in a Constraint_Error exception at run time and are enforced in
8772 default mode by the compiler, so this switch should not be necessary in
8773 normal operating mode. It might be useful in conjunction with @code{-gnato0}
8774 for very peculiar cases of low-level programming.
8775 @end table
8777 @geindex -fstack-check (gcc)
8780 @table @asis
8782 @item @code{-fstack-check}
8784 Activates stack checking.
8785 See @ref{e7,,Stack Overflow Checking} for details.
8786 @end table
8788 @geindex -fstack-usage (gcc)
8791 @table @asis
8793 @item @code{-fstack-usage}
8795 Makes the compiler output stack usage information for the program, on a
8796 per-subprogram basis. See @ref{e8,,Static Stack Usage Analysis} for details.
8797 @end table
8799 @geindex -g (gcc)
8802 @table @asis
8804 @item @code{-g}
8806 Generate debugging information. This information is stored in the object
8807 file and copied from there to the final executable file by the linker,
8808 where it can be read by the debugger. You must use the
8809 @code{-g} switch if you plan on using the debugger.
8810 @end table
8812 @geindex -gnat05 (gcc)
8815 @table @asis
8817 @item @code{-gnat05}
8819 Allow full Ada 2005 features.
8820 @end table
8822 @geindex -gnat12 (gcc)
8825 @table @asis
8827 @item @code{-gnat12}
8829 Allow full Ada 2012 features.
8830 @end table
8832 @geindex -gnat83 (gcc)
8834 @geindex -gnat2005 (gcc)
8837 @table @asis
8839 @item @code{-gnat2005}
8841 Allow full Ada 2005 features (same as @code{-gnat05})
8842 @end table
8844 @geindex -gnat2012 (gcc)
8847 @table @asis
8849 @item @code{-gnat2012}
8851 Allow full Ada 2012 features (same as @code{-gnat12})
8852 @end table
8854 @geindex -gnat2022 (gcc)
8857 @table @asis
8859 @item @code{-gnat2022}
8861 Allow full Ada 2022 features
8863 @item @code{-gnat83}
8865 Enforce Ada 83 restrictions.
8866 @end table
8868 @geindex -gnat95 (gcc)
8871 @table @asis
8873 @item @code{-gnat95}
8875 Enforce Ada 95 restrictions.
8877 Note: for compatibility with some Ada 95 compilers which support only
8878 the @code{overriding} keyword of Ada 2005, the @code{-gnatd.D} switch can
8879 be used along with @code{-gnat95} to achieve a similar effect with GNAT.
8881 @code{-gnatd.D} instructs GNAT to consider @code{overriding} as a keyword
8882 and handle its associated semantic checks, even in Ada 95 mode.
8883 @end table
8885 @geindex -gnata (gcc)
8888 @table @asis
8890 @item @code{-gnata}
8892 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
8893 activated. Note that these pragmas can also be controlled using the
8894 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
8895 It also activates pragmas @code{Check}, @code{Precondition}, and
8896 @code{Postcondition}. Note that these pragmas can also be controlled
8897 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
8898 also activates all assertions defined in the RM as aspects: preconditions,
8899 postconditions, type invariants and (sub)type predicates. In all Ada modes,
8900 corresponding pragmas for type invariants and (sub)type predicates are
8901 also activated. The default is that all these assertions are disabled,
8902 and have no effect, other than being checked for syntactic validity, and
8903 in the case of subtype predicates, constructions such as membership tests
8904 still test predicates even if assertions are turned off.
8905 @end table
8907 @geindex -gnatA (gcc)
8910 @table @asis
8912 @item @code{-gnatA}
8914 Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
8915 it will be ignored.
8916 @end table
8918 @geindex -gnatb (gcc)
8921 @table @asis
8923 @item @code{-gnatb}
8925 Generate brief messages to @code{stderr} even if verbose mode set.
8926 @end table
8928 @geindex -gnatB (gcc)
8931 @table @asis
8933 @item @code{-gnatB}
8935 Assume no invalid (bad) values except for ‘Valid attribute use
8936 (@ref{e9,,Validity Checking}).
8937 @end table
8939 @geindex -gnatc (gcc)
8942 @table @asis
8944 @item @code{-gnatc}
8946 Check syntax and semantics only (no code generation attempted). When the
8947 compiler is invoked by @code{gnatmake}, if the switch @code{-gnatc} is
8948 only given to the compiler (after @code{-cargs} or in package Compiler of
8949 the project file), @code{gnatmake} will fail because it will not find the
8950 object file after compilation. If @code{gnatmake} is called with
8951 @code{-gnatc} as a builder switch (before @code{-cargs} or in package
8952 Builder of the project file) then @code{gnatmake} will not fail because
8953 it will not look for the object files after compilation, and it will not try
8954 to build and link.
8955 @end table
8957 @geindex -gnatC (gcc)
8960 @table @asis
8962 @item @code{-gnatC}
8964 Generate CodePeer intermediate format (no code generation attempted).
8965 This switch will generate an intermediate representation suitable for
8966 use by CodePeer (@code{.scil} files). This switch is not compatible with
8967 code generation (it will, among other things, disable some switches such
8968 as @code{-gnatn}, and enable others such as @code{-gnata}).
8969 @end table
8971 @geindex -gnatd (gcc)
8974 @table @asis
8976 @item @code{-gnatd}
8978 Specify debug options for the compiler. The string of characters after
8979 the @code{-gnatd} specifies the specific debug options. The possible
8980 characters are 0-9, a-z, A-Z, optionally preceded by a dot or underscore.
8981 See compiler source file @code{debug.adb} for details of the implemented
8982 debug options. Certain debug options are relevant to application
8983 programmers, and these are documented at appropriate points in this
8984 user’s guide.
8985 @end table
8987 @geindex -gnatD[nn] (gcc)
8990 @table @asis
8992 @item @code{-gnatD}
8994 Create expanded source files for source level debugging. This switch
8995 also suppresses generation of cross-reference information
8996 (see @code{-gnatx}). Note that this switch is not allowed if a previous
8997 @code{-gnatR} switch has been given, since these two switches are not compatible.
8998 @end table
9000 @geindex -gnateA (gcc)
9003 @table @asis
9005 @item @code{-gnateA}
9007 Check that the actual parameters of a subprogram call are not aliases of one
9008 another. To qualify as aliasing, their memory locations must be identical or
9009 overlapping, at least one of the corresponding formal parameters must be of
9010 mode OUT or IN OUT, and at least one of the corresponding formal parameters
9011 must have its parameter passing mechanism not specified.
9013 @example
9014 type Rec_Typ is record
9015    Data : Integer := 0;
9016 end record;
9018 function Self (Val : Rec_Typ) return Rec_Typ is
9019 begin
9020    return Val;
9021 end Self;
9023 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
9024 begin
9025    null;
9026 end Detect_Aliasing;
9028 Obj : Rec_Typ;
9030 Detect_Aliasing (Obj, Obj);
9031 Detect_Aliasing (Obj, Self (Obj));
9032 @end example
9034 In the example above, the first call to @code{Detect_Aliasing} fails with a
9035 @code{Program_Error} at run time because the actuals for @code{Val_1} and
9036 @code{Val_2} denote the same object. The second call executes without raising
9037 an exception because @code{Self(Obj)} produces an anonymous object which does
9038 not share the memory location of @code{Obj}.
9039 @end table
9041 @geindex -gnateb (gcc)
9044 @table @asis
9046 @item @code{-gnateb}
9048 Store configuration files by their basename in ALI files. This switch is
9049 used for instance by gprbuild for distributed builds in order to prevent
9050 issues where machine-specific absolute paths could end up being stored in
9051 ALI files.
9052 @end table
9054 @geindex -gnatec (gcc)
9057 @table @asis
9059 @item @code{-gnatec=`path'}
9061 Specify a configuration pragma file
9062 (the equal sign is optional)
9063 (@ref{63,,The Configuration Pragmas Files}).
9064 @end table
9066 @geindex -gnateC (gcc)
9069 @table @asis
9071 @item @code{-gnateC}
9073 Generate CodePeer messages in a compiler-like format. This switch is only
9074 effective if @code{-gnatcC} is also specified and requires an installation
9075 of CodePeer.
9076 @end table
9078 @geindex -gnated (gcc)
9081 @table @asis
9083 @item @code{-gnated}
9085 Disable atomic synchronization
9086 @end table
9088 @geindex -gnateD (gcc)
9091 @table @asis
9093 @item @code{-gnateDsymbol[=`value']}
9095 Defines a symbol, associated with @code{value}, for preprocessing.
9096 (@ref{91,,Integrated Preprocessing}).
9097 @end table
9099 @geindex -gnateE (gcc)
9102 @table @asis
9104 @item @code{-gnateE}
9106 Generate extra information in exception messages. In particular, display
9107 extra column information and the value and range associated with index and
9108 range check failures, and extra column information for access checks.
9109 In cases where the compiler is able to determine at compile time that
9110 a check will fail, it gives a warning, and the extra information is not
9111 produced at run time.
9112 @end table
9114 @geindex -gnatef (gcc)
9117 @table @asis
9119 @item @code{-gnatef}
9121 Display full source path name in brief error messages and absolute paths in
9122 @code{-fdiagnostics-format=json}’s output.
9123 @end table
9125 @geindex -gnateF (gcc)
9128 @table @asis
9130 @item @code{-gnateF}
9132 Check for overflow on all floating-point operations, including those
9133 for unconstrained predefined types. See description of pragma
9134 @code{Check_Float_Overflow} in GNAT RM.
9135 @end table
9137 @geindex -gnateg (gcc)
9139 @code{-gnateg}
9140 @code{-gnatceg}
9142 @quotation
9144 The @code{-gnatc} switch must always be specified before this switch, e.g.
9145 @code{-gnatceg}. Generate a C header from the Ada input file. See
9146 @ref{b9,,Generating C Headers for Ada Specifications} for more
9147 information.
9148 @end quotation
9150 @geindex -gnateG (gcc)
9153 @table @asis
9155 @item @code{-gnateG}
9157 Save result of preprocessing in a text file.
9158 @end table
9160 @geindex -gnateH (gcc)
9163 @table @asis
9165 @item @code{-gnateH}
9167 Set the threshold from which the RM 13.5.1(13.3/2) clause applies to 64.
9168 This is useful only on 64-bit plaforms where this threshold is 128, but
9169 used to be 64 in earlier versions of the compiler.
9170 @end table
9172 @geindex -gnatei (gcc)
9175 @table @asis
9177 @item @code{-gnatei`nnn'}
9179 Set maximum number of instantiations during compilation of a single unit to
9180 @code{nnn}. This may be useful in increasing the default maximum of 8000 for
9181 the rare case when a single unit legitimately exceeds this limit.
9182 @end table
9184 @geindex -gnateI (gcc)
9187 @table @asis
9189 @item @code{-gnateI`nnn'}
9191 Indicates that the source is a multi-unit source and that the index of the
9192 unit to compile is @code{nnn}. @code{nnn} needs to be a positive number and need
9193 to be a valid index in the multi-unit source.
9194 @end table
9196 @geindex -gnatel (gcc)
9199 @table @asis
9201 @item @code{-gnatel}
9203 This switch can be used with the static elaboration model to issue info
9204 messages showing
9205 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
9206 are generated. This is useful in diagnosing elaboration circularities
9207 caused by these implicit pragmas when using the static elaboration
9208 model. See the section in this guide on elaboration checking for
9209 further details. These messages are not generated by default, and are
9210 intended only for temporary use when debugging circularity problems.
9211 @end table
9213 @geindex -gnatel (gcc)
9216 @table @asis
9218 @item @code{-gnateL}
9220 This switch turns off the info messages about implicit elaboration pragmas.
9221 @end table
9223 @geindex -gnatem (gcc)
9226 @table @asis
9228 @item @code{-gnatem=`path'}
9230 Specify a mapping file
9231 (the equal sign is optional)
9232 (@ref{ea,,Units to Sources Mapping Files}).
9233 @end table
9235 @geindex -gnatep (gcc)
9238 @table @asis
9240 @item @code{-gnatep=`file'}
9242 Specify a preprocessing data file
9243 (the equal sign is optional)
9244 (@ref{91,,Integrated Preprocessing}).
9245 @end table
9247 @geindex -gnateP (gcc)
9250 @table @asis
9252 @item @code{-gnateP}
9254 Turn categorization dependency errors into warnings.
9255 Ada requires that units that WITH one another have compatible categories, for
9256 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9257 these errors become warnings (which can be ignored, or suppressed in the usual
9258 manner). This can be useful in some specialized circumstances such as the
9259 temporary use of special test software.
9260 @end table
9262 @geindex -gnateS (gcc)
9265 @table @asis
9267 @item @code{-gnateS}
9269 Synonym of @code{-fdump-scos}, kept for backwards compatibility.
9270 @end table
9272 @geindex -gnatet=file (gcc)
9275 @table @asis
9277 @item @code{-gnatet=`path'}
9279 Generate target dependent information. The format of the output file is
9280 described in the section about switch @code{-gnateT}.
9281 @end table
9283 @geindex -gnateT (gcc)
9286 @table @asis
9288 @item @code{-gnateT=`path'}
9290 Read target dependent information, such as endianness or sizes and alignments
9291 of base type. If this switch is passed, the default target dependent
9292 information of the compiler is replaced by the one read from the input file.
9293 This is used by tools other than the compiler, e.g. to do
9294 semantic analysis of programs that will run on some other target than
9295 the machine on which the tool is run.
9297 The following target dependent values should be defined,
9298 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
9299 positive integer value, and fields marked with a question mark are
9300 boolean fields, where a value of 0 is False, and a value of 1 is True:
9302 @example
9303 Bits_BE                    : Nat; -- Bits stored big-endian?
9304 Bits_Per_Unit              : Pos; -- Bits in a storage unit
9305 Bits_Per_Word              : Pos; -- Bits in a word
9306 Bytes_BE                   : Nat; -- Bytes stored big-endian?
9307 Char_Size                  : Pos; -- Standard.Character'Size
9308 Double_Float_Alignment     : Nat; -- Alignment of double float
9309 Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
9310 Double_Size                : Pos; -- Standard.Long_Float'Size
9311 Float_Size                 : Pos; -- Standard.Float'Size
9312 Float_Words_BE             : Nat; -- Float words stored big-endian?
9313 Int_Size                   : Pos; -- Standard.Integer'Size
9314 Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
9315 Long_Long_Long_Size        : Pos; -- Standard.Long_Long_Long_Integer'Size
9316 Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
9317 Long_Size                  : Pos; -- Standard.Long_Integer'Size
9318 Maximum_Alignment          : Pos; -- Maximum permitted alignment
9319 Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
9320 Pointer_Size               : Pos; -- System.Address'Size
9321 Short_Enums                : Nat; -- Foreign enums use short size?
9322 Short_Size                 : Pos; -- Standard.Short_Integer'Size
9323 Strict_Alignment           : Nat; -- Strict alignment?
9324 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9325 Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
9326 Words_BE                   : Nat; -- Words stored big-endian?
9327 @end example
9329 @code{Bits_Per_Unit} is the number of bits in a storage unit, the equivalent of
9330 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.}
9332 @code{Bits_Per_Word} is the number of bits in a machine word, the equivalent of
9333 GCC macro @code{BITS_PER_WORD} documented as follows: @cite{Number of bits in a word; normally 32.}
9335 @code{Double_Float_Alignment}, if not zero, is the maximum alignment that the
9336 compiler can choose by default for a 64-bit floating-point type or object.
9338 @code{Double_Scalar_Alignment}, if not zero, is the maximum alignment that the
9339 compiler can choose by default for a 64-bit or larger scalar type or object.
9341 @code{Maximum_Alignment} is the maximum alignment that the compiler can choose
9342 by default for a type or object, which is also the maximum alignment that can
9343 be specified in GNAT. It is computed for GCC backends as @code{BIGGEST_ALIGNMENT
9344 / BITS_PER_UNIT} where GCC macro @code{BIGGEST_ALIGNMENT} is documented as
9345 follows: @cite{Biggest alignment that any data type can require on this machine@comma{} in bits.}
9347 @code{Max_Unaligned_Field} is the maximum size for unaligned bit field, which is
9348 64 for the majority of GCC targets (but can be different on some targets).
9350 @code{Strict_Alignment} is the equivalent of GCC macro @code{STRICT_ALIGNMENT}
9351 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.}
9353 @code{System_Allocator_Alignment} is the guaranteed alignment of data returned
9354 by calls to @code{malloc}.
9356 The format of the input file is as follows. First come the values of
9357 the variables defined above, with one line per value:
9359 @example
9360 name  value
9361 @end example
9363 where @code{name} is the name of the parameter, spelled out in full,
9364 and cased as in the above list, and @code{value} is an unsigned decimal
9365 integer. Two or more blanks separates the name from the value.
9367 All the variables must be present, in alphabetical order (i.e. the
9368 same order as the list above).
9370 Then there is a blank line to separate the two parts of the file. Then
9371 come the lines showing the floating-point types to be registered, with
9372 one line per registered mode:
9374 @example
9375 name  digs float_rep size alignment
9376 @end example
9378 where @code{name} is the string name of the type (which can have
9379 single spaces embedded in the name, e.g. long double), @code{digs} is
9380 the number of digits for the floating-point type, @code{float_rep} is
9381 the float representation (I for IEEE-754-Binary, which is
9382 the only one supported at this time),
9383 @code{size} is the size in bits, @code{alignment} is the
9384 alignment in bits. The name is followed by at least two blanks, fields
9385 are separated by at least one blank, and a LF character immediately
9386 follows the alignment field.
9388 Here is an example of a target parameterization file:
9390 @example
9391 Bits_BE                       0
9392 Bits_Per_Unit                 8
9393 Bits_Per_Word                64
9394 Bytes_BE                      0
9395 Char_Size                     8
9396 Double_Float_Alignment        0
9397 Double_Scalar_Alignment       0
9398 Double_Size                  64
9399 Float_Size                   32
9400 Float_Words_BE                0
9401 Int_Size                     64
9402 Long_Double_Size            128
9403 Long_Long_Long_Size         128
9404 Long_Long_Size               64
9405 Long_Size                    64
9406 Maximum_Alignment            16
9407 Max_Unaligned_Field          64
9408 Pointer_Size                 64
9409 Short_Size                   16
9410 Strict_Alignment              0
9411 System_Allocator_Alignment   16
9412 Wchar_T_Size                 32
9413 Words_BE                      0
9415 float         15  I  64  64
9416 double        15  I  64  64
9417 long double   18  I  80 128
9418 TF            33  I 128 128
9419 @end example
9420 @end table
9422 @geindex -gnateu (gcc)
9425 @table @asis
9427 @item @code{-gnateu}
9429 Ignore unrecognized validity, warning, and style switches that
9430 appear after this switch is given. This may be useful when
9431 compiling sources developed on a later version of the compiler
9432 with an earlier version. Of course the earlier version must
9433 support this switch.
9434 @end table
9436 @geindex -gnateV (gcc)
9439 @table @asis
9441 @item @code{-gnateV}
9443 Check that all actual parameters of a subprogram call are valid according to
9444 the rules of validity checking (@ref{e9,,Validity Checking}).
9445 @end table
9447 @geindex -gnateY (gcc)
9450 @table @asis
9452 @item @code{-gnateY}
9454 Ignore all STYLE_CHECKS pragmas. Full legality checks
9455 are still carried out, but the pragmas have no effect
9456 on what style checks are active. This allows all style
9457 checking options to be controlled from the command line.
9458 @end table
9460 @geindex -gnatE (gcc)
9463 @table @asis
9465 @item @code{-gnatE}
9467 Dynamic elaboration checking mode enabled. For further details see
9468 @ref{f,,Elaboration Order Handling in GNAT}.
9469 @end table
9471 @geindex -gnatf (gcc)
9474 @table @asis
9476 @item @code{-gnatf}
9478 Full errors. Multiple errors per line, all undefined references, do not
9479 attempt to suppress cascaded errors.
9480 @end table
9482 @geindex -gnatF (gcc)
9485 @table @asis
9487 @item @code{-gnatF}
9489 Externals names are folded to all uppercase.
9490 @end table
9492 @geindex -gnatg (gcc)
9495 @table @asis
9497 @item @code{-gnatg}
9499 Internal GNAT implementation mode. This should not be used for applications
9500 programs, it is intended only for use by the compiler and its run-time
9501 library. For documentation, see the GNAT sources. Note that @code{-gnatg}
9502 implies @code{-gnatw.ge} and @code{-gnatyg} so that all standard
9503 warnings and all standard style options are turned on. All warnings and style
9504 messages are treated as errors.
9505 @end table
9507 @geindex -gnatG[nn] (gcc)
9510 @table @asis
9512 @item @code{-gnatG=nn}
9514 List generated expanded code in source form.
9515 @end table
9517 @geindex -gnath (gcc)
9520 @table @asis
9522 @item @code{-gnath}
9524 Output usage information. The output is written to @code{stdout}.
9525 @end table
9527 @geindex -gnatH (gcc)
9530 @table @asis
9532 @item @code{-gnatH}
9534 Legacy elaboration-checking mode enabled. When this switch is in effect,
9535 the pre-18.x access-before-elaboration model becomes the de facto model.
9536 For further details see @ref{f,,Elaboration Order Handling in GNAT}.
9537 @end table
9539 @geindex -gnati (gcc)
9542 @table @asis
9544 @item @code{-gnati`c'}
9546 Identifier character set (@code{c} = 1/2/3/4/5/9/p/8/f/n/w).
9547 For details of the possible selections for @code{c},
9548 see @ref{31,,Character Set Control}.
9549 @end table
9551 @geindex -gnatI (gcc)
9554 @table @asis
9556 @item @code{-gnatI}
9558 Ignore representation clauses. When this switch is used,
9559 representation clauses are treated as comments. This is useful
9560 when initially porting code where you want to ignore rep clause
9561 problems, and also for compiling foreign code (particularly
9562 for use with ASIS). The representation clauses that are ignored
9563 are: enumeration_representation_clause, record_representation_clause,
9564 and attribute_definition_clause for the following attributes:
9565 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9566 Object_Size, Scalar_Storage_Order, Size, Small, Stream_Size,
9567 and Value_Size. Pragma Default_Scalar_Storage_Order is also ignored.
9568 Note that this option should be used only for compiling – the
9569 code is likely to malfunction at run time.
9570 @end table
9572 @geindex -gnatjnn (gcc)
9575 @table @asis
9577 @item @code{-gnatj`nn'}
9579 Reformat error messages to fit on @code{nn} character lines
9580 @end table
9582 @geindex -gnatJ (gcc)
9585 @table @asis
9587 @item @code{-gnatJ}
9589 Permissive elaboration-checking mode enabled. When this switch is in effect,
9590 the post-18.x access-before-elaboration model ignores potential issues with:
9593 @itemize -
9595 @item 
9596 Accept statements
9598 @item 
9599 Activations of tasks defined in instances
9601 @item 
9602 Assertion pragmas
9604 @item 
9605 Calls from within an instance to its enclosing context
9607 @item 
9608 Calls through generic formal parameters
9610 @item 
9611 Calls to subprograms defined in instances
9613 @item 
9614 Entry calls
9616 @item 
9617 Indirect calls using ‘Access
9619 @item 
9620 Requeue statements
9622 @item 
9623 Select statements
9625 @item 
9626 Synchronous task suspension
9627 @end itemize
9629 and does not emit compile-time diagnostics or run-time checks. For further
9630 details see @ref{f,,Elaboration Order Handling in GNAT}.
9631 @end table
9633 @geindex -gnatk (gcc)
9636 @table @asis
9638 @item @code{-gnatk=`n'}
9640 Limit file names to @code{n} (1-999) characters (@code{k} = krunch).
9641 @end table
9643 @geindex -gnatl (gcc)
9646 @table @asis
9648 @item @code{-gnatl}
9650 Output full source listing with embedded error messages.
9651 @end table
9653 @geindex -gnatL (gcc)
9656 @table @asis
9658 @item @code{-gnatL}
9660 Used in conjunction with -gnatG or -gnatD to intersperse original
9661 source lines (as comment lines with line numbers) in the expanded
9662 source output.
9663 @end table
9665 @geindex -gnatm (gcc)
9668 @table @asis
9670 @item @code{-gnatm=`n'}
9672 Limit number of detected error or warning messages to @code{n}
9673 where @code{n} is in the range 1..999999. The default setting if
9674 no switch is given is 9999. If the number of warnings reaches this
9675 limit, then a message is output and further warnings are suppressed,
9676 but the compilation is continued. If the number of error messages
9677 reaches this limit, then a message is output and the compilation
9678 is abandoned. The equal sign here is optional. A value of zero
9679 means that no limit applies.
9680 @end table
9682 @geindex -gnatn (gcc)
9685 @table @asis
9687 @item @code{-gnatn[12]}
9689 Activate inlining across units for subprograms for which pragma @code{Inline}
9690 is specified. This inlining is performed by the GCC back-end. An optional
9691 digit sets the inlining level: 1 for moderate inlining across units
9692 or 2 for full inlining across units. If no inlining level is specified,
9693 the compiler will pick it based on the optimization level.
9694 @end table
9696 @geindex -gnatN (gcc)
9699 @table @asis
9701 @item @code{-gnatN}
9703 Activate front end inlining for subprograms for which
9704 pragma @code{Inline} is specified. This inlining is performed
9705 by the front end and will be visible in the
9706 @code{-gnatG} output.
9708 When using a gcc-based back end, then the use of
9709 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
9710 Historically front end inlining was more extensive than the gcc back end
9711 inlining, but that is no longer the case.
9712 @end table
9714 @geindex -gnato0 (gcc)
9717 @table @asis
9719 @item @code{-gnato0}
9721 Suppresses overflow checking. This causes the behavior of the compiler to
9722 match the default for older versions where overflow checking was suppressed
9723 by default. This is equivalent to having
9724 @code{pragma Suppress (Overflow_Check)} in a configuration pragma file.
9725 @end table
9727 @geindex -gnato?? (gcc)
9730 @table @asis
9732 @item @code{-gnato??}
9734 Set default mode for handling generation of code to avoid intermediate
9735 arithmetic overflow. Here @code{??} is two digits, a
9736 single digit, or nothing. Each digit is one of the digits @code{1}
9737 through @code{3}:
9740 @multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
9741 @item
9743 Digit
9745 @tab
9747 Interpretation
9749 @item
9753 @tab
9755 All intermediate overflows checked against base type (@code{STRICT})
9757 @item
9761 @tab
9763 Minimize intermediate overflows (@code{MINIMIZED})
9765 @item
9769 @tab
9771 Eliminate intermediate overflows (@code{ELIMINATED})
9773 @end multitable
9776 If only one digit appears, then it applies to all
9777 cases; if two digits are given, then the first applies outside
9778 assertions, pre/postconditions, and type invariants, and the second
9779 applies within assertions, pre/postconditions, and type invariants.
9781 If no digits follow the @code{-gnato}, then it is equivalent to
9782 @code{-gnato11},
9783 causing all intermediate overflows to be handled in strict
9784 mode.
9786 This switch also causes arithmetic overflow checking to be performed
9787 (as though @code{pragma Unsuppress (Overflow_Check)} had been specified).
9789 The default if no option @code{-gnato} is given is that overflow handling
9790 is in @code{STRICT} mode (computations done using the base type), and that
9791 overflow checking is enabled.
9793 Note that division by zero is a separate check that is not
9794 controlled by this switch (divide-by-zero checking is on by default).
9796 See also @ref{eb,,Specifying the Desired Mode}.
9797 @end table
9799 @geindex -gnatp (gcc)
9802 @table @asis
9804 @item @code{-gnatp}
9806 Suppress all checks. See @ref{ec,,Run-Time Checks} for details. This switch
9807 has no effect if cancelled by a subsequent @code{-gnat-p} switch.
9808 @end table
9810 @geindex -gnat-p (gcc)
9813 @table @asis
9815 @item @code{-gnat-p}
9817 Cancel effect of previous @code{-gnatp} switch.
9818 @end table
9820 @geindex -gnatq (gcc)
9823 @table @asis
9825 @item @code{-gnatq}
9827 Don’t quit. Try semantics, even if parse errors.
9828 @end table
9830 @geindex -gnatQ (gcc)
9833 @table @asis
9835 @item @code{-gnatQ}
9837 Don’t quit. Generate @code{ALI} and tree files even if illegalities.
9838 Note that code generation is still suppressed in the presence of any
9839 errors, so even with @code{-gnatQ} no object file is generated.
9840 @end table
9842 @geindex -gnatr (gcc)
9845 @table @asis
9847 @item @code{-gnatr}
9849 Treat pragma Restrictions as Restriction_Warnings.
9850 @end table
9852 @geindex -gnatR (gcc)
9855 @table @asis
9857 @item @code{-gnatR[0|1|2|3|4][e][j][m][s]}
9859 Output representation information for declared types, objects and
9860 subprograms. Note that this switch is not allowed if a previous
9861 @code{-gnatD} switch has been given, since these two switches
9862 are not compatible.
9863 @end table
9865 @geindex -gnats (gcc)
9868 @table @asis
9870 @item @code{-gnats}
9872 Syntax check only.
9873 @end table
9875 @geindex -gnatS (gcc)
9878 @table @asis
9880 @item @code{-gnatS}
9882 Print package Standard.
9883 @end table
9885 @geindex -gnatT (gcc)
9888 @table @asis
9890 @item @code{-gnatT`nnn'}
9892 All compiler tables start at @code{nnn} times usual starting size.
9893 @end table
9895 @geindex -gnatu (gcc)
9898 @table @asis
9900 @item @code{-gnatu}
9902 List units for this compilation.
9903 @end table
9905 @geindex -gnatU (gcc)
9908 @table @asis
9910 @item @code{-gnatU}
9912 Tag all error messages with the unique string ‘error:’
9913 @end table
9915 @geindex -gnatv (gcc)
9918 @table @asis
9920 @item @code{-gnatv}
9922 Verbose mode. Full error output with source lines to @code{stdout}.
9923 @end table
9925 @geindex -gnatV (gcc)
9928 @table @asis
9930 @item @code{-gnatV}
9932 Control level of validity checking (@ref{e9,,Validity Checking}).
9933 @end table
9935 @geindex -gnatw (gcc)
9938 @table @asis
9940 @item @code{-gnatw`xxx'}
9942 Warning mode where
9943 @code{xxx} is a string of option letters that denotes
9944 the exact warnings that
9945 are enabled or disabled (@ref{ed,,Warning Message Control}).
9946 @end table
9948 @geindex -gnatW (gcc)
9951 @table @asis
9953 @item @code{-gnatW`e'}
9955 Wide character encoding method
9956 (@code{e}=n/h/u/s/e/8).
9957 @end table
9959 @geindex -gnatx (gcc)
9962 @table @asis
9964 @item @code{-gnatx}
9966 Suppress generation of cross-reference information.
9967 @end table
9969 @geindex -gnatX (gcc)
9972 @table @asis
9974 @item @code{-gnatX}
9976 Enable core GNAT implementation extensions and latest Ada version.
9977 @end table
9979 @geindex -gnatX0 (gcc)
9982 @table @asis
9984 @item @code{-gnatX0}
9986 Enable all GNAT implementation extensions and latest Ada version.
9987 @end table
9989 @geindex -gnaty (gcc)
9992 @table @asis
9994 @item @code{-gnaty}
9996 Enable built-in style checks (@ref{ee,,Style Checking}).
9997 @end table
9999 @geindex -gnatz (gcc)
10002 @table @asis
10004 @item @code{-gnatz`m'}
10006 Distribution stub generation and compilation
10007 (@code{m}=r/c for receiver/caller stubs).
10008 @end table
10010 @geindex -I (gcc)
10013 @table @asis
10015 @item @code{-I`dir'}
10017 @geindex RTL
10019 Direct GNAT to search the @code{dir} directory for source files needed by
10020 the current compilation
10021 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
10022 @end table
10024 @geindex -I- (gcc)
10027 @table @asis
10029 @item @code{-I-}
10031 @geindex RTL
10033 Except for the source file named in the command line, do not look for source
10034 files in the directory containing the source file named in the command line
10035 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
10036 @end table
10038 @geindex -o (gcc)
10041 @table @asis
10043 @item @code{-o `file'}
10045 This switch is used in @code{gcc} to redirect the generated object file
10046 and its associated ALI file. Beware of this switch with GNAT, because it may
10047 cause the object file and ALI file to have different names which in turn
10048 may confuse the binder and the linker.
10049 @end table
10051 @geindex -nostdinc (gcc)
10054 @table @asis
10056 @item @code{-nostdinc}
10058 Inhibit the search of the default location for the GNAT Run Time
10059 Library (RTL) source files.
10060 @end table
10062 @geindex -nostdlib (gcc)
10065 @table @asis
10067 @item @code{-nostdlib}
10069 Inhibit the search of the default location for the GNAT Run Time
10070 Library (RTL) ALI files.
10071 @end table
10073 @geindex -O (gcc)
10076 @table @asis
10078 @item @code{-O[`n']}
10080 @code{n} controls the optimization level:
10083 @multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
10084 @item
10088 @tab
10090 Effect
10092 @item
10096 @tab
10098 No optimization, the default setting if no @code{-O} appears
10100 @item
10104 @tab
10106 Normal optimization, the default if you specify @code{-O} without an
10107 operand. A good compromise between code quality and compilation
10108 time.
10110 @item
10114 @tab
10116 Extensive optimization, may improve execution time, possibly at
10117 the cost of substantially increased compilation time.
10119 @item
10123 @tab
10125 Same as @code{-O2}, and also includes inline expansion for small
10126 subprograms in the same unit.
10128 @item
10132 @tab
10134 Optimize space usage
10136 @end multitable
10139 See also @ref{ef,,Optimization Levels}.
10140 @end table
10142 @geindex -pass-exit-codes (gcc)
10145 @table @asis
10147 @item @code{-pass-exit-codes}
10149 Catch exit codes from the compiler and use the most meaningful as
10150 exit status.
10151 @end table
10153 @geindex --RTS (gcc)
10156 @table @asis
10158 @item @code{--RTS=`rts-path'}
10160 Specifies the default location of the run-time library. Same meaning as the
10161 equivalent @code{gnatmake} flag (@ref{d0,,Switches for gnatmake}).
10162 @end table
10164 @geindex -S (gcc)
10167 @table @asis
10169 @item @code{-S}
10171 Used in place of @code{-c} to
10172 cause the assembler source file to be
10173 generated, using @code{.s} as the extension,
10174 instead of the object file.
10175 This may be useful if you need to examine the generated assembly code.
10176 @end table
10178 @geindex -fverbose-asm (gcc)
10181 @table @asis
10183 @item @code{-fverbose-asm}
10185 Used in conjunction with @code{-S}
10186 to cause the generated assembly code file to be annotated with variable
10187 names, making it significantly easier to follow.
10188 @end table
10190 @geindex -v (gcc)
10193 @table @asis
10195 @item @code{-v}
10197 Show commands generated by the @code{gcc} driver. Normally used only for
10198 debugging purposes or if you need to be sure what version of the
10199 compiler you are executing.
10200 @end table
10202 @geindex -V (gcc)
10205 @table @asis
10207 @item @code{-V `ver'}
10209 Execute @code{ver} version of the compiler. This is the @code{gcc}
10210 version, not the GNAT version.
10211 @end table
10213 @geindex -w (gcc)
10216 @table @asis
10218 @item @code{-w}
10220 Turn off warnings generated by the back end of the compiler. Use of
10221 this switch also causes the default for front end warnings to be set
10222 to suppress (as though @code{-gnatws} had appeared at the start of
10223 the options).
10224 @end table
10226 @geindex Combining GNAT switches
10228 You may combine a sequence of GNAT switches into a single switch. For
10229 example, the combined switch
10231 @quotation
10233 @example
10234 -gnatofi3
10235 @end example
10236 @end quotation
10238 is equivalent to specifying the following sequence of switches:
10240 @quotation
10242 @example
10243 -gnato -gnatf -gnati3
10244 @end example
10245 @end quotation
10247 The following restrictions apply to the combination of switches
10248 in this manner:
10251 @itemize *
10253 @item 
10254 The switch @code{-gnatc} if combined with other switches must come
10255 first in the string.
10257 @item 
10258 The switch @code{-gnats} if combined with other switches must come
10259 first in the string.
10261 @item 
10262 The switches
10263 @code{-gnatzc} and @code{-gnatzr} may not be combined with any other
10264 switches, and only one of them may appear in the command line.
10266 @item 
10267 The switch @code{-gnat-p} may not be combined with any other switch.
10269 @item 
10270 Once a ‘y’ appears in the string (that is a use of the @code{-gnaty}
10271 switch), then all further characters in the switch are interpreted
10272 as style modifiers (see description of @code{-gnaty}).
10274 @item 
10275 Once a ‘d’ appears in the string (that is a use of the @code{-gnatd}
10276 switch), then all further characters in the switch are interpreted
10277 as debug flags (see description of @code{-gnatd}).
10279 @item 
10280 Once a ‘w’ appears in the string (that is a use of the @code{-gnatw}
10281 switch), then all further characters in the switch are interpreted
10282 as warning mode modifiers (see description of @code{-gnatw}).
10284 @item 
10285 Once a ‘V’ appears in the string (that is a use of the @code{-gnatV}
10286 switch), then all further characters in the switch are interpreted
10287 as validity checking options (@ref{e9,,Validity Checking}).
10289 @item 
10290 Option ‘em’, ‘ec’, ‘ep’, ‘l=’ and ‘R’ must be the last options in
10291 a combined list of options.
10292 @end itemize
10294 @node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10295 @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}
10296 @subsection Output and Error Message Control
10299 @geindex stderr
10301 The standard default format for error messages is called ‘brief format’.
10302 Brief format messages are written to @code{stderr} (the standard error
10303 file) and have the following form:
10305 @example
10306 e.adb:3:04: Incorrect spelling of keyword "function"
10307 e.adb:4:20: ";" should be "is"
10308 @end example
10310 The first integer after the file name is the line number in the file,
10311 and the second integer is the column number within the line.
10312 @code{GNAT Studio} can parse the error messages
10313 and point to the referenced character.
10314 The following switches provide control over the error message
10315 format:
10317 @geindex -gnatv (gcc)
10320 @table @asis
10322 @item @code{-gnatv}
10324 The @code{v} stands for verbose.
10325 The effect of this setting is to write long-format error
10326 messages to @code{stdout} (the standard output file).
10327 The same program compiled with the
10328 @code{-gnatv} switch would generate:
10330 @example
10331 3. funcion X (Q : Integer)
10332    |
10333 >>> Incorrect spelling of keyword "function"
10334 4. return Integer;
10335                  |
10336 >>> ";" should be "is"
10337 @end example
10339 The vertical bar indicates the location of the error, and the @code{>>>}
10340 prefix can be used to search for error messages. When this switch is
10341 used the only source lines output are those with errors.
10342 @end table
10344 @geindex -gnatl (gcc)
10347 @table @asis
10349 @item @code{-gnatl}
10351 The @code{l} stands for list.
10352 This switch causes a full listing of
10353 the file to be generated. In the case where a body is
10354 compiled, the corresponding spec is also listed, along
10355 with any subunits. Typical output from compiling a package
10356 body @code{p.adb} might look like:
10358 @example
10359 Compiling: p.adb
10361      1. package body p is
10362      2.    procedure a;
10363      3.    procedure a is separate;
10364      4. begin
10365      5.    null
10366                |
10367         >>> missing ";"
10369      6. end;
10371 Compiling: p.ads
10373      1. package p is
10374      2.    pragma Elaborate_Body
10375                                 |
10376         >>> missing ";"
10378      3. end p;
10380 Compiling: p-a.adb
10382      1. separate p
10383                 |
10384         >>> missing "("
10386      2. procedure a is
10387      3. begin
10388      4.    null
10389                |
10390         >>> missing ";"
10392      5. end;
10393 @end example
10395 When you specify the @code{-gnatv} or @code{-gnatl} switches and
10396 standard output is redirected, a brief summary is written to
10397 @code{stderr} (standard error) giving the number of error messages and
10398 warning messages generated.
10399 @end table
10401 @geindex -gnatl=fname (gcc)
10404 @table @asis
10406 @item @code{-gnatl=`fname'}
10408 This has the same effect as @code{-gnatl} except that the output is
10409 written to a file instead of to standard output. If the given name
10410 @code{fname} does not start with a period, then it is the full name
10411 of the file to be written. If @code{fname} is an extension, it is
10412 appended to the name of the file being compiled. For example, if
10413 file @code{xyz.adb} is compiled with @code{-gnatl=.lst},
10414 then the output is written to file xyz.adb.lst.
10415 @end table
10417 @geindex -gnatU (gcc)
10420 @table @asis
10422 @item @code{-gnatU}
10424 This switch forces all error messages to be preceded by the unique
10425 string ‘error:’. This means that error messages take a few more
10426 characters in space, but allows easy searching for and identification
10427 of error messages.
10428 @end table
10430 @geindex -gnatb (gcc)
10433 @table @asis
10435 @item @code{-gnatb}
10437 The @code{b} stands for brief.
10438 This switch causes GNAT to generate the
10439 brief format error messages to @code{stderr} (the standard error
10440 file) as well as the verbose
10441 format message or full listing (which as usual is written to
10442 @code{stdout}, the standard output file).
10443 @end table
10445 @geindex -gnatm (gcc)
10448 @table @asis
10450 @item @code{-gnatm=`n'}
10452 The @code{m} stands for maximum.
10453 @code{n} is a decimal integer in the
10454 range of 1 to 999999 and limits the number of error or warning
10455 messages to be generated. For example, using
10456 @code{-gnatm2} might yield
10458 @example
10459 e.adb:3:04: Incorrect spelling of keyword "function"
10460 e.adb:5:35: missing ".."
10461 fatal error: maximum number of errors detected
10462 compilation abandoned
10463 @end example
10465 The default setting if
10466 no switch is given is 9999. If the number of warnings reaches this
10467 limit, then a message is output and further warnings are suppressed,
10468 but the compilation is continued. If the number of error messages
10469 reaches this limit, then a message is output and the compilation
10470 is abandoned. A value of zero means that no limit applies.
10472 Note that the equal sign is optional, so the switches
10473 @code{-gnatm2} and @code{-gnatm=2} are equivalent.
10474 @end table
10476 @geindex -gnatf (gcc)
10479 @table @asis
10481 @item @code{-gnatf}
10483 @geindex Error messages
10484 @geindex suppressing
10486 The @code{f} stands for full.
10487 Normally, the compiler suppresses error messages that are likely to be
10488 redundant. This switch causes all error
10489 messages to be generated. In particular, in the case of
10490 references to undefined variables. If a given variable is referenced
10491 several times, the normal format of messages is
10493 @example
10494 e.adb:7:07: "V" is undefined (more references follow)
10495 @end example
10497 where the parenthetical comment warns that there are additional
10498 references to the variable @code{V}. Compiling the same program with the
10499 @code{-gnatf} switch yields
10501 @example
10502 e.adb:7:07: "V" is undefined
10503 e.adb:8:07: "V" is undefined
10504 e.adb:8:12: "V" is undefined
10505 e.adb:8:16: "V" is undefined
10506 e.adb:9:07: "V" is undefined
10507 e.adb:9:12: "V" is undefined
10508 @end example
10510 The @code{-gnatf} switch also generates additional information for
10511 some error messages.  Some examples are:
10514 @itemize *
10516 @item 
10517 Details on possibly non-portable unchecked conversion
10519 @item 
10520 List possible interpretations for ambiguous calls
10522 @item 
10523 Additional details on incorrect parameters
10524 @end itemize
10525 @end table
10527 @geindex -gnatjnn (gcc)
10530 @table @asis
10532 @item @code{-gnatjnn}
10534 In normal operation mode (or if @code{-gnatj0} is used), then error messages
10535 with continuation lines are treated as though the continuation lines were
10536 separate messages (and so a warning with two continuation lines counts as
10537 three warnings, and is listed as three separate messages).
10539 If the @code{-gnatjnn} switch is used with a positive value for nn, then
10540 messages are output in a different manner. A message and all its continuation
10541 lines are treated as a unit, and count as only one warning or message in the
10542 statistics totals. Furthermore, the message is reformatted so that no line
10543 is longer than nn characters.
10544 @end table
10546 @geindex -gnatq (gcc)
10549 @table @asis
10551 @item @code{-gnatq}
10553 The @code{q} stands for quit (really ‘don’t quit’).
10554 In normal operation mode, the compiler first parses the program and
10555 determines if there are any syntax errors. If there are, appropriate
10556 error messages are generated and compilation is immediately terminated.
10557 This switch tells
10558 GNAT to continue with semantic analysis even if syntax errors have been
10559 found. This may enable the detection of more errors in a single run. On
10560 the other hand, the semantic analyzer is more likely to encounter some
10561 internal fatal error when given a syntactically invalid tree.
10562 @end table
10564 @geindex -gnatQ (gcc)
10567 @table @asis
10569 @item @code{-gnatQ}
10571 In normal operation mode, the @code{ALI} file is not generated if any
10572 illegalities are detected in the program. The use of @code{-gnatQ} forces
10573 generation of the @code{ALI} file. This file is marked as being in
10574 error, so it cannot be used for binding purposes, but it does contain
10575 reasonably complete cross-reference information, and thus may be useful
10576 for use by tools (e.g., semantic browsing tools or integrated development
10577 environments) that are driven from the @code{ALI} file. This switch
10578 implies @code{-gnatq}, since the semantic phase must be run to get a
10579 meaningful ALI file.
10581 When @code{-gnatQ} is used and the generated @code{ALI} file is marked as
10582 being in error, @code{gnatmake} will attempt to recompile the source when it
10583 finds such an @code{ALI} file, including with switch @code{-gnatc}.
10585 Note that @code{-gnatQ} has no effect if @code{-gnats} is specified,
10586 since ALI files are never generated if @code{-gnats} is set.
10587 @end table
10589 @node Warning Message Control,Info message Control,Output and Error Message Control,Compiler Switches
10590 @anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{f2}@anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{ed}
10591 @subsection Warning Message Control
10594 @geindex Warning messages
10596 In addition to error messages, which correspond to illegalities as defined
10597 in the Ada Reference Manual, the compiler detects two kinds of warning
10598 situations.
10600 First, the compiler considers some constructs suspicious and generates a
10601 warning message to alert you to a possible error. Second, if the
10602 compiler detects a situation that is sure to raise an exception at
10603 run time, it generates a warning message. The following shows an example
10604 of warning messages:
10606 @example
10607 e.adb:4:24: warning: creation of object may raise Storage_Error
10608 e.adb:10:17: warning: static value out of range
10609 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10610 @end example
10612 GNAT considers a large number of situations as appropriate
10613 for the generation of warning messages. As always, warnings are not
10614 definite indications of errors. For example, if you do an out-of-range
10615 assignment with the deliberate intention of raising a
10616 @code{Constraint_Error} exception, then the warning that may be
10617 issued does not indicate an error. Some of the situations for which GNAT
10618 issues warnings (at least some of the time) are given in the following
10619 list. This list is not complete, and new warnings are often added to
10620 subsequent versions of GNAT. The list is intended to give a general idea
10621 of the kinds of warnings that are generated.
10624 @itemize *
10626 @item 
10627 Possible infinitely recursive calls
10629 @item 
10630 Out-of-range values being assigned
10632 @item 
10633 Possible order of elaboration problems
10635 @item 
10636 Size not a multiple of alignment for a record type
10638 @item 
10639 Assertions (pragma Assert) that are sure to fail
10641 @item 
10642 Unreachable code
10644 @item 
10645 Address clauses with possibly unaligned values, or where an attempt is
10646 made to overlay a smaller variable with a larger one.
10648 @item 
10649 Fixed-point type declarations with a null range
10651 @item 
10652 Direct_IO or Sequential_IO instantiated with a type that has access values
10654 @item 
10655 Variables that are never assigned a value
10657 @item 
10658 Variables that are referenced before being initialized
10660 @item 
10661 Task entries with no corresponding @code{accept} statement
10663 @item 
10664 Duplicate accepts for the same task entry in a @code{select}
10666 @item 
10667 Objects that take too much storage
10669 @item 
10670 Unchecked conversion between types of differing sizes
10672 @item 
10673 Missing @code{return} statement along some execution path in a function
10675 @item 
10676 Incorrect (unrecognized) pragmas
10678 @item 
10679 Incorrect external names
10681 @item 
10682 Allocation from empty storage pool
10684 @item 
10685 Potentially blocking operation in protected type
10687 @item 
10688 Suspicious parenthesization of expressions
10690 @item 
10691 Mismatching bounds in an aggregate
10693 @item 
10694 Attempt to return local value by reference
10696 @item 
10697 Premature instantiation of a generic body
10699 @item 
10700 Attempt to pack aliased components
10702 @item 
10703 Out of bounds array subscripts
10705 @item 
10706 Wrong length on string assignment
10708 @item 
10709 Violations of style rules if style checking is enabled
10711 @item 
10712 Unused `with' clauses
10714 @item 
10715 @code{Bit_Order} usage that does not have any effect
10717 @item 
10718 @code{Standard.Duration} used to resolve universal fixed expression
10720 @item 
10721 Dereference of possibly null value
10723 @item 
10724 Declaration that is likely to cause storage error
10726 @item 
10727 Internal GNAT unit `with'ed by application unit
10729 @item 
10730 Values known to be out of range at compile time
10732 @item 
10733 Unreferenced or unmodified variables. Note that a special
10734 exemption applies to variables which contain any of the substrings
10735 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
10736 are considered likely to be intentionally used in a situation where
10737 otherwise a warning would be given, so warnings of this kind are
10738 always suppressed for such variables.
10740 @item 
10741 Address overlays that could clobber memory
10743 @item 
10744 Unexpected initialization when address clause present
10746 @item 
10747 Bad alignment for address clause
10749 @item 
10750 Useless type conversions
10752 @item 
10753 Redundant assignment statements and other redundant constructs
10755 @item 
10756 Useless exception handlers
10758 @item 
10759 Accidental hiding of name by child unit
10761 @item 
10762 Access before elaboration detected at compile time
10764 @item 
10765 A range in a @code{for} loop that is known to be null or might be null
10766 @end itemize
10768 The following section lists compiler switches that are available
10769 to control the handling of warning messages. It is also possible
10770 to exercise much finer control over what warnings are issued and
10771 suppressed using the GNAT pragma Warnings (see the description
10772 of the pragma in the @cite{GNAT_Reference_manual}).
10774 @geindex -gnatwa (gcc)
10777 @table @asis
10779 @item @code{-gnatwa}
10781 `Activate most optional warnings.'
10783 This switch activates most optional warning messages. See the remaining list
10784 in this section for details on optional warning messages that can be
10785 individually controlled.  The warnings that are not turned on by this
10786 switch are:
10789 @itemize *
10791 @item 
10792 @code{-gnatwd} (implicit dereferencing)
10794 @item 
10795 @code{-gnatw.d} (tag warnings with -gnatw switch)
10797 @item 
10798 @code{-gnatwh} (hiding)
10800 @item 
10801 @code{-gnatw.h} (holes in record layouts)
10803 @item 
10804 @code{-gnatw.j} (late primitives of tagged types)
10806 @item 
10807 @code{-gnatw.k} (redefinition of names in standard)
10809 @item 
10810 @code{-gnatwl} (elaboration warnings)
10812 @item 
10813 @code{-gnatw.l} (inherited aspects)
10815 @item 
10816 @code{-gnatw.n} (atomic synchronization)
10818 @item 
10819 @code{-gnatwo} (address clause overlay)
10821 @item 
10822 @code{-gnatw.o} (values set by out parameters ignored)
10824 @item 
10825 @code{-gnatw.q} (questionable layout of record types)
10827 @item 
10828 @code{-gnatw_q} (ignored equality)
10830 @item 
10831 @code{-gnatw_r} (out-of-order record representation clauses)
10833 @item 
10834 @code{-gnatw.s} (overridden size clause)
10836 @item 
10837 @code{-gnatw_s} (ineffective predicate test)
10839 @item 
10840 @code{-gnatwt} (tracking of deleted conditional code)
10842 @item 
10843 @code{-gnatw.u} (unordered enumeration)
10845 @item 
10846 @code{-gnatw.w} (use of Warnings Off)
10848 @item 
10849 @code{-gnatw.y} (reasons for package needing body)
10850 @end itemize
10852 All other optional warnings are turned on.
10853 @end table
10855 @geindex -gnatwA (gcc)
10858 @table @asis
10860 @item @code{-gnatwA}
10862 `Suppress all optional errors.'
10864 This switch suppresses all optional warning messages, see remaining list
10865 in this section for details on optional warning messages that can be
10866 individually controlled. Note that unlike switch @code{-gnatws}, the
10867 use of switch @code{-gnatwA} does not suppress warnings that are
10868 normally given unconditionally and cannot be individually controlled
10869 (for example, the warning about a missing exit path in a function).
10870 Also, again unlike switch @code{-gnatws}, warnings suppressed by
10871 the use of switch @code{-gnatwA} can be individually turned back
10872 on. For example the use of switch @code{-gnatwA} followed by
10873 switch @code{-gnatwd} will suppress all optional warnings except
10874 the warnings for implicit dereferencing.
10875 @end table
10877 @geindex -gnatw.a (gcc)
10880 @table @asis
10882 @item @code{-gnatw.a}
10884 `Activate warnings on failing assertions.'
10886 @geindex Assert failures
10888 This switch activates warnings for assertions where the compiler can tell at
10889 compile time that the assertion will fail. Note that this warning is given
10890 even if assertions are disabled. The default is that such warnings are
10891 generated.
10892 @end table
10894 @geindex -gnatw.A (gcc)
10897 @table @asis
10899 @item @code{-gnatw.A}
10901 `Suppress warnings on failing assertions.'
10903 @geindex Assert failures
10905 This switch suppresses warnings for assertions where the compiler can tell at
10906 compile time that the assertion will fail.
10907 @end table
10909 @geindex -gnatw_a
10912 @table @asis
10914 @item @code{-gnatw_a}
10916 `Activate warnings on anonymous allocators.'
10918 @geindex Anonymous allocators
10920 This switch activates warnings for allocators of anonymous access types,
10921 which can involve run-time accessibility checks and lead to unexpected
10922 accessibility violations. For more details on the rules involved, see
10923 RM 3.10.2 (14).
10924 @end table
10926 @geindex -gnatw_A
10929 @table @asis
10931 @item @code{-gnatw_A}
10933 `Suppress warnings on anonymous allocators.'
10935 @geindex Anonymous allocators
10937 This switch suppresses warnings for anonymous access type allocators.
10938 @end table
10940 @geindex -gnatwb (gcc)
10943 @table @asis
10945 @item @code{-gnatwb}
10947 `Activate warnings on bad fixed values.'
10949 @geindex Bad fixed values
10951 @geindex Fixed-point Small value
10953 @geindex Small value
10955 This switch activates warnings for static fixed-point expressions whose
10956 value is not an exact multiple of Small. Such values are implementation
10957 dependent, since an implementation is free to choose either of the multiples
10958 that surround the value. GNAT always chooses the closer one, but this is not
10959 required behavior, and it is better to specify a value that is an exact
10960 multiple, ensuring predictable execution. The default is that such warnings
10961 are not generated.
10962 @end table
10964 @geindex -gnatwB (gcc)
10967 @table @asis
10969 @item @code{-gnatwB}
10971 `Suppress warnings on bad fixed values.'
10973 This switch suppresses warnings for static fixed-point expressions whose
10974 value is not an exact multiple of Small.
10975 @end table
10977 @geindex -gnatw.b (gcc)
10980 @table @asis
10982 @item @code{-gnatw.b}
10984 `Activate warnings on biased representation.'
10986 @geindex Biased representation
10988 This switch activates warnings when a size clause, value size clause, component
10989 clause, or component size clause forces the use of biased representation for an
10990 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
10991 to represent 10/11). The default is that such warnings are generated.
10992 @end table
10994 @geindex -gnatwB (gcc)
10997 @table @asis
10999 @item @code{-gnatw.B}
11001 `Suppress warnings on biased representation.'
11003 This switch suppresses warnings for representation clauses that force the use
11004 of biased representation.
11005 @end table
11007 @geindex -gnatwc (gcc)
11010 @table @asis
11012 @item @code{-gnatwc}
11014 `Activate warnings on conditionals.'
11016 @geindex Conditionals
11017 @geindex constant
11019 This switch activates warnings for boolean expressions that are known to
11020 be True or False at compile time. The default
11021 is that such warnings are not generated.
11022 Note that this warning does
11023 not get issued for the use of boolean constants whose
11024 values are known at compile time, since this is a standard technique
11025 for conditional compilation in Ada, and this would generate too many
11026 false positive warnings.
11028 This warning option also activates a special test for comparisons using
11029 the operators ‘>=’ and’ <=’.
11030 If the compiler can tell that only the equality condition is possible,
11031 then it will warn that the ‘>’ or ‘<’ part of the test
11032 is useless and that the operator could be replaced by ‘=’.
11033 An example would be comparing a @code{Natural} variable <= 0.
11035 This warning option also generates warnings if
11036 one or both tests is optimized away in a membership test for integer
11037 values if the result can be determined at compile time. Range tests on
11038 enumeration types are not included, since it is common for such tests
11039 to include an end point.
11041 This warning can also be turned on using @code{-gnatwa}.
11042 @end table
11044 @geindex -gnatwC (gcc)
11047 @table @asis
11049 @item @code{-gnatwC}
11051 `Suppress warnings on conditionals.'
11053 This switch suppresses warnings for conditional expressions used in
11054 tests that are known to be True or False at compile time.
11055 @end table
11057 @geindex -gnatw.c (gcc)
11060 @table @asis
11062 @item @code{-gnatw.c}
11064 `Activate warnings on missing component clauses.'
11066 @geindex Component clause
11067 @geindex missing
11069 This switch activates warnings for record components where a record
11070 representation clause is present and has component clauses for the
11071 majority, but not all, of the components. A warning is given for each
11072 component for which no component clause is present.
11073 @end table
11075 @geindex -gnatw.C (gcc)
11078 @table @asis
11080 @item @code{-gnatw.C}
11082 `Suppress warnings on missing component clauses.'
11084 This switch suppresses warnings for record components that are
11085 missing a component clause in the situation described above.
11086 @end table
11088 @geindex -gnatw_c (gcc)
11091 @table @asis
11093 @item @code{-gnatw_c}
11095 `Activate warnings on unknown condition in Compile_Time_Warning.'
11097 @geindex Compile_Time_Warning
11099 @geindex Compile_Time_Error
11101 This switch activates warnings on a pragma Compile_Time_Warning
11102 or Compile_Time_Error whose condition has a value that is not
11103 known at compile time.
11104 The default is that such warnings are generated.
11105 @end table
11107 @geindex -gnatw_C (gcc)
11110 @table @asis
11112 @item @code{-gnatw_C}
11114 `Suppress warnings on unknown condition in Compile_Time_Warning.'
11116 This switch suppresses warnings on a pragma Compile_Time_Warning
11117 or Compile_Time_Error whose condition has a value that is not
11118 known at compile time.
11119 @end table
11121 @geindex -gnatwd (gcc)
11124 @table @asis
11126 @item @code{-gnatwd}
11128 `Activate warnings on implicit dereferencing.'
11130 If this switch is set, then the use of a prefix of an access type
11131 in an indexed component, slice, or selected component without an
11132 explicit @code{.all} will generate a warning. With this warning
11133 enabled, access checks occur only at points where an explicit
11134 @code{.all} appears in the source code (assuming no warnings are
11135 generated as a result of this switch). The default is that such
11136 warnings are not generated.
11137 @end table
11139 @geindex -gnatwD (gcc)
11142 @table @asis
11144 @item @code{-gnatwD}
11146 `Suppress warnings on implicit dereferencing.'
11148 @geindex Implicit dereferencing
11150 @geindex Dereferencing
11151 @geindex implicit
11153 This switch suppresses warnings for implicit dereferences in
11154 indexed components, slices, and selected components.
11155 @end table
11157 @geindex -gnatw.d (gcc)
11160 @table @asis
11162 @item @code{-gnatw.d}
11164 `Activate tagging of warning and info messages.'
11166 If this switch is set, then warning messages are tagged, with one of the
11167 following strings:
11169 @quotation
11172 @itemize -
11174 @item 
11175 `[-gnatw?]'
11176 Used to tag warnings controlled by the switch @code{-gnatwx} where x
11177 is a letter a-z.
11179 @item 
11180 `[-gnatw.?]'
11181 Used to tag warnings controlled by the switch @code{-gnatw.x} where x
11182 is a letter a-z.
11184 @item 
11185 `[-gnatel]'
11186 Used to tag elaboration information (info) messages generated when the
11187 static model of elaboration is used and the @code{-gnatel} switch is set.
11189 @item 
11190 `[restriction warning]'
11191 Used to tag warning messages for restriction violations, activated by use
11192 of the pragma @code{Restriction_Warnings}.
11194 @item 
11195 `[warning-as-error]'
11196 Used to tag warning messages that have been converted to error messages by
11197 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11198 the string “error: ” rather than “warning: “.
11200 @item 
11201 `[enabled by default]'
11202 Used to tag all other warnings that are always given by default, unless
11203 warnings are completely suppressed using pragma `Warnings(Off)' or
11204 the switch @code{-gnatws}.
11205 @end itemize
11206 @end quotation
11207 @end table
11209 @geindex -gnatw.d (gcc)
11212 @table @asis
11214 @item @code{-gnatw.D}
11216 `Deactivate tagging of warning and info messages messages.'
11218 If this switch is set, then warning messages return to the default
11219 mode in which warnings and info messages are not tagged as described above for
11220 @code{-gnatw.d}.
11221 @end table
11223 @geindex -gnatwe (gcc)
11225 @geindex Warnings
11226 @geindex treat as error
11229 @table @asis
11231 @item @code{-gnatwe}
11233 `Treat warnings and style checks as errors.'
11235 This switch causes warning messages and style check messages to be
11236 treated as errors.
11237 The warning string still appears, but the warning messages are counted
11238 as errors, and prevent the generation of an object file. Note that this
11239 is the only -gnatw switch that affects the handling of style check messages.
11240 Note also that this switch has no effect on info (information) messages, which
11241 are not treated as errors if this switch is present.
11242 @end table
11244 @geindex -gnatw.e (gcc)
11247 @table @asis
11249 @item @code{-gnatw.e}
11251 `Activate every optional warning.'
11253 @geindex Warnings
11254 @geindex activate every optional warning
11256 This switch activates all optional warnings, including those which
11257 are not activated by @code{-gnatwa}. The use of this switch is not
11258 recommended for normal use. If you turn this switch on, it is almost
11259 certain that you will get large numbers of useless warnings. The
11260 warnings that are excluded from @code{-gnatwa} are typically highly
11261 specialized warnings that are suitable for use only in code that has
11262 been specifically designed according to specialized coding rules.
11263 @end table
11265 @geindex -gnatwE (gcc)
11267 @geindex Warnings
11268 @geindex treat as error
11271 @table @asis
11273 @item @code{-gnatwE}
11275 `Treat all run-time exception warnings as errors.'
11277 This switch causes warning messages regarding errors that will be raised
11278 during run-time execution to be treated as errors.
11279 @end table
11281 @geindex -gnatwf (gcc)
11284 @table @asis
11286 @item @code{-gnatwf}
11288 `Activate warnings on unreferenced formals.'
11290 @geindex Formals
11291 @geindex unreferenced
11293 This switch causes a warning to be generated if a formal parameter
11294 is not referenced in the body of the subprogram. This warning can
11295 also be turned on using @code{-gnatwu}. The
11296 default is that these warnings are not generated.
11297 @end table
11299 @geindex -gnatwF (gcc)
11302 @table @asis
11304 @item @code{-gnatwF}
11306 `Suppress warnings on unreferenced formals.'
11308 This switch suppresses warnings for unreferenced formal
11309 parameters. Note that the
11310 combination @code{-gnatwu} followed by @code{-gnatwF} has the
11311 effect of warning on unreferenced entities other than subprogram
11312 formals.
11313 @end table
11315 @geindex -gnatwg (gcc)
11318 @table @asis
11320 @item @code{-gnatwg}
11322 `Activate warnings on unrecognized pragmas.'
11324 @geindex Pragmas
11325 @geindex unrecognized
11327 This switch causes a warning to be generated if an unrecognized
11328 pragma is encountered. Apart from issuing this warning, the
11329 pragma is ignored and has no effect. The default
11330 is that such warnings are issued (satisfying the Ada Reference
11331 Manual requirement that such warnings appear).
11332 @end table
11334 @geindex -gnatwG (gcc)
11337 @table @asis
11339 @item @code{-gnatwG}
11341 `Suppress warnings on unrecognized pragmas.'
11343 This switch suppresses warnings for unrecognized pragmas.
11344 @end table
11346 @geindex -gnatw.g (gcc)
11349 @table @asis
11351 @item @code{-gnatw.g}
11353 `Warnings used for GNAT sources.'
11355 This switch sets the warning categories that are used by the standard
11356 GNAT style. Currently this is equivalent to
11357 @code{-gnatwAao.q.s.CI.V.X.Z}
11358 but more warnings may be added in the future without advanced notice.
11359 @end table
11361 @geindex -gnatwh (gcc)
11364 @table @asis
11366 @item @code{-gnatwh}
11368 `Activate warnings on hiding.'
11370 @geindex Hiding of Declarations
11372 This switch activates warnings on hiding declarations that are considered
11373 potentially confusing. Not all cases of hiding cause warnings; for example an
11374 overriding declaration hides an implicit declaration, which is just normal
11375 code. The default is that warnings on hiding are not generated.
11376 @end table
11378 @geindex -gnatwH (gcc)
11381 @table @asis
11383 @item @code{-gnatwH}
11385 `Suppress warnings on hiding.'
11387 This switch suppresses warnings on hiding declarations.
11388 @end table
11390 @geindex -gnatw.h (gcc)
11393 @table @asis
11395 @item @code{-gnatw.h}
11397 `Activate warnings on holes/gaps in records.'
11399 @geindex Record Representation (gaps)
11401 This switch activates warnings on component clauses in record
11402 representation clauses that leave holes (gaps) in the record layout.
11403 If a record representation clause does not specify a location for
11404 every component of the record type, then the warnings generated (or not
11405 generated) are unspecified. For example, there may be gaps for which
11406 either no warning is generated or a warning is generated that
11407 incorrectly describes the location of the gap. This undesirable situation
11408 can sometimes be avoided by adding (and specifying the location for) unused
11409 fill fields.
11410 @end table
11412 @geindex -gnatw.H (gcc)
11415 @table @asis
11417 @item @code{-gnatw.H}
11419 `Suppress warnings on holes/gaps in records.'
11421 This switch suppresses warnings on component clauses in record
11422 representation clauses that leave holes (haps) in the record layout.
11423 @end table
11425 @geindex -gnatwi (gcc)
11428 @table @asis
11430 @item @code{-gnatwi}
11432 `Activate warnings on implementation units.'
11434 This switch activates warnings for a `with' of an internal GNAT
11435 implementation unit, defined as any unit from the @code{Ada},
11436 @code{Interfaces}, @code{GNAT},
11437 or @code{System}
11438 hierarchies that is not
11439 documented in either the Ada Reference Manual or the GNAT
11440 Programmer’s Reference Manual. Such units are intended only
11441 for internal implementation purposes and should not be `with'ed
11442 by user programs. The default is that such warnings are generated
11443 @end table
11445 @geindex -gnatwI (gcc)
11448 @table @asis
11450 @item @code{-gnatwI}
11452 `Disable warnings on implementation units.'
11454 This switch disables warnings for a `with' of an internal GNAT
11455 implementation unit.
11456 @end table
11458 @geindex -gnatw.i (gcc)
11461 @table @asis
11463 @item @code{-gnatw.i}
11465 `Activate warnings on overlapping actuals.'
11467 This switch enables a warning on statically detectable overlapping actuals in
11468 a subprogram call, when one of the actuals is an in-out parameter, and the
11469 types of the actuals are not by-copy types. This warning is off by default.
11470 @end table
11472 @geindex -gnatw.I (gcc)
11475 @table @asis
11477 @item @code{-gnatw.I}
11479 `Disable warnings on overlapping actuals.'
11481 This switch disables warnings on overlapping actuals in a call.
11482 @end table
11484 @geindex -gnatwj (gcc)
11487 @table @asis
11489 @item @code{-gnatwj}
11491 `Activate warnings on obsolescent features (Annex J).'
11493 @geindex Features
11494 @geindex obsolescent
11496 @geindex Obsolescent features
11498 If this warning option is activated, then warnings are generated for
11499 calls to subprograms marked with @code{pragma Obsolescent} and
11500 for use of features in Annex J of the Ada Reference Manual. In the
11501 case of Annex J, not all features are flagged. In particular, uses of package
11502 @code{ASCII} are not flagged, since these are very common and
11503 would generate many annoying positive warnings. The default is that
11504 such warnings are not generated.
11506 In addition to the above cases, warnings are also generated for
11507 GNAT features that have been provided in past versions but which
11508 have been superseded (typically by features in the new Ada standard).
11509 For example, @code{pragma Ravenscar} will be flagged since its
11510 function is replaced by @code{pragma Profile(Ravenscar)}, and
11511 @code{pragma Interface_Name} will be flagged since its function
11512 is replaced by @code{pragma Import}.
11514 Note that this warning option functions differently from the
11515 restriction @code{No_Obsolescent_Features} in two respects.
11516 First, the restriction applies only to annex J features.
11517 Second, the restriction does flag uses of package @code{ASCII}.
11518 @end table
11520 @geindex -gnatwJ (gcc)
11523 @table @asis
11525 @item @code{-gnatwJ}
11527 `Suppress warnings on obsolescent features (Annex J).'
11529 This switch disables warnings on use of obsolescent features.
11530 @end table
11532 @geindex -gnatw.j (gcc)
11535 @table @asis
11537 @item @code{-gnatw.j}
11539 `Activate warnings on late declarations of tagged type primitives.'
11541 This switch activates warnings on visible primitives added to a
11542 tagged type after deriving a private extension from it.
11543 @end table
11545 @geindex -gnatw.J (gcc)
11548 @table @asis
11550 @item @code{-gnatw.J}
11552 `Suppress warnings on late declarations of tagged type primitives.'
11554 This switch suppresses warnings on visible primitives added to a
11555 tagged type after deriving a private extension from it.
11556 @end table
11558 @geindex -gnatwk (gcc)
11561 @table @asis
11563 @item @code{-gnatwk}
11565 `Activate warnings on variables that could be constants.'
11567 This switch activates warnings for variables that are initialized but
11568 never modified, and then could be declared constants. The default is that
11569 such warnings are not given.
11570 @end table
11572 @geindex -gnatwK (gcc)
11575 @table @asis
11577 @item @code{-gnatwK}
11579 `Suppress warnings on variables that could be constants.'
11581 This switch disables warnings on variables that could be declared constants.
11582 @end table
11584 @geindex -gnatw.k (gcc)
11587 @table @asis
11589 @item @code{-gnatw.k}
11591 `Activate warnings on redefinition of names in standard.'
11593 This switch activates warnings for declarations that declare a name that
11594 is defined in package Standard. Such declarations can be confusing,
11595 especially since the names in package Standard continue to be directly
11596 visible, meaning that use visibility on such redeclared names does not
11597 work as expected. Names of discriminants and components in records are
11598 not included in this check.
11599 @end table
11601 @geindex -gnatwK (gcc)
11604 @table @asis
11606 @item @code{-gnatw.K}
11608 `Suppress warnings on redefinition of names in standard.'
11610 This switch disables warnings for declarations that declare a name that
11611 is defined in package Standard.
11612 @end table
11614 @geindex -gnatwl (gcc)
11617 @table @asis
11619 @item @code{-gnatwl}
11621 `Activate warnings for elaboration pragmas.'
11623 @geindex Elaboration
11624 @geindex warnings
11626 This switch activates warnings for possible elaboration problems,
11627 including suspicious use
11628 of @code{Elaborate} pragmas, when using the static elaboration model, and
11629 possible situations that may raise @code{Program_Error} when using the
11630 dynamic elaboration model.
11631 See the section in this guide on elaboration checking for further details.
11632 The default is that such warnings
11633 are not generated.
11634 @end table
11636 @geindex -gnatwL (gcc)
11639 @table @asis
11641 @item @code{-gnatwL}
11643 `Suppress warnings for elaboration pragmas.'
11645 This switch suppresses warnings for possible elaboration problems.
11646 @end table
11648 @geindex -gnatw.l (gcc)
11651 @table @asis
11653 @item @code{-gnatw.l}
11655 `List inherited aspects as info messages.'
11657 This switch causes the compiler to list inherited invariants,
11658 preconditions, and postconditions from Type_Invariant’Class, Invariant’Class,
11659 Pre’Class, and Post’Class aspects. Also list inherited subtype predicates.
11660 @end table
11662 @geindex -gnatw.L (gcc)
11665 @table @asis
11667 @item @code{-gnatw.L}
11669 `Suppress listing of inherited aspects as info messages.'
11671 This switch suppresses listing of inherited aspects.
11672 @end table
11674 @geindex -gnatwm (gcc)
11677 @table @asis
11679 @item @code{-gnatwm}
11681 `Activate warnings on modified but unreferenced variables.'
11683 This switch activates warnings for variables that are assigned (using
11684 an initialization value or with one or more assignment statements) but
11685 whose value is never read. The warning is suppressed for volatile
11686 variables and also for variables that are renamings of other variables
11687 or for which an address clause is given.
11688 The default is that these warnings are not given.
11689 @end table
11691 @geindex -gnatwM (gcc)
11694 @table @asis
11696 @item @code{-gnatwM}
11698 `Disable warnings on modified but unreferenced variables.'
11700 This switch disables warnings for variables that are assigned or
11701 initialized, but never read.
11702 @end table
11704 @geindex -gnatw.m (gcc)
11707 @table @asis
11709 @item @code{-gnatw.m}
11711 `Activate warnings on suspicious modulus values.'
11713 This switch activates warnings for modulus values that seem suspicious.
11714 The cases caught are where the size is the same as the modulus (e.g.
11715 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11716 with no size clause. The guess in both cases is that 2**x was intended
11717 rather than x. In addition expressions of the form 2*x for small x
11718 generate a warning (the almost certainly accurate guess being that
11719 2**x was intended). This switch also activates warnings for negative
11720 literal values of a modular type, which are interpreted as large positive
11721 integers after wrap-around. The default is that these warnings are given.
11722 @end table
11724 @geindex -gnatw.M (gcc)
11727 @table @asis
11729 @item @code{-gnatw.M}
11731 `Disable warnings on suspicious modulus values.'
11733 This switch disables warnings for suspicious modulus values.
11734 @end table
11736 @geindex -gnatwn (gcc)
11739 @table @asis
11741 @item @code{-gnatwn}
11743 `Set normal warnings mode.'
11745 This switch sets normal warning mode, in which enabled warnings are
11746 issued and treated as warnings rather than errors. This is the default
11747 mode. the switch @code{-gnatwn} can be used to cancel the effect of
11748 an explicit @code{-gnatws} or
11749 @code{-gnatwe}. It also cancels the effect of the
11750 implicit @code{-gnatwe} that is activated by the
11751 use of @code{-gnatg}.
11752 @end table
11754 @geindex -gnatw.n (gcc)
11756 @geindex Atomic Synchronization
11757 @geindex warnings
11760 @table @asis
11762 @item @code{-gnatw.n}
11764 `Activate warnings on atomic synchronization.'
11766 This switch activates warnings when an access to an atomic variable
11767 requires the generation of atomic synchronization code. These
11768 warnings are off by default.
11769 @end table
11771 @geindex -gnatw.N (gcc)
11774 @table @asis
11776 @item @code{-gnatw.N}
11778 `Suppress warnings on atomic synchronization.'
11780 @geindex Atomic Synchronization
11781 @geindex warnings
11783 This switch suppresses warnings when an access to an atomic variable
11784 requires the generation of atomic synchronization code.
11785 @end table
11787 @geindex -gnatwo (gcc)
11789 @geindex Address Clauses
11790 @geindex warnings
11793 @table @asis
11795 @item @code{-gnatwo}
11797 `Activate warnings on address clause overlays.'
11799 This switch activates warnings for possibly unintended initialization
11800 effects of defining address clauses that cause one variable to overlap
11801 another. The default is that such warnings are generated.
11802 @end table
11804 @geindex -gnatwO (gcc)
11807 @table @asis
11809 @item @code{-gnatwO}
11811 `Suppress warnings on address clause overlays.'
11813 This switch suppresses warnings on possibly unintended initialization
11814 effects of defining address clauses that cause one variable to overlap
11815 another.
11816 @end table
11818 @geindex -gnatw.o (gcc)
11821 @table @asis
11823 @item @code{-gnatw.o}
11825 `Activate warnings on modified but unreferenced out parameters.'
11827 This switch activates warnings for variables that are modified by using
11828 them as actuals for a call to a procedure with an out mode formal, where
11829 the resulting assigned value is never read. It is applicable in the case
11830 where there is more than one out mode formal. If there is only one out
11831 mode formal, the warning is issued by default (controlled by -gnatwu).
11832 The warning is suppressed for volatile
11833 variables and also for variables that are renamings of other variables
11834 or for which an address clause is given.
11835 The default is that these warnings are not given.
11836 @end table
11838 @geindex -gnatw.O (gcc)
11841 @table @asis
11843 @item @code{-gnatw.O}
11845 `Disable warnings on modified but unreferenced out parameters.'
11847 This switch suppresses warnings for variables that are modified by using
11848 them as actuals for a call to a procedure with an out mode formal, where
11849 the resulting assigned value is never read.
11850 @end table
11852 @geindex -gnatwp (gcc)
11854 @geindex Inlining
11855 @geindex warnings
11858 @table @asis
11860 @item @code{-gnatwp}
11862 `Activate warnings on ineffective pragma Inlines.'
11864 This switch activates warnings for failure of front end inlining
11865 (activated by @code{-gnatN}) to inline a particular call. There are
11866 many reasons for not being able to inline a call, including most
11867 commonly that the call is too complex to inline. The default is
11868 that such warnings are not given.
11869 Warnings on ineffective inlining by the gcc back-end can be activated
11870 separately, using the gcc switch -Winline.
11871 @end table
11873 @geindex -gnatwP (gcc)
11876 @table @asis
11878 @item @code{-gnatwP}
11880 `Suppress warnings on ineffective pragma Inlines.'
11882 This switch suppresses warnings on ineffective pragma Inlines. If the
11883 inlining mechanism cannot inline a call, it will simply ignore the
11884 request silently.
11885 @end table
11887 @geindex -gnatw.p (gcc)
11889 @geindex Parameter order
11890 @geindex warnings
11893 @table @asis
11895 @item @code{-gnatw.p}
11897 `Activate warnings on parameter ordering.'
11899 This switch activates warnings for cases of suspicious parameter
11900 ordering when the list of arguments are all simple identifiers that
11901 match the names of the formals, but are in a different order. The
11902 warning is suppressed if any use of named parameter notation is used,
11903 so this is the appropriate way to suppress a false positive (and
11904 serves to emphasize that the “misordering” is deliberate). The
11905 default is that such warnings are not given.
11906 @end table
11908 @geindex -gnatw.P (gcc)
11911 @table @asis
11913 @item @code{-gnatw.P}
11915 `Suppress warnings on parameter ordering.'
11917 This switch suppresses warnings on cases of suspicious parameter
11918 ordering.
11919 @end table
11921 @geindex -gnatw_p (gcc)
11924 @table @asis
11926 @item @code{-gnatw_p}
11928 `Activate warnings for pedantic checks.'
11930 This switch activates warnings for the failure of certain pedantic checks.
11931 The only case currently supported is a check that the subtype_marks given
11932 for corresponding formal parameter and function results in a subprogram
11933 declaration and its body denote the same subtype declaration. The default
11934 is that such warnings are not given.
11935 @end table
11937 @geindex -gnatw_P (gcc)
11940 @table @asis
11942 @item @code{-gnatw_P}
11944 `Suppress warnings for pedantic checks.'
11946 This switch suppresses warnings on violations of pedantic checks.
11947 @end table
11949 @geindex -gnatwq (gcc)
11951 @geindex Parentheses
11952 @geindex warnings
11955 @table @asis
11957 @item @code{-gnatwq}
11959 `Activate warnings on questionable missing parentheses.'
11961 This switch activates warnings for cases where parentheses are not used and
11962 the result is potential ambiguity from a readers point of view. For example
11963 (not a > b) when a and b are modular means ((not a) > b) and very likely the
11964 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11965 quite likely ((-x) mod 5) was intended. In such situations it seems best to
11966 follow the rule of always parenthesizing to make the association clear, and
11967 this warning switch warns if such parentheses are not present. The default
11968 is that these warnings are given.
11969 @end table
11971 @geindex -gnatwQ (gcc)
11974 @table @asis
11976 @item @code{-gnatwQ}
11978 `Suppress warnings on questionable missing parentheses.'
11980 This switch suppresses warnings for cases where the association is not
11981 clear and the use of parentheses is preferred.
11982 @end table
11984 @geindex -gnatw.q (gcc)
11986 @geindex Layout
11987 @geindex warnings
11990 @table @asis
11992 @item @code{-gnatw.q}
11994 `Activate warnings on questionable layout of record types.'
11996 This switch activates warnings for cases where the default layout of
11997 a record type, that is to say the layout of its components in textual
11998 order of the source code, would very likely cause inefficiencies in
11999 the code generated by the compiler, both in terms of space and speed
12000 during execution. One warning is issued for each problematic component
12001 without representation clause in the nonvariant part and then in each
12002 variant recursively, if any.
12004 The purpose of these warnings is neither to prescribe an optimal layout
12005 nor to force the use of representation clauses, but rather to get rid of
12006 the most blatant inefficiencies in the layout. Therefore, the default
12007 layout is matched against the following synthetic ordered layout and
12008 the deviations are flagged on a component-by-component basis:
12011 @itemize *
12013 @item 
12014 first all components or groups of components whose length is fixed
12015 and a multiple of the storage unit,
12017 @item 
12018 then the remaining components whose length is fixed and not a multiple
12019 of the storage unit,
12021 @item 
12022 then the remaining components whose length doesn’t depend on discriminants
12023 (that is to say, with variable but uniform length for all objects),
12025 @item 
12026 then all components whose length depends on discriminants,
12028 @item 
12029 finally the variant part (if any),
12030 @end itemize
12032 for the nonvariant part and for each variant recursively, if any.
12034 The exact wording of the warning depends on whether the compiler is allowed
12035 to reorder the components in the record type or precluded from doing it by
12036 means of pragma @code{No_Component_Reordering}.
12038 The default is that these warnings are not given.
12039 @end table
12041 @geindex -gnatw.Q (gcc)
12044 @table @asis
12046 @item @code{-gnatw.Q}
12048 `Suppress warnings on questionable layout of record types.'
12050 This switch suppresses warnings for cases where the default layout of
12051 a record type would very likely cause inefficiencies.
12052 @end table
12054 @geindex -gnatw_q (gcc)
12057 @table @asis
12059 @item @code{-gnatw_q}
12061 `Activate warnings for ignored equality operators.'
12063 This switch activates warnings for a user-defined “=” function that does
12064 not compose (i.e. is ignored for a predefined “=” for a composite type
12065 containing a component whose type has the user-defined “=” as
12066 primitive). Note that the user-defined “=” must be a primitive operator
12067 in order to trigger the warning.
12068 See RM-4.5.2(14/3-15/5, 21, 24/3, 32.1/1)
12069 for the exact Ada rules on composability of “=”.
12071 The default is that these warnings are not given.
12072 @end table
12074 @geindex -gnatw_Q (gcc)
12077 @table @asis
12079 @item @code{-gnatw_Q}
12081 `Suppress warnings for ignored equality operators.'
12082 @end table
12084 @geindex -gnatwr (gcc)
12087 @table @asis
12089 @item @code{-gnatwr}
12091 `Activate warnings on redundant constructs.'
12093 This switch activates warnings for redundant constructs. The following
12094 is the current list of constructs regarded as redundant:
12097 @itemize *
12099 @item 
12100 Assignment of an item to itself.
12102 @item 
12103 Type conversion that converts an expression to its own type.
12105 @item 
12106 Use of the attribute @code{Base} where @code{typ'Base} is the same
12107 as @code{typ}.
12109 @item 
12110 Use of pragma @code{Pack} when all components are placed by a record
12111 representation clause.
12113 @item 
12114 Exception handler containing only a reraise statement (raise with no
12115 operand) which has no effect.
12117 @item 
12118 Use of the operator abs on an operand that is known at compile time
12119 to be non-negative
12121 @item 
12122 Comparison of an object or (unary or binary) operation of boolean type to
12123 an explicit True value.
12125 @item 
12126 Import of parent package.
12127 @end itemize
12129 The default is that warnings for redundant constructs are not given.
12130 @end table
12132 @geindex -gnatwR (gcc)
12135 @table @asis
12137 @item @code{-gnatwR}
12139 `Suppress warnings on redundant constructs.'
12141 This switch suppresses warnings for redundant constructs.
12142 @end table
12144 @geindex -gnatw.r (gcc)
12147 @table @asis
12149 @item @code{-gnatw.r}
12151 `Activate warnings for object renaming function.'
12153 This switch activates warnings for an object renaming that renames a
12154 function call, which is equivalent to a constant declaration (as
12155 opposed to renaming the function itself).  The default is that these
12156 warnings are given.
12157 @end table
12159 @geindex -gnatw.R (gcc)
12162 @table @asis
12164 @item @code{-gnatw.R}
12166 `Suppress warnings for object renaming function.'
12168 This switch suppresses warnings for object renaming function.
12169 @end table
12171 @geindex -gnatw_r (gcc)
12174 @table @asis
12176 @item @code{-gnatw_r}
12178 `Activate warnings for out-of-order record representation clauses.'
12180 This switch activates warnings for record representation clauses,
12181 if the order of component declarations, component clauses,
12182 and bit-level layout do not all agree.
12183 The default is that these warnings are not given.
12184 @end table
12186 @geindex -gnatw_R (gcc)
12189 @table @asis
12191 @item @code{-gnatw_R}
12193 `Suppress warnings for out-of-order record representation clauses.'
12194 @end table
12196 @geindex -gnatws (gcc)
12199 @table @asis
12201 @item @code{-gnatws}
12203 `Suppress all warnings.'
12205 This switch completely suppresses the
12206 output of all warning messages from the GNAT front end, including
12207 both warnings that can be controlled by switches described in this
12208 section, and those that are normally given unconditionally. The
12209 effect of this suppress action can only be cancelled by a subsequent
12210 use of the switch @code{-gnatwn}.
12212 Note that switch @code{-gnatws} does not suppress
12213 warnings from the @code{gcc} back end.
12214 To suppress these back end warnings as well, use the switch @code{-w}
12215 in addition to @code{-gnatws}. Also this switch has no effect on the
12216 handling of style check messages.
12217 @end table
12219 @geindex -gnatw.s (gcc)
12221 @geindex Record Representation (component sizes)
12224 @table @asis
12226 @item @code{-gnatw.s}
12228 `Activate warnings on overridden size clauses.'
12230 This switch activates warnings on component clauses in record
12231 representation clauses where the length given overrides that
12232 specified by an explicit size clause for the component type. A
12233 warning is similarly given in the array case if a specified
12234 component size overrides an explicit size clause for the array
12235 component type.
12236 @end table
12238 @geindex -gnatw.S (gcc)
12241 @table @asis
12243 @item @code{-gnatw.S}
12245 `Suppress warnings on overridden size clauses.'
12247 This switch suppresses warnings on component clauses in record
12248 representation clauses that override size clauses, and similar
12249 warnings when an array component size overrides a size clause.
12250 @end table
12252 @geindex -gnatw_s (gcc)
12254 @geindex Warnings
12257 @table @asis
12259 @item @code{-gnatw_s}
12261 `Activate warnings on ineffective predicate tests.'
12263 This switch activates warnings on Static_Predicate aspect
12264 specifications that test for values that do not belong to
12265 the parent subtype. Not all such ineffective tests are detected.
12266 @end table
12268 @geindex -gnatw_S (gcc)
12271 @table @asis
12273 @item @code{-gnatw_S}
12275 `Suppress warnings on ineffective predicate tests.'
12277 This switch suppresses warnings on Static_Predicate aspect
12278 specifications that test for values that do not belong to
12279 the parent subtype.
12280 @end table
12282 @geindex -gnatwt (gcc)
12284 @geindex Deactivated code
12285 @geindex warnings
12287 @geindex Deleted code
12288 @geindex warnings
12291 @table @asis
12293 @item @code{-gnatwt}
12295 `Activate warnings for tracking of deleted conditional code.'
12297 This switch activates warnings for tracking of code in conditionals (IF and
12298 CASE statements) that is detected to be dead code which cannot be executed, and
12299 which is removed by the front end. This warning is off by default. This may be
12300 useful for detecting deactivated code in certified applications.
12301 @end table
12303 @geindex -gnatwT (gcc)
12306 @table @asis
12308 @item @code{-gnatwT}
12310 `Suppress warnings for tracking of deleted conditional code.'
12312 This switch suppresses warnings for tracking of deleted conditional code.
12313 @end table
12315 @geindex -gnatw.t (gcc)
12318 @table @asis
12320 @item @code{-gnatw.t}
12322 `Activate warnings on suspicious contracts.'
12324 This switch activates warnings on suspicious contracts. This includes
12325 warnings on suspicious postconditions (whether a pragma @code{Postcondition} or a
12326 @code{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
12327 @code{Contract_Cases}). A function postcondition or contract case is suspicious
12328 when no postcondition or contract case for this function mentions the result
12329 of the function.  A procedure postcondition or contract case is suspicious
12330 when it only refers to the pre-state of the procedure, because in that case
12331 it should rather be expressed as a precondition. This switch also controls
12332 warnings on suspicious cases of expressions typically found in contracts like
12333 quantified expressions and uses of Update attribute. The default is that such
12334 warnings are generated.
12335 @end table
12337 @geindex -gnatw.T (gcc)
12340 @table @asis
12342 @item @code{-gnatw.T}
12344 `Suppress warnings on suspicious contracts.'
12346 This switch suppresses warnings on suspicious contracts.
12347 @end table
12349 @geindex -gnatwu (gcc)
12352 @table @asis
12354 @item @code{-gnatwu}
12356 `Activate warnings on unused entities.'
12358 This switch activates warnings to be generated for entities that
12359 are declared but not referenced, and for units that are `with'ed
12360 and not
12361 referenced. In the case of packages, a warning is also generated if
12362 no entities in the package are referenced. This means that if a with’ed
12363 package is referenced but the only references are in @code{use}
12364 clauses or @code{renames}
12365 declarations, a warning is still generated. A warning is also generated
12366 for a generic package that is `with'ed but never instantiated.
12367 In the case where a package or subprogram body is compiled, and there
12368 is a `with' on the corresponding spec
12369 that is only referenced in the body,
12370 a warning is also generated, noting that the
12371 `with' can be moved to the body. The default is that
12372 such warnings are not generated.
12373 This switch also activates warnings on unreferenced formals
12374 (it includes the effect of @code{-gnatwf}).
12375 @end table
12377 @geindex -gnatwU (gcc)
12380 @table @asis
12382 @item @code{-gnatwU}
12384 `Suppress warnings on unused entities.'
12386 This switch suppresses warnings for unused entities and packages.
12387 It also turns off warnings on unreferenced formals (and thus includes
12388 the effect of @code{-gnatwF}).
12389 @end table
12391 @geindex -gnatw.u (gcc)
12394 @table @asis
12396 @item @code{-gnatw.u}
12398 `Activate warnings on unordered enumeration types.'
12400 This switch causes enumeration types to be considered as conceptually
12401 unordered, unless an explicit pragma @code{Ordered} is given for the type.
12402 The effect is to generate warnings in clients that use explicit comparisons
12403 or subranges, since these constructs both treat objects of the type as
12404 ordered. (A `client' is defined as a unit that is other than the unit in
12405 which the type is declared, or its body or subunits.) Please refer to
12406 the description of pragma @code{Ordered} in the
12407 @cite{GNAT Reference Manual} for further details.
12408 The default is that such warnings are not generated.
12409 @end table
12411 @geindex -gnatw.U (gcc)
12414 @table @asis
12416 @item @code{-gnatw.U}
12418 `Deactivate warnings on unordered enumeration types.'
12420 This switch causes all enumeration types to be considered as ordered, so
12421 that no warnings are given for comparisons or subranges for any type.
12422 @end table
12424 @geindex -gnatwv (gcc)
12426 @geindex Unassigned variable warnings
12429 @table @asis
12431 @item @code{-gnatwv}
12433 `Activate warnings on unassigned variables.'
12435 This switch activates warnings for access to variables which
12436 may not be properly initialized. The default is that
12437 such warnings are generated. This switch will also be emitted when
12438 initializing an array or record object via the following aggregate:
12440 @example
12441 Array_Or_Record : XXX := (others => <>);
12442 @end example
12444 unless the relevant type fully initializes all components.
12445 @end table
12447 @geindex -gnatwV (gcc)
12450 @table @asis
12452 @item @code{-gnatwV}
12454 `Suppress warnings on unassigned variables.'
12456 This switch suppresses warnings for access to variables which
12457 may not be properly initialized.
12458 @end table
12460 @geindex -gnatw.v (gcc)
12462 @geindex bit order warnings
12465 @table @asis
12467 @item @code{-gnatw.v}
12469 `Activate warnings for non-default bit order.'
12471 This switch activates warning messages about the effects of non-default
12472 bit-order on records to which a component clause is applied. The effect of
12473 specifying non-default bit ordering is a bit subtle
12474 (and changed with Ada 2005), so these messages, which are given by default,
12475 are useful in understanding the exact consequences of using this feature.
12476 @end table
12478 @geindex -gnatw.V (gcc)
12481 @table @asis
12483 @item @code{-gnatw.V}
12485 `Suppress warnings for non-default bit order.'
12487 This switch suppresses warnings for the effects of specifying
12488 non-default bit order on record components with component clauses.
12489 @end table
12491 @geindex -gnatww (gcc)
12493 @geindex String indexing warnings
12496 @table @asis
12498 @item @code{-gnatww}
12500 `Activate warnings on wrong low bound assumption.'
12502 This switch activates warnings for indexing an unconstrained string parameter
12503 with a literal or S’Length. This is a case where the code is assuming that the
12504 low bound is one, which is in general not true (for example when a slice is
12505 passed). The default is that such warnings are generated.
12506 @end table
12508 @geindex -gnatwW (gcc)
12511 @table @asis
12513 @item @code{-gnatwW}
12515 `Suppress warnings on wrong low bound assumption.'
12517 This switch suppresses warnings for indexing an unconstrained string parameter
12518 with a literal or S’Length. Note that this warning can also be suppressed
12519 in a particular case by adding an assertion that the lower bound is 1,
12520 as shown in the following example:
12522 @example
12523 procedure K (S : String) is
12524    pragma Assert (S'First = 1);
12525    ...
12526 @end example
12527 @end table
12529 @geindex -gnatw.w (gcc)
12531 @geindex Warnings Off control
12534 @table @asis
12536 @item @code{-gnatw.w}
12538 `Activate warnings on Warnings Off pragmas.'
12540 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
12541 where either the pragma is entirely useless (because it suppresses no
12542 warnings), or it could be replaced by @code{pragma Unreferenced} or
12543 @code{pragma Unmodified}.
12544 Also activates warnings for the case of
12545 Warnings (Off, String), where either there is no matching
12546 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12547 The default is that these warnings are not given.
12548 @end table
12550 @geindex -gnatw.W (gcc)
12553 @table @asis
12555 @item @code{-gnatw.W}
12557 `Suppress warnings on unnecessary Warnings Off pragmas.'
12559 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
12560 @end table
12562 @geindex -gnatwx (gcc)
12564 @geindex Export/Import pragma warnings
12567 @table @asis
12569 @item @code{-gnatwx}
12571 `Activate warnings on Export/Import pragmas.'
12573 This switch activates warnings on Export/Import pragmas when
12574 the compiler detects a possible conflict between the Ada and
12575 foreign language calling sequences. For example, the use of
12576 default parameters in a convention C procedure is dubious
12577 because the C compiler cannot supply the proper default, so
12578 a warning is issued. The default is that such warnings are
12579 generated.
12580 @end table
12582 @geindex -gnatwX (gcc)
12585 @table @asis
12587 @item @code{-gnatwX}
12589 `Suppress warnings on Export/Import pragmas.'
12591 This switch suppresses warnings on Export/Import pragmas.
12592 The sense of this is that you are telling the compiler that
12593 you know what you are doing in writing the pragma, and it
12594 should not complain at you.
12595 @end table
12597 @geindex -gnatw.x (gcc)
12600 @table @asis
12602 @item @code{-gnatw.x}
12604 `Activate warnings for No_Exception_Propagation mode.'
12606 This switch activates warnings for exception usage when pragma Restrictions
12607 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
12608 explicit exception raises which are not covered by a local handler, and for
12609 exception handlers which do not cover a local raise. The default is that
12610 these warnings are given for units that contain exception handlers.
12612 @item @code{-gnatw.X}
12614 `Disable warnings for No_Exception_Propagation mode.'
12616 This switch disables warnings for exception usage when pragma Restrictions
12617 (No_Exception_Propagation) is in effect.
12618 @end table
12620 @geindex -gnatwy (gcc)
12622 @geindex Ada compatibility issues warnings
12625 @table @asis
12627 @item @code{-gnatwy}
12629 `Activate warnings for Ada compatibility issues.'
12631 For the most part, newer versions of Ada are upwards compatible
12632 with older versions. For example, Ada 2005 programs will almost
12633 always work when compiled as Ada 2012.
12634 However there are some exceptions (for example the fact that
12635 @code{some} is now a reserved word in Ada 2012). This
12636 switch activates several warnings to help in identifying
12637 and correcting such incompatibilities. The default is that
12638 these warnings are generated. Note that at one point Ada 2005
12639 was called Ada 0Y, hence the choice of character.
12640 @end table
12642 @geindex -gnatwY (gcc)
12644 @geindex Ada compatibility issues warnings
12647 @table @asis
12649 @item @code{-gnatwY}
12651 `Disable warnings for Ada compatibility issues.'
12653 This switch suppresses the warnings intended to help in identifying
12654 incompatibilities between Ada language versions.
12655 @end table
12657 @geindex -gnatw.y (gcc)
12659 @geindex Package spec needing body
12662 @table @asis
12664 @item @code{-gnatw.y}
12666 `Activate information messages for why package spec needs body.'
12668 There are a number of cases in which a package spec needs a body.
12669 For example, the use of pragma Elaborate_Body, or the declaration
12670 of a procedure specification requiring a completion. This switch
12671 causes information messages to be output showing why a package
12672 specification requires a body. This can be useful in the case of
12673 a large package specification which is unexpectedly requiring a
12674 body. The default is that such information messages are not output.
12675 @end table
12677 @geindex -gnatw.Y (gcc)
12679 @geindex No information messages for why package spec needs body
12682 @table @asis
12684 @item @code{-gnatw.Y}
12686 `Disable information messages for why package spec needs body.'
12688 This switch suppresses the output of information messages showing why
12689 a package specification needs a body.
12690 @end table
12692 @geindex -gnatwz (gcc)
12694 @geindex Unchecked_Conversion warnings
12697 @table @asis
12699 @item @code{-gnatwz}
12701 `Activate warnings on unchecked conversions.'
12703 This switch activates warnings for unchecked conversions
12704 where the types are known at compile time to have different
12705 sizes. The default is that such warnings are generated. Warnings are also
12706 generated for subprogram pointers with different conventions.
12707 @end table
12709 @geindex -gnatwZ (gcc)
12712 @table @asis
12714 @item @code{-gnatwZ}
12716 `Suppress warnings on unchecked conversions.'
12718 This switch suppresses warnings for unchecked conversions
12719 where the types are known at compile time to have different
12720 sizes or conventions.
12721 @end table
12723 @geindex -gnatw.z (gcc)
12725 @geindex Size/Alignment warnings
12728 @table @asis
12730 @item @code{-gnatw.z}
12732 `Activate warnings for size not a multiple of alignment.'
12734 This switch activates warnings for cases of array and record types
12735 with specified @code{Size} and @code{Alignment} attributes where the
12736 size is not a multiple of the alignment, resulting in an object
12737 size that is greater than the specified size. The default
12738 is that such warnings are generated.
12739 @end table
12741 @geindex -gnatw.Z (gcc)
12743 @geindex Size/Alignment warnings
12746 @table @asis
12748 @item @code{-gnatw.Z}
12750 `Suppress warnings for size not a multiple of alignment.'
12752 This switch suppresses warnings for cases of array and record types
12753 with specified @code{Size} and @code{Alignment} attributes where the
12754 size is not a multiple of the alignment, resulting in an object
12755 size that is greater than the specified size. The warning can also
12756 be suppressed by giving an explicit @code{Object_Size} value.
12757 @end table
12759 @geindex -Wunused (gcc)
12762 @table @asis
12764 @item @code{-Wunused}
12766 The warnings controlled by the @code{-gnatw} switch are generated by
12767 the front end of the compiler. The GCC back end can provide
12768 additional warnings and they are controlled by the @code{-W} switch.
12769 For example, @code{-Wunused} activates back end
12770 warnings for entities that are declared but not referenced.
12771 @end table
12773 @geindex -Wuninitialized (gcc)
12776 @table @asis
12778 @item @code{-Wuninitialized}
12780 Similarly, @code{-Wuninitialized} activates
12781 the back end warning for uninitialized variables. This switch must be
12782 used in conjunction with an optimization level greater than zero.
12783 @end table
12785 @geindex -Wstack-usage (gcc)
12788 @table @asis
12790 @item @code{-Wstack-usage=`len'}
12792 Warn if the stack usage of a subprogram might be larger than @code{len} bytes.
12793 See @ref{e8,,Static Stack Usage Analysis} for details.
12794 @end table
12796 @geindex -Wall (gcc)
12799 @table @asis
12801 @item @code{-Wall}
12803 This switch enables most warnings from the GCC back end.
12804 The code generator detects a number of warning situations that are missed
12805 by the GNAT front end, and this switch can be used to activate them.
12806 The use of this switch also sets the default front-end warning mode to
12807 @code{-gnatwa}, that is, most front-end warnings are activated as well.
12808 @end table
12810 @geindex -w (gcc)
12813 @table @asis
12815 @item @code{-w}
12817 Conversely, this switch suppresses warnings from the GCC back end.
12818 The use of this switch also sets the default front-end warning mode to
12819 @code{-gnatws}, that is, front-end warnings are suppressed as well.
12820 @end table
12822 @geindex -Werror (gcc)
12825 @table @asis
12827 @item @code{-Werror}
12829 This switch causes warnings from the GCC back end to be treated as
12830 errors.  The warning string still appears, but the warning messages are
12831 counted as errors, and prevent the generation of an object file.
12832 The use of this switch also sets the default front-end warning mode to
12833 @code{-gnatwe}, that is, front-end warning messages and style check
12834 messages are treated as errors as well.
12835 @end table
12837 A string of warning parameters can be used in the same parameter. For example:
12839 @example
12840 -gnatwaGe
12841 @end example
12843 will turn on all optional warnings except for unrecognized pragma warnings,
12844 and also specify that warnings should be treated as errors.
12846 When no switch @code{-gnatw} is used, this is equivalent to:
12848 @quotation
12851 @itemize *
12853 @item 
12854 @code{-gnatw.a}
12856 @item 
12857 @code{-gnatwB}
12859 @item 
12860 @code{-gnatw.b}
12862 @item 
12863 @code{-gnatwC}
12865 @item 
12866 @code{-gnatw.C}
12868 @item 
12869 @code{-gnatwD}
12871 @item 
12872 @code{-gnatw.D}
12874 @item 
12875 @code{-gnatwF}
12877 @item 
12878 @code{-gnatw.F}
12880 @item 
12881 @code{-gnatwg}
12883 @item 
12884 @code{-gnatwH}
12886 @item 
12887 @code{-gnatw.H}
12889 @item 
12890 @code{-gnatwi}
12892 @item 
12893 @code{-gnatwJ}
12895 @item 
12896 @code{-gnatw.J}
12898 @item 
12899 @code{-gnatwK}
12901 @item 
12902 @code{-gnatw.K}
12904 @item 
12905 @code{-gnatwL}
12907 @item 
12908 @code{-gnatw.L}
12910 @item 
12911 @code{-gnatwM}
12913 @item 
12914 @code{-gnatw.m}
12916 @item 
12917 @code{-gnatwn}
12919 @item 
12920 @code{-gnatw.N}
12922 @item 
12923 @code{-gnatwo}
12925 @item 
12926 @code{-gnatw.O}
12928 @item 
12929 @code{-gnatwP}
12931 @item 
12932 @code{-gnatw.P}
12934 @item 
12935 @code{-gnatwq}
12937 @item 
12938 @code{-gnatw.Q}
12940 @item 
12941 @code{-gnatwR}
12943 @item 
12944 @code{-gnatw.R}
12946 @item 
12947 @code{-gnatw.S}
12949 @item 
12950 @code{-gnatwT}
12952 @item 
12953 @code{-gnatw.t}
12955 @item 
12956 @code{-gnatwU}
12958 @item 
12959 @code{-gnatw.U}
12961 @item 
12962 @code{-gnatwv}
12964 @item 
12965 @code{-gnatw.v}
12967 @item 
12968 @code{-gnatww}
12970 @item 
12971 @code{-gnatw.W}
12973 @item 
12974 @code{-gnatwx}
12976 @item 
12977 @code{-gnatw.X}
12979 @item 
12980 @code{-gnatwy}
12982 @item 
12983 @code{-gnatw.Y}
12985 @item 
12986 @code{-gnatwz}
12988 @item 
12989 @code{-gnatw.z}
12990 @end itemize
12991 @end quotation
12993 @node Info message Control,Debugging and Assertion Control,Warning Message Control,Compiler Switches
12994 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-and-assertion-control}@anchor{f3}@anchor{gnat_ugn/building_executable_programs_with_gnat info-message-control}@anchor{f4}
12995 @subsection Info message Control
12998 In addition to the warning messages, the compiler can also generate info
12999 messages. In order to control the generation of these messages, the following
13000 switch is provided:
13003 @table @asis
13005 @item @code{-gnatis}
13007 `Suppress all info messages.'
13009 This switch completely suppresses the output of all info messages from the
13010 GNAT front end.
13011 @end table
13013 @node Debugging and Assertion Control,Validity Checking,Info message Control,Compiler Switches
13014 @anchor{gnat_ugn/building_executable_programs_with_gnat id16}@anchor{f5}
13015 @subsection Debugging and Assertion Control
13018 @geindex -gnata (gcc)
13021 @table @asis
13023 @item @code{-gnata}
13025 @geindex Assert
13027 @geindex Debug
13029 @geindex Assertions
13031 @geindex Precondition
13033 @geindex Postcondition
13035 @geindex Type invariants
13037 @geindex Subtype predicates
13039 The @code{-gnata} option is equivalent to the following @code{Assertion_Policy} pragma:
13041 @example
13042 pragma Assertion_Policy (Check);
13043 @end example
13045 Which is a shorthand for:
13047 @example
13048 pragma Assertion_Policy
13049 --  Ada RM assertion pragmas
13050   (Assert                    => Check,
13051    Static_Predicate          => Check,
13052    Dynamic_Predicate         => Check,
13053    Pre                       => Check,
13054    Pre'Class                 => Check,
13055    Post                      => Check,
13056    Post'Class                => Check,
13057    Type_Invariant            => Check,
13058    Type_Invariant'Class      => Check,
13059    Default_Initial_Condition => Check,
13060 --  GNAT specific assertion pragmas
13061    Assert_And_Cut            => Check,
13062    Assume                    => Check,
13063    Contract_Cases            => Check,
13064    Debug                     => Check,
13065    Ghost                     => Check,
13066    Initial_Condition         => Check,
13067    Loop_Invariant            => Check,
13068    Loop_Variant              => Check,
13069    Postcondition             => Check,
13070    Precondition              => Check,
13071    Predicate                 => Check,
13072    Refined_Post              => Check,
13073    Subprogram_Variant        => Check);
13074 @end example
13076 The pragmas @code{Assert} and @code{Debug} normally have no effect and
13077 are ignored. This switch, where @code{a} stands for ‘assert’, causes
13078 pragmas @code{Assert} and @code{Debug} to be activated. This switch also
13079 causes preconditions, postconditions, subtype predicates, and
13080 type invariants to be activated.
13082 The pragmas have the form:
13084 @example
13085 pragma Assert (<Boolean-expression> [, <static-string-expression>])
13086 pragma Debug (<procedure call>)
13087 pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
13088 pragma Predicate (<type-local-name>, <Boolean-expression>)
13089 pragma Precondition (<Boolean-expression>, <string-expression>)
13090 pragma Postcondition (<Boolean-expression>, <string-expression>)
13091 @end example
13093 The aspects have the form:
13095 @example
13096 with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
13097   => <Boolean-expression>;
13098 @end example
13100 The @code{Assert} pragma causes @code{Boolean-expression} to be tested.
13101 If the result is @code{True}, the pragma has no effect (other than
13102 possible side effects from evaluating the expression). If the result is
13103 @code{False}, the exception @code{Assert_Failure} declared in the package
13104 @code{System.Assertions} is raised (passing @code{static-string-expression}, if
13105 present, as the message associated with the exception). If no string
13106 expression is given, the default is a string containing the file name and
13107 line number of the pragma.
13109 The @code{Debug} pragma causes @code{procedure} to be called. Note that
13110 @code{pragma Debug} may appear within a declaration sequence, allowing
13111 debugging procedures to be called between declarations.
13113 For the aspect specification, the @code{Boolean-expression} is evaluated.
13114 If the result is @code{True}, the aspect has no effect. If the result
13115 is @code{False}, the exception @code{Assert_Failure} is raised.
13116 @end table
13118 @node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
13119 @anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{e9}
13120 @subsection Validity Checking
13123 @geindex Validity Checking
13125 The Ada Reference Manual defines the concept of invalid values (see
13126 RM 13.9.1). The primary source of invalid values is uninitialized
13127 variables. A scalar variable that is left uninitialized may contain
13128 an invalid value; the concept of invalid does not apply to access or
13129 composite types.
13131 It is an error to read an invalid value, but the RM does not require
13132 run-time checks to detect such errors, except for some minimal
13133 checking to prevent erroneous execution (i.e. unpredictable
13134 behavior). This corresponds to the @code{-gnatVd} switch below,
13135 which is the default. For example, by default, if the expression of a
13136 case statement is invalid, it will raise Constraint_Error rather than
13137 causing a wild jump, and if an array index on the left-hand side of an
13138 assignment is invalid, it will raise Constraint_Error rather than
13139 overwriting an arbitrary memory location.
13141 The @code{-gnatVa} may be used to enable additional validity checks,
13142 which are not required by the RM. These checks are often very
13143 expensive (which is why the RM does not require them). These checks
13144 are useful in tracking down uninitialized variables, but they are
13145 not usually recommended for production builds, and in particular
13146 we do not recommend using these extra validity checking options in
13147 combination with optimization, since this can confuse the optimizer.
13148 If performance is a consideration, leading to the need to optimize,
13149 then the validity checking options should not be used.
13151 The other @code{-gnatV`x'} switches below allow finer-grained
13152 control; you can enable whichever validity checks you desire. However,
13153 for most debugging purposes, @code{-gnatVa} is sufficient, and the
13154 default @code{-gnatVd} (i.e. standard Ada behavior) is usually
13155 sufficient for non-debugging use.
13157 The @code{-gnatB} switch tells the compiler to assume that all
13158 values are valid (that is, within their declared subtype range)
13159 except in the context of a use of the Valid attribute. This means
13160 the compiler can generate more efficient code, since the range
13161 of values is better known at compile time. However, an uninitialized
13162 variable can cause wild jumps and memory corruption in this mode.
13164 The @code{-gnatV`x'} switch allows control over the validity
13165 checking mode as described below.
13166 The @code{x} argument is a string of letters that
13167 indicate validity checks that are performed or not performed in addition
13168 to the default checks required by Ada as described above.
13170 @geindex -gnatVa (gcc)
13173 @table @asis
13175 @item @code{-gnatVa}
13177 `All validity checks.'
13179 All validity checks are turned on.
13180 That is, @code{-gnatVa} is
13181 equivalent to @code{gnatVcdefimoprst}.
13182 @end table
13184 @geindex -gnatVc (gcc)
13187 @table @asis
13189 @item @code{-gnatVc}
13191 `Validity checks for copies.'
13193 The right-hand side of assignments, and the (explicit) initializing values
13194 of object declarations are validity checked.
13195 @end table
13197 @geindex -gnatVd (gcc)
13200 @table @asis
13202 @item @code{-gnatVd}
13204 `Default (RM) validity checks.'
13206 Some validity checks are required by Ada (see RM 13.9.1 (9-11)); these
13207 (and only these) validity checks are enabled by default.
13208 For case statements (and case expressions) that lack a “when others =>”
13209 choice, a check is made that the value of the selector expression
13210 belongs to its nominal subtype. If it does not, Constraint_Error is raised.
13211 For assignments to array components (and for indexed components in some
13212 other contexts), a check is made that each index expression belongs to the
13213 corresponding index subtype. If it does not, Constraint_Error is raised.
13214 Both these validity checks may be turned off using switch @code{-gnatVD}.
13215 They are turned on by default. If @code{-gnatVD} is specified, a subsequent
13216 switch @code{-gnatVd} will leave the checks turned on.
13217 Switch @code{-gnatVD} should be used only if you are sure that all such
13218 expressions have valid values. If you use this switch and invalid values
13219 are present, then the program is erroneous, and wild jumps or memory
13220 overwriting may occur.
13221 @end table
13223 @geindex -gnatVe (gcc)
13226 @table @asis
13228 @item @code{-gnatVe}
13230 `Validity checks for scalar components.'
13232 In the absence of this switch, assignments to scalar components of
13233 enclosing record or array objects are not validity checked, even if
13234 validity checks for assignments generally (@code{-gnatVc}) are turned on.
13235 Specifying this switch enables such checks.
13236 This switch has no effect if the @code{-gnatVc} switch is not specified.
13237 @end table
13239 @geindex -gnatVf (gcc)
13242 @table @asis
13244 @item @code{-gnatVf}
13246 `Validity checks for floating-point values.'
13248 Specifying this switch enables validity checking for floating-point
13249 values in the same contexts where validity checking is enabled for
13250 other scalar values.
13251 In the absence of this switch, validity checking is not performed for
13252 floating-point values. This takes precedence over other statements about
13253 performing validity checking for scalar objects in various scenarios.
13254 One way to look at it is that if this switch is not set, then whenever
13255 any of the other rules in this section use the word “scalar” they
13256 really mean “scalar and not floating-point”.
13257 If @code{-gnatVf} is specified, then validity checking also applies
13258 for floating-point values, and NaNs and infinities are considered invalid,
13259 as well as out-of-range values for constrained types. The exact contexts
13260 in which floating-point values are checked depends on the setting of other
13261 options. For example, @code{-gnatVif} or @code{-gnatVfi}
13262 (the order does not matter) specifies that floating-point parameters of mode
13263 @code{in} should be validity checked.
13264 @end table
13266 @geindex -gnatVi (gcc)
13269 @table @asis
13271 @item @code{-gnatVi}
13273 `Validity checks for `@w{`}in`@w{`} mode parameters.'
13275 Arguments for parameters of mode @code{in} are validity checked in function
13276 and procedure calls at the point of call.
13277 @end table
13279 @geindex -gnatVm (gcc)
13282 @table @asis
13284 @item @code{-gnatVm}
13286 `Validity checks for `@w{`}in out`@w{`} mode parameters.'
13288 Arguments for parameters of mode @code{in out} are validity checked in
13289 procedure calls at the point of call. The @code{'m'} here stands for
13290 modify, since this concerns parameters that can be modified by the call.
13291 Note that there is no specific option to test @code{out} parameters,
13292 but any reference within the subprogram will be tested in the usual
13293 manner, and if an invalid value is copied back, any reference to it
13294 will be subject to validity checking.
13295 @end table
13297 @geindex -gnatVn (gcc)
13300 @table @asis
13302 @item @code{-gnatVn}
13304 `No validity checks.'
13306 This switch turns off all validity checking, including the default checking
13307 for case statements and left hand side subscripts. Note that the use of
13308 the switch @code{-gnatp} suppresses all run-time checks, including
13309 validity checks, and thus implies @code{-gnatVn}. When this switch
13310 is used, it cancels any other @code{-gnatV} previously issued.
13311 @end table
13313 @geindex -gnatVo (gcc)
13316 @table @asis
13318 @item @code{-gnatVo}
13320 `Validity checks for operator and attribute operands.'
13322 Scalar arguments for predefined operators and for attributes are
13323 validity checked.
13324 This includes all operators in package @code{Standard},
13325 the shift operators defined as intrinsic in package @code{Interfaces}
13326 and operands for attributes such as @code{Pos}. Checks are also made
13327 on individual component values for composite comparisons, and on the
13328 expressions in type conversions and qualified expressions. Checks are
13329 also made on explicit ranges using @code{..} (e.g., slices, loops etc).
13330 @end table
13332 @geindex -gnatVp (gcc)
13335 @table @asis
13337 @item @code{-gnatVp}
13339 `Validity checks for parameters.'
13341 This controls the treatment of formal parameters within a subprogram (as
13342 opposed to @code{-gnatVi} and @code{-gnatVm}, which control validity
13343 testing of actual parameters of a call). If either of these call options is
13344 specified, then normally an assumption is made within a subprogram that
13345 the validity of any incoming formal parameters of the corresponding mode(s)
13346 has already been checked at the point of call and does not need rechecking.
13347 If @code{-gnatVp} is set, then this assumption is not made and so their
13348 validity may be checked (or rechecked) within the subprogram. If neither of
13349 the two call-related options is specified, then this switch has no effect.
13350 @end table
13352 @geindex -gnatVr (gcc)
13355 @table @asis
13357 @item @code{-gnatVr}
13359 `Validity checks for function returns.'
13361 The expression in simple @code{return} statements in functions is validity
13362 checked.
13363 @end table
13365 @geindex -gnatVs (gcc)
13368 @table @asis
13370 @item @code{-gnatVs}
13372 `Validity checks for subscripts.'
13374 All subscript expressions are checked for validity, whatever context
13375 they occur in (in default mode some subscripts are not validity checked;
13376 for example, validity checking may be omitted in some cases involving
13377 a read of a component of an array).
13378 @end table
13380 @geindex -gnatVt (gcc)
13383 @table @asis
13385 @item @code{-gnatVt}
13387 `Validity checks for tests.'
13389 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
13390 statements are checked, as well as guard expressions in entry calls.
13391 @end table
13393 The @code{-gnatV} switch may be followed by a string of letters
13394 to turn on a series of validity checking options.
13395 For example, @code{-gnatVcr}
13396 specifies that in addition to the default validity checking, copies and
13397 function return expressions are to be validity checked.
13398 In order to make it easier to specify the desired combination of effects,
13399 the upper case letters @code{CDFIMORST} may
13400 be used to turn off the corresponding lower case option.
13401 Thus @code{-gnatVaM} turns on all validity checking options except for
13402 checking of @code{in out} parameters.
13404 The specification of additional validity checking generates extra code (and
13405 in the case of @code{-gnatVa} the code expansion can be substantial).
13406 However, these additional checks can be very useful in detecting
13407 uninitialized variables, incorrect use of unchecked conversion, and other
13408 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
13409 is useful in conjunction with the extra validity checking, since this
13410 ensures that wherever possible uninitialized variables have invalid values.
13412 See also the pragma @code{Validity_Checks} which allows modification of
13413 the validity checking mode at the program source level, and also allows for
13414 temporary disabling of validity checks.
13416 @node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
13417 @anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{f7}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{ee}
13418 @subsection Style Checking
13421 @geindex Style checking
13423 @geindex -gnaty (gcc)
13425 The @code{-gnaty} switch causes the compiler to
13426 enforce specified style rules. A limited set of style rules has been used
13427 in writing the GNAT sources themselves. This switch allows user programs
13428 to activate all or some of these checks. If the source program fails a
13429 specified style check, an appropriate message is given, preceded by
13430 the character sequence ‘(style)’. This message does not prevent
13431 successful compilation (unless the @code{-gnatwe} switch is used).
13433 Note that this is by no means intended to be a general facility for
13434 checking arbitrary coding standards. It is simply an embedding of the
13435 style rules we have chosen for the GNAT sources. If you are starting
13436 a project which does not have established style standards, you may
13437 find it useful to adopt the entire set of GNAT coding standards, or
13438 some subset of them.
13441 The string @code{x} is a sequence of letters or digits
13442 indicating the particular style
13443 checks to be performed. The following checks are defined:
13445 @geindex -gnaty[0-9] (gcc)
13448 @table @asis
13450 @item @code{-gnaty0}
13452 `Specify indentation level.'
13454 If a digit from 1-9 appears
13455 in the string after @code{-gnaty}
13456 then proper indentation is checked, with the digit indicating the
13457 indentation level required. A value of zero turns off this style check.
13458 The rule checks that the following constructs start on a column that is
13459 a multiple of the alignment level:
13462 @itemize *
13464 @item 
13465 beginnings of declarations (except record component declarations)
13466 and statements;
13468 @item 
13469 beginnings of the structural components of compound statements;
13471 @item 
13472 @code{end} keyword that completes the declaration of a program unit declaration
13473 or body or that completes a compound statement.
13474 @end itemize
13476 Full line comments must be
13477 aligned with the @code{--} starting on a column that is a multiple of
13478 the alignment level, or they may be aligned the same way as the following
13479 non-blank line (this is useful when full line comments appear in the middle
13480 of a statement, or they may be aligned with the source line on the previous
13481 non-blank line.
13482 @end table
13484 @geindex -gnatya (gcc)
13487 @table @asis
13489 @item @code{-gnatya}
13491 `Check attribute casing.'
13493 Attribute names, including the case of keywords such as @code{digits}
13494 used as attributes names, must be written in mixed case, that is, the
13495 initial letter and any letter following an underscore must be uppercase.
13496 All other letters must be lowercase.
13497 @end table
13499 @geindex -gnatyA (gcc)
13502 @table @asis
13504 @item @code{-gnatyA}
13506 `Use of array index numbers in array attributes.'
13508 When using the array attributes First, Last, Range,
13509 or Length, the index number must be omitted for one-dimensional arrays
13510 and is required for multi-dimensional arrays.
13511 @end table
13513 @geindex -gnatyb (gcc)
13516 @table @asis
13518 @item @code{-gnatyb}
13520 `Blanks not allowed at statement end.'
13522 Trailing blanks are not allowed at the end of statements. The purpose of this
13523 rule, together with h (no horizontal tabs), is to enforce a canonical format
13524 for the use of blanks to separate source tokens.
13525 @end table
13527 @geindex -gnatyB (gcc)
13530 @table @asis
13532 @item @code{-gnatyB}
13534 `Check Boolean operators.'
13536 The use of AND/OR operators is not permitted except in the cases of modular
13537 operands, array operands, and simple stand-alone boolean variables or
13538 boolean constants. In all other cases @code{and then}/@cite{or else} are
13539 required.
13540 @end table
13542 @geindex -gnatyc (gcc)
13545 @table @asis
13547 @item @code{-gnatyc}
13549 `Check comments, double space.'
13551 Comments must meet the following set of rules:
13554 @itemize *
13556 @item 
13557 The @code{--} that starts the column must either start in column one,
13558 or else at least one blank must precede this sequence.
13560 @item 
13561 Comments that follow other tokens on a line must have at least one blank
13562 following the @code{--} at the start of the comment.
13564 @item 
13565 Full line comments must have at least two blanks following the
13566 @code{--} that starts the comment, with the following exceptions.
13568 @item 
13569 A line consisting only of the @code{--} characters, possibly preceded
13570 by blanks is permitted.
13572 @item 
13573 A comment starting with @code{--x} where @code{x} is a special character
13574 is permitted.
13575 This allows proper processing of the output from specialized tools
13576 such as @code{gnatprep} (where @code{--!} is used) and in earlier versions of the SPARK
13577 annotation
13578 language (where @code{--#} is used). For the purposes of this rule, a
13579 special character is defined as being in one of the ASCII ranges
13580 @code{16#21#...16#2F#} or @code{16#3A#...16#3F#}.
13581 Note that this usage is not permitted
13582 in GNAT implementation units (i.e., when @code{-gnatg} is used).
13584 @item 
13585 A line consisting entirely of minus signs, possibly preceded by blanks, is
13586 permitted. This allows the construction of box comments where lines of minus
13587 signs are used to form the top and bottom of the box.
13589 @item 
13590 A comment that starts and ends with @code{--} is permitted as long as at
13591 least one blank follows the initial @code{--}. Together with the preceding
13592 rule, this allows the construction of box comments, as shown in the following
13593 example:
13595 @example
13596 ---------------------------
13597 -- This is a box comment --
13598 -- with two text lines.  --
13599 ---------------------------
13600 @end example
13601 @end itemize
13602 @end table
13604 @geindex -gnatyC (gcc)
13607 @table @asis
13609 @item @code{-gnatyC}
13611 `Check comments, single space.'
13613 This is identical to @code{c} except that only one space
13614 is required following the @code{--} of a comment instead of two.
13615 @end table
13617 @geindex -gnatyd (gcc)
13620 @table @asis
13622 @item @code{-gnatyd}
13624 `Check no DOS line terminators present.'
13626 All lines must be terminated by a single ASCII.LF
13627 character (in particular the DOS line terminator sequence CR/LF is not
13628 allowed).
13629 @end table
13631 @geindex -gnatyD (gcc)
13634 @table @asis
13636 @item @code{-gnatyD}
13638 `Check declared identifiers in mixed case.'
13640 Declared identifiers must be in mixed case, as in
13641 This_Is_An_Identifier. Use -gnatyr in addition to ensure
13642 that references match declarations.
13643 @end table
13645 @geindex -gnatye (gcc)
13648 @table @asis
13650 @item @code{-gnatye}
13652 `Check end/exit labels.'
13654 Optional labels on @code{end} statements ending subprograms and on
13655 @code{exit} statements exiting named loops, are required to be present.
13656 @end table
13658 @geindex -gnatyf (gcc)
13661 @table @asis
13663 @item @code{-gnatyf}
13665 `No form feeds or vertical tabs.'
13667 Neither form feeds nor vertical tab characters are permitted
13668 in the source text.
13669 @end table
13671 @geindex -gnatyg (gcc)
13674 @table @asis
13676 @item @code{-gnatyg}
13678 `GNAT style mode.'
13680 The set of style check switches is set to match that used by the GNAT sources.
13681 This may be useful when developing code that is eventually intended to be
13682 incorporated into GNAT. Currently this is equivalent to
13683 @code{-gnatyydISuxz}) but additional style switches may be added to this
13684 set in the future without advance notice.
13685 @end table
13687 @geindex -gnatyh (gcc)
13690 @table @asis
13692 @item @code{-gnatyh}
13694 `No horizontal tabs.'
13696 Horizontal tab characters are not permitted in the source text.
13697 Together with the b (no blanks at end of line) check, this
13698 enforces a canonical form for the use of blanks to separate
13699 source tokens.
13700 @end table
13702 @geindex -gnatyi (gcc)
13705 @table @asis
13707 @item @code{-gnatyi}
13709 `Check if-then layout.'
13711 The keyword @code{then} must appear either on the same
13712 line as corresponding @code{if}, or on a line on its own, lined
13713 up under the @code{if}.
13714 @end table
13716 @geindex -gnatyI (gcc)
13719 @table @asis
13721 @item @code{-gnatyI}
13723 `check mode IN keywords.'
13725 Mode @code{in} (the default mode) is not
13726 allowed to be given explicitly. @code{in out} is fine,
13727 but not @code{in} on its own.
13728 @end table
13730 @geindex -gnatyk (gcc)
13733 @table @asis
13735 @item @code{-gnatyk}
13737 `Check keyword casing.'
13739 All keywords must be in lower case (with the exception of keywords
13740 such as @code{digits} used as attribute names to which this check
13741 does not apply). A single error is reported for each line breaking
13742 this rule even if multiple casing issues exist on a same line.
13743 @end table
13745 @geindex -gnatyl (gcc)
13748 @table @asis
13750 @item @code{-gnatyl}
13752 `Check layout.'
13754 Layout of statement and declaration constructs must follow the
13755 recommendations in the Ada Reference Manual, as indicated by the
13756 form of the syntax rules. For example an @code{else} keyword must
13757 be lined up with the corresponding @code{if} keyword.
13759 There are two respects in which the style rule enforced by this check
13760 option are more liberal than those in the Ada Reference Manual. First
13761 in the case of record declarations, it is permissible to put the
13762 @code{record} keyword on the same line as the @code{type} keyword, and
13763 then the @code{end} in @code{end record} must line up under @code{type}.
13764 This is also permitted when the type declaration is split on two lines.
13765 For example, any of the following three layouts is acceptable:
13767 @example
13768 type q is record
13769    a : integer;
13770    b : integer;
13771 end record;
13773 type q is
13774    record
13775       a : integer;
13776       b : integer;
13777    end record;
13779 type q is
13780    record
13781       a : integer;
13782       b : integer;
13783 end record;
13784 @end example
13786 Second, in the case of a block statement, a permitted alternative
13787 is to put the block label on the same line as the @code{declare} or
13788 @code{begin} keyword, and then line the @code{end} keyword up under
13789 the block label. For example both the following are permitted:
13791 @example
13792 Block : declare
13793    A : Integer := 3;
13794 begin
13795    Proc (A, A);
13796 end Block;
13798 Block :
13799    declare
13800       A : Integer := 3;
13801    begin
13802       Proc (A, A);
13803    end Block;
13804 @end example
13806 The same alternative format is allowed for loops. For example, both of
13807 the following are permitted:
13809 @example
13810 Clear : while J < 10 loop
13811    A (J) := 0;
13812 end loop Clear;
13814 Clear :
13815    while J < 10 loop
13816       A (J) := 0;
13817    end loop Clear;
13818 @end example
13819 @end table
13821 @geindex -gnatyLnnn (gcc)
13824 @table @asis
13826 @item @code{-gnatyL}
13828 `Set maximum nesting level.'
13830 The maximum level of nesting of constructs (including subprograms, loops,
13831 blocks, packages, and conditionals) may not exceed the given value
13832 `nnn'. A value of zero disconnects this style check.
13833 @end table
13835 @geindex -gnatym (gcc)
13838 @table @asis
13840 @item @code{-gnatym}
13842 `Check maximum line length.'
13844 The length of source lines must not exceed 79 characters, including
13845 any trailing blanks. The value of 79 allows convenient display on an
13846 80 character wide device or window, allowing for possible special
13847 treatment of 80 character lines. Note that this count is of
13848 characters in the source text. This means that a tab character counts
13849 as one character in this count and a wide character sequence counts as
13850 a single character (however many bytes are needed in the encoding).
13851 @end table
13853 @geindex -gnatyMnnn (gcc)
13856 @table @asis
13858 @item @code{-gnatyM}
13860 `Set maximum line length.'
13862 The length of lines must not exceed the
13863 given value `nnn'. The maximum value that can be specified is 32767.
13864 If neither style option for setting the line length is used, then the
13865 default is 255. This also controls the maximum length of lexical elements,
13866 where the only restriction is that they must fit on a single line.
13867 @end table
13869 @geindex -gnatyn (gcc)
13872 @table @asis
13874 @item @code{-gnatyn}
13876 `Check casing of entities in Standard.'
13878 Any identifier from Standard must be cased
13879 to match the presentation in the Ada Reference Manual (for example,
13880 @code{Integer} and @code{ASCII.NUL}).
13881 @end table
13883 @geindex -gnatyN (gcc)
13886 @table @asis
13888 @item @code{-gnatyN}
13890 `Turn off all style checks.'
13892 All style check options are turned off.
13893 @end table
13895 @geindex -gnatyo (gcc)
13898 @table @asis
13900 @item @code{-gnatyo}
13902 `Check order of subprogram bodies.'
13904 All subprogram bodies in a given scope
13905 (e.g., a package body) must be in alphabetical order. The ordering
13906 rule uses normal Ada rules for comparing strings, ignoring casing
13907 of letters, except that if there is a trailing numeric suffix, then
13908 the value of this suffix is used in the ordering (e.g., Junk2 comes
13909 before Junk10).
13910 @end table
13912 @geindex -gnatyO (gcc)
13915 @table @asis
13917 @item @code{-gnatyO}
13919 `Check that overriding subprograms are explicitly marked as such.'
13921 This applies to all subprograms of a derived type that override a primitive
13922 operation of the type, for both tagged and untagged types. In particular,
13923 the declaration of a primitive operation of a type extension that overrides
13924 an inherited operation must carry an overriding indicator. Another case is
13925 the declaration of a function that overrides a predefined operator (such
13926 as an equality operator).
13927 @end table
13929 @geindex -gnatyp (gcc)
13932 @table @asis
13934 @item @code{-gnatyp}
13936 `Check pragma casing.'
13938 Pragma names must be written in mixed case, that is, the
13939 initial letter and any letter following an underscore must be uppercase.
13940 All other letters must be lowercase. An exception is that SPARK_Mode is
13941 allowed as an alternative for Spark_Mode.
13942 @end table
13944 @geindex -gnatyr (gcc)
13947 @table @asis
13949 @item @code{-gnatyr}
13951 `Check references.'
13953 All identifier references must be cased in the same way as the
13954 corresponding declaration. No specific casing style is imposed on
13955 identifiers. The only requirement is for consistency of references
13956 with declarations.
13957 @end table
13959 @geindex -gnatys (gcc)
13962 @table @asis
13964 @item @code{-gnatys}
13966 `Check separate specs.'
13968 Separate declarations (‘specs’) are required for subprograms (a
13969 body is not allowed to serve as its own declaration). The only
13970 exception is that parameterless library level procedures are
13971 not required to have a separate declaration. This exception covers
13972 the most frequent form of main program procedures.
13973 @end table
13975 @geindex -gnatyS (gcc)
13978 @table @asis
13980 @item @code{-gnatyS}
13982 `Check no statements after then/else.'
13984 No statements are allowed
13985 on the same line as a @code{then} or @code{else} keyword following the
13986 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
13987 affected, and a special exception allows a pragma to appear after @code{else}.
13988 @end table
13990 @geindex -gnatyt (gcc)
13993 @table @asis
13995 @item @code{-gnatyt}
13997 `Check token spacing.'
13999 The following token spacing rules are enforced:
14002 @itemize *
14004 @item 
14005 The keywords @code{abs} and @code{not} must be followed by a space.
14007 @item 
14008 The token @code{=>} must be surrounded by spaces.
14010 @item 
14011 The token @code{<>} must be preceded by a space or a left parenthesis.
14013 @item 
14014 Binary operators other than @code{**} must be surrounded by spaces.
14015 There is no restriction on the layout of the @code{**} binary operator.
14017 @item 
14018 Colon must be surrounded by spaces.
14020 @item 
14021 Colon-equal (assignment, initialization) must be surrounded by spaces.
14023 @item 
14024 Comma must be the first non-blank character on the line, or be
14025 immediately preceded by a non-blank character, and must be followed
14026 by a space.
14028 @item 
14029 If the token preceding a left parenthesis ends with a letter or digit, then
14030 a space must separate the two tokens.
14032 @item 
14033 If the token following a right parenthesis starts with a letter or digit, then
14034 a space must separate the two tokens.
14036 @item 
14037 A right parenthesis must either be the first non-blank character on
14038 a line, or it must be preceded by a non-blank character.
14040 @item 
14041 A semicolon must not be preceded by a space, and must not be followed by
14042 a non-blank character.
14044 @item 
14045 A unary plus or minus may not be followed by a space.
14047 @item 
14048 A vertical bar must be surrounded by spaces.
14049 @end itemize
14051 Exactly one blank (and no other white space) must appear between
14052 a @code{not} token and a following @code{in} token.
14053 @end table
14055 @geindex -gnatyu (gcc)
14058 @table @asis
14060 @item @code{-gnatyu}
14062 `Check unnecessary blank lines.'
14064 Unnecessary blank lines are not allowed. A blank line is considered
14065 unnecessary if it appears at the end of the file, or if more than
14066 one blank line occurs in sequence.
14067 @end table
14069 @geindex -gnatyx (gcc)
14072 @table @asis
14074 @item @code{-gnatyx}
14076 `Check extra parentheses.'
14078 Unnecessary extra levels of parentheses (C-style) are not allowed
14079 around conditions (or selection expressions) in @code{if}, @code{while},
14080 @code{case}, and @code{exit} statements, as well as part of ranges.
14081 @end table
14083 @geindex -gnatyy (gcc)
14086 @table @asis
14088 @item @code{-gnatyy}
14090 `Set all standard style check options.'
14092 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
14093 options enabled with the exception of @code{-gnatyB}, @code{-gnatyd},
14094 @code{-gnatyI}, @code{-gnatyLnnn}, @code{-gnatyo}, @code{-gnatyO},
14095 @code{-gnatyS}, @code{-gnatyu}, and @code{-gnatyx}.
14096 @end table
14098 @geindex -gnatyz (gcc)
14101 @table @asis
14103 @item @code{-gnatyz}
14105 `Check extra parentheses (operator precedence).'
14107 Extra levels of parentheses that are not required by operator precedence
14108 rules are flagged. See also @code{-gnatyx}.
14109 @end table
14111 @geindex -gnaty- (gcc)
14114 @table @asis
14116 @item @code{-gnaty-}
14118 `Remove style check options.'
14120 This causes any subsequent options in the string to act as canceling the
14121 corresponding style check option. To cancel maximum nesting level control,
14122 use the @code{L} parameter without any integer value after that, because any
14123 digit following `-' in the parameter string of the @code{-gnaty}
14124 option will be treated as canceling the indentation check. The same is true
14125 for the @code{M} parameter. @code{y} and @code{N} parameters are not
14126 allowed after `-'.
14127 @end table
14129 @geindex -gnaty+ (gcc)
14132 @table @asis
14134 @item @code{-gnaty+}
14136 `Enable style check options.'
14138 This causes any subsequent options in the string to enable the corresponding
14139 style check option. That is, it cancels the effect of a previous -,
14140 if any.
14141 @end table
14143 @c end of switch description (leave this comment to ease automatic parsing for
14145 @c GNAT Studio)
14147 In the above rules, appearing in column one is always permitted, that is,
14148 counts as meeting either a requirement for a required preceding space,
14149 or as meeting a requirement for no preceding space.
14151 Appearing at the end of a line is also always permitted, that is, counts
14152 as meeting either a requirement for a following space, or as meeting
14153 a requirement for no following space.
14155 If any of these style rules is violated, a message is generated giving
14156 details on the violation. The initial characters of such messages are
14157 always ‘@cite{(style)}’. Note that these messages are treated as warning
14158 messages, so they normally do not prevent the generation of an object
14159 file. The @code{-gnatwe} switch can be used to treat warning messages,
14160 including style messages, as fatal errors.
14162 The switch @code{-gnaty} on its own (that is not
14163 followed by any letters or digits) is equivalent
14164 to the use of @code{-gnatyy} as described above, that is all
14165 built-in standard style check options are enabled.
14167 The switch @code{-gnatyN} clears any previously set style checks.
14169 @node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
14170 @anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{f8}@anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{ec}
14171 @subsection Run-Time Checks
14174 @geindex Division by zero
14176 @geindex Access before elaboration
14178 @geindex Checks
14179 @geindex division by zero
14181 @geindex Checks
14182 @geindex access before elaboration
14184 @geindex Checks
14185 @geindex stack overflow checking
14187 By default, the following checks are suppressed: stack overflow
14188 checks, and checks for access before elaboration on subprogram
14189 calls. All other checks, including overflow checks, range checks and
14190 array bounds checks, are turned on by default. The following @code{gcc}
14191 switches refine this default behavior.
14193 @geindex -gnatp (gcc)
14196 @table @asis
14198 @item @code{-gnatp}
14200 @geindex Suppressing checks
14202 @geindex Checks
14203 @geindex suppressing
14205 This switch causes the unit to be compiled
14206 as though @code{pragma Suppress (All_checks)}
14207 had been present in the source. Validity checks are also eliminated (in
14208 other words @code{-gnatp} also implies @code{-gnatVn}.
14209 Use this switch to improve the performance
14210 of the code at the expense of safety in the presence of invalid data or
14211 program bugs.
14213 Note that when checks are suppressed, the compiler is allowed, but not
14214 required, to omit the checking code. If the run-time cost of the
14215 checking code is zero or near-zero, the compiler will generate it even
14216 if checks are suppressed. In particular, if the compiler can prove
14217 that a certain check will necessarily fail, it will generate code to
14218 do an unconditional ‘raise’, even if checks are suppressed. The
14219 compiler warns in this case. Another case in which checks may not be
14220 eliminated is when they are embedded in certain run-time routines such
14221 as math library routines.
14223 Of course, run-time checks are omitted whenever the compiler can prove
14224 that they will not fail, whether or not checks are suppressed.
14226 Note that if you suppress a check that would have failed, program
14227 execution is erroneous, which means the behavior is totally
14228 unpredictable. The program might crash, or print wrong answers, or
14229 do anything else. It might even do exactly what you wanted it to do
14230 (and then it might start failing mysteriously next week or next
14231 year). The compiler will generate code based on the assumption that
14232 the condition being checked is true, which can result in erroneous
14233 execution if that assumption is wrong.
14235 The checks subject to suppression include all the checks defined by the Ada
14236 standard, the additional implementation defined checks @code{Alignment_Check},
14237 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, @code{Container_Checks}, @code{Tampering_Check},
14238 and @code{Validity_Check}, as well as any checks introduced using @code{pragma Check_Name}.
14239 Note that @code{Atomic_Synchronization} is not automatically suppressed by use of this option.
14241 If the code depends on certain checks being active, you can use
14242 pragma @code{Unsuppress} either as a configuration pragma or as
14243 a local pragma to make sure that a specified check is performed
14244 even if @code{gnatp} is specified.
14246 The @code{-gnatp} switch has no effect if a subsequent
14247 @code{-gnat-p} switch appears.
14248 @end table
14250 @geindex -gnat-p (gcc)
14252 @geindex Suppressing checks
14254 @geindex Checks
14255 @geindex suppressing
14257 @geindex Suppress
14260 @table @asis
14262 @item @code{-gnat-p}
14264 This switch cancels the effect of a previous @code{gnatp} switch.
14265 @end table
14267 @geindex -gnato?? (gcc)
14269 @geindex Overflow checks
14271 @geindex Overflow mode
14273 @geindex Check
14274 @geindex overflow
14277 @table @asis
14279 @item @code{-gnato??}
14281 This switch controls the mode used for computing intermediate
14282 arithmetic integer operations, and also enables overflow checking.
14283 For a full description of overflow mode and checking control, see
14284 the ‘Overflow Check Handling in GNAT’ appendix in this
14285 User’s Guide.
14287 Overflow checks are always enabled by this switch. The argument
14288 controls the mode, using the codes
14291 @table @asis
14293 @item `1 = STRICT'
14295 In STRICT mode, intermediate operations are always done using the
14296 base type, and overflow checking ensures that the result is within
14297 the base type range.
14299 @item `2 = MINIMIZED'
14301 In MINIMIZED mode, overflows in intermediate operations are avoided
14302 where possible by using a larger integer type for the computation
14303 (typically @code{Long_Long_Integer}). Overflow checking ensures that
14304 the result fits in this larger integer type.
14306 @item `3 = ELIMINATED'
14308 In ELIMINATED mode, overflows in intermediate operations are avoided
14309 by using multi-precision arithmetic. In this case, overflow checking
14310 has no effect on intermediate operations (since overflow is impossible).
14311 @end table
14313 If two digits are present after @code{-gnato} then the first digit
14314 sets the mode for expressions outside assertions, and the second digit
14315 sets the mode for expressions within assertions. Here assertions is used
14316 in the technical sense (which includes for example precondition and
14317 postcondition expressions).
14319 If one digit is present, the corresponding mode is applicable to both
14320 expressions within and outside assertion expressions.
14322 If no digits are present, the default is to enable overflow checks
14323 and set STRICT mode for both kinds of expressions. This is compatible
14324 with the use of @code{-gnato} in previous versions of GNAT.
14326 @geindex Machine_Overflows
14328 Note that the @code{-gnato??} switch does not affect the code generated
14329 for any floating-point operations; it applies only to integer semantics.
14330 For floating-point, GNAT has the @code{Machine_Overflows}
14331 attribute set to @code{False} and the normal mode of operation is to
14332 generate IEEE NaN and infinite values on overflow or invalid operations
14333 (such as dividing 0.0 by 0.0).
14335 The reason that we distinguish overflow checking from other kinds of
14336 range constraint checking is that a failure of an overflow check, unlike
14337 for example the failure of a range check, can result in an incorrect
14338 value, but cannot cause random memory destruction (like an out of range
14339 subscript), or a wild jump (from an out of range case value). Overflow
14340 checking is also quite expensive in time and space, since in general it
14341 requires the use of double length arithmetic.
14343 Note again that the default is @code{-gnato11} (equivalent to @code{-gnato1}),
14344 so overflow checking is performed in STRICT mode by default.
14345 @end table
14347 @geindex -gnatE (gcc)
14349 @geindex Elaboration checks
14351 @geindex Check
14352 @geindex elaboration
14355 @table @asis
14357 @item @code{-gnatE}
14359 Enables dynamic checks for access-before-elaboration
14360 on subprogram calls and generic instantiations.
14361 Note that @code{-gnatE} is not necessary for safety, because in the
14362 default mode, GNAT ensures statically that the checks would not fail.
14363 For full details of the effect and use of this switch,
14364 @ref{c9,,Compiling with gcc}.
14365 @end table
14367 @geindex -fstack-check (gcc)
14369 @geindex Stack Overflow Checking
14371 @geindex Checks
14372 @geindex stack overflow checking
14375 @table @asis
14377 @item @code{-fstack-check}
14379 Activates stack overflow checking. For full details of the effect and use of
14380 this switch see @ref{e7,,Stack Overflow Checking}.
14381 @end table
14383 @geindex Unsuppress
14385 The setting of these switches only controls the default setting of the
14386 checks. You may modify them using either @code{Suppress} (to remove
14387 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
14388 the program source.
14390 @node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
14391 @anchor{gnat_ugn/building_executable_programs_with_gnat id20}@anchor{f9}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-syntax-checking}@anchor{fa}
14392 @subsection Using @code{gcc} for Syntax Checking
14395 @geindex -gnats (gcc)
14398 @table @asis
14400 @item @code{-gnats}
14402 The @code{s} stands for ‘syntax’.
14404 Run GNAT in syntax checking only mode. For
14405 example, the command
14407 @example
14408 $ gcc -c -gnats x.adb
14409 @end example
14411 compiles file @code{x.adb} in syntax-check-only mode. You can check a
14412 series of files in a single command
14413 , and can use wildcards to specify such a group of files.
14414 Note that you must specify the @code{-c} (compile
14415 only) flag in addition to the @code{-gnats} flag.
14417 You may use other switches in conjunction with @code{-gnats}. In
14418 particular, @code{-gnatl} and @code{-gnatv} are useful to control the
14419 format of any generated error messages.
14421 When the source file is empty or contains only empty lines and/or comments,
14422 the output is a warning:
14424 @example
14425 $ gcc -c -gnats -x ada toto.txt
14426 toto.txt:1:01: warning: empty file, contains no compilation units
14428 @end example
14430 Otherwise, the output is simply the error messages, if any. No object file or
14431 ALI file is generated by a syntax-only compilation. Also, no units other
14432 than the one specified are accessed. For example, if a unit @code{X}
14433 `with's a unit @code{Y}, compiling unit @code{X} in syntax
14434 check only mode does not access the source file containing unit
14435 @code{Y}.
14437 @geindex Multiple units
14438 @geindex syntax checking
14440 Normally, GNAT allows only a single unit in a source file. However, this
14441 restriction does not apply in syntax-check-only mode, and it is possible
14442 to check a file containing multiple compilation units concatenated
14443 together. This is primarily used by the @code{gnatchop} utility
14444 (@ref{1d,,Renaming Files with gnatchop}).
14445 @end table
14447 @node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
14448 @anchor{gnat_ugn/building_executable_programs_with_gnat id21}@anchor{fb}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-semantic-checking}@anchor{fc}
14449 @subsection Using @code{gcc} for Semantic Checking
14452 @geindex -gnatc (gcc)
14455 @table @asis
14457 @item @code{-gnatc}
14459 The @code{c} stands for ‘check’.
14460 Causes the compiler to operate in semantic check mode,
14461 with full checking for all illegalities specified in the
14462 Ada Reference Manual, but without generation of any object code
14463 (no object file is generated).
14465 Because dependent files must be accessed, you must follow the GNAT
14466 semantic restrictions on file structuring to operate in this mode:
14469 @itemize *
14471 @item 
14472 The needed source files must be accessible
14473 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}).
14475 @item 
14476 Each file must contain only one compilation unit.
14478 @item 
14479 The file name and unit name must match (@ref{3b,,File Naming Rules}).
14480 @end itemize
14482 The output consists of error messages as appropriate. No object file is
14483 generated. An @code{ALI} file is generated for use in the context of
14484 cross-reference tools, but this file is marked as not being suitable
14485 for binding (since no object file is generated).
14486 The checking corresponds exactly to the notion of
14487 legality in the Ada Reference Manual.
14489 Any unit can be compiled in semantics-checking-only mode, including
14490 units that would not normally be compiled (subunits,
14491 and specifications where a separate body is present).
14492 @end table
14494 @node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14495 @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{fd}
14496 @subsection Compiling Different Versions of Ada
14499 The switches described in this section allow you to explicitly specify
14500 the version of the Ada language that your programs are written in.
14501 The default mode is Ada 2012,
14502 but you can also specify Ada 95, Ada 2005 mode, or
14503 indicate Ada 83 compatibility mode.
14505 @geindex Compatibility with Ada 83
14507 @geindex -gnat83 (gcc)
14509 @geindex ACVC
14510 @geindex Ada 83 tests
14512 @geindex Ada 83 mode
14515 @table @asis
14517 @item @code{-gnat83} (Ada 83 Compatibility Mode)
14519 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14520 specifies that the program is to be compiled in Ada 83 mode. With
14521 @code{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14522 semantics where this can be done easily.
14523 It is not possible to guarantee this switch does a perfect
14524 job; some subtle tests, such as are
14525 found in earlier ACVC tests (and that have been removed from the ACATS suite
14526 for Ada 95), might not compile correctly.
14527 Nevertheless, this switch may be useful in some circumstances, for example
14528 where, due to contractual reasons, existing code needs to be maintained
14529 using only Ada 83 features.
14531 With few exceptions (most notably the need to use @code{<>} on
14532 unconstrained 
14533 @geindex Generic formal parameters
14534 generic formal parameters,
14535 the use of the new Ada 95 / Ada 2005
14536 reserved words, and the use of packages
14537 with optional bodies), it is not necessary to specify the
14538 @code{-gnat83} switch when compiling Ada 83 programs, because, with rare
14539 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14540 a correct Ada 83 program is usually also a correct program
14541 in these later versions of the language standard. For further information
14542 please refer to the `Compatibility and Porting Guide' chapter in the
14543 @cite{GNAT Reference Manual}.
14544 @end table
14546 @geindex -gnat95 (gcc)
14548 @geindex Ada 95 mode
14551 @table @asis
14553 @item @code{-gnat95} (Ada 95 mode)
14555 This switch directs the compiler to implement the Ada 95 version of the
14556 language.
14557 Since Ada 95 is almost completely upwards
14558 compatible with Ada 83, Ada 83 programs may generally be compiled using
14559 this switch (see the description of the @code{-gnat83} switch for further
14560 information about Ada 83 mode).
14561 If an Ada 2005 program is compiled in Ada 95 mode,
14562 uses of the new Ada 2005 features will cause error
14563 messages or warnings.
14565 This switch also can be used to cancel the effect of a previous
14566 @code{-gnat83}, @code{-gnat05/2005}, or @code{-gnat12/2012}
14567 switch earlier in the command line.
14568 @end table
14570 @geindex -gnat05 (gcc)
14572 @geindex -gnat2005 (gcc)
14574 @geindex Ada 2005 mode
14577 @table @asis
14579 @item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14581 This switch directs the compiler to implement the Ada 2005 version of the
14582 language, as documented in the official Ada standards document.
14583 Since Ada 2005 is almost completely upwards
14584 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14585 may generally be compiled using this switch (see the description of the
14586 @code{-gnat83} and @code{-gnat95} switches for further
14587 information).
14588 @end table
14590 @geindex -gnat12 (gcc)
14592 @geindex -gnat2012 (gcc)
14594 @geindex Ada 2012 mode
14597 @table @asis
14599 @item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14601 This switch directs the compiler to implement the Ada 2012 version of the
14602 language (also the default).
14603 Since Ada 2012 is almost completely upwards
14604 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14605 Ada 83 and Ada 95 programs
14606 may generally be compiled using this switch (see the description of the
14607 @code{-gnat83}, @code{-gnat95}, and @code{-gnat05/2005} switches
14608 for further information).
14609 @end table
14611 @geindex -gnat2022 (gcc)
14613 @geindex Ada 2022 mode
14616 @table @asis
14618 @item @code{-gnat2022} (Ada 2022 mode)
14620 This switch directs the compiler to implement the Ada 2022 version of the
14621 language.
14622 @end table
14624 @geindex -gnatX0 (gcc)
14626 @geindex Ada language extensions
14628 @geindex GNAT extensions
14631 @table @asis
14633 @item @code{-gnatX0} (Enable GNAT Extensions)
14635 This switch directs the compiler to implement the latest version of the
14636 language (currently Ada 2022) and also to enable certain GNAT implementation
14637 extensions that are not part of any Ada standard. For a full list of these
14638 extensions, see the GNAT reference manual, @code{Pragma Extensions_Allowed}.
14639 @end table
14641 @geindex -gnatX (gcc)
14643 @geindex Ada language extensions
14645 @geindex GNAT extensions
14648 @table @asis
14650 @item @code{-gnatX} (Enable core GNAT Extensions)
14652 This switch is similar to -gnatX0 except that only some, not all, of the
14653 GNAT-defined language extensions are enabled. For a list of the
14654 extensions enabled by this switch, see the GNAT reference manual
14655 @code{Pragma Extensions_Allowed} and the description of that pragma’s
14656 “On” (as opposed to “All”) argument.
14657 @end table
14659 @node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14660 @anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{31}@anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{fe}
14661 @subsection Character Set Control
14664 @geindex -gnati (gcc)
14667 @table @asis
14669 @item @code{-gnati`c'}
14671 Normally GNAT recognizes the Latin-1 character set in source program
14672 identifiers, as described in the Ada Reference Manual.
14673 This switch causes
14674 GNAT to recognize alternate character sets in identifiers. @code{c} is a
14675 single character  indicating the character set, as follows:
14678 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14679 @item
14683 @tab
14685 ISO 8859-1 (Latin-1) identifiers
14687 @item
14691 @tab
14693 ISO 8859-2 (Latin-2) letters allowed in identifiers
14695 @item
14699 @tab
14701 ISO 8859-3 (Latin-3) letters allowed in identifiers
14703 @item
14707 @tab
14709 ISO 8859-4 (Latin-4) letters allowed in identifiers
14711 @item
14715 @tab
14717 ISO 8859-5 (Cyrillic) letters allowed in identifiers
14719 @item
14723 @tab
14725 ISO 8859-15 (Latin-9) letters allowed in identifiers
14727 @item
14731 @tab
14733 IBM PC letters (code page 437) allowed in identifiers
14735 @item
14739 @tab
14741 IBM PC letters (code page 850) allowed in identifiers
14743 @item
14747 @tab
14749 Full upper-half codes allowed in identifiers
14751 @item
14755 @tab
14757 No upper-half codes allowed in identifiers
14759 @item
14763 @tab
14765 Wide-character codes (that is, codes greater than 255)
14766 allowed in identifiers
14768 @end multitable
14771 See @ref{23,,Foreign Language Representation} for full details on the
14772 implementation of these character sets.
14773 @end table
14775 @geindex -gnatW (gcc)
14778 @table @asis
14780 @item @code{-gnatW`e'}
14782 Specify the method of encoding for wide characters.
14783 @code{e} is one of the following:
14786 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14787 @item
14791 @tab
14793 Hex encoding (brackets coding also recognized)
14795 @item
14799 @tab
14801 Upper half encoding (brackets encoding also recognized)
14803 @item
14807 @tab
14809 Shift/JIS encoding (brackets encoding also recognized)
14811 @item
14815 @tab
14817 EUC encoding (brackets encoding also recognized)
14819 @item
14823 @tab
14825 UTF-8 encoding (brackets encoding also recognized)
14827 @item
14831 @tab
14833 Brackets encoding only (default value)
14835 @end multitable
14838 For full details on these encoding
14839 methods see @ref{37,,Wide_Character Encodings}.
14840 Note that brackets coding is always accepted, even if one of the other
14841 options is specified, so for example @code{-gnatW8} specifies that both
14842 brackets and UTF-8 encodings will be recognized. The units that are
14843 with’ed directly or indirectly will be scanned using the specified
14844 representation scheme, and so if one of the non-brackets scheme is
14845 used, it must be used consistently throughout the program. However,
14846 since brackets encoding is always recognized, it may be conveniently
14847 used in standard libraries, allowing these libraries to be used with
14848 any of the available coding schemes.
14850 Note that brackets encoding only applies to program text. Within comments,
14851 brackets are considered to be normal graphic characters, and bracket sequences
14852 are never recognized as wide characters.
14854 If no @code{-gnatW?} parameter is present, then the default
14855 representation is normally Brackets encoding only. However, if the
14856 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14857 byte order mark or BOM for UTF-8), then these three characters are
14858 skipped and the default representation for the file is set to UTF-8.
14860 Note that the wide character representation that is specified (explicitly
14861 or by default) for the main program also acts as the default encoding used
14862 for Wide_Text_IO files if not specifically overridden by a WCEM form
14863 parameter.
14864 @end table
14866 When no @code{-gnatW?} is specified, then characters (other than wide
14867 characters represented using brackets notation) are treated as 8-bit
14868 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14869 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14870 characters in the range 16#00#..16#1F# are not accepted in program text
14871 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14872 in program text, but allowed and ignored in comments. Note in particular
14873 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14874 as an end of line in this default mode. If your source program contains
14875 instances of the NEL character used as a line terminator,
14876 you must use UTF-8 encoding for the whole
14877 source program. In default mode, all lines must be ended by a standard
14878 end of line sequence (CR, CR/LF, or LF).
14880 Note that the convention of simply accepting all upper half characters in
14881 comments means that programs that use standard ASCII for program text, but
14882 UTF-8 encoding for comments are accepted in default mode, providing that the
14883 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14884 This is a common mode for many programs with foreign language comments.
14886 @node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14887 @anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{ff}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{100}
14888 @subsection File Naming Control
14891 @geindex -gnatk (gcc)
14894 @table @asis
14896 @item @code{-gnatk`n'}
14898 Activates file name ‘krunching’. @code{n}, a decimal integer in the range
14899 1-999, indicates the maximum allowable length of a file name (not
14900 including the @code{.ads} or @code{.adb} extension). The default is not
14901 to enable file name krunching.
14903 For the source file naming rules, @ref{3b,,File Naming Rules}.
14904 @end table
14906 @node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14907 @anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{101}@anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{102}
14908 @subsection Subprogram Inlining Control
14911 @geindex -gnatn (gcc)
14914 @table @asis
14916 @item @code{-gnatn[12]}
14918 The @code{n} here is intended to suggest the first syllable of the word ‘inline’.
14919 GNAT recognizes and processes @code{Inline} pragmas. However, for inlining to
14920 actually occur, optimization must be enabled and, by default, inlining of
14921 subprograms across units is not performed. If you want to additionally
14922 enable inlining of subprograms specified by pragma @code{Inline} across units,
14923 you must also specify this switch.
14925 In the absence of this switch, GNAT does not attempt inlining across units
14926 and does not access the bodies of subprograms for which @code{pragma Inline} is
14927 specified if they are not in the current unit.
14929 You can optionally specify the inlining level: 1 for moderate inlining across
14930 units, which is a good compromise between compilation times and performances
14931 at run time, or 2 for full inlining across units, which may bring about
14932 longer compilation times. If no inlining level is specified, the compiler will
14933 pick it based on the optimization level: 1 for @code{-O1}, @code{-O2} or
14934 @code{-Os} and 2 for @code{-O3}.
14936 If you specify this switch the compiler will access these bodies,
14937 creating an extra source dependency for the resulting object file, and
14938 where possible, the call will be inlined.
14939 For further details on when inlining is possible
14940 see @ref{103,,Inlining of Subprograms}.
14941 @end table
14943 @geindex -gnatN (gcc)
14946 @table @asis
14948 @item @code{-gnatN}
14950 This switch activates front-end inlining which also
14951 generates additional dependencies.
14953 When using a gcc-based back end, then the use of
14954 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
14955 Historically front end inlining was more extensive than the gcc back end
14956 inlining, but that is no longer the case.
14957 @end table
14959 @node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14960 @anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{104}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{105}
14961 @subsection Auxiliary Output Control
14964 @geindex -gnatu (gcc)
14967 @table @asis
14969 @item @code{-gnatu}
14971 Print a list of units required by this compilation on @code{stdout}.
14972 The listing includes all units on which the unit being compiled depends
14973 either directly or indirectly.
14974 @end table
14976 @geindex -pass-exit-codes (gcc)
14979 @table @asis
14981 @item @code{-pass-exit-codes}
14983 If this switch is not used, the exit code returned by @code{gcc} when
14984 compiling multiple files indicates whether all source files have
14985 been successfully used to generate object files or not.
14987 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
14988 exit status and allows an integrated development environment to better
14989 react to a compilation failure. Those exit status are:
14992 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14993 @item
14997 @tab
14999 There was an error in at least one source file.
15001 @item
15005 @tab
15007 At least one source file did not generate an object file.
15009 @item
15013 @tab
15015 The compiler died unexpectedly (internal error for example).
15017 @item
15021 @tab
15023 An object file has been generated for every source file.
15025 @end multitable
15027 @end table
15029 @node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
15030 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{106}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{107}
15031 @subsection Debugging Control
15034 @quotation
15036 @geindex Debugging options
15037 @end quotation
15039 @geindex -gnatd (gcc)
15042 @table @asis
15044 @item @code{-gnatd`x'}
15046 Activate internal debugging switches. @code{x} is a letter or digit, or
15047 string of letters or digits, which specifies the type of debugging
15048 outputs desired. Normally these are used only for internal development
15049 or system debugging purposes. You can find full documentation for these
15050 switches in the body of the @code{Debug} unit in the compiler source
15051 file @code{debug.adb}.
15052 @end table
15054 @geindex -gnatG (gcc)
15057 @table @asis
15059 @item @code{-gnatG[=`nn']}
15061 This switch causes the compiler to generate auxiliary output containing
15062 a pseudo-source listing of the generated expanded code. Like most Ada
15063 compilers, GNAT works by first transforming the high level Ada code into
15064 lower level constructs. For example, tasking operations are transformed
15065 into calls to the tasking run-time routines. A unique capability of GNAT
15066 is to list this expanded code in a form very close to normal Ada source.
15067 This is very useful in understanding the implications of various Ada
15068 usage on the efficiency of the generated code. There are many cases in
15069 Ada (e.g., the use of controlled types), where simple Ada statements can
15070 generate a lot of run-time code. By using @code{-gnatG} you can identify
15071 these cases, and consider whether it may be desirable to modify the coding
15072 approach to improve efficiency.
15074 The optional parameter @code{nn} if present after -gnatG specifies an
15075 alternative maximum line length that overrides the normal default of 72.
15076 This value is in the range 40-999999, values less than 40 being silently
15077 reset to 40. The equal sign is optional.
15079 The format of the output is very similar to standard Ada source, and is
15080 easily understood by an Ada programmer. The following special syntactic
15081 additions correspond to low level features used in the generated code that
15082 do not have any exact analogies in pure Ada source form. The following
15083 is a partial list of these special constructions. See the spec
15084 of package @code{Sprint} in file @code{sprint.ads} for a full list.
15086 @geindex -gnatL (gcc)
15088 If the switch @code{-gnatL} is used in conjunction with
15089 @code{-gnatG}, then the original source lines are interspersed
15090 in the expanded source (as comment lines with the original line number).
15093 @table @asis
15095 @item @code{new @var{xxx} [storage_pool = @var{yyy}]}
15097 Shows the storage pool being used for an allocator.
15099 @item @code{at end @var{procedure-name};}
15101 Shows the finalization (cleanup) procedure for a scope.
15103 @item @code{(if @var{expr} then @var{expr} else @var{expr})}
15105 Conditional expression equivalent to the @code{x?y:z} construction in C.
15107 @item @code{@var{target}^(@var{source})}
15109 A conversion with floating-point truncation instead of rounding.
15111 @item @code{@var{target}?(@var{source})}
15113 A conversion that bypasses normal Ada semantic checking. In particular
15114 enumeration types and fixed-point types are treated simply as integers.
15116 @item @code{@var{target}?^(@var{source})}
15118 Combines the above two cases.
15119 @end table
15121 @code{@var{x} #/ @var{y}}
15123 @code{@var{x} #mod @var{y}}
15125 @code{@var{x} # @var{y}}
15128 @table @asis
15130 @item @code{@var{x} #rem @var{y}}
15132 A division or multiplication of fixed-point values which are treated as
15133 integers without any kind of scaling.
15135 @item @code{free @var{expr} [storage_pool = @var{xxx}]}
15137 Shows the storage pool associated with a @code{free} statement.
15139 @item @code{[subtype or type declaration]}
15141 Used to list an equivalent declaration for an internally generated
15142 type that is referenced elsewhere in the listing.
15144 @item @code{freeze @var{type-name} [@var{actions}]}
15146 Shows the point at which @code{type-name} is frozen, with possible
15147 associated actions to be performed at the freeze point.
15149 @item @code{reference @var{itype}}
15151 Reference (and hence definition) to internal type @code{itype}.
15153 @item @code{@var{function-name}! (@var{arg}, @var{arg}, @var{arg})}
15155 Intrinsic function call.
15157 @item @code{@var{label-name} : label}
15159 Declaration of label @code{labelname}.
15161 @item @code{#$ @var{subprogram-name}}
15163 An implicit call to a run-time support routine
15164 (to meet the requirement of H.3.1(9) in a
15165 convenient manner).
15167 @item @code{@var{expr} && @var{expr} && @var{expr} ... && @var{expr}}
15169 A multiple concatenation (same effect as @code{expr} & @code{expr} &
15170 @code{expr}, but handled more efficiently).
15172 @item @code{[constraint_error]}
15174 Raise the @code{Constraint_Error} exception.
15176 @item @code{@var{expression}'reference}
15178 A pointer to the result of evaluating @{expression@}.
15180 @item @code{@var{target-type}!(@var{source-expression})}
15182 An unchecked conversion of @code{source-expression} to @code{target-type}.
15184 @item @code{[@var{numerator}/@var{denominator}]}
15186 Used to represent internal real literals (that) have no exact
15187 representation in base 2-16 (for example, the result of compile time
15188 evaluation of the expression 1.0/27.0).
15189 @end table
15190 @end table
15192 @geindex -gnatD (gcc)
15195 @table @asis
15197 @item @code{-gnatD[=nn]}
15199 When used in conjunction with @code{-gnatG}, this switch causes
15200 the expanded source, as described above for
15201 @code{-gnatG} to be written to files with names
15202 @code{xxx.dg}, where @code{xxx} is the normal file name,
15203 instead of to the standard output file. For
15204 example, if the source file name is @code{hello.adb}, then a file
15205 @code{hello.adb.dg} will be written.  The debugging
15206 information generated by the @code{gcc} @code{-g} switch
15207 will refer to the generated @code{xxx.dg} file. This allows
15208 you to do source level debugging using the generated code which is
15209 sometimes useful for complex code, for example to find out exactly
15210 which part of a complex construction raised an exception. This switch
15211 also suppresses generation of cross-reference information (see
15212 @code{-gnatx}) since otherwise the cross-reference information
15213 would refer to the @code{.dg} file, which would cause
15214 confusion since this is not the original source file.
15216 Note that @code{-gnatD} actually implies @code{-gnatG}
15217 automatically, so it is not necessary to give both options.
15218 In other words @code{-gnatD} is equivalent to @code{-gnatDG}).
15220 @geindex -gnatL (gcc)
15222 If the switch @code{-gnatL} is used in conjunction with
15223 @code{-gnatDG}, then the original source lines are interspersed
15224 in the expanded source (as comment lines with the original line number).
15226 The optional parameter @code{nn} if present after -gnatD specifies an
15227 alternative maximum line length that overrides the normal default of 72.
15228 This value is in the range 40-999999, values less than 40 being silently
15229 reset to 40. The equal sign is optional.
15230 @end table
15232 @geindex -gnatr (gcc)
15234 @geindex pragma Restrictions
15237 @table @asis
15239 @item @code{-gnatr}
15241 This switch causes pragma Restrictions to be treated as Restriction_Warnings
15242 so that violation of restrictions causes warnings rather than illegalities.
15243 This is useful during the development process when new restrictions are added
15244 or investigated. The switch also causes pragma Profile to be treated as
15245 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
15246 restriction warnings rather than restrictions.
15247 @end table
15249 @geindex -gnatR (gcc)
15252 @table @asis
15254 @item @code{-gnatR[0|1|2|3|4][e][j][m][s]}
15256 This switch controls output from the compiler of a listing showing
15257 representation information for declared types, objects and subprograms.
15258 For @code{-gnatR0}, no information is output (equivalent to omitting
15259 the @code{-gnatR} switch). For @code{-gnatR1} (which is the default,
15260 so @code{-gnatR} with no parameter has the same effect), size and
15261 alignment information is listed for declared array and record types.
15263 For @code{-gnatR2}, size and alignment information is listed for all
15264 declared types and objects. The @code{Linker_Section} is also listed for any
15265 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
15266 latter case occurs for objects of a type for which a @code{Linker_Section}
15267 is set).
15269 For @code{-gnatR3}, symbolic expressions for values that are computed
15270 at run time for records are included. These symbolic expressions have
15271 a mostly obvious format with #n being used to represent the value of the
15272 n’th discriminant. See source files @code{repinfo.ads/adb} in the
15273 GNAT sources for full details on the format of @code{-gnatR3} output.
15275 For @code{-gnatR4}, information for relevant compiler-generated types
15276 is also listed, i.e. when they are structurally part of other declared
15277 types and objects.
15279 If the switch is followed by an @code{e} (e.g. @code{-gnatR2e}), then
15280 extended representation information for record sub-components of records
15281 is included.
15283 If the switch is followed by an @code{m} (e.g. @code{-gnatRm}), then
15284 subprogram conventions and parameter passing mechanisms for all the
15285 subprograms are included.
15287 If the switch is followed by a @code{j} (e.g., @code{-gnatRj}), then
15288 the output is in the JSON data interchange format specified by the
15289 ECMA-404 standard. The semantic description of this JSON output is
15290 available in the specification of the Repinfo unit present in the
15291 compiler sources.
15293 If the switch is followed by an @code{s} (e.g., @code{-gnatR3s}), then
15294 the output is to a file with the name @code{file.rep} where @code{file} is
15295 the name of the corresponding source file, except if @code{j} is also
15296 specified, in which case the file name is @code{file.json}.
15298 Note that it is possible for record components to have zero size. In
15299 this case, the component clause uses an obvious extension of permitted
15300 Ada syntax, for example @code{at 0 range 0 .. -1}.
15301 @end table
15303 @geindex -gnatS (gcc)
15306 @table @asis
15308 @item @code{-gnatS}
15310 The use of the switch @code{-gnatS} for an
15311 Ada compilation will cause the compiler to output a
15312 representation of package Standard in a form very
15313 close to standard Ada. It is not quite possible to
15314 do this entirely in standard Ada (since new
15315 numeric base types cannot be created in standard
15316 Ada), but the output is easily
15317 readable to any Ada programmer, and is useful to
15318 determine the characteristics of target dependent
15319 types in package Standard.
15320 @end table
15322 @geindex -gnatx (gcc)
15325 @table @asis
15327 @item @code{-gnatx}
15329 Normally the compiler generates full cross-referencing information in
15330 the @code{ALI} file. This information is used by a number of tools.
15331 The @code{-gnatx} switch suppresses this information. This saves some space
15332 and may slightly speed up compilation, but means that tools depending
15333 on this information cannot be used.
15334 @end table
15336 @geindex -fgnat-encodings (gcc)
15339 @table @asis
15341 @item @code{-fgnat-encodings=[all|gdb|minimal]}
15343 This switch controls the balance between GNAT encodings and standard DWARF
15344 emitted in the debug information.
15346 Historically, old debug formats like stabs were not powerful enough to
15347 express some Ada types (for instance, variant records or fixed-point types).
15348 To work around this, GNAT introduced proprietary encodings that embed the
15349 missing information (“GNAT encodings”).
15351 Recent versions of the DWARF debug information format are now able to
15352 correctly describe most of these Ada constructs (“standard DWARF”). As
15353 third-party tools started to use this format, GNAT has been enhanced to
15354 generate it. However, most tools (including GDB) are still relying on GNAT
15355 encodings.
15357 To support all tools, GNAT needs to be versatile about the balance between
15358 generation of GNAT encodings and standard DWARF. This is what
15359 @code{-fgnat-encodings} is about.
15362 @itemize *
15364 @item 
15365 @code{=all}: Emit all GNAT encodings, and then emit as much standard DWARF as
15366 possible so it does not conflict with GNAT encodings.
15368 @item 
15369 @code{=gdb}: Emit as much standard DWARF as possible as long as the current
15370 GDB handles it. Emit GNAT encodings for the rest.
15372 @item 
15373 @code{=minimal}: Emit as much standard DWARF as possible and emit GNAT
15374 encodings for the rest.
15375 @end itemize
15376 @end table
15378 @node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
15379 @anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{108}@anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{109}
15380 @subsection Exception Handling Control
15383 GNAT uses two methods for handling exceptions at run time. The
15384 @code{setjmp/longjmp} method saves the context when entering
15385 a frame with an exception handler. Then when an exception is
15386 raised, the context can be restored immediately, without the
15387 need for tracing stack frames. This method provides very fast
15388 exception propagation, but introduces significant overhead for
15389 the use of exception handlers, even if no exception is raised.
15391 The other approach is called ‘zero cost’ exception handling.
15392 With this method, the compiler builds static tables to describe
15393 the exception ranges. No dynamic code is required when entering
15394 a frame containing an exception handler. When an exception is
15395 raised, the tables are used to control a back trace of the
15396 subprogram invocation stack to locate the required exception
15397 handler. This method has considerably poorer performance for
15398 the propagation of exceptions, but there is no overhead for
15399 exception handlers if no exception is raised. Note that in this
15400 mode and in the context of mixed Ada and C/C++ programming,
15401 to propagate an exception through a C/C++ code, the C/C++ code
15402 must be compiled with the @code{-funwind-tables} GCC’s
15403 option.
15405 The following switches may be used to control which of the
15406 two exception handling methods is used.
15408 @geindex --RTS=sjlj (gnatmake)
15411 @table @asis
15413 @item @code{--RTS=sjlj}
15415 This switch causes the setjmp/longjmp run-time (when available) to be used
15416 for exception handling. If the default
15417 mechanism for the target is zero cost exceptions, then
15418 this switch can be used to modify this default, and must be
15419 used for all units in the partition.
15420 This option is rarely used. One case in which it may be
15421 advantageous is if you have an application where exception
15422 raising is common and the overall performance of the
15423 application is improved by favoring exception propagation.
15424 @end table
15426 @geindex --RTS=zcx (gnatmake)
15428 @geindex Zero Cost Exceptions
15431 @table @asis
15433 @item @code{--RTS=zcx}
15435 This switch causes the zero cost approach to be used
15436 for exception handling. If this is the default mechanism for the
15437 target (see below), then this switch is unneeded. If the default
15438 mechanism for the target is setjmp/longjmp exceptions, then
15439 this switch can be used to modify this default, and must be
15440 used for all units in the partition.
15441 This option can only be used if the zero cost approach
15442 is available for the target in use, otherwise it will generate an error.
15443 @end table
15445 The same option @code{--RTS} must be used both for @code{gcc}
15446 and @code{gnatbind}. Passing this option to @code{gnatmake}
15447 (@ref{d0,,Switches for gnatmake}) will ensure the required consistency
15448 through the compilation and binding steps.
15450 @node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
15451 @anchor{gnat_ugn/building_executable_programs_with_gnat id29}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat units-to-sources-mapping-files}@anchor{ea}
15452 @subsection Units to Sources Mapping Files
15455 @geindex -gnatem (gcc)
15458 @table @asis
15460 @item @code{-gnatem=`path'}
15462 A mapping file is a way to communicate to the compiler two mappings:
15463 from unit names to file names (without any directory information) and from
15464 file names to path names (with full directory information). These mappings
15465 are used by the compiler to short-circuit the path search.
15467 The use of mapping files is not required for correct operation of the
15468 compiler, but mapping files can improve efficiency, particularly when
15469 sources are read over a slow network connection. In normal operation,
15470 you need not be concerned with the format or use of mapping files,
15471 and the @code{-gnatem} switch is not a switch that you would use
15472 explicitly. It is intended primarily for use by automatic tools such as
15473 @code{gnatmake} running under the project file facility. The
15474 description here of the format of mapping files is provided
15475 for completeness and for possible use by other tools.
15477 A mapping file is a sequence of sets of three lines. In each set, the
15478 first line is the unit name, in lower case, with @code{%s} appended
15479 for specs and @code{%b} appended for bodies; the second line is the
15480 file name; and the third line is the path name.
15482 Example:
15484 @example
15485 main%b
15486 main.2.ada
15487 /gnat/project1/sources/main.2.ada
15488 @end example
15490 When the switch @code{-gnatem} is specified, the compiler will
15491 create in memory the two mappings from the specified file. If there is
15492 any problem (nonexistent file, truncated file or duplicate entries),
15493 no mapping will be created.
15495 Several @code{-gnatem} switches may be specified; however, only the
15496 last one on the command line will be taken into account.
15498 When using a project file, @code{gnatmake} creates a temporary
15499 mapping file and communicates it to the compiler using this switch.
15500 @end table
15502 @node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
15503 @anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{10b}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{10c}
15504 @subsection Code Generation Control
15507 The GCC technology provides a wide range of target dependent
15508 @code{-m} switches for controlling
15509 details of code generation with respect to different versions of
15510 architectures. This includes variations in instruction sets (e.g.,
15511 different members of the power pc family), and different requirements
15512 for optimal arrangement of instructions (e.g., different members of
15513 the x86 family). The list of available @code{-m} switches may be
15514 found in the GCC documentation.
15516 Use of these @code{-m} switches may in some cases result in improved
15517 code performance.
15519 The GNAT technology is tested and qualified without any
15520 @code{-m} switches,
15521 so generally the most reliable approach is to avoid the use of these
15522 switches. However, we generally expect most of these switches to work
15523 successfully with GNAT, and many customers have reported successful
15524 use of these options.
15526 Our general advice is to avoid the use of @code{-m} switches unless
15527 special needs lead to requirements in this area. In particular,
15528 there is no point in using @code{-m} switches to improve performance
15529 unless you actually see a performance improvement.
15531 @node Linker Switches,Binding with gnatbind,Compiler Switches,Building Executable Programs with GNAT
15532 @anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{10d}@anchor{gnat_ugn/building_executable_programs_with_gnat linker-switches}@anchor{10e}
15533 @section Linker Switches
15536 Linker switches can be specified after @code{-largs} builder switch.
15538 @geindex -fuse-ld=name
15541 @table @asis
15543 @item @code{-fuse-ld=`name'}
15545 Linker to be used. The default is @code{bfd} for @code{ld.bfd}; @code{gold}
15546 (for @code{ld.gold}) and @code{mold} (for @code{ld.mold}) are more
15547 recent and faster alternatives, but only available on GNU/Linux
15548 platforms.
15549 @end table
15551 @node Binding with gnatbind,Linking with gnatlink,Linker Switches,Building Executable Programs with GNAT
15552 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{ca}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{10f}
15553 @section Binding with @code{gnatbind}
15556 @geindex gnatbind
15558 This chapter describes the GNAT binder, @code{gnatbind}, which is used
15559 to bind compiled GNAT objects.
15561 The @code{gnatbind} program performs four separate functions:
15564 @itemize *
15566 @item 
15567 Checks that a program is consistent, in accordance with the rules in
15568 Chapter 10 of the Ada Reference Manual. In particular, error
15569 messages are generated if a program uses inconsistent versions of a
15570 given unit.
15572 @item 
15573 Checks that an acceptable order of elaboration exists for the program
15574 and issues an error message if it cannot find an order of elaboration
15575 that satisfies the rules in Chapter 10 of the Ada Language Manual.
15577 @item 
15578 Generates a main program incorporating the given elaboration order.
15579 This program is a small Ada package (body and spec) that
15580 must be subsequently compiled
15581 using the GNAT compiler. The necessary compilation step is usually
15582 performed automatically by @code{gnatlink}. The two most important
15583 functions of this program
15584 are to call the elaboration routines of units in an appropriate order
15585 and to call the main program.
15587 @item 
15588 Determines the set of object files required by the given main program.
15589 This information is output in the forms of comments in the generated program,
15590 to be read by the @code{gnatlink} utility used to link the Ada application.
15591 @end itemize
15593 @menu
15594 * Running gnatbind:: 
15595 * Switches for gnatbind:: 
15596 * Command-Line Access:: 
15597 * Search Paths for gnatbind:: 
15598 * Examples of gnatbind Usage:: 
15600 @end menu
15602 @node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15603 @anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{110}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{111}
15604 @subsection Running @code{gnatbind}
15607 The form of the @code{gnatbind} command is
15609 @example
15610 $ gnatbind [ switches ] mainprog[.ali] [ switches ]
15611 @end example
15613 where @code{mainprog.adb} is the Ada file containing the main program
15614 unit body. @code{gnatbind} constructs an Ada
15615 package in two files whose names are
15616 @code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15617 For example, if given the
15618 parameter @code{hello.ali}, for a main program contained in file
15619 @code{hello.adb}, the binder output files would be @code{b~hello.ads}
15620 and @code{b~hello.adb}.
15622 When doing consistency checking, the binder takes into consideration
15623 any source files it can locate. For example, if the binder determines
15624 that the given main program requires the package @code{Pack}, whose
15625 @code{.ALI}
15626 file is @code{pack.ali} and whose corresponding source spec file is
15627 @code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15628 (using the same search path conventions as previously described for the
15629 @code{gcc} command). If it can locate this source file, it checks that
15630 the time stamps
15631 or source checksums of the source and its references to in @code{ALI} files
15632 match. In other words, any @code{ALI} files that mentions this spec must have
15633 resulted from compiling this version of the source file (or in the case
15634 where the source checksums match, a version close enough that the
15635 difference does not matter).
15637 @geindex Source files
15638 @geindex use by binder
15640 The effect of this consistency checking, which includes source files, is
15641 that the binder ensures that the program is consistent with the latest
15642 version of the source files that can be located at bind time. Editing a
15643 source file without compiling files that depend on the source file cause
15644 error messages to be generated by the binder.
15646 For example, suppose you have a main program @code{hello.adb} and a
15647 package @code{P}, from file @code{p.ads} and you perform the following
15648 steps:
15651 @itemize *
15653 @item 
15654 Enter @code{gcc -c hello.adb} to compile the main program.
15656 @item 
15657 Enter @code{gcc -c p.ads} to compile package @code{P}.
15659 @item 
15660 Edit file @code{p.ads}.
15662 @item 
15663 Enter @code{gnatbind hello}.
15664 @end itemize
15666 At this point, the file @code{p.ali} contains an out-of-date time stamp
15667 because the file @code{p.ads} has been edited. The attempt at binding
15668 fails, and the binder generates the following error messages:
15670 @example
15671 error: "hello.adb" must be recompiled ("p.ads" has been modified)
15672 error: "p.ads" has been modified and must be recompiled
15673 @end example
15675 Now both files must be recompiled as indicated, and then the bind can
15676 succeed, generating a main program. You need not normally be concerned
15677 with the contents of this file, but for reference purposes a sample
15678 binder output file is given in @ref{e,,Example of Binder Output File}.
15680 In most normal usage, the default mode of @code{gnatbind} which is to
15681 generate the main package in Ada, as described in the previous section.
15682 In particular, this means that any Ada programmer can read and understand
15683 the generated main program. It can also be debugged just like any other
15684 Ada code provided the @code{-g} switch is used for
15685 @code{gnatbind} and @code{gnatlink}.
15687 @node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15688 @anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{112}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{113}
15689 @subsection Switches for @code{gnatbind}
15692 The following switches are available with @code{gnatbind}; details will
15693 be presented in subsequent sections.
15695 @geindex --version (gnatbind)
15698 @table @asis
15700 @item @code{--version}
15702 Display Copyright and version, then exit disregarding all other options.
15703 @end table
15705 @geindex --help (gnatbind)
15708 @table @asis
15710 @item @code{--help}
15712 If @code{--version} was not used, display usage, then exit disregarding
15713 all other options.
15714 @end table
15716 @geindex -a (gnatbind)
15719 @table @asis
15721 @item @code{-a}
15723 Indicates that, if supported by the platform, the adainit procedure should
15724 be treated as an initialisation routine by the linker (a constructor). This
15725 is intended to be used by the Project Manager to automatically initialize
15726 shared Stand-Alone Libraries.
15727 @end table
15729 @geindex -aO (gnatbind)
15732 @table @asis
15734 @item @code{-aO}
15736 Specify directory to be searched for ALI files.
15737 @end table
15739 @geindex -aI (gnatbind)
15742 @table @asis
15744 @item @code{-aI}
15746 Specify directory to be searched for source file.
15747 @end table
15749 @geindex -A (gnatbind)
15752 @table @asis
15754 @item @code{-A[=`filename']}
15756 Output ALI list (to standard output or to the named file).
15757 @end table
15759 @geindex -b (gnatbind)
15762 @table @asis
15764 @item @code{-b}
15766 Generate brief messages to @code{stderr} even if verbose mode set.
15767 @end table
15769 @geindex -c (gnatbind)
15772 @table @asis
15774 @item @code{-c}
15776 Check only, no generation of binder output file.
15777 @end table
15779 @geindex -dnn[k|m] (gnatbind)
15782 @table @asis
15784 @item @code{-d`nn'[k|m]}
15786 This switch can be used to change the default task stack size value
15787 to a specified size @code{nn}, which is expressed in bytes by default, or
15788 in kilobytes when suffixed with @code{k} or in megabytes when suffixed
15789 with @code{m}.
15790 In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15791 in effect, to completing all task specs with
15793 @example
15794 pragma Storage_Size (nn);
15795 @end example
15797 When they do not already have such a pragma.
15798 @end table
15800 @geindex -D (gnatbind)
15803 @table @asis
15805 @item @code{-D`nn'[k|m]}
15807 Set the default secondary stack size to @code{nn}. The suffix indicates whether
15808 the size is in bytes (no suffix), kilobytes (@code{k} suffix) or megabytes
15809 (@code{m} suffix).
15811 The secondary stack holds objects of unconstrained types that are returned by
15812 functions, for example unconstrained Strings. The size of the secondary stack
15813 can be dynamic or fixed depending on the target.
15815 For most targets, the secondary stack grows on demand and is implemented as
15816 a chain of blocks in the heap. In this case, the default secondary stack size
15817 determines the initial size of the secondary stack for each task and the
15818 smallest amount the secondary stack can grow by.
15820 For Light, Light-Tasking, and Embedded run-times the size of the secondary
15821 stack is fixed. This switch can be used to change the default size of these
15822 stacks. The default secondary stack size can be overridden on a per-task
15823 basis if individual tasks have different secondary stack requirements. This
15824 is achieved through the Secondary_Stack_Size aspect, which takes the size of
15825 the secondary stack in bytes.
15826 @end table
15828 @geindex -e (gnatbind)
15831 @table @asis
15833 @item @code{-e}
15835 Output complete list of elaboration-order dependencies.
15836 @end table
15838 @geindex -Ea (gnatbind)
15841 @table @asis
15843 @item @code{-Ea}
15845 Store tracebacks in exception occurrences when the target supports it.
15846 The “a” is for “address”; tracebacks will contain hexadecimal addresses,
15847 unless symbolic tracebacks are enabled.
15849 See also the packages @code{GNAT.Traceback} and
15850 @code{GNAT.Traceback.Symbolic} for more information.
15851 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
15852 @code{gcc} option.
15853 @end table
15855 @geindex -Es (gnatbind)
15858 @table @asis
15860 @item @code{-Es}
15862 Store tracebacks in exception occurrences when the target supports it.
15863 The “s” is for “symbolic”; symbolic tracebacks are enabled.
15864 @end table
15866 @geindex -E (gnatbind)
15869 @table @asis
15871 @item @code{-E}
15873 Currently the same as @code{-Ea}.
15874 @end table
15876 @geindex -f (gnatbind)
15879 @table @asis
15881 @item @code{-f`elab-order'}
15883 Force elaboration order. For further details see @ref{114,,Elaboration Control}
15884 and @ref{f,,Elaboration Order Handling in GNAT}.
15885 @end table
15887 @geindex -F (gnatbind)
15890 @table @asis
15892 @item @code{-F}
15894 Force the checks of elaboration flags. @code{gnatbind} does not normally
15895 generate checks of elaboration flags for the main executable, except when
15896 a Stand-Alone Library is used. However, there are cases when this cannot be
15897 detected by gnatbind. An example is importing an interface of a Stand-Alone
15898 Library through a pragma Import and only specifying through a linker switch
15899 this Stand-Alone Library. This switch is used to guarantee that elaboration
15900 flag checks are generated.
15901 @end table
15903 @geindex -h (gnatbind)
15906 @table @asis
15908 @item @code{-h}
15910 Output usage (help) information.
15911 @end table
15913 @geindex -H (gnatbind)
15916 @table @asis
15918 @item @code{-H}
15920 Legacy elaboration order model enabled. For further details see
15921 @ref{f,,Elaboration Order Handling in GNAT}.
15922 @end table
15924 @geindex -H32 (gnatbind)
15927 @table @asis
15929 @item @code{-H32}
15931 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
15932 For further details see @ref{115,,Dynamic Allocation Control}.
15933 @end table
15935 @geindex -H64 (gnatbind)
15937 @geindex __gnat_malloc
15940 @table @asis
15942 @item @code{-H64}
15944 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
15945 For further details see @ref{115,,Dynamic Allocation Control}.
15947 @geindex -I (gnatbind)
15949 @item @code{-I}
15951 Specify directory to be searched for source and ALI files.
15953 @geindex -I- (gnatbind)
15955 @item @code{-I-}
15957 Do not look for sources in the current directory where @code{gnatbind} was
15958 invoked, and do not look for ALI files in the directory containing the
15959 ALI file named in the @code{gnatbind} command line.
15961 @geindex -k (gnatbind)
15963 @item @code{-k}
15965 Disable checking of elaboration flags. When using @code{-n}
15966 either explicitly or implicitly, @code{-F} is also implied,
15967 unless @code{-k} is used. This switch should be used with care
15968 and you should ensure manually that elaboration routines are not called
15969 twice unintentionally.
15971 @geindex -K (gnatbind)
15973 @item @code{-K}
15975 Give list of linker options specified for link.
15977 @geindex -l (gnatbind)
15979 @item @code{-l}
15981 Output chosen elaboration order.
15983 @geindex -L (gnatbind)
15985 @item @code{-L`xxx'}
15987 Bind the units for library building. In this case the @code{adainit} and
15988 @code{adafinal} procedures (@ref{7e,,Binding with Non-Ada Main Programs})
15989 are renamed to @code{@var{xxx}init} and
15990 @code{@var{xxx}final}.
15991 Implies -n.
15992 (@ref{2a,,GNAT and Libraries}, for more details.)
15994 @geindex -M (gnatbind)
15996 @item @code{-M`xyz'}
15998 Rename generated main program from main to xyz. This option is
15999 supported on cross environments only.
16001 @geindex -m (gnatbind)
16003 @item @code{-m`n'}
16005 Limit number of detected errors or warnings to @code{n}, where @code{n} is
16006 in the range 1..999999. The default value if no switch is
16007 given is 9999. If the number of warnings reaches this limit, then a
16008 message is output and further warnings are suppressed, the bind
16009 continues in this case. If the number of errors reaches this
16010 limit, then a message is output and the bind is abandoned.
16011 A value of zero means that no limit is enforced. The equal
16012 sign is optional.
16014 @geindex -minimal (gnatbind)
16016 @item @code{-minimal}
16018 Generate a binder file suitable for space-constrained applications. When
16019 active, binder-generated objects not required for program operation are no
16020 longer generated. `Warning:' this option comes with the following
16021 limitations:
16024 @itemize *
16026 @item 
16027 Starting the program’s execution in the debugger will cause it to
16028 stop at the start of the @code{main} function instead of the main subprogram.
16029 This can be worked around by manually inserting a breakpoint on that
16030 subprogram and resuming the program’s execution until reaching that breakpoint.
16032 @item 
16033 Programs using GNAT.Compiler_Version will not link.
16034 @end itemize
16036 @geindex -n (gnatbind)
16038 @item @code{-n}
16040 No main program.
16042 @geindex -nostdinc (gnatbind)
16044 @item @code{-nostdinc}
16046 Do not look for sources in the system default directory.
16048 @geindex -nostdlib (gnatbind)
16050 @item @code{-nostdlib}
16052 Do not look for library files in the system default directory.
16054 @geindex --RTS (gnatbind)
16056 @item @code{--RTS=`rts-path'}
16058 Specifies the default location of the run-time library. Same meaning as the
16059 equivalent @code{gnatmake} flag (@ref{d0,,Switches for gnatmake}).
16061 @geindex -o (gnatbind)
16063 @item @code{-o `file'}
16065 Name the output file @code{file} (default is @code{b~`xxx}.adb`).
16066 Note that if this option is used, then linking must be done manually,
16067 gnatlink cannot be used.
16069 @geindex -O (gnatbind)
16071 @item @code{-O[=`filename']}
16073 Output object list (to standard output or to the named file).
16075 @geindex -p (gnatbind)
16077 @item @code{-p}
16079 Pessimistic (worst-case) elaboration order.
16081 @geindex -P (gnatbind)
16083 @item @code{-P}
16085 Generate binder file suitable for CodePeer.
16086 @end table
16088 @geindex -Q (gnatbind)
16091 @table @asis
16093 @item @code{-Q`nnn'}
16095 Generate @code{nnn} additional default-sized secondary stacks.
16097 Tasks declared at the library level that use default-size secondary stacks
16098 have their secondary stacks allocated from a pool of stacks generated by
16099 gnatbind. This allows the default secondary stack size to be quickly changed
16100 by rebinding the application.
16102 While the binder sizes this pool to match the number of such tasks defined in
16103 the application, the pool size may need to be increased with the @code{-Q}
16104 switch to accommodate foreign threads registered with the Light run-time. For
16105 more information, please see the `The Primary and Secondary Stack' chapter in
16106 the `GNAT User’s Guide Supplement for Cross Platforms'.
16108 @geindex -R (gnatbind)
16110 @item @code{-R}
16112 Output closure source list, which includes all non-run-time units that are
16113 included in the bind.
16115 @geindex -Ra (gnatbind)
16117 @item @code{-Ra}
16119 Like @code{-R} but the list includes run-time units.
16121 @geindex -s (gnatbind)
16123 @item @code{-s}
16125 Require all source files to be present.
16127 @geindex -S (gnatbind)
16129 @item @code{-S`xxx'}
16131 Specifies the value to be used when detecting uninitialized scalar
16132 objects with pragma Initialize_Scalars.
16133 The @code{xxx} string specified with the switch is one of:
16136 @itemize *
16138 @item 
16139 @code{in} for an invalid value.
16141 If zero is invalid for the discrete type in question,
16142 then the scalar value is set to all zero bits.
16143 For signed discrete types, the largest possible negative value of
16144 the underlying scalar is set (i.e. a one bit followed by all zero bits).
16145 For unsigned discrete types, the underlying scalar value is set to all
16146 one bits. For floating-point types, a NaN value is set
16147 (see body of package System.Scalar_Values for exact values).
16149 @item 
16150 @code{lo} for low value.
16152 If zero is invalid for the discrete type in question,
16153 then the scalar value is set to all zero bits.
16154 For signed discrete types, the largest possible negative value of
16155 the underlying scalar is set (i.e. a one bit followed by all zero bits).
16156 For unsigned discrete types, the underlying scalar value is set to all
16157 zero bits. For floating-point, a small value is set
16158 (see body of package System.Scalar_Values for exact values).
16160 @item 
16161 @code{hi} for high value.
16163 If zero is invalid for the discrete type in question,
16164 then the scalar value is set to all one bits.
16165 For signed discrete types, the largest possible positive value of
16166 the underlying scalar is set (i.e. a zero bit followed by all one bits).
16167 For unsigned discrete types, the underlying scalar value is set to all
16168 one bits. For floating-point, a large value is set
16169 (see body of package System.Scalar_Values for exact values).
16171 @item 
16172 @code{xx} for hex value (two hex digits).
16174 The underlying scalar is set to a value consisting of repeated bytes, whose
16175 value corresponds to the given value. For example if @code{BF} is given,
16176 then a 32-bit scalar value will be set to the bit pattern @code{16#BFBFBFBF#}.
16177 @end itemize
16179 @geindex GNAT_INIT_SCALARS
16181 In addition, you can specify @code{-Sev} to indicate that the value is
16182 to be set at run time. In this case, the program will look for an environment
16183 variable of the form @code{GNAT_INIT_SCALARS=@var{yy}}, where @code{yy} is one
16184 of @code{in/lo/hi/@var{xx}} with the same meanings as above.
16185 If no environment variable is found, or if it does not have a valid value,
16186 then the default is @code{in} (invalid values).
16187 @end table
16189 @geindex -static (gnatbind)
16192 @table @asis
16194 @item @code{-static}
16196 Link against a static GNAT run-time.
16198 @geindex -shared (gnatbind)
16200 @item @code{-shared}
16202 Link against a shared GNAT run-time when available.
16204 @geindex -t (gnatbind)
16206 @item @code{-t}
16208 Tolerate time stamp and other consistency errors.
16210 @geindex -T (gnatbind)
16212 @item @code{-T`n'}
16214 Set the time slice value to @code{n} milliseconds. If the system supports
16215 the specification of a specific time slice value, then the indicated value
16216 is used. If the system does not support specific time slice values, but
16217 does support some general notion of round-robin scheduling, then any
16218 nonzero value will activate round-robin scheduling.
16220 A value of zero is treated specially. It turns off time
16221 slicing, and in addition, indicates to the tasking run-time that the
16222 semantics should match as closely as possible the Annex D
16223 requirements of the Ada RM, and in particular sets the default
16224 scheduling policy to @code{FIFO_Within_Priorities}.
16226 @geindex -u (gnatbind)
16228 @item @code{-u`n'}
16230 Enable dynamic stack usage, with @code{n} results stored and displayed
16231 at program termination. A result is generated when a task
16232 terminates. Results that can’t be stored are displayed on the fly, at
16233 task termination. This option is currently not supported on Itanium
16234 platforms. (See @ref{116,,Dynamic Stack Usage Analysis} for details.)
16236 @geindex -v (gnatbind)
16238 @item @code{-v}
16240 Verbose mode. Write error messages, header, summary output to
16241 @code{stdout}.
16243 @geindex -V (gnatbind)
16245 @item @code{-V`key'=`value'}
16247 Store the given association of @code{key} to @code{value} in the bind environment.
16248 Values stored this way can be retrieved at run time using
16249 @code{GNAT.Bind_Environment}.
16251 @geindex -w (gnatbind)
16253 @item @code{-w`x'}
16255 Warning mode; @code{x} = s/e for suppress/treat as error.
16257 @geindex -Wx (gnatbind)
16259 @item @code{-Wx`e'}
16261 Override default wide character encoding for standard Text_IO files.
16263 @geindex -x (gnatbind)
16265 @item @code{-x}
16267 Exclude source files (check object consistency only).
16269 @geindex -xdr (gnatbind)
16271 @item @code{-xdr}
16273 Use the target-independent XDR protocol for stream oriented attributes
16274 instead of the default implementation which is based on direct binary
16275 representations and is therefore target-and endianness-dependent.
16276 However it does not support 128-bit integer types and the exception
16277 @code{Ada.IO_Exceptions.Device_Error} is raised if any attempt is made
16278 at streaming 128-bit integer types with it.
16280 @geindex -Xnnn (gnatbind)
16282 @item @code{-X`nnn'}
16284 Set default exit status value, normally 0 for POSIX compliance.
16286 @geindex -y (gnatbind)
16288 @item @code{-y}
16290 Enable leap seconds support in @code{Ada.Calendar} and its children.
16292 @geindex -z (gnatbind)
16294 @item @code{-z}
16296 No main subprogram.
16297 @end table
16299 You may obtain this listing of switches by running @code{gnatbind} with
16300 no arguments.
16302 @menu
16303 * Consistency-Checking Modes:: 
16304 * Binder Error Message Control:: 
16305 * Elaboration Control:: 
16306 * Output Control:: 
16307 * Dynamic Allocation Control:: 
16308 * Binding with Non-Ada Main Programs:: 
16309 * Binding Programs with No Main Subprogram:: 
16311 @end menu
16313 @node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
16314 @anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{117}@anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{118}
16315 @subsubsection Consistency-Checking Modes
16318 As described earlier, by default @code{gnatbind} checks
16319 that object files are consistent with one another and are consistent
16320 with any source files it can locate. The following switches control binder
16321 access to sources.
16323 @quotation
16325 @geindex -s (gnatbind)
16326 @end quotation
16329 @table @asis
16331 @item @code{-s}
16333 Require source files to be present. In this mode, the binder must be
16334 able to locate all source files that are referenced, in order to check
16335 their consistency. In normal mode, if a source file cannot be located it
16336 is simply ignored. If you specify this switch, a missing source
16337 file is an error.
16339 @geindex -Wx (gnatbind)
16341 @item @code{-Wx`e'}
16343 Override default wide character encoding for standard Text_IO files.
16344 Normally the default wide character encoding method used for standard
16345 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
16346 the main source input (see description of switch
16347 @code{-gnatWx} for the compiler). The
16348 use of this switch for the binder (which has the same set of
16349 possible arguments) overrides this default as specified.
16351 @geindex -x (gnatbind)
16353 @item @code{-x}
16355 Exclude source files. In this mode, the binder only checks that ALI
16356 files are consistent with one another. Source files are not accessed.
16357 The binder runs faster in this mode, and there is still a guarantee that
16358 the resulting program is self-consistent.
16359 If a source file has been edited since it was last compiled, and you
16360 specify this switch, the binder will not detect that the object
16361 file is out of date with respect to the source file. Note that this is the
16362 mode that is automatically used by @code{gnatmake} because in this
16363 case the checking against sources has already been performed by
16364 @code{gnatmake} in the course of compilation (i.e., before binding).
16365 @end table
16367 @node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
16368 @anchor{gnat_ugn/building_executable_programs_with_gnat binder-error-message-control}@anchor{119}@anchor{gnat_ugn/building_executable_programs_with_gnat id36}@anchor{11a}
16369 @subsubsection Binder Error Message Control
16372 The following switches provide control over the generation of error
16373 messages from the binder:
16375 @quotation
16377 @geindex -v (gnatbind)
16378 @end quotation
16381 @table @asis
16383 @item @code{-v}
16385 Verbose mode. In the normal mode, brief error messages are generated to
16386 @code{stderr}. If this switch is present, a header is written
16387 to @code{stdout} and any error messages are directed to @code{stdout}.
16388 All that is written to @code{stderr} is a brief summary message.
16390 @geindex -b (gnatbind)
16392 @item @code{-b}
16394 Generate brief error messages to @code{stderr} even if verbose mode is
16395 specified. This is relevant only when used with the
16396 @code{-v} switch.
16398 @geindex -m (gnatbind)
16400 @item @code{-m`n'}
16402 Limits the number of error messages to @code{n}, a decimal integer in the
16403 range 1-999. The binder terminates immediately if this limit is reached.
16405 @geindex -M (gnatbind)
16407 @item @code{-M`xxx'}
16409 Renames the generated main program from @code{main} to @code{xxx}.
16410 This is useful in the case of some cross-building environments, where
16411 the actual main program is separate from the one generated
16412 by @code{gnatbind}.
16414 @geindex -ws (gnatbind)
16416 @geindex Warnings
16418 @item @code{-ws}
16420 Suppress all warning messages.
16422 @geindex -we (gnatbind)
16424 @item @code{-we}
16426 Treat any warning messages as fatal errors.
16428 @geindex -t (gnatbind)
16430 @geindex Time stamp checks
16431 @geindex in binder
16433 @geindex Binder consistency checks
16435 @geindex Consistency checks
16436 @geindex in binder
16438 @item @code{-t}
16440 The binder performs a number of consistency checks including:
16443 @itemize *
16445 @item 
16446 Check that time stamps of a given source unit are consistent
16448 @item 
16449 Check that checksums of a given source unit are consistent
16451 @item 
16452 Check that consistent versions of @code{GNAT} were used for compilation
16454 @item 
16455 Check consistency of configuration pragmas as required
16456 @end itemize
16458 Normally failure of such checks, in accordance with the consistency
16459 requirements of the Ada Reference Manual, causes error messages to be
16460 generated which abort the binder and prevent the output of a binder
16461 file and subsequent link to obtain an executable.
16463 The @code{-t} switch converts these error messages
16464 into warnings, so that
16465 binding and linking can continue to completion even in the presence of such
16466 errors. The result may be a failed link (due to missing symbols), or a
16467 non-functional executable which has undefined semantics.
16469 @cartouche
16470 @quotation Note 
16471 This means that @code{-t} should be used only in unusual situations,
16472 with extreme care.
16473 @end quotation
16474 @end cartouche
16475 @end table
16477 @node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
16478 @anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{114}@anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{11b}
16479 @subsubsection Elaboration Control
16482 The following switches provide additional control over the elaboration
16483 order. For further details see @ref{f,,Elaboration Order Handling in GNAT}.
16485 @geindex -f (gnatbind)
16488 @table @asis
16490 @item @code{-f`elab-order'}
16492 Force elaboration order.
16494 @code{elab-order} should be the name of a “forced elaboration order file”, that
16495 is, a text file containing library item names, one per line. A name of the
16496 form “some.unit%s” or “some.unit (spec)” denotes the spec of Some.Unit. A
16497 name of the form “some.unit%b” or “some.unit (body)” denotes the body of
16498 Some.Unit. Each pair of lines is taken to mean that there is an elaboration
16499 dependence of the second line on the first. For example, if the file
16500 contains:
16502 @example
16503 this (spec)
16504 this (body)
16505 that (spec)
16506 that (body)
16507 @end example
16509 then the spec of This will be elaborated before the body of This, and the
16510 body of This will be elaborated before the spec of That, and the spec of That
16511 will be elaborated before the body of That. The first and last of these three
16512 dependences are already required by Ada rules, so this file is really just
16513 forcing the body of This to be elaborated before the spec of That.
16515 The given order must be consistent with Ada rules, or else @code{gnatbind} will
16516 give elaboration cycle errors. For example, if you say x (body) should be
16517 elaborated before x (spec), there will be a cycle, because Ada rules require
16518 x (spec) to be elaborated before x (body); you can’t have the spec and body
16519 both elaborated before each other.
16521 If you later add “with That;” to the body of This, there will be a cycle, in
16522 which case you should erase either “this (body)” or “that (spec)” from the
16523 above forced elaboration order file.
16525 Blank lines and Ada-style comments are ignored. Unit names that do not exist
16526 in the program are ignored. Units in the GNAT predefined library are also
16527 ignored.
16528 @end table
16530 @geindex -p (gnatbind)
16533 @table @asis
16535 @item @code{-p}
16537 Pessimistic elaboration order
16539 This switch is only applicable to the pre-20.x legacy elaboration models.
16540 The post-20.x elaboration model uses a more informed approach of ordering
16541 the units.
16543 Normally the binder attempts to choose an elaboration order that is likely to
16544 minimize the likelihood of an elaboration order error resulting in raising a
16545 @code{Program_Error} exception. This switch reverses the action of the binder,
16546 and requests that it deliberately choose an order that is likely to maximize
16547 the likelihood of an elaboration error. This is useful in ensuring
16548 portability and avoiding dependence on accidental fortuitous elaboration
16549 ordering.
16551 Normally it only makes sense to use the @code{-p} switch if dynamic
16552 elaboration checking is used (@code{-gnatE} switch used for compilation).
16553 This is because in the default static elaboration mode, all necessary
16554 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
16555 These implicit pragmas are still respected by the binder in @code{-p}
16556 mode, so a safe elaboration order is assured.
16558 Note that @code{-p} is not intended for production use; it is more for
16559 debugging/experimental use.
16560 @end table
16562 @node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
16563 @anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{11c}@anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{11d}
16564 @subsubsection Output Control
16567 The following switches allow additional control over the output
16568 generated by the binder.
16570 @quotation
16572 @geindex -c (gnatbind)
16573 @end quotation
16576 @table @asis
16578 @item @code{-c}
16580 Check only. Do not generate the binder output file. In this mode the
16581 binder performs all error checks but does not generate an output file.
16583 @geindex -e (gnatbind)
16585 @item @code{-e}
16587 Output complete list of elaboration-order dependencies, showing the
16588 reason for each dependency. This output can be rather extensive but may
16589 be useful in diagnosing problems with elaboration order. The output is
16590 written to @code{stdout}.
16592 @geindex -h (gnatbind)
16594 @item @code{-h}
16596 Output usage information. The output is written to @code{stdout}.
16598 @geindex -K (gnatbind)
16600 @item @code{-K}
16602 Output linker options to @code{stdout}. Includes library search paths,
16603 contents of pragmas Ident and Linker_Options, and libraries added
16604 by @code{gnatbind}.
16606 @geindex -l (gnatbind)
16608 @item @code{-l}
16610 Output chosen elaboration order. The output is written to @code{stdout}.
16612 @geindex -O (gnatbind)
16614 @item @code{-O}
16616 Output full names of all the object files that must be linked to provide
16617 the Ada component of the program. The output is written to @code{stdout}.
16618 This list includes the files explicitly supplied and referenced by the user
16619 as well as implicitly referenced run-time unit files. The latter are
16620 omitted if the corresponding units reside in shared libraries. The
16621 directory names for the run-time units depend on the system configuration.
16623 @geindex -o (gnatbind)
16625 @item @code{-o `file'}
16627 Set name of output file to @code{file} instead of the normal
16628 @code{b~`mainprog}.adb` default. Note that @code{file} denote the Ada
16629 binder generated body filename.
16630 Note that if this option is used, then linking must be done manually.
16631 It is not possible to use gnatlink in this case, since it cannot locate
16632 the binder file.
16634 @geindex -r (gnatbind)
16636 @item @code{-r}
16638 Generate list of @code{pragma Restrictions} that could be applied to
16639 the current unit. This is useful for code audit purposes, and also may
16640 be used to improve code generation in some cases.
16641 @end table
16643 @node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
16644 @anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{115}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{11e}
16645 @subsubsection Dynamic Allocation Control
16648 The heap control switches – @code{-H32} and @code{-H64} –
16649 determine whether dynamic allocation uses 32-bit or 64-bit memory.
16650 They only affect compiler-generated allocations via @code{__gnat_malloc};
16651 explicit calls to @code{malloc} and related functions from the C
16652 run-time library are unaffected.
16655 @table @asis
16657 @item @code{-H32}
16659 Allocate memory on 32-bit heap
16661 @item @code{-H64}
16663 Allocate memory on 64-bit heap.  This is the default
16664 unless explicitly overridden by a @code{'Size} clause on the access type.
16665 @end table
16667 These switches are only effective on VMS platforms.
16669 @node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
16670 @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{11f}
16671 @subsubsection Binding with Non-Ada Main Programs
16674 The description so far has assumed that the main
16675 program is in Ada, and that the task of the binder is to generate a
16676 corresponding function @code{main} that invokes this Ada main
16677 program. GNAT also supports the building of executable programs where
16678 the main program is not in Ada, but some of the called routines are
16679 written in Ada and compiled using GNAT (@ref{2c,,Mixed Language Programming}).
16680 The following switch is used in this situation:
16682 @quotation
16684 @geindex -n (gnatbind)
16685 @end quotation
16688 @table @asis
16690 @item @code{-n}
16692 No main program. The main program is not in Ada.
16693 @end table
16695 In this case, most of the functions of the binder are still required,
16696 but instead of generating a main program, the binder generates a file
16697 containing the following callable routines:
16699 @quotation
16701 @geindex adainit
16704 @table @asis
16706 @item @code{adainit}
16708 You must call this routine to initialize the Ada part of the program by
16709 calling the necessary elaboration routines. A call to @code{adainit} is
16710 required before the first call to an Ada subprogram.
16712 Note that it is assumed that the basic execution environment must be setup
16713 to be appropriate for Ada execution at the point where the first Ada
16714 subprogram is called. In particular, if the Ada code will do any
16715 floating-point operations, then the FPU must be setup in an appropriate
16716 manner. For the case of the x86, for example, full precision mode is
16717 required. The procedure GNAT.Float_Control.Reset may be used to ensure
16718 that the FPU is in the right state.
16719 @end table
16721 @geindex adafinal
16724 @table @asis
16726 @item @code{adafinal}
16728 You must call this routine to perform any library-level finalization
16729 required by the Ada subprograms. A call to @code{adafinal} is required
16730 after the last call to an Ada subprogram, and before the program
16731 terminates.
16732 @end table
16733 @end quotation
16735 @geindex -n (gnatbind)
16737 @geindex Binder
16738 @geindex multiple input files
16740 If the @code{-n} switch
16741 is given, more than one ALI file may appear on
16742 the command line for @code{gnatbind}. The normal @code{closure}
16743 calculation is performed for each of the specified units. Calculating
16744 the closure means finding out the set of units involved by tracing
16745 `with' references. The reason it is necessary to be able to
16746 specify more than one ALI file is that a given program may invoke two or
16747 more quite separate groups of Ada units.
16749 The binder takes the name of its output file from the last specified ALI
16750 file, unless overridden by the use of the @code{-o file}.
16752 @geindex -o (gnatbind)
16754 The output is an Ada unit in source form that can be compiled with GNAT.
16755 This compilation occurs automatically as part of the @code{gnatlink}
16756 processing.
16758 Currently the GNAT run-time requires a FPU using 80 bits mode
16759 precision. Under targets where this is not the default it is required to
16760 call GNAT.Float_Control.Reset before using floating point numbers (this
16761 include float computation, float input and output) in the Ada code. A
16762 side effect is that this could be the wrong mode for the foreign code
16763 where floating point computation could be broken after this call.
16765 @node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16766 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-programs-with-no-main-subprogram}@anchor{120}@anchor{gnat_ugn/building_executable_programs_with_gnat id41}@anchor{121}
16767 @subsubsection Binding Programs with No Main Subprogram
16770 It is possible to have an Ada program which does not have a main
16771 subprogram. This program will call the elaboration routines of all the
16772 packages, then the finalization routines.
16774 The following switch is used to bind programs organized in this manner:
16776 @quotation
16778 @geindex -z (gnatbind)
16779 @end quotation
16782 @table @asis
16784 @item @code{-z}
16786 Normally the binder checks that the unit name given on the command line
16787 corresponds to a suitable main subprogram. When this switch is used,
16788 a list of ALI files can be given, and the execution of the program
16789 consists of elaboration of these units in an appropriate order. Note
16790 that the default wide character encoding method for standard Text_IO
16791 files is always set to Brackets if this switch is set (you can use
16792 the binder switch
16793 @code{-Wx} to override this default).
16794 @end table
16796 @node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16797 @anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{122}@anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{123}
16798 @subsection Command-Line Access
16801 The package @code{Ada.Command_Line} provides access to the command-line
16802 arguments and program name. In order for this interface to operate
16803 correctly, the two variables
16805 @example
16806 int gnat_argc;
16807 char **gnat_argv;
16808 @end example
16810 @geindex gnat_argv
16812 @geindex gnat_argc
16814 are declared in one of the GNAT library routines. These variables must
16815 be set from the actual @code{argc} and @code{argv} values passed to the
16816 main program. With no `n' present, @code{gnatbind}
16817 generates the C main program to automatically set these variables.
16818 If the `n' switch is used, there is no automatic way to
16819 set these variables. If they are not set, the procedures in
16820 @code{Ada.Command_Line} will not be available, and any attempt to use
16821 them will raise @code{Constraint_Error}. If command line access is
16822 required, your main program must set @code{gnat_argc} and
16823 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
16826 @node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16827 @anchor{gnat_ugn/building_executable_programs_with_gnat id43}@anchor{124}@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-for-gnatbind}@anchor{76}
16828 @subsection Search Paths for @code{gnatbind}
16831 The binder takes the name of an ALI file as its argument and needs to
16832 locate source files as well as other ALI files to verify object consistency.
16834 For source files, it follows exactly the same search rules as @code{gcc}
16835 (see @ref{73,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16836 directories searched are:
16839 @itemize *
16841 @item 
16842 The directory containing the ALI file named in the command line, unless
16843 the switch @code{-I-} is specified.
16845 @item 
16846 All directories specified by @code{-I}
16847 switches on the @code{gnatbind}
16848 command line, in the order given.
16850 @geindex ADA_PRJ_OBJECTS_FILE
16852 @item 
16853 Each of the directories listed in the text file whose name is given
16854 by the 
16855 @geindex ADA_PRJ_OBJECTS_FILE
16856 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16857 @code{ADA_PRJ_OBJECTS_FILE} environment variable.
16859 @geindex ADA_PRJ_OBJECTS_FILE
16860 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16861 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16862 driver when project files are used. It should not normally be set
16863 by other means.
16865 @geindex ADA_OBJECTS_PATH
16867 @item 
16868 Each of the directories listed in the value of the
16869 @geindex ADA_OBJECTS_PATH
16870 @geindex environment variable; ADA_OBJECTS_PATH
16871 @code{ADA_OBJECTS_PATH} environment variable.
16872 Construct this value
16873 exactly as the 
16874 @geindex PATH
16875 @geindex environment variable; PATH
16876 @code{PATH} environment variable: a list of directory
16877 names separated by colons (semicolons when working with the NT version
16878 of GNAT).
16880 @item 
16881 The content of the @code{ada_object_path} file which is part of the GNAT
16882 installation tree and is used to store standard libraries such as the
16883 GNAT Run-Time Library (RTL) unless the switch @code{-nostdlib} is
16884 specified. See @ref{72,,Installing a library}
16885 @end itemize
16887 @geindex -I (gnatbind)
16889 @geindex -aI (gnatbind)
16891 @geindex -aO (gnatbind)
16893 In the binder the switch @code{-I}
16894 is used to specify both source and
16895 library file paths. Use @code{-aI}
16896 instead if you want to specify
16897 source paths only, and @code{-aO}
16898 if you want to specify library paths
16899 only. This means that for the binder
16900 @code{-I`dir'} is equivalent to
16901 @code{-aI`dir'}
16902 @code{-aO``dir'}.
16903 The binder generates the bind file (a C language source file) in the
16904 current working directory.
16906 @geindex Ada
16908 @geindex System
16910 @geindex Interfaces
16912 @geindex GNAT
16914 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
16915 children make up the GNAT Run-Time Library, together with the package
16916 GNAT and its children, which contain a set of useful additional
16917 library functions provided by GNAT. The sources for these units are
16918 needed by the compiler and are kept together in one directory. The ALI
16919 files and object files generated by compiling the RTL are needed by the
16920 binder and the linker and are kept together in one directory, typically
16921 different from the directory containing the sources. In a normal
16922 installation, you need not specify these directory names when compiling
16923 or binding. Either the environment variables or the built-in defaults
16924 cause these files to be found.
16926 Besides simplifying access to the RTL, a major use of search paths is
16927 in compiling sources from multiple directories. This can make
16928 development environments much more flexible.
16930 @node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16931 @anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatbind-usage}@anchor{125}@anchor{gnat_ugn/building_executable_programs_with_gnat id44}@anchor{126}
16932 @subsection Examples of @code{gnatbind} Usage
16935 Here are some examples of @code{gnatbind} invocations:
16937 @quotation
16939 @example
16940 gnatbind hello
16941 @end example
16943 The main program @code{Hello} (source program in @code{hello.adb}) is
16944 bound using the standard switch settings. The generated main program is
16945 @code{b~hello.adb}. This is the normal, default use of the binder.
16947 @example
16948 gnatbind hello -o mainprog.adb
16949 @end example
16951 The main program @code{Hello} (source program in @code{hello.adb}) is
16952 bound using the standard switch settings. The generated main program is
16953 @code{mainprog.adb} with the associated spec in
16954 @code{mainprog.ads}. Note that you must specify the body here not the
16955 spec. Note that if this option is used, then linking must be done manually,
16956 since gnatlink will not be able to find the generated file.
16957 @end quotation
16959 @node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16960 @anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{127}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{cb}
16961 @section Linking with @code{gnatlink}
16964 @geindex gnatlink
16966 This chapter discusses @code{gnatlink}, a tool that links
16967 an Ada program and builds an executable file. This utility
16968 invokes the system linker (via the @code{gcc} command)
16969 with a correct list of object files and library references.
16970 @code{gnatlink} automatically determines the list of files and
16971 references for the Ada part of a program. It uses the binder file
16972 generated by the @code{gnatbind} to determine this list.
16974 @menu
16975 * Running gnatlink:: 
16976 * Switches for gnatlink:: 
16978 @end menu
16980 @node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16981 @anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{128}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{129}
16982 @subsection Running @code{gnatlink}
16985 The form of the @code{gnatlink} command is
16987 @example
16988 $ gnatlink [ switches ] mainprog [.ali]
16989            [ non-Ada objects ] [ linker options ]
16990 @end example
16992 The arguments of @code{gnatlink} (switches, main @code{ALI} file,
16993 non-Ada objects
16994 or linker options) may be in any order, provided that no non-Ada object may
16995 be mistaken for a main @code{ALI} file.
16996 Any file name @code{F} without the @code{.ali}
16997 extension will be taken as the main @code{ALI} file if a file exists
16998 whose name is the concatenation of @code{F} and @code{.ali}.
17000 @code{mainprog.ali} references the ALI file of the main program.
17001 The @code{.ali} extension of this file can be omitted. From this
17002 reference, @code{gnatlink} locates the corresponding binder file
17003 @code{b~mainprog.adb} and, using the information in this file along
17004 with the list of non-Ada objects and linker options, constructs a
17005 linker command file to create the executable.
17007 The arguments other than the @code{gnatlink} switches and the main
17008 @code{ALI} file are passed to the linker uninterpreted.
17009 They typically include the names of
17010 object files for units written in other languages than Ada and any library
17011 references required to resolve references in any of these foreign language
17012 units, or in @code{Import} pragmas in any Ada units.
17014 @code{linker options} is an optional list of linker specific
17015 switches.
17016 The default linker called by gnatlink is @code{gcc} which in
17017 turn calls the appropriate system linker.
17019 One useful option for the linker is @code{-s}: it reduces the size of the
17020 executable by removing all symbol table and relocation information from the
17021 executable.
17023 Standard options for the linker such as @code{-lmy_lib} or
17024 @code{-Ldir} can be added as is.
17025 For options that are not recognized by
17026 @code{gcc} as linker options, use the @code{gcc} switches
17027 @code{-Xlinker} or @code{-Wl,}.
17029 Refer to the GCC documentation for
17030 details.
17032 Here is an example showing how to generate a linker map:
17034 @example
17035 $ gnatlink my_prog -Wl,-Map,MAPFILE
17036 @end example
17038 Using @code{linker options} it is possible to set the program stack and
17039 heap size.
17040 See @ref{12a,,Setting Stack Size from gnatlink} and
17041 @ref{12b,,Setting Heap Size from gnatlink}.
17043 @code{gnatlink} determines the list of objects required by the Ada
17044 program and prepends them to the list of objects passed to the linker.
17045 @code{gnatlink} also gathers any arguments set by the use of
17046 @code{pragma Linker_Options} and adds them to the list of arguments
17047 presented to the linker.
17049 @node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
17050 @anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{12c}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{12d}
17051 @subsection Switches for @code{gnatlink}
17054 The following switches are available with the @code{gnatlink} utility:
17056 @geindex --version (gnatlink)
17059 @table @asis
17061 @item @code{--version}
17063 Display Copyright and version, then exit disregarding all other options.
17064 @end table
17066 @geindex --help (gnatlink)
17069 @table @asis
17071 @item @code{--help}
17073 If @code{--version} was not used, display usage, then exit disregarding
17074 all other options.
17075 @end table
17077 @geindex Command line length
17079 @geindex -f (gnatlink)
17082 @table @asis
17084 @item @code{-f}
17086 On some targets, the command line length is limited, and @code{gnatlink}
17087 will generate a separate file for the linker if the list of object files
17088 is too long.
17089 The @code{-f} switch forces this file
17090 to be generated even if
17091 the limit is not exceeded. This is useful in some cases to deal with
17092 special situations where the command line length is exceeded.
17093 @end table
17095 @geindex Debugging information
17096 @geindex including
17098 @geindex -g (gnatlink)
17101 @table @asis
17103 @item @code{-g}
17105 The option to include debugging information causes the Ada bind file (in
17106 other words, @code{b~mainprog.adb}) to be compiled with @code{-g}.
17107 In addition, the binder does not delete the @code{b~mainprog.adb},
17108 @code{b~mainprog.o} and @code{b~mainprog.ali} files.
17109 Without @code{-g}, the binder removes these files by default.
17110 @end table
17112 @geindex -n (gnatlink)
17115 @table @asis
17117 @item @code{-n}
17119 Do not compile the file generated by the binder. This may be used when
17120 a link is rerun with different options, but there is no need to recompile
17121 the binder file.
17122 @end table
17124 @geindex -v (gnatlink)
17127 @table @asis
17129 @item @code{-v}
17131 Verbose mode. Causes additional information to be output, including a full
17132 list of the included object files.
17133 This switch option is most useful when you want
17134 to see what set of object files are being used in the link step.
17135 @end table
17137 @geindex -v -v (gnatlink)
17140 @table @asis
17142 @item @code{-v -v}
17144 Very verbose mode. Requests that the compiler operate in verbose mode when
17145 it compiles the binder file, and that the system linker run in verbose mode.
17146 @end table
17148 @geindex -o (gnatlink)
17151 @table @asis
17153 @item @code{-o `exec-name'}
17155 @code{exec-name} specifies an alternate name for the generated
17156 executable program. If this switch is omitted, the executable has the same
17157 name as the main unit. For example, @code{gnatlink try.ali} creates
17158 an executable called @code{try}.
17159 @end table
17161 @geindex -B (gnatlink)
17164 @table @asis
17166 @item @code{-B`dir'}
17168 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
17169 from @code{dir} instead of the default location. Only use this switch
17170 when multiple versions of the GNAT compiler are available.
17171 See the @code{Directory Options} section in @cite{The_GNU_Compiler_Collection}
17172 for further details. You would normally use the @code{-b} or
17173 @code{-V} switch instead.
17174 @end table
17176 @geindex -M (gnatlink)
17179 @table @asis
17181 @item @code{-M}
17183 When linking an executable, create a map file. The name of the map file
17184 has the same name as the executable with extension “.map”.
17185 @end table
17187 @geindex -M= (gnatlink)
17190 @table @asis
17192 @item @code{-M=`mapfile'}
17194 When linking an executable, create a map file. The name of the map file is
17195 @code{mapfile}.
17196 @end table
17198 @geindex --GCC=compiler_name (gnatlink)
17201 @table @asis
17203 @item @code{--GCC=`compiler_name'}
17205 Program used for compiling the binder file. The default is
17206 @code{gcc}. You need to use quotes around @code{compiler_name} if
17207 @code{compiler_name} contains spaces or other separator characters.
17208 As an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to
17209 use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
17210 inserted after your command name. Thus in the above example the compiler
17211 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
17212 A limitation of this syntax is that the name and path name of the executable
17213 itself must not include any embedded spaces. If the compiler executable is
17214 different from the default one (gcc or <prefix>-gcc), then the back-end
17215 switches in the ALI file are not used to compile the binder generated source.
17216 For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
17217 switches will be used for @code{--GCC="gcc -gnatv"}. If several
17218 @code{--GCC=compiler_name} are used, only the last @code{compiler_name}
17219 is taken into account. However, all the additional switches are also taken
17220 into account. Thus,
17221 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
17222 @code{--GCC="bar -x -y -z -t"}.
17223 @end table
17225 @geindex --LINK= (gnatlink)
17228 @table @asis
17230 @item @code{--LINK=`name'}
17232 @code{name} is the name of the linker to be invoked. This is especially
17233 useful in mixed language programs since languages such as C++ require
17234 their own linker to be used. When this switch is omitted, the default
17235 name for the linker is @code{gcc}. When this switch is used, the
17236 specified linker is called instead of @code{gcc} with exactly the same
17237 parameters that would have been passed to @code{gcc} so if the desired
17238 linker requires different parameters it is necessary to use a wrapper
17239 script that massages the parameters before invoking the real linker. It
17240 may be useful to control the exact invocation by using the verbose
17241 switch.
17242 @end table
17244 @node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
17245 @anchor{gnat_ugn/building_executable_programs_with_gnat id48}@anchor{12e}@anchor{gnat_ugn/building_executable_programs_with_gnat using-the-gnu-make-utility}@anchor{70}
17246 @section Using the GNU @code{make} Utility
17249 @geindex make (GNU)
17250 @geindex GNU make
17252 This chapter offers some examples of makefiles that solve specific
17253 problems. It does not explain how to write a makefile, nor does it try to replace the
17254 @code{gnatmake} utility (@ref{c8,,Building with gnatmake}).
17256 All the examples in this section are specific to the GNU version of
17257 make. Although @code{make} is a standard utility, and the basic language
17258 is the same, these examples use some advanced features found only in
17259 @code{GNU make}.
17261 @menu
17262 * Using gnatmake in a Makefile:: 
17263 * Automatically Creating a List of Directories:: 
17264 * Generating the Command Line Switches:: 
17265 * Overcoming Command Line Length Limits:: 
17267 @end menu
17269 @node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
17270 @anchor{gnat_ugn/building_executable_programs_with_gnat id49}@anchor{12f}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gnatmake-in-a-makefile}@anchor{130}
17271 @subsection Using gnatmake in a Makefile
17274 @c index makefile (GNU make)
17276 Complex project organizations can be handled in a very powerful way by
17277 using GNU make combined with gnatmake. For instance, here is a Makefile
17278 which allows you to build each subsystem of a big project into a separate
17279 shared library. Such a makefile allows you to significantly reduce the link
17280 time of very big applications while maintaining full coherence at
17281 each step of the build process.
17283 The list of dependencies are handled automatically by
17284 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
17285 the appropriate directories.
17287 Note that you should also read the example on how to automatically
17288 create the list of directories
17289 (@ref{131,,Automatically Creating a List of Directories})
17290 which might help you in case your project has a lot of subdirectories.
17292 @example
17293 ## This Makefile is intended to be used with the following directory
17294 ## configuration:
17295 ##  - The sources are split into a series of csc (computer software components)
17296 ##    Each of these csc is put in its own directory.
17297 ##    Their name are referenced by the directory names.
17298 ##    They will be compiled into shared library (although this would also work
17299 ##    with static libraries)
17300 ##  - The main program (and possibly other packages that do not belong to any
17301 ##    csc) is put in the top level directory (where the Makefile is).
17302 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17303 ##                    \\_ second_csc (sources) __ lib (will contain the library)
17304 ##                    \\_ ...
17305 ## Although this Makefile is build for shared library, it is easy to modify
17306 ## to build partial link objects instead (modify the lines with -shared and
17307 ## gnatlink below)
17309 ## With this makefile, you can change any file in the system or add any new
17310 ## file, and everything will be recompiled correctly (only the relevant shared
17311 ## objects will be recompiled, and the main program will be re-linked).
17313 # The list of computer software component for your project. This might be
17314 # generated automatically.
17315 CSC_LIST=aa bb cc
17317 # Name of the main program (no extension)
17318 MAIN=main
17320 # If we need to build objects with -fPIC, uncomment the following line
17321 #NEED_FPIC=-fPIC
17323 # The following variable should give the directory containing libgnat.so
17324 # You can get this directory through 'gnatls -v'. This is usually the last
17325 # directory in the Object_Path.
17326 GLIB=...
17328 # The directories for the libraries
17329 # (This macro expands the list of CSC to the list of shared libraries, you
17330 # could simply use the expanded form:
17331 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17332 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17334 $@{MAIN@}: objects $@{LIB_DIR@}
17335     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17336     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17338 objects::
17339     # recompile the sources
17340     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17342 # Note: In a future version of GNAT, the following commands will be simplified
17343 # by a new tool, gnatmlib
17344 $@{LIB_DIR@}:
17345     mkdir -p $@{dir $@@ @}
17346     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17347     cd $@{dir $@@ @} && cp -f ../*.ali .
17349 # The dependencies for the modules
17350 # Note that we have to force the expansion of *.o, since in some cases
17351 # make won't be able to do it itself.
17352 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17353 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17354 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17356 # Make sure all of the shared libraries are in the path before starting the
17357 # program
17358 run::
17359     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17361 clean::
17362     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17363     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17364     $@{RM@} $@{CSC_LIST:%=%/*.o@}
17365     $@{RM@} *.o *.ali $@{MAIN@}
17366 @end example
17368 @node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
17369 @anchor{gnat_ugn/building_executable_programs_with_gnat automatically-creating-a-list-of-directories}@anchor{131}@anchor{gnat_ugn/building_executable_programs_with_gnat id50}@anchor{132}
17370 @subsection Automatically Creating a List of Directories
17373 In most makefiles, you will have to specify a list of directories, and
17374 store it in a variable. For small projects, it is often easier to
17375 specify each of them by hand, since you then have full control over what
17376 is the proper order for these directories, which ones should be
17377 included.
17379 However, in larger projects, which might involve hundreds of
17380 subdirectories, it might be more convenient to generate this list
17381 automatically.
17383 The example below presents two methods. The first one, although less
17384 general, gives you more control over the list. It involves wildcard
17385 characters, that are automatically expanded by @code{make}. Its
17386 shortcoming is that you need to explicitly specify some of the
17387 organization of your project, such as for instance the directory tree
17388 depth, whether some directories are found in a separate tree, etc.
17390 The second method is the most general one. It requires an external
17391 program, called @code{find}, which is standard on all Unix systems. All
17392 the directories found under a given root directory will be added to the
17393 list.
17395 @example
17396 # The examples below are based on the following directory hierarchy:
17397 # All the directories can contain any number of files
17398 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17399 #                       ->  ab
17400 #                       ->  ac
17401 #                ->  b  ->  ba  ->  baa
17402 #                       ->  bb
17403 #                       ->  bc
17404 # This Makefile creates a variable called DIRS, that can be reused any time
17405 # you need this list (see the other examples in this section)
17407 # The root of your project's directory hierarchy
17408 ROOT_DIRECTORY=.
17410 ####
17411 # First method: specify explicitly the list of directories
17412 # This allows you to specify any subset of all the directories you need.
17413 ####
17415 DIRS := a/aa/ a/ab/ b/ba/
17417 ####
17418 # Second method: use wildcards
17419 # Note that the argument(s) to wildcard below should end with a '/'.
17420 # Since wildcards also return file names, we have to filter them out
17421 # to avoid duplicate directory names.
17422 # We thus use make's `@w{`}dir`@w{`} and `@w{`}sort`@w{`} functions.
17423 # It sets DIRs to the following value (note that the directories aaa and baa
17424 # are not given, unless you change the arguments to wildcard).
17425 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17426 ####
17428 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17429                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17431 ####
17432 # Third method: use an external program
17433 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17434 # This is the most complete command: it sets DIRs to the following value:
17435 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17436 ####
17438 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17439 @end example
17441 @node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
17442 @anchor{gnat_ugn/building_executable_programs_with_gnat generating-the-command-line-switches}@anchor{133}@anchor{gnat_ugn/building_executable_programs_with_gnat id51}@anchor{134}
17443 @subsection Generating the Command Line Switches
17446 Once you have created the list of directories as explained in the
17447 previous section (@ref{131,,Automatically Creating a List of Directories}),
17448 you can easily generate the command line arguments to pass to gnatmake.
17450 For the sake of completeness, this example assumes that the source path
17451 is not the same as the object path, and that you have two separate lists
17452 of directories.
17454 @example
17455 # see "Automatically creating a list of directories" to create
17456 # these variables
17457 SOURCE_DIRS=
17458 OBJECT_DIRS=
17460 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17461 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17463 all:
17464         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17465 @end example
17467 @node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
17468 @anchor{gnat_ugn/building_executable_programs_with_gnat id52}@anchor{135}@anchor{gnat_ugn/building_executable_programs_with_gnat overcoming-command-line-length-limits}@anchor{136}
17469 @subsection Overcoming Command Line Length Limits
17472 One problem that might be encountered on big projects is that many
17473 operating systems limit the length of the command line. It is thus hard to give
17474 gnatmake the list of source and object directories.
17476 This example shows how you can set up environment variables, which will
17477 make @code{gnatmake} behave exactly as if the directories had been
17478 specified on the command line, but have a much higher length limit (or
17479 even none on most systems).
17481 It assumes that you have created a list of directories in your Makefile,
17482 using one of the methods presented in
17483 @ref{131,,Automatically Creating a List of Directories}.
17484 For the sake of completeness, we assume that the object
17485 path (where the ALI files are found) is different from the sources patch.
17487 Note a small trick in the Makefile below: for efficiency reasons, we
17488 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17489 expanded immediately by @code{make}. This way we overcome the standard
17490 make behavior which is to expand the variables only when they are
17491 actually used.
17493 On Windows, if you are using the standard Windows command shell, you must
17494 replace colons with semicolons in the assignments to these variables.
17496 @example
17497 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17498 # This is the same thing as putting the -I arguments on the command line.
17499 # (the equivalent of using -aI on the command line would be to define
17500 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17501 # You can of course have different values for these variables.
17503 # Note also that we need to keep the previous values of these variables, since
17504 # they might have been set before running 'make' to specify where the GNAT
17505 # library is installed.
17507 # see "Automatically creating a list of directories" to create these
17508 # variables
17509 SOURCE_DIRS=
17510 OBJECT_DIRS=
17512 empty:=
17513 space:=$@{empty@} $@{empty@}
17514 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17515 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17516 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17517 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17518 export ADA_INCLUDE_PATH
17519 export ADA_OBJECTS_PATH
17521 all:
17522         gnatmake main_unit
17523 @end example
17525 @node GNAT Utility Programs,GNAT and Program Execution,Building Executable Programs with GNAT,Top
17526 @anchor{gnat_ugn/gnat_utility_programs doc}@anchor{137}@anchor{gnat_ugn/gnat_utility_programs gnat-utility-programs}@anchor{b}@anchor{gnat_ugn/gnat_utility_programs id1}@anchor{138}
17527 @chapter GNAT Utility Programs
17530 This chapter describes a number of utility programs:
17534 @itemize *
17536 @item 
17537 @ref{139,,The File Cleanup Utility gnatclean}
17539 @item 
17540 @ref{13a,,The GNAT Library Browser gnatls}
17541 @end itemize
17543 Other GNAT utilities are described elsewhere in this manual:
17546 @itemize *
17548 @item 
17549 @ref{42,,Handling Arbitrary File Naming Conventions with gnatname}
17551 @item 
17552 @ref{4c,,File Name Krunching with gnatkr}
17554 @item 
17555 @ref{1d,,Renaming Files with gnatchop}
17557 @item 
17558 @ref{90,,Preprocessing with gnatprep}
17559 @end itemize
17561 @menu
17562 * The File Cleanup Utility gnatclean:: 
17563 * The GNAT Library Browser gnatls:: 
17565 @end menu
17567 @node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
17568 @anchor{gnat_ugn/gnat_utility_programs id2}@anchor{13b}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{139}
17569 @section The File Cleanup Utility @code{gnatclean}
17572 @geindex File cleanup tool
17574 @geindex gnatclean
17576 @code{gnatclean} is a tool that allows the deletion of files produced by the
17577 compiler, binder and linker, including ALI files, object files, tree files,
17578 expanded source files, library files, interface copy source files, binder
17579 generated files and executable files.
17581 @menu
17582 * Running gnatclean:: 
17583 * Switches for gnatclean:: 
17585 @end menu
17587 @node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
17588 @anchor{gnat_ugn/gnat_utility_programs id3}@anchor{13c}@anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{13d}
17589 @subsection Running @code{gnatclean}
17592 The @code{gnatclean} command has the form:
17594 @quotation
17596 @example
17597 $ gnatclean switches names
17598 @end example
17599 @end quotation
17601 where @code{names} is a list of source file names. Suffixes @code{.ads} and
17602 @code{adb} may be omitted. If a project file is specified using switch
17603 @code{-P}, then @code{names} may be completely omitted.
17605 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17606 if switch @code{-c} is not specified, by the binder and
17607 the linker. In informative-only mode, specified by switch
17608 @code{-n}, the list of files that would have been deleted in
17609 normal mode is listed, but no file is actually deleted.
17611 @node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
17612 @anchor{gnat_ugn/gnat_utility_programs id4}@anchor{13e}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{13f}
17613 @subsection Switches for @code{gnatclean}
17616 @code{gnatclean} recognizes the following switches:
17618 @geindex --version (gnatclean)
17621 @table @asis
17623 @item @code{--version}
17625 Display copyright and version, then exit disregarding all other options.
17626 @end table
17628 @geindex --help (gnatclean)
17631 @table @asis
17633 @item @code{--help}
17635 If @code{--version} was not used, display usage, then exit disregarding
17636 all other options.
17638 @item @code{--subdirs=`subdir'}
17640 Actual object directory of each project file is the subdirectory subdir of the
17641 object directory specified or defaulted in the project file.
17643 @item @code{--unchecked-shared-lib-imports}
17645 By default, shared library projects are not allowed to import static library
17646 projects. When this switch is used on the command line, this restriction is
17647 relaxed.
17648 @end table
17650 @geindex -c (gnatclean)
17653 @table @asis
17655 @item @code{-c}
17657 Only attempt to delete the files produced by the compiler, not those produced
17658 by the binder or the linker. The files that are not to be deleted are library
17659 files, interface copy files, binder generated files and executable files.
17660 @end table
17662 @geindex -D (gnatclean)
17665 @table @asis
17667 @item @code{-D `dir'}
17669 Indicate that ALI and object files should normally be found in directory @code{dir}.
17670 @end table
17672 @geindex -F (gnatclean)
17675 @table @asis
17677 @item @code{-F}
17679 When using project files, if some errors or warnings are detected during
17680 parsing and verbose mode is not in effect (no use of switch
17681 -v), then error lines start with the full path name of the project
17682 file, rather than its simple file name.
17683 @end table
17685 @geindex -h (gnatclean)
17688 @table @asis
17690 @item @code{-h}
17692 Output a message explaining the usage of @code{gnatclean}.
17693 @end table
17695 @geindex -n (gnatclean)
17698 @table @asis
17700 @item @code{-n}
17702 Informative-only mode. Do not delete any files. Output the list of the files
17703 that would have been deleted if this switch was not specified.
17704 @end table
17706 @geindex -P (gnatclean)
17709 @table @asis
17711 @item @code{-P`project'}
17713 Use project file @code{project}. Only one such switch can be used.
17714 When cleaning a project file, the files produced by the compilation of the
17715 immediate sources or inherited sources of the project files are to be
17716 deleted. This is not depending on the presence or not of executable names
17717 on the command line.
17718 @end table
17720 @geindex -q (gnatclean)
17723 @table @asis
17725 @item @code{-q}
17727 Quiet output. If there are no errors, do not output anything, except in
17728 verbose mode (switch -v) or in informative-only mode
17729 (switch -n).
17730 @end table
17732 @geindex -r (gnatclean)
17735 @table @asis
17737 @item @code{-r}
17739 When a project file is specified (using switch -P),
17740 clean all imported and extended project files, recursively. If this switch
17741 is not specified, only the files related to the main project file are to be
17742 deleted. This switch has no effect if no project file is specified.
17743 @end table
17745 @geindex -v (gnatclean)
17748 @table @asis
17750 @item @code{-v}
17752 Verbose mode.
17753 @end table
17755 @geindex -vP (gnatclean)
17758 @table @asis
17760 @item @code{-vP`x'}
17762 Indicates the verbosity of the parsing of GNAT project files.
17763 @ref{d1,,Switches Related to Project Files}.
17764 @end table
17766 @geindex -X (gnatclean)
17769 @table @asis
17771 @item @code{-X`name'=`value'}
17773 Indicates that external variable @code{name} has the value @code{value}.
17774 The Project Manager will use this value for occurrences of
17775 @code{external(name)} when parsing the project file.
17776 See @ref{d1,,Switches Related to Project Files}.
17777 @end table
17779 @geindex -aO (gnatclean)
17782 @table @asis
17784 @item @code{-aO`dir'}
17786 When searching for ALI and object files, look in directory @code{dir}.
17787 @end table
17789 @geindex -I (gnatclean)
17792 @table @asis
17794 @item @code{-I`dir'}
17796 Equivalent to @code{-aO`dir'}.
17797 @end table
17799 @geindex -I- (gnatclean)
17801 @geindex Source files
17802 @geindex suppressing search
17805 @table @asis
17807 @item @code{-I-}
17809 Do not look for ALI or object files in the directory
17810 where @code{gnatclean} was invoked.
17811 @end table
17813 @node The GNAT Library Browser gnatls,,The File Cleanup Utility gnatclean,GNAT Utility Programs
17814 @anchor{gnat_ugn/gnat_utility_programs id5}@anchor{140}@anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{13a}
17815 @section The GNAT Library Browser @code{gnatls}
17818 @geindex Library browser
17820 @geindex gnatls
17822 @code{gnatls} is a tool that outputs information about compiled
17823 units. It gives the relationship between objects, unit names and source
17824 files. It can also be used to check the source dependencies of a unit
17825 as well as various characteristics.
17827 @menu
17828 * Running gnatls:: 
17829 * Switches for gnatls:: 
17830 * Example of gnatls Usage:: 
17832 @end menu
17834 @node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
17835 @anchor{gnat_ugn/gnat_utility_programs id6}@anchor{141}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{142}
17836 @subsection Running @code{gnatls}
17839 The @code{gnatls} command has the form
17841 @quotation
17843 @example
17844 $ gnatls switches object_or_ali_file
17845 @end example
17846 @end quotation
17848 The main argument is the list of object or @code{ali} files
17849 (see @ref{28,,The Ada Library Information Files})
17850 for which information is requested.
17852 In normal mode, without additional option, @code{gnatls} produces a
17853 four-column listing. Each line represents information for a specific
17854 object. The first column gives the full path of the object, the second
17855 column gives the name of the principal unit in this object, the third
17856 column gives the status of the source and the fourth column gives the
17857 full path of the source representing this unit.
17858 Here is a simple example of use:
17860 @quotation
17862 @example
17863 $ gnatls *.o
17864 ./demo1.o            demo1            DIF demo1.adb
17865 ./demo2.o            demo2             OK demo2.adb
17866 ./hello.o            h1                OK hello.adb
17867 ./instr-child.o      instr.child      MOK instr-child.adb
17868 ./instr.o            instr             OK instr.adb
17869 ./tef.o              tef              DIF tef.adb
17870 ./text_io_example.o  text_io_example   OK text_io_example.adb
17871 ./tgef.o             tgef             DIF tgef.adb
17872 @end example
17873 @end quotation
17875 The first line can be interpreted as follows: the main unit which is
17876 contained in
17877 object file @code{demo1.o} is demo1, whose main source is in
17878 @code{demo1.adb}. Furthermore, the version of the source used for the
17879 compilation of demo1 has been modified (DIF). Each source file has a status
17880 qualifier which can be:
17883 @table @asis
17885 @item `OK (unchanged)'
17887 The version of the source file used for the compilation of the
17888 specified unit corresponds exactly to the actual source file.
17890 @item `MOK (slightly modified)'
17892 The version of the source file used for the compilation of the
17893 specified unit differs from the actual source file but not enough to
17894 require recompilation. If you use gnatmake with the option
17895 @code{-m} (minimal recompilation), a file marked
17896 MOK will not be recompiled.
17898 @item `DIF (modified)'
17900 No version of the source found on the path corresponds to the source
17901 used to build this object.
17903 @item `??? (file not found)'
17905 No source file was found for this unit.
17907 @item `HID (hidden,  unchanged version not first on PATH)'
17909 The version of the source that corresponds exactly to the source used
17910 for compilation has been found on the path but it is hidden by another
17911 version of the same source that has been modified.
17912 @end table
17914 @node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
17915 @anchor{gnat_ugn/gnat_utility_programs id7}@anchor{143}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{144}
17916 @subsection Switches for @code{gnatls}
17919 @code{gnatls} recognizes the following switches:
17921 @geindex --version (gnatls)
17924 @table @asis
17926 @item @code{--version}
17928 Display copyright and version, then exit disregarding all other options.
17929 @end table
17931 @geindex --help (gnatls)
17934 @table @asis
17936 @item @code{--help}
17938 If @code{--version} was not used, display usage, then exit disregarding
17939 all other options.
17940 @end table
17942 @geindex -a (gnatls)
17945 @table @asis
17947 @item @code{-a}
17949 Consider all units, including those of the predefined Ada library.
17950 Especially useful with @code{-d}.
17951 @end table
17953 @geindex -d (gnatls)
17956 @table @asis
17958 @item @code{-d}
17960 List sources from which specified units depend on.
17961 @end table
17963 @geindex -h (gnatls)
17966 @table @asis
17968 @item @code{-h}
17970 Output the list of options.
17971 @end table
17973 @geindex -o (gnatls)
17976 @table @asis
17978 @item @code{-o}
17980 Only output information about object files.
17981 @end table
17983 @geindex -s (gnatls)
17986 @table @asis
17988 @item @code{-s}
17990 Only output information about source files.
17991 @end table
17993 @geindex -u (gnatls)
17996 @table @asis
17998 @item @code{-u}
18000 Only output information about compilation units.
18001 @end table
18003 @geindex -files (gnatls)
18006 @table @asis
18008 @item @code{-files=`file'}
18010 Take as arguments the files listed in text file @code{file}.
18011 Text file @code{file} may contain empty lines that are ignored.
18012 Each nonempty line should contain the name of an existing file.
18013 Several such switches may be specified simultaneously.
18014 @end table
18016 @geindex -aO (gnatls)
18018 @geindex -aI (gnatls)
18020 @geindex -I (gnatls)
18022 @geindex -I- (gnatls)
18025 @table @asis
18027 @item @code{-aO`dir'}, @code{-aI`dir'}, @code{-I`dir'}, @code{-I-}, @code{-nostdinc}
18029 Source path manipulation. Same meaning as the equivalent @code{gnatmake}
18030 flags (@ref{d0,,Switches for gnatmake}).
18031 @end table
18033 @geindex -aP (gnatls)
18036 @table @asis
18038 @item @code{-aP`dir'}
18040 Add @code{dir} at the beginning of the project search dir.
18041 @end table
18043 @geindex --RTS (gnatls)
18046 @table @asis
18048 @item @code{--RTS=`rts-path'}
18050 Specifies the default location of the runtime library. Same meaning as the
18051 equivalent @code{gnatmake} flag (@ref{d0,,Switches for gnatmake}).
18052 @end table
18054 @geindex -v (gnatls)
18057 @table @asis
18059 @item @code{-v}
18061 Verbose mode. Output the complete source, object and project paths. Do not use
18062 the default column layout but instead use long format giving as much as
18063 information possible on each requested units, including special
18064 characteristics such as:
18067 @itemize *
18069 @item 
18070 `Preelaborable': The unit is preelaborable in the Ada sense.
18072 @item 
18073 `No_Elab_Code':  No elaboration code has been produced by the compiler for this unit.
18075 @item 
18076 `Pure': The unit is pure in the Ada sense.
18078 @item 
18079 `Elaborate_Body': The unit contains a pragma Elaborate_Body.
18081 @item 
18082 `Remote_Types': The unit contains a pragma Remote_Types.
18084 @item 
18085 `Shared_Passive': The unit contains a pragma Shared_Passive.
18087 @item 
18088 `Predefined': This unit is part of the predefined environment and cannot be modified
18089 by the user.
18091 @item 
18092 `Remote_Call_Interface': The unit contains a pragma Remote_Call_Interface.
18093 @end itemize
18094 @end table
18096 @node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
18097 @anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{145}@anchor{gnat_ugn/gnat_utility_programs id8}@anchor{146}
18098 @subsection Example of @code{gnatls} Usage
18101 Example of using the verbose switch. Note how the source and
18102 object paths are affected by the -I switch.
18104 @quotation
18106 @example
18107 $ gnatls -v -I.. demo1.o
18109 GNATLS 5.03w (20041123-34)
18110 Copyright 1997-2004 Free Software Foundation, Inc.
18112 Source Search Path:
18113    <Current_Directory>
18114    ../
18115    /home/comar/local/adainclude/
18117 Object Search Path:
18118    <Current_Directory>
18119    ../
18120    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
18122 Project Search Path:
18123    <Current_Directory>
18124    /home/comar/local/lib/gnat/
18126 ./demo1.o
18127    Unit =>
18128      Name   => demo1
18129      Kind   => subprogram body
18130      Flags  => No_Elab_Code
18131      Source => demo1.adb    modified
18132 @end example
18133 @end quotation
18135 The following is an example of use of the dependency list.
18136 Note the use of the -s switch
18137 which gives a straight list of source files. This can be useful for
18138 building specialized scripts.
18140 @quotation
18142 @example
18143 $ gnatls -d demo2.o
18144 ./demo2.o   demo2        OK demo2.adb
18145                          OK gen_list.ads
18146                          OK gen_list.adb
18147                          OK instr.ads
18148                          OK instr-child.ads
18150 $ gnatls -d -s -a demo1.o
18151 demo1.adb
18152 /home/comar/local/adainclude/ada.ads
18153 /home/comar/local/adainclude/a-finali.ads
18154 /home/comar/local/adainclude/a-filico.ads
18155 /home/comar/local/adainclude/a-stream.ads
18156 /home/comar/local/adainclude/a-tags.ads
18157 gen_list.ads
18158 gen_list.adb
18159 /home/comar/local/adainclude/gnat.ads
18160 /home/comar/local/adainclude/g-io.ads
18161 instr.ads
18162 /home/comar/local/adainclude/system.ads
18163 /home/comar/local/adainclude/s-exctab.ads
18164 /home/comar/local/adainclude/s-finimp.ads
18165 /home/comar/local/adainclude/s-finroo.ads
18166 /home/comar/local/adainclude/s-secsta.ads
18167 /home/comar/local/adainclude/s-stalib.ads
18168 /home/comar/local/adainclude/s-stoele.ads
18169 /home/comar/local/adainclude/s-stratt.ads
18170 /home/comar/local/adainclude/s-tasoli.ads
18171 /home/comar/local/adainclude/s-unstyp.ads
18172 /home/comar/local/adainclude/unchconv.ads
18173 @end example
18174 @end quotation
18180 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
18182 @node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
18183 @anchor{gnat_ugn/gnat_and_program_execution doc}@anchor{147}@anchor{gnat_ugn/gnat_and_program_execution gnat-and-program-execution}@anchor{c}@anchor{gnat_ugn/gnat_and_program_execution id1}@anchor{148}
18184 @chapter GNAT and Program Execution
18187 This chapter covers several topics:
18190 @itemize *
18192 @item 
18193 @ref{149,,Running and Debugging Ada Programs}
18195 @item 
18196 @ref{14a,,Profiling}
18198 @item 
18199 @ref{14b,,Improving Performance}
18201 @item 
18202 @ref{14c,,Overflow Check Handling in GNAT}
18204 @item 
18205 @ref{14d,,Performing Dimensionality Analysis in GNAT}
18207 @item 
18208 @ref{14e,,Stack Related Facilities}
18210 @item 
18211 @ref{14f,,Memory Management Issues}
18212 @end itemize
18214 @menu
18215 * Running and Debugging Ada Programs:: 
18216 * Profiling:: 
18217 * Improving Performance:: 
18218 * Overflow Check Handling in GNAT:: 
18219 * Performing Dimensionality Analysis in GNAT:: 
18220 * Stack Related Facilities:: 
18221 * Memory Management Issues:: 
18223 @end menu
18225 @node Running and Debugging Ada Programs,Profiling,,GNAT and Program Execution
18226 @anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{149}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{150}
18227 @section Running and Debugging Ada Programs
18230 @geindex Debugging
18232 This section discusses how to debug Ada programs.
18234 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18237 @itemize *
18239 @item 
18240 The illegality may be a violation of the static semantics of Ada. In
18241 that case GNAT diagnoses the constructs in the program that are illegal.
18242 It is then a straightforward matter for the user to modify those parts of
18243 the program.
18245 @item 
18246 The illegality may be a violation of the dynamic semantics of Ada. In
18247 that case the program compiles and executes, but may generate incorrect
18248 results, or may terminate abnormally with some exception.
18250 @item 
18251 When presented with a program that contains convoluted errors, GNAT
18252 itself may terminate abnormally without providing full diagnostics on
18253 the incorrect user program.
18254 @end itemize
18256 @geindex Debugger
18258 @geindex gdb
18260 @menu
18261 * The GNAT Debugger GDB:: 
18262 * Running GDB:: 
18263 * Introduction to GDB Commands:: 
18264 * Using Ada Expressions:: 
18265 * Calling User-Defined Subprograms:: 
18266 * Using the next Command in a Function:: 
18267 * Stopping When Ada Exceptions Are Raised:: 
18268 * Ada Tasks:: 
18269 * Debugging Generic Units:: 
18270 * Remote Debugging with gdbserver:: 
18271 * GNAT Abnormal Termination or Failure to Terminate:: 
18272 * Naming Conventions for GNAT Source Files:: 
18273 * Getting Internal Debugging Information:: 
18274 * Stack Traceback:: 
18275 * Pretty-Printers for the GNAT runtime:: 
18277 @end menu
18279 @node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
18280 @anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{151}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{152}
18281 @subsection The GNAT Debugger GDB
18284 @code{GDB} is a general purpose, platform-independent debugger that
18285 can be used to debug mixed-language programs compiled with @code{gcc},
18286 and in particular is capable of debugging Ada programs compiled with
18287 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
18288 complex Ada data structures.
18290 See @cite{Debugging with GDB},
18291 for full details on the usage of @code{GDB}, including a section on
18292 its usage on programs. This manual should be consulted for full
18293 details. The section that follows is a brief introduction to the
18294 philosophy and use of @code{GDB}.
18296 When GNAT programs are compiled, the compiler optionally writes debugging
18297 information into the generated object file, including information on
18298 line numbers, and on declared types and variables. This information is
18299 separate from the generated code. It makes the object files considerably
18300 larger, but it does not add to the size of the actual executable that
18301 will be loaded into memory, and has no impact on run-time performance. The
18302 generation of debug information is triggered by the use of the
18303 @code{-g} switch in the @code{gcc} or @code{gnatmake} command
18304 used to carry out the compilations. It is important to emphasize that
18305 the use of these options does not change the generated code.
18307 The debugging information is written in standard system formats that
18308 are used by many tools, including debuggers and profilers. The format
18309 of the information is typically designed to describe C types and
18310 semantics, but GNAT implements a translation scheme which allows full
18311 details about Ada types and variables to be encoded into these
18312 standard C formats. Details of this encoding scheme may be found in
18313 the file exp_dbug.ads in the GNAT source distribution. However, the
18314 details of this encoding are, in general, of no interest to a user,
18315 since @code{GDB} automatically performs the necessary decoding.
18317 When a program is bound and linked, the debugging information is
18318 collected from the object files, and stored in the executable image of
18319 the program. Again, this process significantly increases the size of
18320 the generated executable file, but it does not increase the size of
18321 the executable program itself. Furthermore, if this program is run in
18322 the normal manner, it runs exactly as if the debug information were
18323 not present, and takes no more actual memory.
18325 However, if the program is run under control of @code{GDB}, the
18326 debugger is activated.  The image of the program is loaded, at which
18327 point it is ready to run.  If a run command is given, then the program
18328 will run exactly as it would have if @code{GDB} were not present. This
18329 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
18330 entirely non-intrusive until a breakpoint is encountered.  If no
18331 breakpoint is ever hit, the program will run exactly as it would if no
18332 debugger were present. When a breakpoint is hit, @code{GDB} accesses
18333 the debugging information and can respond to user commands to inspect
18334 variables, and more generally to report on the state of execution.
18336 @node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
18337 @anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{153}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{154}
18338 @subsection Running GDB
18341 This section describes how to initiate the debugger.
18343 The debugger can be launched from a @code{GNAT Studio} menu or
18344 directly from the command line. The description below covers the latter use.
18345 All the commands shown can be used in the @code{GNAT Studio} debug console window,
18346 but there are usually more GUI-based ways to achieve the same effect.
18348 The command to run @code{GDB} is
18350 @quotation
18352 @example
18353 $ gdb program
18354 @end example
18355 @end quotation
18357 where @code{program} is the name of the executable file. This
18358 activates the debugger and results in a prompt for debugger commands.
18359 The simplest command is simply @code{run}, which causes the program to run
18360 exactly as if the debugger were not present. The following section
18361 describes some of the additional commands that can be given to @code{GDB}.
18363 @node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
18364 @anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{155}@anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{156}
18365 @subsection Introduction to GDB Commands
18368 @code{GDB} contains a large repertoire of commands.
18369 See @cite{Debugging with GDB} for extensive documentation on the use
18370 of these commands, together with examples of their use. Furthermore,
18371 the command `help' invoked from within GDB activates a simple help
18372 facility which summarizes the available commands and their options.
18373 In this section we summarize a few of the most commonly
18374 used commands to give an idea of what @code{GDB} is about. You should create
18375 a simple program with debugging information and experiment with the use of
18376 these @code{GDB} commands on the program as you read through the
18377 following section.
18380 @itemize *
18382 @item 
18384 @table @asis
18386 @item @code{set args @var{arguments}}
18388 The `arguments' list above is a list of arguments to be passed to
18389 the program on a subsequent run command, just as though the arguments
18390 had been entered on a normal invocation of the program. The @code{set args}
18391 command is not needed if the program does not require arguments.
18392 @end table
18394 @item 
18396 @table @asis
18398 @item @code{run}
18400 The @code{run} command causes execution of the program to start from
18401 the beginning. If the program is already running, that is to say if
18402 you are currently positioned at a breakpoint, then a prompt will ask
18403 for confirmation that you want to abandon the current execution and
18404 restart.
18405 @end table
18407 @item 
18409 @table @asis
18411 @item @code{breakpoint @var{location}}
18413 The breakpoint command sets a breakpoint, that is to say a point at which
18414 execution will halt and @code{GDB} will await further
18415 commands. `location' is
18416 either a line number within a file, given in the format @code{file:linenumber},
18417 or it is the name of a subprogram. If you request that a breakpoint be set on
18418 a subprogram that is overloaded, a prompt will ask you to specify on which of
18419 those subprograms you want to breakpoint. You can also
18420 specify that all of them should be breakpointed. If the program is run
18421 and execution encounters the breakpoint, then the program
18422 stops and @code{GDB} signals that the breakpoint was encountered by
18423 printing the line of code before which the program is halted.
18424 @end table
18426 @item 
18428 @table @asis
18430 @item @code{catch exception @var{name}}
18432 This command causes the program execution to stop whenever exception
18433 @code{name} is raised.  If @code{name} is omitted, then the execution is
18434 suspended when any exception is raised.
18435 @end table
18437 @item 
18439 @table @asis
18441 @item @code{print @var{expression}}
18443 This will print the value of the given expression. Most simple
18444 Ada expression formats are properly handled by @code{GDB}, so the expression
18445 can contain function calls, variables, operators, and attribute references.
18446 @end table
18448 @item 
18450 @table @asis
18452 @item @code{continue}
18454 Continues execution following a breakpoint, until the next breakpoint or the
18455 termination of the program.
18456 @end table
18458 @item 
18460 @table @asis
18462 @item @code{step}
18464 Executes a single line after a breakpoint. If the next statement
18465 is a subprogram call, execution continues into (the first statement of)
18466 the called subprogram.
18467 @end table
18469 @item 
18471 @table @asis
18473 @item @code{next}
18475 Executes a single line. If this line is a subprogram call, executes and
18476 returns from the call.
18477 @end table
18479 @item 
18481 @table @asis
18483 @item @code{list}
18485 Lists a few lines around the current source location. In practice, it
18486 is usually more convenient to have a separate edit window open with the
18487 relevant source file displayed. Successive applications of this command
18488 print subsequent lines. The command can be given an argument which is a
18489 line number, in which case it displays a few lines around the specified one.
18490 @end table
18492 @item 
18494 @table @asis
18496 @item @code{backtrace}
18498 Displays a backtrace of the call chain. This command is typically
18499 used after a breakpoint has occurred, to examine the sequence of calls that
18500 leads to the current breakpoint. The display includes one line for each
18501 activation record (frame) corresponding to an active subprogram.
18502 @end table
18504 @item 
18506 @table @asis
18508 @item @code{up}
18510 At a breakpoint, @code{GDB} can display the values of variables local
18511 to the current frame. The command @code{up} can be used to
18512 examine the contents of other active frames, by moving the focus up
18513 the stack, that is to say from callee to caller, one frame at a time.
18514 @end table
18516 @item 
18518 @table @asis
18520 @item @code{down}
18522 Moves the focus of @code{GDB} down from the frame currently being
18523 examined to the frame of its callee (the reverse of the previous command),
18524 @end table
18526 @item 
18528 @table @asis
18530 @item @code{frame @var{n}}
18532 Inspect the frame with the given number. The value 0 denotes the frame
18533 of the current breakpoint, that is to say the top of the call stack.
18534 @end table
18536 @item 
18538 @table @asis
18540 @item @code{kill}
18542 Kills the child process in which the program is running under GDB.
18543 This may be useful for several purposes:
18546 @itemize *
18548 @item 
18549 It allows you to recompile and relink your program, since on many systems
18550 you cannot regenerate an executable file while it is running in a process.
18552 @item 
18553 You can run your program outside the debugger, on systems that do not
18554 permit executing a program outside GDB while breakpoints are set
18555 within GDB.
18557 @item 
18558 It allows you to debug a core dump rather than a running process.
18559 @end itemize
18560 @end table
18561 @end itemize
18563 The above list is a very short introduction to the commands that
18564 @code{GDB} provides. Important additional capabilities, including conditional
18565 breakpoints, the ability to execute command sequences on a breakpoint,
18566 the ability to debug at the machine instruction level and many other
18567 features are described in detail in @cite{Debugging with GDB}.
18568 Note that most commands can be abbreviated
18569 (for example, c for continue, bt for backtrace).
18571 @node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
18572 @anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{157}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{158}
18573 @subsection Using Ada Expressions
18576 @geindex Ada expressions (in gdb)
18578 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
18579 extensions. The philosophy behind the design of this subset is
18581 @quotation
18584 @itemize *
18586 @item 
18587 That @code{GDB} should provide basic literals and access to operations for
18588 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
18589 leaving more sophisticated computations to subprograms written into the
18590 program (which therefore may be called from @code{GDB}).
18592 @item 
18593 That type safety and strict adherence to Ada language restrictions
18594 are not particularly relevant in a debugging context.
18596 @item 
18597 That brevity is important to the @code{GDB} user.
18598 @end itemize
18599 @end quotation
18601 Thus, for brevity, the debugger acts as if there were
18602 implicit @code{with} and @code{use} clauses in effect for all user-written
18603 packages, thus making it unnecessary to fully qualify most names with
18604 their packages, regardless of context. Where this causes ambiguity,
18605 @code{GDB} asks the user’s intent.
18607 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
18609 @node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
18610 @anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{159}@anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{15a}
18611 @subsection Calling User-Defined Subprograms
18614 An important capability of @code{GDB} is the ability to call user-defined
18615 subprograms while debugging. This is achieved simply by entering
18616 a subprogram call statement in the form:
18618 @quotation
18620 @example
18621 call subprogram-name (parameters)
18622 @end example
18623 @end quotation
18625 The keyword @code{call} can be omitted in the normal case where the
18626 @code{subprogram-name} does not coincide with any of the predefined
18627 @code{GDB} commands.
18629 The effect is to invoke the given subprogram, passing it the
18630 list of parameters that is supplied. The parameters can be expressions and
18631 can include variables from the program being debugged. The
18632 subprogram must be defined
18633 at the library level within your program, and @code{GDB} will call the
18634 subprogram within the environment of your program execution (which
18635 means that the subprogram is free to access or even modify variables
18636 within your program).
18638 The most important use of this facility is in allowing the inclusion of
18639 debugging routines that are tailored to particular data structures
18640 in your program. Such debugging routines can be written to provide a suitably
18641 high-level description of an abstract type, rather than a low-level dump
18642 of its physical layout. After all, the standard
18643 @code{GDB print} command only knows the physical layout of your
18644 types, not their abstract meaning. Debugging routines can provide information
18645 at the desired semantic level and are thus enormously useful.
18647 For example, when debugging GNAT itself, it is crucial to have access to
18648 the contents of the tree nodes used to represent the program internally.
18649 But tree nodes are represented simply by an integer value (which in turn
18650 is an index into a table of nodes).
18651 Using the @code{print} command on a tree node would simply print this integer
18652 value, which is not very useful. But the PN routine (defined in file
18653 treepr.adb in the GNAT sources) takes a tree node as input, and displays
18654 a useful high level representation of the tree node, which includes the
18655 syntactic category of the node, its position in the source, the integers
18656 that denote descendant nodes and parent node, as well as varied
18657 semantic information. To study this example in more detail, you might want to
18658 look at the body of the PN procedure in the stated file.
18660 Another useful application of this capability is to deal with situations of
18661 complex data which are not handled suitably by GDB. For example, if you specify
18662 Convention Fortran for a multi-dimensional array, GDB does not know that
18663 the ordering of array elements has been switched and will not properly
18664 address the array elements. In such a case, instead of trying to print the
18665 elements directly from GDB, you can write a callable procedure that prints
18666 the elements in the desired format.
18668 @node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
18669 @anchor{gnat_ugn/gnat_and_program_execution id8}@anchor{15b}@anchor{gnat_ugn/gnat_and_program_execution using-the-next-command-in-a-function}@anchor{15c}
18670 @subsection Using the `next' Command in a Function
18673 When you use the @code{next} command in a function, the current source
18674 location will advance to the next statement as usual. A special case
18675 arises in the case of a @code{return} statement.
18677 Part of the code for a return statement is the ‘epilogue’ of the function.
18678 This is the code that returns to the caller. There is only one copy of
18679 this epilogue code, and it is typically associated with the last return
18680 statement in the function if there is more than one return. In some
18681 implementations, this epilogue is associated with the first statement
18682 of the function.
18684 The result is that if you use the @code{next} command from a return
18685 statement that is not the last return statement of the function you
18686 may see a strange apparent jump to the last return statement or to
18687 the start of the function. You should simply ignore this odd jump.
18688 The value returned is always that from the first return statement
18689 that was stepped through.
18691 @node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
18692 @anchor{gnat_ugn/gnat_and_program_execution id9}@anchor{15d}@anchor{gnat_ugn/gnat_and_program_execution stopping-when-ada-exceptions-are-raised}@anchor{15e}
18693 @subsection Stopping When Ada Exceptions Are Raised
18696 @geindex Exceptions (in gdb)
18698 You can set catchpoints that stop the program execution when your program
18699 raises selected exceptions.
18702 @itemize *
18704 @item 
18706 @table @asis
18708 @item @code{catch exception}
18710 Set a catchpoint that stops execution whenever (any task in the) program
18711 raises any exception.
18712 @end table
18714 @item 
18716 @table @asis
18718 @item @code{catch exception @var{name}}
18720 Set a catchpoint that stops execution whenever (any task in the) program
18721 raises the exception `name'.
18722 @end table
18724 @item 
18726 @table @asis
18728 @item @code{catch exception unhandled}
18730 Set a catchpoint that stops executing whenever (any task in the) program
18731 raises an exception for which there is no handler.
18732 @end table
18734 @item 
18736 @table @asis
18738 @item @code{info exceptions}, @code{info exceptions @var{regexp}}
18740 The @code{info exceptions} command permits the user to examine all defined
18741 exceptions within Ada programs. With a regular expression, `regexp', as
18742 argument, prints out only those exceptions whose name matches `regexp'.
18743 @end table
18744 @end itemize
18746 @geindex Tasks (in gdb)
18748 @node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
18749 @anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{15f}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{160}
18750 @subsection Ada Tasks
18753 @code{GDB} allows the following task-related commands:
18756 @itemize *
18758 @item 
18760 @table @asis
18762 @item @code{info tasks}
18764 This command shows a list of current Ada tasks, as in the following example:
18766 @example
18767 (gdb) info tasks
18768   ID       TID P-ID   Thread Pri State                 Name
18769    1   8088000   0   807e000  15 Child Activation Wait main_task
18770    2   80a4000   1   80ae000  15 Accept/Select Wait    b
18771    3   809a800   1   80a4800  15 Child Activation Wait a
18772 *  4   80ae800   3   80b8000  15 Running               c
18773 @end example
18775 In this listing, the asterisk before the first task indicates it to be the
18776 currently running task. The first column lists the task ID that is used
18777 to refer to tasks in the following commands.
18778 @end table
18779 @end itemize
18781 @geindex Breakpoints and tasks
18784 @itemize *
18786 @item 
18787 @code{break} `linespec' @code{task} `taskid', @code{break} `linespec' @code{task} `taskid' @code{if} …
18789 @quotation
18791 These commands are like the @code{break ... thread ...}.
18792 `linespec' specifies source lines.
18794 Use the qualifier @code{task @var{taskid}} with a breakpoint command
18795 to specify that you only want @code{GDB} to stop the program when a
18796 particular Ada task reaches this breakpoint. `taskid' is one of the
18797 numeric task identifiers assigned by @code{GDB}, shown in the first
18798 column of the @code{info tasks} display.
18800 If you do not specify @code{task @var{taskid}} when you set a
18801 breakpoint, the breakpoint applies to `all' tasks of your
18802 program.
18804 You can use the @code{task} qualifier on conditional breakpoints as
18805 well; in this case, place @code{task @var{taskid}} before the
18806 breakpoint condition (before the @code{if}).
18807 @end quotation
18808 @end itemize
18810 @geindex Task switching (in gdb)
18813 @itemize *
18815 @item 
18816 @code{task @var{taskno}}
18818 @quotation
18820 This command allows switching to the task referred by `taskno'. In
18821 particular, this allows browsing of the backtrace of the specified
18822 task. It is advisable to switch back to the original task before
18823 continuing execution otherwise the scheduling of the program may be
18824 perturbed.
18825 @end quotation
18826 @end itemize
18828 For more detailed information on the tasking support,
18829 see @cite{Debugging with GDB}.
18831 @geindex Debugging Generic Units
18833 @geindex Generics
18835 @node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
18836 @anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{161}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{162}
18837 @subsection Debugging Generic Units
18840 GNAT always uses code expansion for generic instantiation. This means that
18841 each time an instantiation occurs, a complete copy of the original code is
18842 made, with appropriate substitutions of formals by actuals.
18844 It is not possible to refer to the original generic entities in
18845 @code{GDB}, but it is always possible to debug a particular instance of
18846 a generic, by using the appropriate expanded names. For example, if we have
18848 @quotation
18850 @example
18851 procedure g is
18853    generic package k is
18854       procedure kp (v1 : in out integer);
18855    end k;
18857    package body k is
18858       procedure kp (v1 : in out integer) is
18859       begin
18860          v1 := v1 + 1;
18861       end kp;
18862    end k;
18864    package k1 is new k;
18865    package k2 is new k;
18867    var : integer := 1;
18869 begin
18870    k1.kp (var);
18871    k2.kp (var);
18872    k1.kp (var);
18873    k2.kp (var);
18874 end;
18875 @end example
18876 @end quotation
18878 Then to break on a call to procedure kp in the k2 instance, simply
18879 use the command:
18881 @quotation
18883 @example
18884 (gdb) break g.k2.kp
18885 @end example
18886 @end quotation
18888 When the breakpoint occurs, you can step through the code of the
18889 instance in the normal manner and examine the values of local variables, as for
18890 other units.
18892 @geindex Remote Debugging with gdbserver
18894 @node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
18895 @anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{163}@anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{164}
18896 @subsection Remote Debugging with gdbserver
18899 On platforms where gdbserver is supported, it is possible to use this tool
18900 to debug your application remotely.  This can be useful in situations
18901 where the program needs to be run on a target host that is different
18902 from the host used for development, particularly when the target has
18903 a limited amount of resources (either CPU and/or memory).
18905 To do so, start your program using gdbserver on the target machine.
18906 gdbserver then automatically suspends the execution of your program
18907 at its entry point, waiting for a debugger to connect to it.  The
18908 following commands starts an application and tells gdbserver to
18909 wait for a connection with the debugger on localhost port 4444.
18911 @quotation
18913 @example
18914 $ gdbserver localhost:4444 program
18915 Process program created; pid = 5685
18916 Listening on port 4444
18917 @end example
18918 @end quotation
18920 Once gdbserver has started listening, we can tell the debugger to establish
18921 a connection with this gdbserver, and then start the same debugging session
18922 as if the program was being debugged on the same host, directly under
18923 the control of GDB.
18925 @quotation
18927 @example
18928 $ gdb program
18929 (gdb) target remote targethost:4444
18930 Remote debugging using targethost:4444
18931 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
18932 (gdb) b foo.adb:3
18933 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
18934 (gdb) continue
18935 Continuing.
18937 Breakpoint 1, foo () at foo.adb:4
18938 4       end foo;
18939 @end example
18940 @end quotation
18942 It is also possible to use gdbserver to attach to an already running
18943 program, in which case the execution of that program is simply suspended
18944 until the connection between the debugger and gdbserver is established.
18946 For more information on how to use gdbserver, see the `Using the gdbserver Program'
18947 section in @cite{Debugging with GDB}.
18948 GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
18950 @geindex Abnormal Termination or Failure to Terminate
18952 @node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
18953 @anchor{gnat_ugn/gnat_and_program_execution gnat-abnormal-termination-or-failure-to-terminate}@anchor{165}@anchor{gnat_ugn/gnat_and_program_execution id13}@anchor{166}
18954 @subsection GNAT Abnormal Termination or Failure to Terminate
18957 When presented with programs that contain serious errors in syntax
18958 or semantics,
18959 GNAT may on rare occasions  experience problems in operation, such
18960 as aborting with a
18961 segmentation fault or illegal memory access, raising an internal
18962 exception, terminating abnormally, or failing to terminate at all.
18963 In such cases, you can activate
18964 various features of GNAT that can help you pinpoint the construct in your
18965 program that is the likely source of the problem.
18967 The following strategies are presented in increasing order of
18968 difficulty, corresponding to your experience in using GNAT and your
18969 familiarity with compiler internals.
18972 @itemize *
18974 @item 
18975 Run @code{gcc} with the @code{-gnatf}. This first
18976 switch causes all errors on a given line to be reported. In its absence,
18977 only the first error on a line is displayed.
18979 The @code{-gnatdO} switch causes errors to be displayed as soon as they
18980 are encountered, rather than after compilation is terminated. If GNAT
18981 terminates prematurely or goes into an infinite loop, the last error
18982 message displayed may help to pinpoint the culprit.
18984 @item 
18985 Run @code{gcc} with the @code{-v} (verbose) switch. In this
18986 mode, @code{gcc} produces ongoing information about the progress of the
18987 compilation and provides the name of each procedure as code is
18988 generated. This switch allows you to find which Ada procedure was being
18989 compiled when it encountered a code generation problem.
18990 @end itemize
18992 @geindex -gnatdc switch
18995 @itemize *
18997 @item 
18998 Run @code{gcc} with the @code{-gnatdc} switch. This is a GNAT specific
18999 switch that does for the front-end what @code{-v} does
19000 for the back end. The system prints the name of each unit,
19001 either a compilation unit or nested unit, as it is being analyzed.
19003 @item 
19004 Finally, you can start
19005 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19006 front-end of GNAT, and can be run independently (normally it is just
19007 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
19008 would on a C program (but @ref{152,,The GNAT Debugger GDB} for caveats). The
19009 @code{where} command is the first line of attack; the variable
19010 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19011 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
19012 which the execution stopped, and @code{input_file name} indicates the name of
19013 the source file.
19014 @end itemize
19016 @node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
19017 @anchor{gnat_ugn/gnat_and_program_execution id14}@anchor{167}@anchor{gnat_ugn/gnat_and_program_execution naming-conventions-for-gnat-source-files}@anchor{168}
19018 @subsection Naming Conventions for GNAT Source Files
19021 In order to examine the workings of the GNAT system, the following
19022 brief description of its organization may be helpful:
19025 @itemize *
19027 @item 
19028 Files with prefix @code{sc} contain the lexical scanner.
19030 @item 
19031 All files prefixed with @code{par} are components of the parser. The
19032 numbers correspond to chapters of the Ada Reference Manual. For example,
19033 parsing of select statements can be found in @code{par-ch9.adb}.
19035 @item 
19036 All files prefixed with @code{sem} perform semantic analysis. The
19037 numbers correspond to chapters of the Ada standard. For example, all
19038 issues involving context clauses can be found in @code{sem_ch10.adb}. In
19039 addition, some features of the language require sufficient special processing
19040 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19041 dynamic dispatching, etc.
19043 @item 
19044 All files prefixed with @code{exp} perform normalization and
19045 expansion of the intermediate representation (abstract syntax tree, or AST).
19046 these files use the same numbering scheme as the parser and semantics files.
19047 For example, the construction of record initialization procedures is done in
19048 @code{exp_ch3.adb}.
19050 @item 
19051 The files prefixed with @code{bind} implement the binder, which
19052 verifies the consistency of the compilation, determines an order of
19053 elaboration, and generates the bind file.
19055 @item 
19056 The files @code{atree.ads} and @code{atree.adb} detail the low-level
19057 data structures used by the front-end.
19059 @item 
19060 The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
19061 the abstract syntax tree as produced by the parser.
19063 @item 
19064 The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
19065 all entities, computed during semantic analysis.
19067 @item 
19068 Library management issues are dealt with in files with prefix
19069 @code{lib}.
19071 @geindex Annex A (in Ada Reference Manual)
19073 @item 
19074 Ada files with the prefix @code{a-} are children of @code{Ada}, as
19075 defined in Annex A.
19077 @geindex Annex B (in Ada reference Manual)
19079 @item 
19080 Files with prefix @code{i-} are children of @code{Interfaces}, as
19081 defined in Annex B.
19083 @geindex System (package in Ada Reference Manual)
19085 @item 
19086 Files with prefix @code{s-} are children of @code{System}. This includes
19087 both language-defined children and GNAT run-time routines.
19089 @geindex GNAT (package)
19091 @item 
19092 Files with prefix @code{g-} are children of @code{GNAT}. These are useful
19093 general-purpose packages, fully documented in their specs. All
19094 the other @code{.c} files are modifications of common @code{gcc} files.
19095 @end itemize
19097 @node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
19098 @anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{169}@anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{16a}
19099 @subsection Getting Internal Debugging Information
19102 Most compilers have internal debugging switches and modes. GNAT
19103 does also, except GNAT internal debugging switches and modes are not
19104 secret. A summary and full description of all the compiler and binder
19105 debug flags are in the file @code{debug.adb}. You must obtain the
19106 sources of the compiler to see the full detailed effects of these flags.
19108 The switches that print the source of the program (reconstructed from
19109 the internal tree) are of general interest for user programs, as are the
19110 options to print
19111 the full internal tree, and the entity table (the symbol table
19112 information). The reconstructed source provides a readable version of the
19113 program after the front-end has completed analysis and  expansion,
19114 and is useful when studying the performance of specific constructs.
19115 For example, constraint checks are indicated, complex aggregates
19116 are replaced with loops and assignments, and tasking primitives
19117 are replaced with run-time calls.
19119 @geindex traceback
19121 @geindex stack traceback
19123 @geindex stack unwinding
19125 @node Stack Traceback,Pretty-Printers for the GNAT runtime,Getting Internal Debugging Information,Running and Debugging Ada Programs
19126 @anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{16b}@anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{16c}
19127 @subsection Stack Traceback
19130 Traceback is a mechanism to display the sequence of subprogram calls that
19131 leads to a specified execution point in a program. Often (but not always)
19132 the execution point is an instruction at which an exception has been raised.
19133 This mechanism is also known as `stack unwinding' because it obtains
19134 its information by scanning the run-time stack and recovering the activation
19135 records of all active subprograms. Stack unwinding is one of the most
19136 important tools for program debugging.
19138 The first entry stored in traceback corresponds to the deepest calling level,
19139 that is to say the subprogram currently executing the instruction
19140 from which we want to obtain the traceback.
19142 Note that there is no runtime performance penalty when stack traceback
19143 is enabled, and no exception is raised during program execution.
19145 @geindex traceback
19146 @geindex non-symbolic
19148 @menu
19149 * Non-Symbolic Traceback:: 
19150 * Symbolic Traceback:: 
19152 @end menu
19154 @node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
19155 @anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{16d}@anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{16e}
19156 @subsubsection Non-Symbolic Traceback
19159 Note: this feature is not supported on all platforms. See
19160 @code{GNAT.Traceback} spec in @code{g-traceb.ads}
19161 for a complete list of supported platforms.
19163 @subsubheading Tracebacks From an Unhandled Exception
19166 A runtime non-symbolic traceback is a list of addresses of call instructions.
19167 To enable this feature you must use the @code{-E} @code{gnatbind} option. With
19168 this option a stack traceback is stored as part of exception information.
19170 You can translate this information using the @code{addr2line} tool, provided that
19171 the program is compiled with debugging options (see @ref{dd,,Compiler Switches})
19172 and linked at a fixed position with @code{-no-pie}.
19174 Here is a simple example with @code{gnatmake}:
19176 @quotation
19178 @example
19179 procedure STB is
19181    procedure P1 is
19182    begin
19183       raise Constraint_Error;
19184    end P1;
19186    procedure P2 is
19187    begin
19188       P1;
19189    end P2;
19191 begin
19192    P2;
19193 end STB;
19194 @end example
19196 @example
19197 $ gnatmake stb -g -bargs -E -largs -no-pie
19198 $ stb
19200 Execution of stb terminated by unhandled exception
19201 raised CONSTRAINT_ERROR : stb.adb:5 explicit raise
19202 Load address: 0x400000
19203 Call stack traceback locations:
19204 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19205 @end example
19206 @end quotation
19208 As we see the traceback lists a sequence of addresses for the unhandled
19209 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19210 guess that this exception come from procedure P1. To translate these
19211 addresses into the source lines where the calls appear, the @code{addr2line}
19212 tool needs to be invoked like this:
19214 @quotation
19216 @example
19217 $ addr2line -e stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19218    0x4011f1 0x77e892a4
19220 d:/stb/stb.adb:5
19221 d:/stb/stb.adb:10
19222 d:/stb/stb.adb:14
19223 d:/stb/b~stb.adb:197
19224 crtexe.c:?
19225 crtexe.c:?
19226 ??:0
19227 @end example
19228 @end quotation
19230 The @code{addr2line} tool has several other useful options:
19232 @quotation
19235 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
19236 @item
19238 @code{-a --addresses}
19240 @tab
19242 to show the addresses alongside the line numbers
19244 @item
19246 @code{-f --functions}
19248 @tab
19250 to get the function name corresponding to a location
19252 @item
19254 @code{-p --pretty-print}
19256 @tab
19258 to print all the information on a single line
19260 @item
19262 @code{--demangle=gnat}
19264 @tab
19266 to use the GNAT decoding mode for the function names
19268 @end multitable
19271 @example
19272 $ addr2line -e stb -a -f -p --demangle=gnat 0x401373 0x40138b
19273    0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19275 0x00401373: stb.p1 at d:/stb/stb.adb:5
19276 0x0040138B: stb.p2 at d:/stb/stb.adb:10
19277 0x0040139C: stb at d:/stb/stb.adb:14
19278 0x00401335: main at d:/stb/b~stb.adb:197
19279 0x004011c4: ?? at crtexe.c:?
19280 0x004011f1: ?? at crtexe.c:?
19281 0x77e892a4: ?? ??:0
19282 @end example
19283 @end quotation
19285 From this traceback we can see that the exception was raised in @code{stb.adb}
19286 at line 5, which was reached from a procedure call in @code{stb.adb} at line
19287 10, and so on. The @code{b~std.adb} is the binder file, which contains the
19288 call to the main program. @ref{111,,Running gnatbind}. The remaining entries are
19289 assorted runtime routines and the output will vary from platform to platform.
19291 It is also possible to use @code{GDB} with these traceback addresses to debug
19292 the program. For example, we can break at a given code location, as reported
19293 in the stack traceback:
19295 @example
19296 $ gdb -nw stb
19298 (gdb) break *0x401373
19299 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19300 @end example
19302 It is important to note that the stack traceback addresses do not change when
19303 debug information is included. This is particularly useful because it makes it
19304 possible to release software without debug information (to minimize object
19305 size), get a field report that includes a stack traceback whenever an internal
19306 bug occurs, and then be able to retrieve the sequence of calls with the same
19307 program compiled with debug information.
19309 However the @code{addr2line} tool does not work with Position-Independent Code
19310 (PIC), the historical example being Linux dynamic libraries and Windows DLLs,
19311 which nowadays encompasse Position-Independent Executables (PIE) on recent
19312 Linux and Windows versions.
19314 In order to translate addresses the source lines with Position-Independent
19315 Executables on recent Linux and Windows versions, in other words without
19316 using the switch @code{-no-pie} during linking, you need to use the
19317 @code{gnatsymbolize} tool with @code{--load} instead of the @code{addr2line}
19318 tool. The main difference is that you need to copy the Load Address output
19319 in the traceback ahead of the sequence of addresses. And the default mode
19320 of @code{gnatsymbolize} is equivalent to that of @code{addr2line} with the above
19321 switches, so none of them is needed:
19323 @example
19324 $ gnatmake stb -g -bargs -E
19325 $ stb
19327 Execution of stb terminated by unhandled exception
19328 raised CONSTRAINT_ERROR : stb.adb:5 explicit raise
19329 Load address: 0x400000
19330 Call stack traceback locations:
19331 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19333 $ gnatsymbolize --load stb 0x400000 0x401373 0x40138b 0x40139c 0x401335 \
19334    0x4011c4 0x4011f1 0x77e892a4
19336 0x00401373 Stb.P1 at stb.adb:5
19337 0x0040138B Stb.P2 at stb.adb:10
19338 0x0040139C Stb at stb.adb:14
19339 0x00401335 Main at b~stb.adb:197
19340 0x004011c4 __tmainCRTStartup at ???
19341 0x004011f1 mainCRTStartup at ???
19342 0x77e892a4 ??? at ???
19343 @end example
19345 @subsubheading Tracebacks From Exception Occurrences
19348 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
19349 The stack traceback is attached to the exception information string, and can
19350 be retrieved in an exception handler within the Ada program, by means of the
19351 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
19353 @quotation
19355 @example
19356 with Ada.Text_IO;
19357 with Ada.Exceptions;
19359 procedure STB is
19361    use Ada;
19362    use Ada.Exceptions;
19364    procedure P1 is
19365       K : Positive := 1;
19366    begin
19367       K := K - 1;
19368    exception
19369       when E : others =>
19370          Text_IO.Put_Line (Exception_Information (E));
19371    end P1;
19373    procedure P2 is
19374    begin
19375       P1;
19376    end P2;
19378 begin
19379    P2;
19380 end STB;
19381 @end example
19383 @example
19384 $ gnatmake stb -g -bargs -E -largs -no-pie
19385 $ stb
19387 raised CONSTRAINT_ERROR : stb.adb:12 range check failed
19388 Load address: 0x400000
19389 Call stack traceback locations:
19390 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
19391 @end example
19392 @end quotation
19394 @subsubheading Tracebacks From Anywhere in a Program
19397 It is also possible to retrieve a stack traceback from anywhere in a program.
19398 For this you need to use the @code{GNAT.Traceback} API. This package includes a
19399 procedure called @code{Call_Chain} that computes a complete stack traceback, as
19400 well as useful display procedures described below. It is not necessary to use
19401 the @code{-E} @code{gnatbind} option in this case, because the stack traceback
19402 mechanism is invoked explicitly.
19404 In the following example we compute a traceback at a specific location in the
19405 program, and we display it using @code{GNAT.Debug_Utilities.Image} to convert
19406 addresses to strings:
19408 @quotation
19410 @example
19411 with Ada.Text_IO;
19412 with GNAT.Traceback;
19413 with GNAT.Debug_Utilities;
19414 with System;
19416 procedure STB is
19418    use Ada;
19419    use Ada.Text_IO;
19420    use GNAT;
19421    use GNAT.Traceback;
19422    use System;
19424    LA : constant Address := Executable_Load_Address;
19426    procedure P1 is
19427       TB  : Tracebacks_Array (1 .. 10);
19428       --  We are asking for a maximum of 10 stack frames.
19429       Len : Natural;
19430       --  Len will receive the actual number of stack frames returned.
19431    begin
19432       Call_Chain (TB, Len);
19434       Put ("In STB.P1 : ");
19436       for K in 1 .. Len loop
19437          Put (Debug_Utilities.Image_C (TB (K)));
19438          Put (' ');
19439       end loop;
19441       New_Line;
19442    end P1;
19444    procedure P2 is
19445    begin
19446       P1;
19447    end P2;
19449 begin
19450    if LA /= Null_Address then
19451       Put_Line ("Load address: " & Debug_Utilities.Image_C (LA));
19452    end if;
19454    P2;
19455 end STB;
19456 @end example
19458 @example
19459 $ gnatmake stb -g
19460 $ stb
19462 Load address: 0x400000
19463 In STB.P1 : 0x40F1E4 0x4014F2 0x40170B 0x40171C 0x401461 0x4011C4 \
19464   0x4011F1 0x77E892A4
19465 @end example
19466 @end quotation
19468 You can then get further information by invoking the @code{addr2line} tool or
19469 the @code{gnatsymbolize} tool as described earlier (note that the hexadecimal
19470 addresses need to be specified in C format, with a leading ‘0x’).
19472 @geindex traceback
19473 @geindex symbolic
19475 @node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
19476 @anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{16f}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{170}
19477 @subsubsection Symbolic Traceback
19480 A symbolic traceback is a stack traceback in which procedure names are
19481 associated with each code location.
19483 Note that this feature is not supported on all platforms. See
19484 @code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
19485 list of currently supported platforms.
19487 Note that the symbolic traceback requires that the program be compiled
19488 with debug information. If it is not compiled with debug information
19489 only the non-symbolic information will be valid.
19491 @subsubheading Tracebacks From Exception Occurrences
19494 Here is an example:
19496 @quotation
19498 @example
19499 with Ada.Text_IO;
19500 with GNAT.Traceback.Symbolic;
19502 procedure STB is
19504    procedure P1 is
19505    begin
19506       raise Constraint_Error;
19507    end P1;
19509    procedure P2 is
19510    begin
19511       P1;
19512    end P2;
19514    procedure P3 is
19515    begin
19516       P2;
19517    end P3;
19519 begin
19520    P3;
19521 exception
19522    when E : others =>
19523       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
19524 end STB;
19525 @end example
19527 @example
19528 $ gnatmake -g stb -bargs -E
19529 $ stb
19531 0040149F in stb.p1 at stb.adb:8
19532 004014B7 in stb.p2 at stb.adb:13
19533 004014CF in stb.p3 at stb.adb:18
19534 004015DD in ada.stb at stb.adb:22
19535 00401461 in main at b~stb.adb:168
19536 004011C4 in __mingw_CRTStartup at crt1.c:200
19537 004011F1 in mainCRTStartup at crt1.c:222
19538 77E892A4 in ?? at ??:0
19539 @end example
19540 @end quotation
19542 @subsubheading Tracebacks From Anywhere in a Program
19545 It is possible to get a symbolic stack traceback
19546 from anywhere in a program, just as for non-symbolic tracebacks.
19547 The first step is to obtain a non-symbolic
19548 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
19549 information. Here is an example:
19551 @quotation
19553 @example
19554 with Ada.Text_IO;
19555 with GNAT.Traceback;
19556 with GNAT.Traceback.Symbolic;
19558 procedure STB is
19560    use Ada;
19561    use GNAT.Traceback;
19562    use GNAT.Traceback.Symbolic;
19564    procedure P1 is
19565       TB  : Tracebacks_Array (1 .. 10);
19566       --  We are asking for a maximum of 10 stack frames.
19567       Len : Natural;
19568       --  Len will receive the actual number of stack frames returned.
19569    begin
19570       Call_Chain (TB, Len);
19571       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
19572    end P1;
19574    procedure P2 is
19575    begin
19576       P1;
19577    end P2;
19579 begin
19580    P2;
19581 end STB;
19582 @end example
19583 @end quotation
19585 @subsubheading Automatic Symbolic Tracebacks
19588 Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
19589 in @code{gprbuild -g ... -bargs -Es}).
19590 This will cause the Exception_Information to contain a symbolic traceback,
19591 which will also be printed if an unhandled exception terminates the
19592 program.
19594 @node Pretty-Printers for the GNAT runtime,,Stack Traceback,Running and Debugging Ada Programs
19595 @anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{171}@anchor{gnat_ugn/gnat_and_program_execution pretty-printers-for-the-gnat-runtime}@anchor{172}
19596 @subsection Pretty-Printers for the GNAT runtime
19599 As discussed in @cite{Calling User-Defined Subprograms}, GDB’s
19600 @code{print} command only knows about the physical layout of program data
19601 structures and therefore normally displays only low-level dumps, which
19602 are often hard to understand.
19604 An example of this is when trying to display the contents of an Ada
19605 standard container, such as @code{Ada.Containers.Ordered_Maps.Map}:
19607 @quotation
19609 @example
19610 with Ada.Containers.Ordered_Maps;
19612 procedure PP is
19613    package Int_To_Nat is
19614       new Ada.Containers.Ordered_Maps (Integer, Natural);
19616    Map : Int_To_Nat.Map;
19617 begin
19618    Map.Insert (1, 10);
19619    Map.Insert (2, 20);
19620    Map.Insert (3, 30);
19622    Map.Clear; --  BREAK HERE
19623 end PP;
19624 @end example
19625 @end quotation
19627 When this program is built with debugging information and run under
19628 GDB up to the @code{Map.Clear} statement, trying to print @code{Map} will
19629 yield information that is only relevant to the developers of our standard
19630 containers:
19632 @quotation
19634 @example
19635 (gdb) print map
19636 $1 = (
19637   tree => (
19638     first => 0x64e010,
19639     last => 0x64e070,
19640     root => 0x64e040,
19641     length => 3,
19642     tc => (
19643       busy => 0,
19644       lock => 0
19645     )
19646   )
19648 @end example
19649 @end quotation
19651 Fortunately, GDB has a feature called pretty-printers@footnote{http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Introduction},
19652 which allows customizing how GDB displays data structures. The GDB
19653 shipped with GNAT embeds such pretty-printers for the most common
19654 containers in the standard library.  To enable them, either run the
19655 following command manually under GDB or add it to your @code{.gdbinit} file:
19657 @quotation
19659 @example
19660 python import gnatdbg; gnatdbg.setup()
19661 @end example
19662 @end quotation
19664 Once this is done, GDB’s @code{print} command will automatically use
19665 these pretty-printers when appropriate. Using the previous example:
19667 @quotation
19669 @example
19670 (gdb) print map
19671 $1 = pp.int_to_nat.map of length 3 = @{
19672   [1] = 10,
19673   [2] = 20,
19674   [3] = 30
19676 @end example
19677 @end quotation
19679 Pretty-printers are invoked each time GDB tries to display a value,
19680 including when displaying the arguments of a called subprogram (in
19681 GDB’s @code{backtrace} command) or when printing the value returned by a
19682 function (in GDB’s @code{finish} command).
19684 To display a value without involving pretty-printers, @code{print} can be
19685 invoked with its @code{/r} option:
19687 @quotation
19689 @example
19690 (gdb) print/r map
19691 $1 = (
19692   tree => (...
19693 @end example
19694 @end quotation
19696 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}
19697 for more information.
19699 @geindex Profiling
19701 @node Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
19702 @anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{173}@anchor{gnat_ugn/gnat_and_program_execution profiling}@anchor{14a}
19703 @section Profiling
19706 This section describes how to use the @code{gprof} profiler tool on Ada programs.
19708 @geindex gprof
19710 @geindex Profiling
19712 @menu
19713 * Profiling an Ada Program with gprof:: 
19715 @end menu
19717 @node Profiling an Ada Program with gprof,,,Profiling
19718 @anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{174}@anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{175}
19719 @subsection Profiling an Ada Program with gprof
19722 This section is not meant to be an exhaustive documentation of @code{gprof}.
19723 Full documentation for it can be found in the @cite{GNU Profiler User’s Guide}
19724 documentation that is part of this GNAT distribution.
19726 Profiling a program helps determine the parts of a program that are executed
19727 most often, and are therefore the most time-consuming.
19729 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
19730 better handle Ada programs and multitasking.
19731 It is currently supported on the following platforms
19734 @itemize *
19736 @item 
19737 Linux x86/x86_64
19739 @item 
19740 Windows x86/x86_64 (without PIE support)
19741 @end itemize
19743 In order to profile a program using @code{gprof}, several steps are needed:
19746 @enumerate 
19748 @item 
19749 Instrument the code, which requires a full recompilation of the project with the
19750 proper switches.
19752 @item 
19753 Execute the program under the analysis conditions, i.e. with the desired
19754 input.
19756 @item 
19757 Analyze the results using the @code{gprof} tool.
19758 @end enumerate
19760 The following sections detail the different steps, and indicate how
19761 to interpret the results.
19763 @menu
19764 * Compilation for profiling:: 
19765 * Program execution:: 
19766 * Running gprof:: 
19767 * Interpretation of profiling results:: 
19769 @end menu
19771 @node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
19772 @anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{176}@anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{177}
19773 @subsubsection Compilation for profiling
19776 @geindex -pg (gcc)
19777 @geindex for profiling
19779 @geindex -pg (gnatlink)
19780 @geindex for profiling
19782 In order to profile a program the first step is to tell the compiler
19783 to generate the necessary profiling information. The compiler switch to be used
19784 is @code{-pg}, which must be added to other compilation switches. This
19785 switch needs to be specified both during compilation and link stages, and can
19786 be specified once when using gnatmake:
19788 @quotation
19790 @example
19791 $ gnatmake -f -pg -P my_project
19792 @end example
19793 @end quotation
19795 Note that only the objects that were compiled with the @code{-pg} switch will
19796 be profiled; if you need to profile your whole project, use the @code{-f}
19797 gnatmake switch to force full recompilation.
19799 Note that on Windows, gprof does not support PIE. The @code{-no-pie} switch
19800 should be added to the linker flags to disable this feature.
19802 @node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
19803 @anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{178}@anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{179}
19804 @subsubsection Program execution
19807 Once the program has been compiled for profiling, you can run it as usual.
19809 The only constraint imposed by profiling is that the program must terminate
19810 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
19811 properly analyzed.
19813 Once the program completes execution, a data file called @code{gmon.out} is
19814 generated in the directory where the program was launched from. If this file
19815 already exists, it will be overwritten.
19817 @node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
19818 @anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{17a}@anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{17b}
19819 @subsubsection Running gprof
19822 The @code{gprof} tool is called as follow:
19824 @quotation
19826 @example
19827 $ gprof my_prog gmon.out
19828 @end example
19829 @end quotation
19831 or simply:
19833 @quotation
19835 @example
19836 $ gprof my_prog
19837 @end example
19838 @end quotation
19840 The complete form of the gprof command line is the following:
19842 @quotation
19844 @example
19845 $ gprof [switches] [executable [data-file]]
19846 @end example
19847 @end quotation
19849 @code{gprof} supports numerous switches. The order of these
19850 switch does not matter. The full list of options can be found in
19851 the GNU Profiler User’s Guide documentation that comes with this documentation.
19853 The following is the subset of those switches that is most relevant:
19855 @geindex --demangle (gprof)
19858 @table @asis
19860 @item @code{--demangle[=@var{style}]}, @code{--no-demangle}
19862 These options control whether symbol names should be demangled when
19863 printing output.  The default is to demangle C++ symbols.  The
19864 @code{--no-demangle} option may be used to turn off demangling. Different
19865 compilers have different mangling styles.  The optional demangling style
19866 argument can be used to choose an appropriate demangling style for your
19867 compiler, in particular Ada symbols generated by GNAT can be demangled using
19868 @code{--demangle=gnat}.
19869 @end table
19871 @geindex -e (gprof)
19874 @table @asis
19876 @item @code{-e @var{function_name}}
19878 The @code{-e @var{function}} option tells @code{gprof} not to print
19879 information about the function @code{function_name} (and its
19880 children…) in the call graph.  The function will still be listed
19881 as a child of any functions that call it, but its index number will be
19882 shown as @code{[not printed]}.  More than one @code{-e} option may be
19883 given; only one @code{function_name} may be indicated with each @code{-e}
19884 option.
19885 @end table
19887 @geindex -E (gprof)
19890 @table @asis
19892 @item @code{-E @var{function_name}}
19894 The @code{-E @var{function}} option works like the @code{-e} option, but
19895 execution time spent in the function (and children who were not called from
19896 anywhere else), will not be used to compute the percentages-of-time for
19897 the call graph.  More than one @code{-E} option may be given; only one
19898 @code{function_name} may be indicated with each @code{-E`} option.
19899 @end table
19901 @geindex -f (gprof)
19904 @table @asis
19906 @item @code{-f @var{function_name}}
19908 The @code{-f @var{function}} option causes @code{gprof} to limit the
19909 call graph to the function @code{function_name} and its children (and
19910 their children…).  More than one @code{-f} option may be given;
19911 only one @code{function_name} may be indicated with each @code{-f}
19912 option.
19913 @end table
19915 @geindex -F (gprof)
19918 @table @asis
19920 @item @code{-F @var{function_name}}
19922 The @code{-F @var{function}} option works like the @code{-f} option, but
19923 only time spent in the function and its children (and their
19924 children…) will be used to determine total-time and
19925 percentages-of-time for the call graph.  More than one @code{-F} option
19926 may be given; only one @code{function_name} may be indicated with each
19927 @code{-F} option.  The @code{-F} option overrides the @code{-E} option.
19928 @end table
19930 @node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
19931 @anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{17c}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{17d}
19932 @subsubsection Interpretation of profiling results
19935 The results of the profiling analysis are represented by two arrays: the
19936 ‘flat profile’ and the ‘call graph’. Full documentation of those outputs
19937 can be found in the GNU Profiler User’s Guide.
19939 The flat profile shows the time spent in each function of the program, and how
19940 many time it has been called. This allows you to locate easily the most
19941 time-consuming functions.
19943 The call graph shows, for each subprogram, the subprograms that call it,
19944 and the subprograms that it calls. It also provides an estimate of the time
19945 spent in each of those callers/called subprograms.
19947 @node Improving Performance,Overflow Check Handling in GNAT,Profiling,GNAT and Program Execution
19948 @anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{14b}@anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{17e}
19949 @section Improving Performance
19952 @geindex Improving performance
19954 This section presents several topics related to program performance.
19955 It first describes some of the tradeoffs that need to be considered
19956 and some of the techniques for making your program run faster.
19958 It then documents the unused subprogram/data elimination feature,
19959 which can reduce the size of program executables.
19961 @menu
19962 * Performance Considerations:: 
19963 * Text_IO Suggestions:: 
19964 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
19966 @end menu
19968 @node Performance Considerations,Text_IO Suggestions,,Improving Performance
19969 @anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{17f}@anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{180}
19970 @subsection Performance Considerations
19973 The GNAT system provides a number of options that allow a trade-off
19974 between
19977 @itemize *
19979 @item 
19980 performance of the generated code
19982 @item 
19983 speed of compilation
19985 @item 
19986 minimization of dependences and recompilation
19988 @item 
19989 the degree of run-time checking.
19990 @end itemize
19992 The defaults (if no options are selected) aim at improving the speed
19993 of compilation and minimizing dependences, at the expense of performance
19994 of the generated code:
19997 @itemize *
19999 @item 
20000 no optimization
20002 @item 
20003 no inlining of subprogram calls
20005 @item 
20006 all run-time checks enabled except overflow and elaboration checks
20007 @end itemize
20009 These options are suitable for most program development purposes. This
20010 section describes how you can modify these choices, and also provides
20011 some guidelines on debugging optimized code.
20013 @menu
20014 * Controlling Run-Time Checks:: 
20015 * Use of Restrictions:: 
20016 * Optimization Levels:: 
20017 * Debugging Optimized Code:: 
20018 * Inlining of Subprograms:: 
20019 * Floating Point Operations:: 
20020 * Vectorization of loops:: 
20021 * Other Optimization Switches:: 
20022 * Optimization and Strict Aliasing:: 
20023 * Aliased Variables and Optimization:: 
20024 * Atomic Variables and Optimization:: 
20025 * Passive Task Optimization:: 
20027 @end menu
20029 @node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
20030 @anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{181}@anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{182}
20031 @subsubsection Controlling Run-Time Checks
20034 By default, GNAT generates all run-time checks, except stack overflow
20035 checks, and checks for access before elaboration on subprogram
20036 calls. The latter are not required in default mode, because all
20037 necessary checking is done at compile time.
20039 @geindex -gnatp (gcc)
20041 @geindex -gnato (gcc)
20043 The gnat switch, @code{-gnatp} allows this default to be modified. See
20044 @ref{ec,,Run-Time Checks}.
20046 Our experience is that the default is suitable for most development
20047 purposes.
20049 Elaboration checks are off by default, and also not needed by default, since
20050 GNAT uses a static elaboration analysis approach that avoids the need for
20051 run-time checking. This manual contains a full chapter discussing the issue
20052 of elaboration checks, and if the default is not satisfactory for your use,
20053 you should read this chapter.
20055 For validity checks, the minimal checks required by the Ada Reference
20056 Manual (for case statements and assignments to array elements) are on
20057 by default. These can be suppressed by use of the @code{-gnatVn} switch.
20058 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20059 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20060 it may be reasonable to routinely use @code{-gnatVn}. Validity checks
20061 are also suppressed entirely if @code{-gnatp} is used.
20063 @geindex Overflow checks
20065 @geindex Checks
20066 @geindex overflow
20068 @geindex Suppress
20070 @geindex Unsuppress
20072 @geindex pragma Suppress
20074 @geindex pragma Unsuppress
20076 Note that the setting of the switches controls the default setting of
20077 the checks. They may be modified using either @code{pragma Suppress} (to
20078 remove checks) or @code{pragma Unsuppress} (to add back suppressed
20079 checks) in the program source.
20081 @node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
20082 @anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{183}@anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{184}
20083 @subsubsection Use of Restrictions
20086 The use of pragma Restrictions allows you to control which features are
20087 permitted in your program. Apart from the obvious point that if you avoid
20088 relatively expensive features like finalization (enforceable by the use
20089 of pragma Restrictions (No_Finalization)), the use of this pragma does not
20090 affect the generated code in most cases.
20092 One notable exception to this rule is that the possibility of task abort
20093 results in some distributed overhead, particularly if finalization or
20094 exception handlers are used. The reason is that certain sections of code
20095 have to be marked as non-abortable.
20097 If you use neither the @code{abort} statement, nor asynchronous transfer
20098 of control (@code{select ... then abort}), then this distributed overhead
20099 is removed, which may have a general positive effect in improving
20100 overall performance.  Especially code involving frequent use of tasking
20101 constructs and controlled types will show much improved performance.
20102 The relevant restrictions pragmas are
20104 @quotation
20106 @example
20107 pragma Restrictions (No_Abort_Statements);
20108 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
20109 @end example
20110 @end quotation
20112 It is recommended that these restriction pragmas be used if possible. Note
20113 that this also means that you can write code without worrying about the
20114 possibility of an immediate abort at any point.
20116 @node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
20117 @anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{185}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{ef}
20118 @subsubsection Optimization Levels
20121 @geindex -O (gcc)
20123 Without any optimization option,
20124 the compiler’s goal is to reduce the cost of
20125 compilation and to make debugging produce the expected results.
20126 Statements are independent: if you stop the program with a breakpoint between
20127 statements, you can then assign a new value to any variable or change
20128 the program counter to any other statement in the subprogram and get exactly
20129 the results you would expect from the source code.
20131 Turning on optimization makes the compiler attempt to improve the
20132 performance and/or code size at the expense of compilation time and
20133 possibly the ability to debug the program.
20135 If you use multiple
20136 -O options, with or without level numbers,
20137 the last such option is the one that is effective.
20139 The default is optimization off. This results in the fastest compile
20140 times, but GNAT makes absolutely no attempt to optimize, and the
20141 generated programs are considerably larger and slower than when
20142 optimization is enabled. You can use the
20143 @code{-O} switch (the permitted forms are @code{-O0}, @code{-O1}
20144 @code{-O2}, @code{-O3}, and @code{-Os})
20145 to @code{gcc} to control the optimization level:
20148 @itemize *
20150 @item 
20152 @table @asis
20154 @item @code{-O0}
20156 No optimization (the default);
20157 generates unoptimized code but has
20158 the fastest compilation time.
20160 Note that many other compilers do substantial optimization even
20161 if ‘no optimization’ is specified. With gcc, it is very unusual
20162 to use @code{-O0} for production if execution time is of any concern,
20163 since @code{-O0} means (almost) no optimization. This difference
20164 between gcc and other compilers should be kept in mind when
20165 doing performance comparisons.
20166 @end table
20168 @item 
20170 @table @asis
20172 @item @code{-O1}
20174 Moderate optimization;
20175 optimizes reasonably well but does not
20176 degrade compilation time significantly.
20177 @end table
20179 @item 
20181 @table @asis
20183 @item @code{-O2}
20185 Full optimization;
20186 generates highly optimized code and has
20187 the slowest compilation time.
20188 @end table
20190 @item 
20192 @table @asis
20194 @item @code{-O3}
20196 Full optimization as in @code{-O2};
20197 also uses more aggressive automatic inlining of subprograms within a unit
20198 (@ref{103,,Inlining of Subprograms}) and attempts to vectorize loops.
20199 @end table
20201 @item 
20203 @table @asis
20205 @item @code{-Os}
20207 Optimize space usage (code and data) of resulting program.
20208 @end table
20209 @end itemize
20211 Higher optimization levels perform more global transformations on the
20212 program and apply more expensive analysis algorithms in order to generate
20213 faster and more compact code. The price in compilation time, and the
20214 resulting improvement in execution time,
20215 both depend on the particular application and the hardware environment.
20216 You should experiment to find the best level for your application.
20218 Since the precise set of optimizations done at each level will vary from
20219 release to release (and sometime from target to target), it is best to think
20220 of the optimization settings in general terms.
20221 See the `Options That Control Optimization' section in
20222 @cite{Using the GNU Compiler Collection (GCC)}
20223 for details about
20224 the @code{-O} settings and a number of @code{-f} options that
20225 individually enable or disable specific optimizations.
20227 Unlike some other compilation systems, @code{gcc} has
20228 been tested extensively at all optimization levels. There are some bugs
20229 which appear only with optimization turned on, but there have also been
20230 bugs which show up only in `unoptimized' code. Selecting a lower
20231 level of optimization does not improve the reliability of the code
20232 generator, which in practice is highly reliable at all optimization
20233 levels.
20235 Note regarding the use of @code{-O3}: The use of this optimization level
20236 ought not to be automatically preferred over that of level @code{-O2},
20237 since it often results in larger executables which may run more slowly.
20238 See further discussion of this point in @ref{103,,Inlining of Subprograms}.
20240 @node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
20241 @anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{186}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{187}
20242 @subsubsection Debugging Optimized Code
20245 @geindex Debugging optimized code
20247 @geindex Optimization and debugging
20249 Although it is possible to do a reasonable amount of debugging at
20250 nonzero optimization levels,
20251 the higher the level the more likely that
20252 source-level constructs will have been eliminated by optimization.
20253 For example, if a loop is strength-reduced, the loop
20254 control variable may be completely eliminated and thus cannot be
20255 displayed in the debugger.
20256 This can only happen at @code{-O2} or @code{-O3}.
20257 Explicit temporary variables that you code might be eliminated at
20258 level @code{-O1} or higher.
20260 @geindex -g (gcc)
20262 The use of the @code{-g} switch,
20263 which is needed for source-level debugging,
20264 affects the size of the program executable on disk,
20265 and indeed the debugging information can be quite large.
20266 However, it has no effect on the generated code (and thus does not
20267 degrade performance)
20269 Since the compiler generates debugging tables for a compilation unit before
20270 it performs optimizations, the optimizing transformations may invalidate some
20271 of the debugging data.  You therefore need to anticipate certain
20272 anomalous situations that may arise while debugging optimized code.
20273 These are the most common cases:
20276 @itemize *
20278 @item 
20279 `The ‘hopping Program Counter’:'  Repeated @code{step} or @code{next}
20280 commands show
20281 the PC bouncing back and forth in the code.  This may result from any of
20282 the following optimizations:
20285 @itemize -
20287 @item 
20288 `Common subexpression elimination:' using a single instance of code for a
20289 quantity that the source computes several times.  As a result you
20290 may not be able to stop on what looks like a statement.
20292 @item 
20293 `Invariant code motion:' moving an expression that does not change within a
20294 loop, to the beginning of the loop.
20296 @item 
20297 `Instruction scheduling:' moving instructions so as to
20298 overlap loads and stores (typically) with other code, or in
20299 general to move computations of values closer to their uses. Often
20300 this causes you to pass an assignment statement without the assignment
20301 happening and then later bounce back to the statement when the
20302 value is actually needed.  Placing a breakpoint on a line of code
20303 and then stepping over it may, therefore, not always cause all the
20304 expected side-effects.
20305 @end itemize
20307 @item 
20308 `The ‘big leap’:' More commonly known as `cross-jumping', in which
20309 two identical pieces of code are merged and the program counter suddenly
20310 jumps to a statement that is not supposed to be executed, simply because
20311 it (and the code following) translates to the same thing as the code
20312 that `was' supposed to be executed.  This effect is typically seen in
20313 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
20314 a @code{break} in a C @code{switch} statement.
20316 @item 
20317 `The ‘roving variable’:' The symptom is an unexpected value in a variable.
20318 There are various reasons for this effect:
20321 @itemize -
20323 @item 
20324 In a subprogram prologue, a parameter may not yet have been moved to its
20325 ‘home’.
20327 @item 
20328 A variable may be dead, and its register re-used.  This is
20329 probably the most common cause.
20331 @item 
20332 As mentioned above, the assignment of a value to a variable may
20333 have been moved.
20335 @item 
20336 A variable may be eliminated entirely by value propagation or
20337 other means.  In this case, GCC may incorrectly generate debugging
20338 information for the variable
20339 @end itemize
20341 In general, when an unexpected value appears for a local variable or parameter
20342 you should first ascertain if that value was actually computed by
20343 your program, as opposed to being incorrectly reported by the debugger.
20344 Record fields or
20345 array elements in an object designated by an access value
20346 are generally less of a problem, once you have ascertained that the access
20347 value is sensible.
20348 Typically, this means checking variables in the preceding code and in the
20349 calling subprogram to verify that the value observed is explainable from other
20350 values (one must apply the procedure recursively to those
20351 other values); or re-running the code and stopping a little earlier
20352 (perhaps before the call) and stepping to better see how the variable obtained
20353 the value in question; or continuing to step `from' the point of the
20354 strange value to see if code motion had simply moved the variable’s
20355 assignments later.
20356 @end itemize
20358 In light of such anomalies, a recommended technique is to use @code{-O0}
20359 early in the software development cycle, when extensive debugging capabilities
20360 are most needed, and then move to @code{-O1} and later @code{-O2} as
20361 the debugger becomes less critical.
20362 Whether to use the @code{-g} switch in the release version is
20363 a release management issue.
20364 Note that if you use @code{-g} you can then use the @code{strip} program
20365 on the resulting executable,
20366 which removes both debugging information and global symbols.
20368 @node Inlining of Subprograms,Floating Point Operations,Debugging Optimized Code,Performance Considerations
20369 @anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{188}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{103}
20370 @subsubsection Inlining of Subprograms
20373 A call to a subprogram in the current unit is inlined if all the
20374 following conditions are met:
20377 @itemize *
20379 @item 
20380 The optimization level is at least @code{-O1}.
20382 @item 
20383 The called subprogram is suitable for inlining: It must be small enough
20384 and not contain something that @code{gcc} cannot support in inlined
20385 subprograms.
20387 @geindex pragma Inline
20389 @geindex Inline
20391 @item 
20392 Any one of the following applies: @code{pragma Inline} is applied to the
20393 subprogram; the subprogram is local to the unit and called once from
20394 within it; the subprogram is small and optimization level @code{-O2} is
20395 specified; optimization level @code{-O3} is specified.
20396 @end itemize
20398 Calls to subprograms in `with'ed units are normally not inlined.
20399 To achieve actual inlining (that is, replacement of the call by the code
20400 in the body of the subprogram), the following conditions must all be true:
20403 @itemize *
20405 @item 
20406 The optimization level is at least @code{-O1}.
20408 @item 
20409 The called subprogram is suitable for inlining: It must be small enough
20410 and not contain something that @code{gcc} cannot support in inlined
20411 subprograms.
20413 @item 
20414 There is a @code{pragma Inline} for the subprogram.
20416 @item 
20417 The @code{-gnatn} switch is used on the command line.
20418 @end itemize
20420 Even if all these conditions are met, it may not be possible for
20421 the compiler to inline the call, due to the length of the body,
20422 or features in the body that make it impossible for the compiler
20423 to do the inlining.
20425 Note that specifying the @code{-gnatn} switch causes additional
20426 compilation dependencies. Consider the following:
20428 @quotation
20430 @example
20431 package R is
20432    procedure Q;
20433    pragma Inline (Q);
20434 end R;
20435 package body R is
20436    ...
20437 end R;
20439 with R;
20440 procedure Main is
20441 begin
20442    ...
20443    R.Q;
20444 end Main;
20445 @end example
20446 @end quotation
20448 With the default behavior (no @code{-gnatn} switch specified), the
20449 compilation of the @code{Main} procedure depends only on its own source,
20450 @code{main.adb}, and the spec of the package in file @code{r.ads}. This
20451 means that editing the body of @code{R} does not require recompiling
20452 @code{Main}.
20454 On the other hand, the call @code{R.Q} is not inlined under these
20455 circumstances. If the @code{-gnatn} switch is present when @code{Main}
20456 is compiled, the call will be inlined if the body of @code{Q} is small
20457 enough, but now @code{Main} depends on the body of @code{R} in
20458 @code{r.adb} as well as on the spec. This means that if this body is edited,
20459 the main program must be recompiled. Note that this extra dependency
20460 occurs whether or not the call is in fact inlined by @code{gcc}.
20462 The use of front end inlining with @code{-gnatN} generates similar
20463 additional dependencies.
20465 @geindex -fno-inline (gcc)
20467 Note: The @code{-fno-inline} switch overrides all other conditions and ensures that
20468 no inlining occurs, unless requested with pragma Inline_Always for @code{gcc}
20469 back-ends. The extra dependences resulting from @code{-gnatn} will still be active,
20470 even if this switch is used to suppress the resulting inlining actions.
20472 @geindex -fno-inline-functions (gcc)
20474 Note: The @code{-fno-inline-functions} switch can be used to prevent
20475 automatic inlining of subprograms if @code{-O3} is used.
20477 @geindex -fno-inline-small-functions (gcc)
20479 Note: The @code{-fno-inline-small-functions} switch can be used to prevent
20480 automatic inlining of small subprograms if @code{-O2} is used.
20482 @geindex -fno-inline-functions-called-once (gcc)
20484 Note: The @code{-fno-inline-functions-called-once} switch
20485 can be used to prevent inlining of subprograms local to the unit
20486 and called once from within it if @code{-O1} is used.
20488 Note regarding the use of @code{-O3}: @code{-gnatn} is made up of two
20489 sub-switches @code{-gnatn1} and @code{-gnatn2} that can be directly
20490 specified in lieu of it, @code{-gnatn} being translated into one of them
20491 based on the optimization level. With @code{-O2} or below, @code{-gnatn}
20492 is equivalent to @code{-gnatn1} which activates pragma @code{Inline} with
20493 moderate inlining across modules. With @code{-O3}, @code{-gnatn} is
20494 equivalent to @code{-gnatn2} which activates pragma @code{Inline} with
20495 full inlining across modules. If you have used pragma @code{Inline} in
20496 appropriate cases, then it is usually much better to use @code{-O2}
20497 and @code{-gnatn} and avoid the use of @code{-O3} which has the additional
20498 effect of inlining subprograms you did not think should be inlined. We have
20499 found that the use of @code{-O3} may slow down the compilation and increase
20500 the code size by performing excessive inlining, leading to increased
20501 instruction cache pressure from the increased code size and thus minor
20502 performance improvements. So the bottom line here is that you should not
20503 automatically assume that @code{-O3} is better than @code{-O2}, and
20504 indeed you should use @code{-O3} only if tests show that it actually
20505 improves performance for your program.
20507 @node Floating Point Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
20508 @anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{189}@anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{18a}
20509 @subsubsection Floating Point Operations
20512 @geindex Floating-Point Operations
20514 On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
20515 64-bit standard IEEE floating-point representations, and operations will
20516 use standard IEEE arithmetic as provided by the processor. On most, but
20517 not all, architectures, the attribute Machine_Overflows is False for these
20518 types, meaning that the semantics of overflow is implementation-defined.
20519 In the case of GNAT, these semantics correspond to the normal IEEE
20520 treatment of infinities and NaN (not a number) values. For example,
20521 1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
20522 avoiding explicit overflow checks, the performance is greatly improved
20523 on many targets. However, if required, floating-point overflow can be
20524 enabled by the use of the pragma Check_Float_Overflow.
20526 Another consideration that applies specifically to x86 32-bit
20527 architectures is which form of floating-point arithmetic is used.
20528 By default the operations use the old style x86 floating-point,
20529 which implements an 80-bit extended precision form (on these
20530 architectures the type Long_Long_Float corresponds to that form).
20531 In addition, generation of efficient code in this mode means that
20532 the extended precision form will be used for intermediate results.
20533 This may be helpful in improving the final precision of a complex
20534 expression. However it means that the results obtained on the x86
20535 will be different from those on other architectures, and for some
20536 algorithms, the extra intermediate precision can be detrimental.
20538 In addition to this old-style floating-point, all modern x86 chips
20539 implement an alternative floating-point operation model referred
20540 to as SSE2. In this model there is no extended form, and furthermore
20541 execution performance is significantly enhanced. To force GNAT to use
20542 this more modern form, use both of the switches:
20544 @quotation
20546 -msse2 -mfpmath=sse
20547 @end quotation
20549 A unit compiled with these switches will automatically use the more
20550 efficient SSE2 instruction set for Float and Long_Float operations.
20551 Note that the ABI has the same form for both floating-point models,
20552 so it is permissible to mix units compiled with and without these
20553 switches.
20555 @node Vectorization of loops,Other Optimization Switches,Floating Point Operations,Performance Considerations
20556 @anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{18b}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{18c}
20557 @subsubsection Vectorization of loops
20560 @geindex Optimization Switches
20562 You can take advantage of the auto-vectorizer present in the @code{gcc}
20563 back end to vectorize loops with GNAT.  The corresponding command line switch
20564 is @code{-ftree-vectorize} but, as it is enabled by default at @code{-O3}
20565 and other aggressive optimizations helpful for vectorization also are enabled
20566 by default at this level, using @code{-O3} directly is recommended.
20568 You also need to make sure that the target architecture features a supported
20569 SIMD instruction set.  For example, for the x86 architecture, you should at
20570 least specify @code{-msse2} to get significant vectorization (but you don’t
20571 need to specify it for x86-64 as it is part of the base 64-bit architecture).
20572 Similarly, for the PowerPC architecture, you should specify @code{-maltivec}.
20574 The preferred loop form for vectorization is the @code{for} iteration scheme.
20575 Loops with a @code{while} iteration scheme can also be vectorized if they are
20576 very simple, but the vectorizer will quickly give up otherwise.  With either
20577 iteration scheme, the flow of control must be straight, in particular no
20578 @code{exit} statement may appear in the loop body.  The loop may however
20579 contain a single nested loop, if it can be vectorized when considered alone:
20581 @quotation
20583 @example
20584 A : array (1..4, 1..4) of Long_Float;
20585 S : array (1..4) of Long_Float;
20587 procedure Sum is
20588 begin
20589    for I in A'Range(1) loop
20590       for J in A'Range(2) loop
20591          S (I) := S (I) + A (I, J);
20592       end loop;
20593    end loop;
20594 end Sum;
20595 @end example
20596 @end quotation
20598 The vectorizable operations depend on the targeted SIMD instruction set, but
20599 the adding and some of the multiplying operators are generally supported, as
20600 well as the logical operators for modular types. Note that compiling
20601 with @code{-gnatp} might well reveal cases where some checks do thwart
20602 vectorization.
20604 Type conversions may also prevent vectorization if they involve semantics that
20605 are not directly supported by the code generator or the SIMD instruction set.
20606 A typical example is direct conversion from floating-point to integer types.
20607 The solution in this case is to use the following idiom:
20609 @quotation
20611 @example
20612 Integer (S'Truncation (F))
20613 @end example
20614 @end quotation
20616 if @code{S} is the subtype of floating-point object @code{F}.
20618 In most cases, the vectorizable loops are loops that iterate over arrays.
20619 All kinds of array types are supported, i.e. constrained array types with
20620 static bounds:
20622 @quotation
20624 @example
20625 type Array_Type is array (1 .. 4) of Long_Float;
20626 @end example
20627 @end quotation
20629 constrained array types with dynamic bounds:
20631 @quotation
20633 @example
20634 type Array_Type is array (1 .. Q.N) of Long_Float;
20636 type Array_Type is array (Q.K .. 4) of Long_Float;
20638 type Array_Type is array (Q.K .. Q.N) of Long_Float;
20639 @end example
20640 @end quotation
20642 or unconstrained array types:
20644 @quotation
20646 @example
20647 type Array_Type is array (Positive range <>) of Long_Float;
20648 @end example
20649 @end quotation
20651 The quality of the generated code decreases when the dynamic aspect of the
20652 array type increases, the worst code being generated for unconstrained array
20653 types.  This is so because, the less information the compiler has about the
20654 bounds of the array, the more fallback code it needs to generate in order to
20655 fix things up at run time.
20657 It is possible to specify that a given loop should be subject to vectorization
20658 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
20660 @quotation
20662 @example
20663 pragma Loop_Optimize (Vector);
20664 @end example
20665 @end quotation
20667 placed immediately within the loop will convey the appropriate hint to the
20668 compiler for this loop.
20670 It is also possible to help the compiler generate better vectorized code
20671 for a given loop by asserting that there are no loop-carried dependencies
20672 in the loop.  Consider for example the procedure:
20674 @quotation
20676 @example
20677 type Arr is array (1 .. 4) of Long_Float;
20679 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
20680 begin
20681   for I in Arr'Range loop
20682     R(I) := X(I) + Y(I);
20683   end loop;
20684 end;
20685 @end example
20686 @end quotation
20688 By default, the compiler cannot unconditionally vectorize the loop because
20689 assigning to a component of the array designated by R in one iteration could
20690 change the value read from the components of the array designated by X or Y
20691 in a later iteration.  As a result, the compiler will generate two versions
20692 of the loop in the object code, one vectorized and the other not vectorized,
20693 as well as a test to select the appropriate version at run time.  This can
20694 be overcome by another hint:
20696 @quotation
20698 @example
20699 pragma Loop_Optimize (Ivdep);
20700 @end example
20701 @end quotation
20703 placed immediately within the loop will tell the compiler that it can safely
20704 omit the non-vectorized version of the loop as well as the run-time test.
20706 @node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
20707 @anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{18d}@anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{18e}
20708 @subsubsection Other Optimization Switches
20711 @geindex Optimization Switches
20713 Since GNAT uses the @code{gcc} back end, all the specialized
20714 @code{gcc} optimization switches are potentially usable. These switches
20715 have not been extensively tested with GNAT but can generally be expected
20716 to work. Examples of switches in this category are @code{-funroll-loops}
20717 and the various target-specific @code{-m} options (in particular, it has
20718 been observed that @code{-march=xxx} can significantly improve performance
20719 on appropriate machines). For full details of these switches, see
20720 the `Submodel Options' section in the `Hardware Models and Configurations'
20721 chapter of @cite{Using the GNU Compiler Collection (GCC)}.
20723 @node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
20724 @anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{18f}@anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{e6}
20725 @subsubsection Optimization and Strict Aliasing
20728 @geindex Aliasing
20730 @geindex Strict Aliasing
20732 @geindex No_Strict_Aliasing
20734 The strong typing capabilities of Ada allow an optimizer to generate
20735 efficient code in situations where other languages would be forced to
20736 make worst case assumptions preventing such optimizations. Consider
20737 the following example:
20739 @quotation
20741 @example
20742 procedure M is
20743    type Int1 is new Integer;
20744    I1 : Int1;
20746    type Int2 is new Integer;
20747    type A2 is access Int2;
20748    V2 : A2;
20749    ...
20751 begin
20752    ...
20753    for J in Data'Range loop
20754       if Data (J) = I1 then
20755          V2.all := V2.all + 1;
20756       end if;
20757    end loop;
20758    ...
20759 end;
20760 @end example
20761 @end quotation
20763 In this example, since @code{V2} can only access objects of type @code{Int2}
20764 and @code{I1} is not one of them, there is no possibility that the assignment
20765 to @code{V2.all} affects the value of @code{I1}. This means that the compiler
20766 optimizer can infer that the value @code{I1} is constant for all iterations
20767 of the loop and load it from memory only once, before entering the loop,
20768 instead of in every iteration (this is called load hoisting).
20770 This kind of optimizations, based on strict type-based aliasing, is
20771 triggered by specifying an optimization level of @code{-O2} or
20772 higher (or @code{-Os}) and allows the compiler to generate more
20773 efficient code.
20775 However, although this optimization is always correct in terms of
20776 the formal semantics of the Ada Reference Manual, difficulties can
20777 arise if features like @code{Unchecked_Conversion} are used to break
20778 the typing system. Consider the following complete program example:
20780 @quotation
20782 @example
20783 package P1 is
20784    type Int1 is new Integer;
20785    type A1 is access Int1;
20787    type Int2 is new Integer;
20788    type A2 is access Int2;
20789 end P1;
20791 with P1; use P1;
20792 package P2 is
20793    function To_A2 (Input : A1) return A2;
20794 end p2;
20796 with Ada.Unchecked_Conversion;
20797 package body P2 is
20798    function To_A2 (Input : A1) return A2 is
20799       function Conv is
20800         new Ada.Unchecked_Conversion (A1, A2);
20801    begin
20802       return Conv (Input);
20803    end To_A2;
20804 end P2;
20806 with P1; use P1;
20807 with P2; use P2;
20808 with Text_IO; use Text_IO;
20809 procedure M is
20810    V1 : A1 := new Int1;
20811    V2 : A2 := To_A2 (V1);
20812 begin
20813    V1.all := 1;
20814    V2.all := 0;
20815    Put_Line (Int1'Image (V1.all));
20816 end;
20817 @end example
20818 @end quotation
20820 This program prints out @code{0} in @code{-O0} or @code{-O1} modes,
20821 but it prints out @code{1} in @code{-O2} mode. That’s because in strict
20822 aliasing mode, the compiler may and does assume that the assignment to
20823 @code{V2.all} could not affect the value of @code{V1.all}, since different
20824 types are involved.
20826 This behavior is not a case of non-conformance with the standard, since
20827 the Ada RM specifies that an unchecked conversion where the resulting
20828 bit pattern is not a correct value of the target type can result in an
20829 abnormal value and attempting to reference an abnormal value makes the
20830 execution of a program erroneous.  That’s the case here since the result
20831 does not point to an object of type @code{Int2}.  This means that the effect
20832 is entirely unpredictable.
20834 However, although that explanation may satisfy a language lawyer, in
20835 practice an application programmer expects an unchecked conversion
20836 involving pointers to create true aliases and the behavior of printing
20837 @code{1} is questionable. In this case, the strict type-based aliasing
20838 optimizations are clearly unwelcome.
20840 Indeed the compiler recognizes this possibility and the instantiation of
20841 Unchecked_Conversion generates a warning:
20843 @quotation
20845 @example
20846 p2.adb:5:07: warning: possible aliasing problem with type "A2"
20847 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
20848 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (A2);"
20849 @end example
20850 @end quotation
20852 Unfortunately the problem is only recognized when compiling the body of
20853 package @code{P2}, but the actual problematic code is generated while
20854 compiling the body of @code{M} and this latter compilation does not see
20855 the suspicious instance of @code{Unchecked_Conversion}.
20857 As implied by the warning message, there are approaches you can use to
20858 avoid the unwanted strict aliasing optimizations in a case like this.
20860 One possibility is to simply avoid the use of @code{-O2}, but
20861 that is quite drastic, since it throws away a number of useful
20862 optimizations that do not involve strict aliasing assumptions.
20864 A less drastic approach is to compile the program using the
20865 option @code{-fno-strict-aliasing}. Actually it is only the
20866 unit containing the dereferencing of the suspicious pointer
20867 that needs to be compiled. So in this case, if we compile
20868 unit @code{M} with this switch, then we get the expected
20869 value of zero printed. Analyzing which units might need
20870 the switch can be painful, so a more reasonable approach
20871 is to compile the entire program with options @code{-O2}
20872 and @code{-fno-strict-aliasing}. If the performance is
20873 satisfactory with this combination of options, then the
20874 advantage is that the entire issue of possible problematic
20875 optimizations due to strict aliasing is avoided.
20877 To avoid the use of compiler switches, the configuration
20878 pragma @code{No_Strict_Aliasing} with no parameters may be
20879 used to specify that for all access types, the strict
20880 aliasing optimizations should be suppressed.
20882 However, these approaches are still overkill, in that they cause
20883 all manipulations of all access values to be deoptimized. A more
20884 refined approach is to concentrate attention on the specific
20885 access type identified as problematic.
20887 The first possibility is to move the instantiation of unchecked
20888 conversion to the unit in which the type is declared. In this
20889 example, we would move the instantiation of @code{Unchecked_Conversion}
20890 from the body of package @code{P2} to the spec of package @code{P1}.
20891 Now the warning disappears because any use of the access type
20892 knows there is a suspicious unchecked conversion, and the strict
20893 aliasing optimizations are automatically suppressed for it.
20895 If it is not practical to move the unchecked conversion to the same unit
20896 in which the destination access type is declared (perhaps because the
20897 source type is not visible in that unit), the second possibiliy is to
20898 use pragma @code{No_Strict_Aliasing} for the type. This pragma must occur
20899 in the same declarative part as the declaration of the access type:
20901 @quotation
20903 @example
20904 type A2 is access Int2;
20905 pragma No_Strict_Aliasing (A2);
20906 @end example
20907 @end quotation
20909 Here again, the compiler now knows that strict aliasing optimizations
20910 should be suppressed for any dereference made through type @code{A2} and
20911 the expected behavior is obtained.
20913 The third possibility is to declare that one of the designated types
20914 involved, namely @code{Int1} or @code{Int2}, is allowed to alias any other
20915 type in the universe, by using pragma @code{Universal_Aliasing}:
20917 @quotation
20919 @example
20920 type Int2 is new Integer;
20921 pragma Universal_Aliasing (Int2);
20922 @end example
20923 @end quotation
20925 The effect is equivalent to applying pragma @code{No_Strict_Aliasing} to
20926 every access type designating @code{Int2}, in particular @code{A2}, and more
20927 generally to every reference made to an object of declared type @code{Int2},
20928 so it is very powerful and effectively takes @code{Int2} out of the alias
20929 analysis performed by the compiler in all circumstances.
20931 This pragma can also be used to deal with aliasing issues that arise
20932 again from the use of @code{Unchecked_Conversion} in the source code but
20933 without the presence of access types. The typical example is code
20934 that streams data by means of arrays of storage units (bytes):
20936 @quotation
20938 @example
20939 type Byte is mod 2**System.Storage_Unit;
20940 for Byte'Size use System.Storage_Unit;
20942 type Chunk_Of_Bytes is array (1 .. 64) of Byte;
20944 procedure Send (S : Chunk_Of_Bytes);
20946 type Rec is record
20947    ...
20948 end record;
20950 procedure Dump (R : Rec) is
20951    function To_Stream is
20952       new Ada.Unchecked_Conversion (Rec, Chunk_Of_Bytes);
20953 begin
20954    Send (To_Stream (R));
20955 end;
20956 @end example
20957 @end quotation
20959 This generates the following warning for the call to @code{Send}:
20961 @quotation
20963 @example
20964 dump.adb:8:25: warning: unchecked conversion implemented by copy
20965 dump.adb:8:25: warning: use pragma Universal_Aliasing on either type
20966 dump.adb:8:25: warning: to enable RM 13.9(12) implementation permission
20967 @end example
20968 @end quotation
20970 This occurs because the formal parameter @code{S} of @code{Send} is passed by
20971 reference by the compiler and it is not possible to pass a reference to
20972 @code{R} directly in the call without violating strict type-based aliasing.
20973 That’s why the compiler generates a temporary of type @code{Chunk_Of_Bytes}
20974 just before the call and passes a reference to this temporary instead.
20976 As implied by the warning message, it is possible to avoid the temporary
20977 (and the warning) by means of pragma @code{Universal_Aliasing}:
20979 @quotation
20981 @example
20982 type Chunk_Of_Bytes is array (1 .. 64) of Byte;
20983 pragma Universal_Aliasing (Chunk_Of_Bytes);
20984 @end example
20985 @end quotation
20987 The pragma can also be applied to the component type instead:
20989 @quotation
20991 @example
20992 type Byte is mod 2**System.Storage_Unit;
20993 for Byte'Size use System.Storage_Unit;
20994 pragma Universal_Aliasing (Byte);
20995 @end example
20996 @end quotation
20998 and every array type whose component is @code{Byte} will inherit the pragma.
21000 To sum up, the alias analysis performed in strict aliasing mode by the
21001 compiler can have significant benefits. We have seen cases of large scale
21002 application code where the execution time is increased by up to 5% when
21003 these optimizations are turned off. However, if you have code that make
21004 significant use of unchecked conversion, you might want to just stick
21005 with @code{-O1} and avoid the entire issue. If you get adequate
21006 performance at this level of optimization, that’s probably the safest
21007 approach. If tests show that you really need higher levels of
21008 optimization, then you can experiment with @code{-O2} and
21009 @code{-O2 -fno-strict-aliasing} to see how much effect this
21010 has on size and speed of the code. If you really need to use
21011 @code{-O2} with strict aliasing in effect, then you should
21012 review any uses of unchecked conversion, particularly if you are
21013 getting the warnings described above.
21015 @node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
21016 @anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{190}@anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{191}
21017 @subsubsection Aliased Variables and Optimization
21020 @geindex Aliasing
21022 There are scenarios in which programs may
21023 use low level techniques to modify variables
21024 that otherwise might be considered to be unassigned. For example,
21025 a variable can be passed to a procedure by reference, which takes
21026 the address of the parameter and uses the address to modify the
21027 variable’s value, even though it is passed as an IN parameter.
21028 Consider the following example:
21030 @quotation
21032 @example
21033 procedure P is
21034    Max_Length : constant Natural := 16;
21035    type Char_Ptr is access all Character;
21037    procedure Get_String(Buffer: Char_Ptr; Size : Integer);
21038    pragma Import (C, Get_String, "get_string");
21040    Name : aliased String (1 .. Max_Length) := (others => ' ');
21041    Temp : Char_Ptr;
21043    function Addr (S : String) return Char_Ptr is
21044       function To_Char_Ptr is
21045         new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
21046    begin
21047       return To_Char_Ptr (S (S'First)'Address);
21048    end;
21050 begin
21051    Temp := Addr (Name);
21052    Get_String (Temp, Max_Length);
21053 end;
21054 @end example
21055 @end quotation
21057 where Get_String is a C function that uses the address in Temp to
21058 modify the variable @code{Name}. This code is dubious, and arguably
21059 erroneous, and the compiler would be entitled to assume that
21060 @code{Name} is never modified, and generate code accordingly.
21062 However, in practice, this would cause some existing code that
21063 seems to work with no optimization to start failing at high
21064 levels of optimization.
21066 What the compiler does for such cases is to assume that marking
21067 a variable as aliased indicates that some “funny business” may
21068 be going on. The optimizer recognizes the aliased keyword and
21069 inhibits optimizations that assume the value cannot be assigned.
21070 This means that the above example will in fact “work” reliably,
21071 that is, it will produce the expected results.
21073 @node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
21074 @anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{192}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{193}
21075 @subsubsection Atomic Variables and Optimization
21078 @geindex Atomic
21080 There are two considerations with regard to performance when
21081 atomic variables are used.
21083 First, the RM only guarantees that access to atomic variables
21084 be atomic, it has nothing to say about how this is achieved,
21085 though there is a strong implication that this should not be
21086 achieved by explicit locking code. Indeed GNAT will never
21087 generate any locking code for atomic variable access (it will
21088 simply reject any attempt to make a variable or type atomic
21089 if the atomic access cannot be achieved without such locking code).
21091 That being said, it is important to understand that you cannot
21092 assume that the entire variable will always be accessed. Consider
21093 this example:
21095 @quotation
21097 @example
21098 type R is record
21099    A,B,C,D : Character;
21100 end record;
21101 for R'Size use 32;
21102 for R'Alignment use 4;
21104 RV : R;
21105 pragma Atomic (RV);
21106 X : Character;
21108 X := RV.B;
21109 @end example
21110 @end quotation
21112 You cannot assume that the reference to @code{RV.B}
21113 will read the entire 32-bit
21114 variable with a single load instruction. It is perfectly legitimate if
21115 the hardware allows it to do a byte read of just the B field. This read
21116 is still atomic, which is all the RM requires. GNAT can and does take
21117 advantage of this, depending on the architecture and optimization level.
21118 Any assumption to the contrary is non-portable and risky. Even if you
21119 examine the assembly language and see a full 32-bit load, this might
21120 change in a future version of the compiler.
21122 If your application requires that all accesses to @code{RV} in this
21123 example be full 32-bit loads, you need to make a copy for the access
21124 as in:
21126 @quotation
21128 @example
21129 declare
21130    RV_Copy : constant R := RV;
21131 begin
21132    X := RV_Copy.B;
21133 end;
21134 @end example
21135 @end quotation
21137 Now the reference to RV must read the whole variable.
21138 Actually one can imagine some compiler which figures
21139 out that the whole copy is not required (because only
21140 the B field is actually accessed), but GNAT
21141 certainly won’t do that, and we don’t know of any
21142 compiler that would not handle this right, and the
21143 above code will in practice work portably across
21144 all architectures (that permit the Atomic declaration).
21146 The second issue with atomic variables has to do with
21147 the possible requirement of generating synchronization
21148 code. For more details on this, consult the sections on
21149 the pragmas Enable/Disable_Atomic_Synchronization in the
21150 GNAT Reference Manual. If performance is critical, and
21151 such synchronization code is not required, it may be
21152 useful to disable it.
21154 @node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
21155 @anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{194}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{195}
21156 @subsubsection Passive Task Optimization
21159 @geindex Passive Task
21161 A passive task is one which is sufficiently simple that
21162 in theory a compiler could recognize it an implement it
21163 efficiently without creating a new thread. The original design
21164 of Ada 83 had in mind this kind of passive task optimization, but
21165 only a few Ada 83 compilers attempted it. The problem was that
21166 it was difficult to determine the exact conditions under which
21167 the optimization was possible. The result is a very fragile
21168 optimization where a very minor change in the program can
21169 suddenly silently make a task non-optimizable.
21171 With the revisiting of this issue in Ada 95, there was general
21172 agreement that this approach was fundamentally flawed, and the
21173 notion of protected types was introduced. When using protected
21174 types, the restrictions are well defined, and you KNOW that the
21175 operations will be optimized, and furthermore this optimized
21176 performance is fully portable.
21178 Although it would theoretically be possible for GNAT to attempt to
21179 do this optimization, but it really doesn’t make sense in the
21180 context of Ada 95, and none of the Ada 95 compilers implement
21181 this optimization as far as we know. In particular GNAT never
21182 attempts to perform this optimization.
21184 In any new Ada 95 code that is written, you should always
21185 use protected types in place of tasks that might be able to
21186 be optimized in this manner.
21187 Of course this does not help if you have legacy Ada 83 code
21188 that depends on this optimization, but it is unusual to encounter
21189 a case where the performance gains from this optimization
21190 are significant.
21192 Your program should work correctly without this optimization. If
21193 you have performance problems, then the most practical
21194 approach is to figure out exactly where these performance problems
21195 arise, and update those particular tasks to be protected types. Note
21196 that typically clients of the tasks who call entries, will not have
21197 to be modified, only the task definition itself.
21199 @node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
21200 @anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{196}@anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{197}
21201 @subsection @code{Text_IO} Suggestions
21204 @geindex Text_IO and performance
21206 The @code{Ada.Text_IO} package has fairly high overheads due in part to
21207 the requirement of maintaining page and line counts. If performance
21208 is critical, a recommendation is to use @code{Stream_IO} instead of
21209 @code{Text_IO} for volume output, since this package has less overhead.
21211 If @code{Text_IO} must be used, note that by default output to the standard
21212 output and standard error files is unbuffered (this provides better
21213 behavior when output statements are used for debugging, or if the
21214 progress of a program is observed by tracking the output, e.g. by
21215 using the Unix `tail -f' command to watch redirected output).
21217 If you are generating large volumes of output with @code{Text_IO} and
21218 performance is an important factor, use a designated file instead
21219 of the standard output file, or change the standard output file to
21220 be buffered using @code{Interfaces.C_Streams.setvbuf}.
21222 @node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
21223 @anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{198}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{199}
21224 @subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
21227 @geindex Uunused subprogram/data elimination
21229 This section describes how you can eliminate unused subprograms and data from
21230 your executable just by setting options at compilation time.
21232 @menu
21233 * About unused subprogram/data elimination:: 
21234 * Compilation options:: 
21235 * Example of unused subprogram/data elimination:: 
21237 @end menu
21239 @node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
21240 @anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{19a}@anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{19b}
21241 @subsubsection About unused subprogram/data elimination
21244 By default, an executable contains all code and data of its composing objects
21245 (directly linked or coming from statically linked libraries), even data or code
21246 never used by this executable.
21248 This feature will allow you to eliminate such unused code from your
21249 executable, making it smaller (in disk and in memory).
21251 This functionality is available on all Linux platforms except for the IA-64
21252 architecture and on all cross platforms using the ELF binary file format.
21253 In both cases GNU binutils version 2.16 or later are required to enable it.
21255 @node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
21256 @anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{19c}@anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{19d}
21257 @subsubsection Compilation options
21260 The operation of eliminating the unused code and data from the final executable
21261 is directly performed by the linker.
21263 @geindex -ffunction-sections (gcc)
21265 @geindex -fdata-sections (gcc)
21267 In order to do this, it has to work with objects compiled with the
21268 following options:
21269 @code{-ffunction-sections} @code{-fdata-sections}.
21271 These options are usable with C and Ada files.
21272 They will place respectively each
21273 function or data in a separate section in the resulting object file.
21275 Once the objects and static libraries are created with these options, the
21276 linker can perform the dead code elimination. You can do this by setting
21277 the @code{-Wl,--gc-sections} option to gcc command or in the
21278 @code{-largs} section of @code{gnatmake}. This will perform a
21279 garbage collection of code and data never referenced.
21281 If the linker performs a partial link (@code{-r} linker option), then you
21282 will need to provide the entry point using the @code{-e} / @code{--entry}
21283 linker option.
21285 Note that objects compiled without the @code{-ffunction-sections} and
21286 @code{-fdata-sections} options can still be linked with the executable.
21287 However, no dead code elimination will be performed on those objects (they will
21288 be linked as is).
21290 The GNAT static library is now compiled with -ffunction-sections and
21291 -fdata-sections on some platforms. This allows you to eliminate the unused code
21292 and data of the GNAT library from your executable.
21294 @node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
21295 @anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{19e}@anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{19f}
21296 @subsubsection Example of unused subprogram/data elimination
21299 Here is a simple example:
21301 @quotation
21303 @example
21304 with Aux;
21306 procedure Test is
21307 begin
21308    Aux.Used (10);
21309 end Test;
21311 package Aux is
21312    Used_Data   : Integer;
21313    Unused_Data : Integer;
21315    procedure Used   (Data : Integer);
21316    procedure Unused (Data : Integer);
21317 end Aux;
21319 package body Aux is
21320    procedure Used (Data : Integer) is
21321    begin
21322       Used_Data := Data;
21323    end Used;
21325    procedure Unused (Data : Integer) is
21326    begin
21327       Unused_Data := Data;
21328    end Unused;
21329 end Aux;
21330 @end example
21331 @end quotation
21333 @code{Unused} and @code{Unused_Data} are never referenced in this code
21334 excerpt, and hence they may be safely removed from the final executable.
21336 @quotation
21338 @example
21339 $ gnatmake test
21341 $ nm test | grep used
21342 020015f0 T aux__unused
21343 02005d88 B aux__unused_data
21344 020015cc T aux__used
21345 02005d84 B aux__used_data
21347 $ gnatmake test -cargs -fdata-sections -ffunction-sections \\
21348      -largs -Wl,--gc-sections
21350 $ nm test | grep used
21351 02005350 T aux__used
21352 0201ffe0 B aux__used_data
21353 @end example
21354 @end quotation
21356 It can be observed that the procedure @code{Unused} and the object
21357 @code{Unused_Data} are removed by the linker when using the
21358 appropriate options.
21360 @geindex Overflow checks
21362 @geindex Checks (overflow)
21364 @node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
21365 @anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{14c}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{1a0}
21366 @section Overflow Check Handling in GNAT
21369 This section explains how to control the handling of overflow checks.
21371 @menu
21372 * Background:: 
21373 * Management of Overflows in GNAT:: 
21374 * Specifying the Desired Mode:: 
21375 * Default Settings:: 
21376 * Implementation Notes:: 
21378 @end menu
21380 @node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
21381 @anchor{gnat_ugn/gnat_and_program_execution background}@anchor{1a1}@anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{1a2}
21382 @subsection Background
21385 Overflow checks are checks that the compiler may make to ensure
21386 that intermediate results are not out of range. For example:
21388 @quotation
21390 @example
21391 A : Integer;
21393 A := A + 1;
21394 @end example
21395 @end quotation
21397 If @code{A} has the value @code{Integer'Last}, then the addition may cause
21398 overflow since the result is out of range of the type @code{Integer}.
21399 In this case @code{Constraint_Error} will be raised if checks are
21400 enabled.
21402 A trickier situation arises in examples like the following:
21404 @quotation
21406 @example
21407 A, C : Integer;
21409 A := (A + 1) + C;
21410 @end example
21411 @end quotation
21413 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
21414 Now the final result of the expression on the right hand side is
21415 @code{Integer'Last} which is in range, but the question arises whether the
21416 intermediate addition of @code{(A + 1)} raises an overflow error.
21418 The (perhaps surprising) answer is that the Ada language
21419 definition does not answer this question. Instead it leaves
21420 it up to the implementation to do one of two things if overflow
21421 checks are enabled.
21424 @itemize *
21426 @item 
21427 raise an exception (@code{Constraint_Error}), or
21429 @item 
21430 yield the correct mathematical result which is then used in
21431 subsequent operations.
21432 @end itemize
21434 If the compiler chooses the first approach, then the assignment of this
21435 example will indeed raise @code{Constraint_Error} if overflow checking is
21436 enabled, or result in erroneous execution if overflow checks are suppressed.
21438 But if the compiler
21439 chooses the second approach, then it can perform both additions yielding
21440 the correct mathematical result, which is in range, so no exception
21441 will be raised, and the right result is obtained, regardless of whether
21442 overflow checks are suppressed.
21444 Note that in the first example an
21445 exception will be raised in either case, since if the compiler
21446 gives the correct mathematical result for the addition, it will
21447 be out of range of the target type of the assignment, and thus
21448 fails the range check.
21450 This lack of specified behavior in the handling of overflow for
21451 intermediate results is a source of non-portability, and can thus
21452 be problematic when programs are ported. Most typically this arises
21453 in a situation where the original compiler did not raise an exception,
21454 and then the application is moved to a compiler where the check is
21455 performed on the intermediate result and an unexpected exception is
21456 raised.
21458 Furthermore, when using Ada 2012’s preconditions and other
21459 assertion forms, another issue arises. Consider:
21461 @quotation
21463 @example
21464 procedure P (A, B : Integer) with
21465   Pre => A + B <= Integer'Last;
21466 @end example
21467 @end quotation
21469 One often wants to regard arithmetic in a context like this from
21470 a mathematical point of view. So for example, if the two actual parameters
21471 for a call to @code{P} are both @code{Integer'Last}, then
21472 the precondition should be regarded as False. If we are executing
21473 in a mode with run-time checks enabled for preconditions, then we would
21474 like this precondition to fail, rather than raising an exception
21475 because of the intermediate overflow.
21477 However, the language definition leaves the specification of
21478 whether the above condition fails (raising @code{Assert_Error}) or
21479 causes an intermediate overflow (raising @code{Constraint_Error})
21480 up to the implementation.
21482 The situation is worse in a case such as the following:
21484 @quotation
21486 @example
21487 procedure Q (A, B, C : Integer) with
21488   Pre => A + B + C <= Integer'Last;
21489 @end example
21490 @end quotation
21492 Consider the call
21494 @quotation
21496 @example
21497 Q (A => Integer'Last, B => 1, C => -1);
21498 @end example
21499 @end quotation
21501 From a mathematical point of view the precondition
21502 is True, but at run time we may (but are not guaranteed to) get an
21503 exception raised because of the intermediate overflow (and we really
21504 would prefer this precondition to be considered True at run time).
21506 @node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
21507 @anchor{gnat_ugn/gnat_and_program_execution id47}@anchor{1a3}@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{1a4}
21508 @subsection Management of Overflows in GNAT
21511 To deal with the portability issue, and with the problem of
21512 mathematical versus run-time interpretation of the expressions in
21513 assertions, GNAT provides comprehensive control over the handling
21514 of intermediate overflow. GNAT can operate in three modes, and
21515 furthermore, permits separate selection of operating modes for
21516 the expressions within assertions (here the term ‘assertions’
21517 is used in the technical sense, which includes preconditions and so forth)
21518 and for expressions appearing outside assertions.
21520 The three modes are:
21523 @itemize *
21525 @item 
21526 `Use base type for intermediate operations' (@code{STRICT})
21528 In this mode, all intermediate results for predefined arithmetic
21529 operators are computed using the base type, and the result must
21530 be in range of the base type. If this is not the
21531 case then either an exception is raised (if overflow checks are
21532 enabled) or the execution is erroneous (if overflow checks are suppressed).
21533 This is the normal default mode.
21535 @item 
21536 `Most intermediate overflows avoided' (@code{MINIMIZED})
21538 In this mode, the compiler attempts to avoid intermediate overflows by
21539 using a larger integer type, typically @code{Long_Long_Integer},
21540 as the type in which arithmetic is
21541 performed for predefined arithmetic operators. This may be slightly more
21542 expensive at
21543 run time (compared to suppressing intermediate overflow checks), though
21544 the cost is negligible on modern 64-bit machines. For the examples given
21545 earlier, no intermediate overflows would have resulted in exceptions,
21546 since the intermediate results are all in the range of
21547 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
21548 of GNAT). In addition, if checks are enabled, this reduces the number of
21549 checks that must be made, so this choice may actually result in an
21550 improvement in space and time behavior.
21552 However, there are cases where @code{Long_Long_Integer} is not large
21553 enough, consider the following example:
21555 @quotation
21557 @example
21558 procedure R (A, B, C, D : Integer) with
21559   Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
21560 @end example
21561 @end quotation
21563 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
21564 Now the intermediate results are
21565 out of the range of @code{Long_Long_Integer} even though the final result
21566 is in range and the precondition is True (from a mathematical point
21567 of view). In such a case, operating in this mode, an overflow occurs
21568 for the intermediate computation (which is why this mode
21569 says `most' intermediate overflows are avoided). In this case,
21570 an exception is raised if overflow checks are enabled, and the
21571 execution is erroneous if overflow checks are suppressed.
21573 @item 
21574 `All intermediate overflows avoided' (@code{ELIMINATED})
21576 In this mode, the compiler  avoids all intermediate overflows
21577 by using arbitrary precision arithmetic as required. In this
21578 mode, the above example with @code{A**2 * B**2} would
21579 not cause intermediate overflow, because the intermediate result
21580 would be evaluated using sufficient precision, and the result
21581 of evaluating the precondition would be True.
21583 This mode has the advantage of avoiding any intermediate
21584 overflows, but at the expense of significant run-time overhead,
21585 including the use of a library (included automatically in this
21586 mode) for multiple-precision arithmetic.
21588 This mode provides cleaner semantics for assertions, since now
21589 the run-time behavior emulates true arithmetic behavior for the
21590 predefined arithmetic operators, meaning that there is never a
21591 conflict between the mathematical view of the assertion, and its
21592 run-time behavior.
21594 Note that in this mode, the behavior is unaffected by whether or
21595 not overflow checks are suppressed, since overflow does not occur.
21596 It is possible for gigantic intermediate expressions to raise
21597 @code{Storage_Error} as a result of attempting to compute the
21598 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
21599 but overflow is impossible.
21600 @end itemize
21602 Note that these modes apply only to the evaluation of predefined
21603 arithmetic, membership, and comparison operators for signed integer
21604 arithmetic.
21606 For fixed-point arithmetic, checks can be suppressed. But if checks
21607 are enabled
21608 then fixed-point values are always checked for overflow against the
21609 base type for intermediate expressions (that is such checks always
21610 operate in the equivalent of @code{STRICT} mode).
21612 For floating-point, on nearly all architectures, @code{Machine_Overflows}
21613 is False, and IEEE infinities are generated, so overflow exceptions
21614 are never raised. If you want to avoid infinities, and check that
21615 final results of expressions are in range, then you can declare a
21616 constrained floating-point type, and range checks will be carried
21617 out in the normal manner (with infinite values always failing all
21618 range checks).
21620 @node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
21621 @anchor{gnat_ugn/gnat_and_program_execution id48}@anchor{1a5}@anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{eb}
21622 @subsection Specifying the Desired Mode
21625 @geindex pragma Overflow_Mode
21627 The desired mode of for handling intermediate overflow can be specified using
21628 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
21629 The pragma has the form
21631 @quotation
21633 @example
21634 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
21635 @end example
21636 @end quotation
21638 where @code{MODE} is one of
21641 @itemize *
21643 @item 
21644 @code{STRICT}:  intermediate overflows checked (using base type)
21646 @item 
21647 @code{MINIMIZED}: minimize intermediate overflows
21649 @item 
21650 @code{ELIMINATED}: eliminate intermediate overflows
21651 @end itemize
21653 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
21654 @code{minimized} all have the same effect.
21656 If only the @code{General} parameter is present, then the given @code{MODE} applies
21657 to expressions both within and outside assertions. If both arguments
21658 are present, then @code{General} applies to expressions outside assertions,
21659 and @code{Assertions} applies to expressions within assertions. For example:
21661 @quotation
21663 @example
21664 pragma Overflow_Mode
21665   (General => Minimized, Assertions => Eliminated);
21666 @end example
21667 @end quotation
21669 specifies that general expressions outside assertions be evaluated
21670 in ‘minimize intermediate overflows’ mode, and expressions within
21671 assertions be evaluated in ‘eliminate intermediate overflows’ mode.
21672 This is often a reasonable choice, avoiding excessive overhead
21673 outside assertions, but assuring a high degree of portability
21674 when importing code from another compiler, while incurring
21675 the extra overhead for assertion expressions to ensure that
21676 the behavior at run time matches the expected mathematical
21677 behavior.
21679 The @code{Overflow_Mode} pragma has the same scoping and placement
21680 rules as pragma @code{Suppress}, so it can occur either as a
21681 configuration pragma, specifying a default for the whole
21682 program, or in a declarative scope, where it applies to the
21683 remaining declarations and statements in that scope.
21685 Note that pragma @code{Overflow_Mode} does not affect whether
21686 overflow checks are enabled or suppressed. It only controls the
21687 method used to compute intermediate values. To control whether
21688 overflow checking is enabled or suppressed, use pragma @code{Suppress}
21689 or @code{Unsuppress} in the usual manner.
21691 @geindex -gnato? (gcc)
21693 @geindex -gnato?? (gcc)
21695 Additionally, a compiler switch @code{-gnato?} or @code{-gnato??}
21696 can be used to control the checking mode default (which can be subsequently
21697 overridden using pragmas).
21699 Here @code{?} is one of the digits @code{1} through @code{3}:
21701 @quotation
21704 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
21705 @item
21707 @code{1}
21709 @tab
21711 use base type for intermediate operations (@code{STRICT})
21713 @item
21715 @code{2}
21717 @tab
21719 minimize intermediate overflows (@code{MINIMIZED})
21721 @item
21723 @code{3}
21725 @tab
21727 eliminate intermediate overflows (@code{ELIMINATED})
21729 @end multitable
21731 @end quotation
21733 As with the pragma, if only one digit appears then it applies to all
21734 cases; if two digits are given, then the first applies outside
21735 assertions, and the second within assertions. Thus the equivalent
21736 of the example pragma above would be
21737 @code{-gnato23}.
21739 If no digits follow the @code{-gnato}, then it is equivalent to
21740 @code{-gnato11},
21741 causing all intermediate operations to be computed using the base
21742 type (@code{STRICT} mode).
21744 @node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
21745 @anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{1a6}@anchor{gnat_ugn/gnat_and_program_execution id49}@anchor{1a7}
21746 @subsection Default Settings
21749 The default mode for overflow checks is
21751 @quotation
21753 @example
21754 General => Strict
21755 @end example
21756 @end quotation
21758 which causes all computations both inside and outside assertions to use the
21759 base type, and is equivalent to @code{-gnato} (with no digits following).
21761 The pragma @code{Suppress (Overflow_Check)} disables overflow
21762 checking, but it has no effect on the method used for computing
21763 intermediate results.
21765 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
21766 checking, but it has no effect on the method used for computing
21767 intermediate results.
21769 @node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
21770 @anchor{gnat_ugn/gnat_and_program_execution id50}@anchor{1a8}@anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{1a9}
21771 @subsection Implementation Notes
21774 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
21775 reasonably efficient, and can be generally used. It also helps
21776 to ensure compatibility with code imported from some other
21777 compiler to GNAT.
21779 Setting all intermediate overflows checking (@code{STRICT} mode)
21780 makes sense if you want to
21781 make sure that your code is compatible with any other possible
21782 Ada implementation. This may be useful in ensuring portability
21783 for code that is to be exported to some other compiler than GNAT.
21785 The Ada standard allows the reassociation of expressions at
21786 the same precedence level if no parentheses are present. For
21787 example, @code{A+B+C} parses as though it were @code{(A+B)+C}, but
21788 the compiler can reintepret this as @code{A+(B+C)}, possibly
21789 introducing or eliminating an overflow exception. The GNAT
21790 compiler never takes advantage of this freedom, and the
21791 expression @code{A+B+C} will be evaluated as @code{(A+B)+C}.
21792 If you need the other order, you can write the parentheses
21793 explicitly @code{A+(B+C)} and GNAT will respect this order.
21795 The use of @code{ELIMINATED} mode will cause the compiler to
21796 automatically include an appropriate arbitrary precision
21797 integer arithmetic package. The compiler will make calls
21798 to this package, though only in cases where it cannot be
21799 sure that @code{Long_Long_Integer} is sufficient to guard against
21800 intermediate overflows. This package does not use dynamic
21801 allocation, but it does use the secondary stack, so an
21802 appropriate secondary stack package must be present (this
21803 is always true for standard full Ada, but may require
21804 specific steps for restricted run times such as ZFP).
21806 Although @code{ELIMINATED} mode causes expressions to use arbitrary
21807 precision arithmetic, avoiding overflow, the final result
21808 must be in an appropriate range. This is true even if the
21809 final result is of type @code{[Long_[Long_]]Integer'Base}, which
21810 still has the same bounds as its associated constrained
21811 type at run-time.
21813 Currently, the @code{ELIMINATED} mode is only available on target
21814 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
21815 platforms).
21817 @node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
21818 @anchor{gnat_ugn/gnat_and_program_execution id51}@anchor{14d}@anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{1aa}
21819 @section Performing Dimensionality Analysis in GNAT
21822 @geindex Dimensionality analysis
21824 The GNAT compiler supports dimensionality checking. The user can
21825 specify physical units for objects, and the compiler will verify that uses
21826 of these objects are compatible with their dimensions, in a fashion that is
21827 familiar to engineering practice. The dimensions of algebraic expressions
21828 (including powers with static exponents) are computed from their constituents.
21830 @geindex Dimension_System aspect
21832 @geindex Dimension aspect
21834 This feature depends on Ada 2012 aspect specifications, and is available from
21835 version 7.0.1 of GNAT onwards.
21836 The GNAT-specific aspect @code{Dimension_System}
21837 allows you to define a system of units; the aspect @code{Dimension}
21838 then allows the user to declare dimensioned quantities within a given system.
21839 (These aspects are described in the `Implementation Defined Aspects'
21840 chapter of the `GNAT Reference Manual').
21842 The major advantage of this model is that it does not require the declaration of
21843 multiple operators for all possible combinations of types: it is only necessary
21844 to use the proper subtypes in object declarations.
21846 @geindex System.Dim.Mks package (GNAT library)
21848 @geindex MKS_Type type
21850 The simplest way to impose dimensionality checking on a computation is to make
21851 use of one of the instantiations of the package @code{System.Dim.Generic_Mks}, which
21852 are part of the GNAT library. This generic package defines a floating-point
21853 type @code{MKS_Type}, for which a sequence of dimension names are specified,
21854 together with their conventional abbreviations.  The following should be read
21855 together with the full specification of the package, in file
21856 @code{s-digemk.ads}.
21858 @quotation
21860 @geindex s-digemk.ads file
21862 @example
21863 type Mks_Type is new Float_Type
21864   with
21865    Dimension_System => (
21866      (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
21867      (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
21868      (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
21869      (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
21870      (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
21871      (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
21872      (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
21873 @end example
21874 @end quotation
21876 The package then defines a series of subtypes that correspond to these
21877 conventional units. For example:
21879 @quotation
21881 @example
21882 subtype Length is Mks_Type
21883   with
21884    Dimension => (Symbol => 'm', Meter  => 1, others => 0);
21885 @end example
21886 @end quotation
21888 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
21889 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
21890 @code{Luminous_Intensity} (the standard set of units of the SI system).
21892 The package also defines conventional names for values of each unit, for
21893 example:
21895 @quotation
21897 @example
21898 m   : constant Length           := 1.0;
21899 kg  : constant Mass             := 1.0;
21900 s   : constant Time             := 1.0;
21901 A   : constant Electric_Current := 1.0;
21902 @end example
21903 @end quotation
21905 as well as useful multiples of these units:
21907 @quotation
21909 @example
21910  cm  : constant Length := 1.0E-02;
21911  g   : constant Mass   := 1.0E-03;
21912  min : constant Time   := 60.0;
21913  day : constant Time   := 60.0 * 24.0 * min;
21915 @end example
21916 @end quotation
21918 There are three instantiations of @code{System.Dim.Generic_Mks} defined in the
21919 GNAT library:
21922 @itemize *
21924 @item 
21925 @code{System.Dim.Float_Mks} based on @code{Float} defined in @code{s-diflmk.ads}.
21927 @item 
21928 @code{System.Dim.Long_Mks} based on @code{Long_Float} defined in @code{s-dilomk.ads}.
21930 @item 
21931 @code{System.Dim.Mks} based on @code{Long_Long_Float} defined in @code{s-dimmks.ads}.
21932 @end itemize
21934 Using one of these packages, you can then define a derived unit by providing
21935 the aspect that specifies its dimensions within the MKS system, as well as the
21936 string to be used for output of a value of that unit:
21938 @quotation
21940 @example
21941 subtype Acceleration is Mks_Type
21942   with Dimension => ("m/sec^2",
21943                      Meter => 1,
21944                      Second => -2,
21945                      others => 0);
21946 @end example
21947 @end quotation
21949 Here is a complete example of use:
21951 @quotation
21953 @example
21954 with System.Dim.MKS; use System.Dim.Mks;
21955 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
21956 with Text_IO; use Text_IO;
21957 procedure Free_Fall is
21958   subtype Acceleration is Mks_Type
21959     with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
21960   G : constant acceleration := 9.81 * m / (s ** 2);
21961   T : Time := 10.0*s;
21962   Distance : Length;
21964 begin
21965   Put ("Gravitational constant: ");
21966   Put (G, Aft => 2, Exp => 0); Put_Line ("");
21967   Distance := 0.5 * G * T ** 2;
21968   Put ("distance travelled in 10 seconds of free fall ");
21969   Put (Distance, Aft => 2, Exp => 0);
21970   Put_Line ("");
21971 end Free_Fall;
21972 @end example
21973 @end quotation
21975 Execution of this program yields:
21977 @quotation
21979 @example
21980 Gravitational constant:  9.81 m/sec^2
21981 distance travelled in 10 seconds of free fall 490.50 m
21982 @end example
21983 @end quotation
21985 However, incorrect assignments such as:
21987 @quotation
21989 @example
21990 Distance := 5.0;
21991 Distance := 5.0 * kg;
21992 @end example
21993 @end quotation
21995 are rejected with the following diagnoses:
21997 @quotation
21999 @example
22000 Distance := 5.0;
22001    >>> dimensions mismatch in assignment
22002    >>> left-hand side has dimension [L]
22003    >>> right-hand side is dimensionless
22005 Distance := 5.0 * kg:
22006    >>> dimensions mismatch in assignment
22007    >>> left-hand side has dimension [L]
22008    >>> right-hand side has dimension [M]
22009 @end example
22010 @end quotation
22012 The dimensions of an expression are properly displayed, even if there is
22013 no explicit subtype for it. If we add to the program:
22015 @quotation
22017 @example
22018 Put ("Final velocity: ");
22019 Put (G * T, Aft =>2, Exp =>0);
22020 Put_Line ("");
22021 @end example
22022 @end quotation
22024 then the output includes:
22026 @quotation
22028 @example
22029 Final velocity: 98.10 m.s**(-1)
22030 @end example
22032 @geindex Dimensionable type
22034 @geindex Dimensioned subtype
22035 @end quotation
22037 The type @code{Mks_Type} is said to be a `dimensionable type' since it has a
22038 @code{Dimension_System} aspect, and the subtypes @code{Length}, @code{Mass}, etc.,
22039 are said to be `dimensioned subtypes' since each one has a @code{Dimension}
22040 aspect.
22042 @quotation
22044 @geindex Dimension Vector (for a dimensioned subtype)
22046 @geindex Dimension aspect
22048 @geindex Dimension_System aspect
22049 @end quotation
22051 The @code{Dimension} aspect of a dimensioned subtype @code{S} defines a mapping
22052 from the base type’s Unit_Names to integer (or, more generally, rational)
22053 values. This mapping is the `dimension vector' (also referred to as the
22054 `dimensionality') for that subtype, denoted by @code{DV(S)}, and thus for each
22055 object of that subtype. Intuitively, the value specified for each
22056 @code{Unit_Name} is the exponent associated with that unit; a zero value
22057 means that the unit is not used. For example:
22059 @quotation
22061 @example
22062 declare
22063    Acc : Acceleration;
22064    ...
22065 begin
22066    ...
22067 end;
22068 @end example
22069 @end quotation
22071 Here @code{DV(Acc)} = @code{DV(Acceleration)} =
22072 @code{(Meter=>1, Kilogram=>0, Second=>-2, Ampere=>0, Kelvin=>0, Mole=>0, Candela=>0)}.
22073 Symbolically, we can express this as @code{Meter / Second**2}.
22075 The dimension vector of an arithmetic expression is synthesized from the
22076 dimension vectors of its components, with compile-time dimensionality checks
22077 that help prevent mismatches such as using an @code{Acceleration} where a
22078 @code{Length} is required.
22080 The dimension vector of the result of an arithmetic expression `expr', or
22081 @code{DV(@var{expr})}, is defined as follows, assuming conventional
22082 mathematical definitions for the vector operations that are used:
22085 @itemize *
22087 @item 
22088 If `expr' is of the type `universal_real', or is not of a dimensioned subtype,
22089 then `expr' is dimensionless; @code{DV(@var{expr})} is the empty vector.
22091 @item 
22092 @code{DV(@var{op expr})}, where `op' is a unary operator, is @code{DV(@var{expr})}
22094 @item 
22095 @code{DV(@var{expr1 op expr2})} where `op' is “+” or “-” is @code{DV(@var{expr1})}
22096 provided that @code{DV(@var{expr1})} = @code{DV(@var{expr2})}.
22097 If this condition is not met then the construct is illegal.
22099 @item 
22100 @code{DV(@var{expr1} * @var{expr2})} is @code{DV(@var{expr1})} + @code{DV(@var{expr2})},
22101 and @code{DV(@var{expr1} / @var{expr2})} = @code{DV(@var{expr1})} - @code{DV(@var{expr2})}.
22102 In this context if one of the `expr's is dimensionless then its empty
22103 dimension vector is treated as @code{(others => 0)}.
22105 @item 
22106 @code{DV(@var{expr} ** @var{power})} is `power' * @code{DV(@var{expr})},
22107 provided that `power' is a static rational value. If this condition is not
22108 met then the construct is illegal.
22109 @end itemize
22111 Note that, by the above rules, it is illegal to use binary “+” or “-” to
22112 combine a dimensioned and dimensionless value.  Thus an expression such as
22113 @code{acc-10.0} is illegal, where @code{acc} is an object of subtype
22114 @code{Acceleration}.
22116 The dimensionality checks for relationals use the same rules as
22117 for “+” and “-”, except when comparing to a literal; thus
22119 @quotation
22121 @example
22122 acc > len
22123 @end example
22124 @end quotation
22126 is equivalent to
22128 @quotation
22130 @example
22131 acc-len > 0.0
22132 @end example
22133 @end quotation
22135 and is thus illegal, but
22137 @quotation
22139 @example
22140 acc > 10.0
22141 @end example
22142 @end quotation
22144 is accepted with a warning. Analogously a conditional expression requires the
22145 same dimension vector for each branch (with no exception for literals).
22147 The dimension vector of a type conversion @code{T(@var{expr})} is defined
22148 as follows, based on the nature of @code{T}:
22151 @itemize *
22153 @item 
22154 If @code{T} is a dimensioned subtype then @code{DV(T(@var{expr}))} is @code{DV(T)}
22155 provided that either `expr' is dimensionless or
22156 @code{DV(T)} = @code{DV(@var{expr})}. The conversion is illegal
22157 if `expr' is dimensioned and @code{DV(@var{expr})} /= @code{DV(T)}.
22158 Note that vector equality does not require that the corresponding
22159 Unit_Names be the same.
22161 As a consequence of the above rule, it is possible to convert between
22162 different dimension systems that follow the same international system
22163 of units, with the seven physical components given in the standard order
22164 (length, mass, time, etc.). Thus a length in meters can be converted to
22165 a length in inches (with a suitable conversion factor) but cannot be
22166 converted, for example, to a mass in pounds.
22168 @item 
22169 If @code{T} is the base type for `expr' (and the dimensionless root type of
22170 the dimension system), then @code{DV(T(@var{expr}))} is @code{DV(expr)}.
22171 Thus, if `expr' is of a dimensioned subtype of @code{T}, the conversion may
22172 be regarded as a “view conversion” that preserves dimensionality.
22174 This rule makes it possible to write generic code that can be instantiated
22175 with compatible dimensioned subtypes.  The generic unit will contain
22176 conversions that will consequently be present in instantiations, but
22177 conversions to the base type will preserve dimensionality and make it
22178 possible to write generic code that is correct with respect to
22179 dimensionality.
22181 @item 
22182 Otherwise (i.e., @code{T} is neither a dimensioned subtype nor a dimensionable
22183 base type), @code{DV(T(@var{expr}))} is the empty vector. Thus a dimensioned
22184 value can be explicitly converted to a non-dimensioned subtype, which
22185 of course then escapes dimensionality analysis.
22186 @end itemize
22188 The dimension vector for a type qualification @code{T'(@var{expr})} is the same
22189 as for the type conversion @code{T(@var{expr})}.
22191 An assignment statement
22193 @quotation
22195 @example
22196 Source := Target;
22197 @end example
22198 @end quotation
22200 requires @code{DV(Source)} = @code{DV(Target)}, and analogously for parameter
22201 passing (the dimension vector for the actual parameter must be equal to the
22202 dimension vector for the formal parameter).
22204 When using dimensioned types with elementary functions it is necessary to
22205 instantiate the @code{Ada.Numerics.Generic_Elementary_Functions} package using
22206 the @code{Mks_Type} and not any of the derived subtypes such as @code{Distance}.
22207 For functions such as @code{Sqrt} the dimensional analysis will fail when using
22208 the subtypes because both the parameter and return are of the same type.
22210 An example instantiation
22212 @quotation
22214 @example
22215 package Mks_Numerics is new
22216    Ada.Numerics.Generic_Elementary_Functions (System.Dim.Mks.Mks_Type);
22217 @end example
22218 @end quotation
22220 @node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
22221 @anchor{gnat_ugn/gnat_and_program_execution id52}@anchor{14e}@anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{1ab}
22222 @section Stack Related Facilities
22225 This section describes some useful tools associated with stack
22226 checking and analysis. In
22227 particular, it deals with dynamic and static stack usage measurements.
22229 @menu
22230 * Stack Overflow Checking:: 
22231 * Static Stack Usage Analysis:: 
22232 * Dynamic Stack Usage Analysis:: 
22234 @end menu
22236 @node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
22237 @anchor{gnat_ugn/gnat_and_program_execution id53}@anchor{1ac}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{e7}
22238 @subsection Stack Overflow Checking
22241 @geindex Stack Overflow Checking
22243 @geindex -fstack-check (gcc)
22245 For most operating systems, @code{gcc} does not perform stack overflow
22246 checking by default. This means that if the main environment task or
22247 some other task exceeds the available stack space, then unpredictable
22248 behavior will occur. Most native systems offer some level of protection by
22249 adding a guard page at the end of each task stack. This mechanism is usually
22250 not enough for dealing properly with stack overflow situations because
22251 a large local variable could “jump” above the guard page.
22252 Furthermore, when the
22253 guard page is hit, there may not be any space left on the stack for executing
22254 the exception propagation code. Enabling stack checking avoids
22255 such situations.
22257 To activate stack checking, compile all units with the @code{gcc} option
22258 @code{-fstack-check}. For example:
22260 @quotation
22262 @example
22263 $ gcc -c -fstack-check package1.adb
22264 @end example
22265 @end quotation
22267 Units compiled with this option will generate extra instructions to check
22268 that any use of the stack (for procedure calls or for declaring local
22269 variables in declare blocks) does not exceed the available stack space.
22270 If the space is exceeded, then a @code{Storage_Error} exception is raised.
22272 For declared tasks, the default stack size is defined by the GNAT runtime,
22273 whose size may be modified at bind time through the @code{-d} bind switch
22274 (@ref{113,,Switches for gnatbind}). Task specific stack sizes may be set using the
22275 @code{Storage_Size} pragma.
22277 For the environment task, the stack size is determined by the operating system.
22278 Consequently, to modify the size of the environment task please refer to your
22279 operating system documentation.
22281 @node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
22282 @anchor{gnat_ugn/gnat_and_program_execution id54}@anchor{1ad}@anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{e8}
22283 @subsection Static Stack Usage Analysis
22286 @geindex Static Stack Usage Analysis
22288 @geindex -fstack-usage
22290 A unit compiled with @code{-fstack-usage} will generate an extra file
22291 that specifies
22292 the maximum amount of stack used, on a per-function basis.
22293 The file has the same
22294 basename as the target object file with a @code{.su} extension.
22295 Each line of this file is made up of three fields:
22298 @itemize *
22300 @item 
22301 The name of the function.
22303 @item 
22304 A number of bytes.
22306 @item 
22307 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
22308 @end itemize
22310 The second field corresponds to the size of the known part of the function
22311 frame.
22313 The qualifier @code{static} means that the function frame size
22314 is purely static.
22315 It usually means that all local variables have a static size.
22316 In this case, the second field is a reliable measure of the function stack
22317 utilization.
22319 The qualifier @code{dynamic} means that the function frame size is not static.
22320 It happens mainly when some local variables have a dynamic size. When this
22321 qualifier appears alone, the second field is not a reliable measure
22322 of the function stack analysis. When it is qualified with  @code{bounded}, it
22323 means that the second field is a reliable maximum of the function stack
22324 utilization.
22326 A unit compiled with @code{-Wstack-usage} will issue a warning for each
22327 subprogram whose stack usage might be larger than the specified amount of
22328 bytes.  The wording is in keeping with the qualifier documented above.
22330 @node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
22331 @anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{116}@anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{1ae}
22332 @subsection Dynamic Stack Usage Analysis
22335 It is possible to measure the maximum amount of stack used by a task, by
22336 adding a switch to @code{gnatbind}, as:
22338 @quotation
22340 @example
22341 $ gnatbind -u0 file
22342 @end example
22343 @end quotation
22345 With this option, at each task termination, its stack usage is output on
22346 @code{stderr}.
22347 Note that this switch is not compatible with tools like
22348 Valgrind and DrMemory; they will report errors.
22350 It is not always convenient to output the stack usage when the program
22351 is still running. Hence, it is possible to delay this output until program
22352 termination. for a given number of tasks specified as the argument of the
22353 @code{-u} option. For instance:
22355 @quotation
22357 @example
22358 $ gnatbind -u100 file
22359 @end example
22360 @end quotation
22362 will buffer the stack usage information of the first 100 tasks to terminate and
22363 output this info at program termination. Results are displayed in four
22364 columns:
22366 @quotation
22368 @example
22369 Index | Task Name | Stack Size | Stack Usage
22370 @end example
22371 @end quotation
22373 where:
22376 @itemize *
22378 @item 
22379 `Index' is a number associated with each task.
22381 @item 
22382 `Task Name' is the name of the task analyzed.
22384 @item 
22385 `Stack Size' is the maximum size for the stack.
22387 @item 
22388 `Stack Usage' is the measure done by the stack analyzer.
22389 In order to prevent overflow, the stack
22390 is not entirely analyzed, and it’s not possible to know exactly how
22391 much has actually been used.
22392 @end itemize
22394 By default the environment task stack, the stack that contains the main unit,
22395 is not processed. To enable processing of the environment task stack, the
22396 environment variable GNAT_STACK_LIMIT needs to be set to the maximum size of
22397 the environment task stack. This amount is given in kilobytes. For example:
22399 @quotation
22401 @example
22402 $ set GNAT_STACK_LIMIT 1600
22403 @end example
22404 @end quotation
22406 would specify to the analyzer that the environment task stack has a limit
22407 of 1.6 megabytes. Any stack usage beyond this will be ignored by the analysis.
22409 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
22410 stack-usage reports at run time. See its body for the details.
22412 @node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
22413 @anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{14f}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{1af}
22414 @section Memory Management Issues
22417 This section describes some useful memory pools provided in the GNAT library
22418 and in particular the GNAT Debug Pool facility, which can be used to detect
22419 incorrect uses of access values (including ‘dangling references’).
22422 @menu
22423 * Some Useful Memory Pools:: 
22424 * The GNAT Debug Pool Facility:: 
22426 @end menu
22428 @node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
22429 @anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{1b0}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{1b1}
22430 @subsection Some Useful Memory Pools
22433 @geindex Memory Pool
22435 @geindex storage
22436 @geindex pool
22438 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
22439 storage pool. Allocations use the standard system call @code{malloc} while
22440 deallocations use the standard system call @code{free}. No reclamation is
22441 performed when the pool goes out of scope. For performance reasons, the
22442 standard default Ada allocators/deallocators do not use any explicit storage
22443 pools but if they did, they could use this storage pool without any change in
22444 behavior. That is why this storage pool is used  when the user
22445 manages to make the default implicit allocator explicit as in this example:
22447 @quotation
22449 @example
22450 type T1 is access Something;
22451  -- no Storage pool is defined for T2
22453 type T2 is access Something_Else;
22454 for T2'Storage_Pool use T1'Storage_Pool;
22455 -- the above is equivalent to
22456 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
22457 @end example
22458 @end quotation
22460 The @code{System.Pool_Local} package offers the @code{Unbounded_Reclaim_Pool} storage
22461 pool. The allocation strategy is similar to @code{Pool_Local}
22462 except that the all
22463 storage allocated with this pool is reclaimed when the pool object goes out of
22464 scope. This pool provides a explicit mechanism similar to the implicit one
22465 provided by several Ada 83 compilers for allocations performed through a local
22466 access type and whose purpose was to reclaim memory when exiting the
22467 scope of a given local access. As an example, the following program does not
22468 leak memory even though it does not perform explicit deallocation:
22470 @quotation
22472 @example
22473 with System.Pool_Local;
22474 procedure Pooloc1 is
22475    procedure Internal is
22476       type A is access Integer;
22477       X : System.Pool_Local.Unbounded_Reclaim_Pool;
22478       for A'Storage_Pool use X;
22479       v : A;
22480    begin
22481       for I in 1 .. 50 loop
22482          v := new Integer;
22483       end loop;
22484    end Internal;
22485 begin
22486    for I in 1 .. 100 loop
22487       Internal;
22488    end loop;
22489 end Pooloc1;
22490 @end example
22491 @end quotation
22493 The @code{System.Pool_Size} package implements the @code{Stack_Bounded_Pool} used when
22494 @code{Storage_Size} is specified for an access type.
22495 The whole storage for the pool is
22496 allocated at once, usually on the stack at the point where the access type is
22497 elaborated. It is automatically reclaimed when exiting the scope where the
22498 access type is defined. This package is not intended to be used directly by the
22499 user and it is implicitly used for each such declaration:
22501 @quotation
22503 @example
22504 type T1 is access Something;
22505 for T1'Storage_Size use 10_000;
22506 @end example
22507 @end quotation
22509 @node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
22510 @anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{1b2}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{1b3}
22511 @subsection The GNAT Debug Pool Facility
22514 @geindex Debug Pool
22516 @geindex storage
22517 @geindex pool
22518 @geindex memory corruption
22520 The use of unchecked deallocation and unchecked conversion can easily
22521 lead to incorrect memory references. The problems generated by such
22522 references are usually difficult to tackle because the symptoms can be
22523 very remote from the origin of the problem. In such cases, it is
22524 very helpful to detect the problem as early as possible. This is the
22525 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
22527 In order to use the GNAT specific debugging pool, the user must
22528 associate a debug pool object with each of the access types that may be
22529 related to suspected memory problems. See Ada Reference Manual 13.11.
22531 @quotation
22533 @example
22534 type Ptr is access Some_Type;
22535 Pool : GNAT.Debug_Pools.Debug_Pool;
22536 for Ptr'Storage_Pool use Pool;
22537 @end example
22538 @end quotation
22540 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
22541 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
22542 allow the user to redefine allocation and deallocation strategies. They
22543 also provide a checkpoint for each dereference, through the use of
22544 the primitive operation @code{Dereference} which is implicitly called at
22545 each dereference of an access value.
22547 Once an access type has been associated with a debug pool, operations on
22548 values of the type may raise four distinct exceptions,
22549 which correspond to four potential kinds of memory corruption:
22552 @itemize *
22554 @item 
22555 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
22557 @item 
22558 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
22560 @item 
22561 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
22563 @item 
22564 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
22565 @end itemize
22567 For types associated with a Debug_Pool, dynamic allocation is performed using
22568 the standard GNAT allocation routine. References to all allocated chunks of
22569 memory are kept in an internal dictionary. Several deallocation strategies are
22570 provided, whereupon the user can choose to release the memory to the system,
22571 keep it allocated for further invalid access checks, or fill it with an easily
22572 recognizable pattern for debug sessions. The memory pattern is the old IBM
22573 hexadecimal convention: @code{16#DEADBEEF#}.
22575 See the documentation in the file g-debpoo.ads for more information on the
22576 various strategies.
22578 Upon each dereference, a check is made that the access value denotes a
22579 properly allocated memory location. Here is a complete example of use of
22580 @code{Debug_Pools}, that includes typical instances of  memory corruption:
22582 @quotation
22584 @example
22585 with GNAT.IO; use GNAT.IO;
22586 with Ada.Unchecked_Deallocation;
22587 with Ada.Unchecked_Conversion;
22588 with GNAT.Debug_Pools;
22589 with System.Storage_Elements;
22590 with Ada.Exceptions; use Ada.Exceptions;
22591 procedure Debug_Pool_Test is
22593    type T is access Integer;
22594    type U is access all T;
22596    P : GNAT.Debug_Pools.Debug_Pool;
22597    for T'Storage_Pool use P;
22599    procedure Free is new Ada.Unchecked_Deallocation (Integer, T);
22600    function UC is new Ada.Unchecked_Conversion (U, T);
22601    A, B : aliased T;
22603    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
22605 begin
22606    Info (P);
22607    A := new Integer;
22608    B := new Integer;
22609    B := A;
22610    Info (P);
22611    Free (A);
22612    begin
22613       Put_Line (Integer'Image(B.all));
22614    exception
22615       when E : others => Put_Line ("raised: " & Exception_Name (E));
22616    end;
22617    begin
22618       Free (B);
22619    exception
22620       when E : others => Put_Line ("raised: " & Exception_Name (E));
22621    end;
22622    B := UC(A'Access);
22623    begin
22624       Put_Line (Integer'Image(B.all));
22625    exception
22626       when E : others => Put_Line ("raised: " & Exception_Name (E));
22627    end;
22628    begin
22629       Free (B);
22630    exception
22631       when E : others => Put_Line ("raised: " & Exception_Name (E));
22632    end;
22633    Info (P);
22634 end Debug_Pool_Test;
22635 @end example
22636 @end quotation
22638 The debug pool mechanism provides the following precise diagnostics on the
22639 execution of this erroneous program:
22641 @quotation
22643 @example
22644 Debug Pool info:
22645   Total allocated bytes :  0
22646   Total deallocated bytes :  0
22647   Current Water Mark:  0
22648   High Water Mark:  0
22650 Debug Pool info:
22651   Total allocated bytes :  8
22652   Total deallocated bytes :  0
22653   Current Water Mark:  8
22654   High Water Mark:  8
22656 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
22657 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
22658 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
22659 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
22660 Debug Pool info:
22661   Total allocated bytes :  8
22662   Total deallocated bytes :  4
22663   Current Water Mark:  4
22664   High Water Mark:  8
22665 @end example
22666 @end quotation
22669 @c -- Non-breaking space in running text
22670 @c -- E.g. Ada |nbsp| 95
22672 @node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
22673 @anchor{gnat_ugn/platform_specific_information doc}@anchor{1b4}@anchor{gnat_ugn/platform_specific_information id1}@anchor{1b5}@anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{d}
22674 @chapter Platform-Specific Information
22677 This appendix contains information relating to the implementation
22678 of run-time libraries on various platforms and also covers topics
22679 related to the GNAT implementation on specific Operating Systems.
22681 @menu
22682 * Run-Time Libraries:: 
22683 * Specifying a Run-Time Library:: 
22684 * GNU/Linux Topics:: 
22685 * Microsoft Windows Topics:: 
22686 * Mac OS Topics:: 
22688 @end menu
22690 @node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
22691 @anchor{gnat_ugn/platform_specific_information id2}@anchor{1b6}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{1b7}
22692 @section Run-Time Libraries
22695 @geindex Tasking and threads libraries
22697 @geindex Threads libraries and tasking
22699 @geindex Run-time libraries (platform-specific information)
22701 The GNAT run-time implementation may vary with respect to both the
22702 underlying threads library and the exception-handling scheme.
22703 For threads support, the default run-time will bind to the thread
22704 package of the underlying operating system.
22706 For exception handling, either or both of two models are supplied:
22708 @quotation
22710 @geindex Zero-Cost Exceptions
22712 @geindex ZCX (Zero-Cost Exceptions)
22713 @end quotation
22716 @itemize *
22718 @item 
22719 `Zero-Cost Exceptions' (“ZCX”),
22720 which uses binder-generated tables that
22721 are interrogated at run time to locate a handler.
22723 @geindex setjmp/longjmp Exception Model
22725 @geindex SJLJ (setjmp/longjmp Exception Model)
22727 @item 
22728 `setjmp / longjmp' (‘SJLJ’),
22729 which uses dynamically-set data to establish
22730 the set of handlers
22731 @end itemize
22733 Most programs should experience a substantial speed improvement by
22734 being compiled with a ZCX run-time.
22735 This is especially true for
22736 tasking applications or applications with many exception handlers.
22737 Note however that the ZCX run-time does not support asynchronous abort
22738 of tasks (@code{abort} and @code{select-then-abort} constructs) and will instead
22739 implement abort by polling points in the runtime. You can also add additional
22740 polling points explicitly if needed in your application via @code{pragma
22741 Abort_Defer}.
22743 This section summarizes which combinations of threads and exception support
22744 are supplied on various GNAT platforms.
22746 @menu
22747 * Summary of Run-Time Configurations:: 
22749 @end menu
22751 @node Summary of Run-Time Configurations,,,Run-Time Libraries
22752 @anchor{gnat_ugn/platform_specific_information id3}@anchor{1b8}@anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{1b9}
22753 @subsection Summary of Run-Time Configurations
22757 @multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
22758 @headitem
22760 Platform
22762 @tab
22764 Run-Time
22766 @tab
22768 Tasking
22770 @tab
22772 Exceptions
22774 @item
22776 GNU/Linux
22778 @tab
22780 rts-native
22781 (default)
22783 @tab
22785 pthread library
22787 @tab
22791 @item
22793 rts-sjlj
22795 @tab
22797 pthread library
22799 @tab
22801 SJLJ
22803 @item
22805 Windows
22807 @tab
22809 rts-native
22810 (default)
22812 @tab
22814 native Win32 threads
22816 @tab
22820 @item
22822 rts-sjlj
22824 @tab
22826 native Win32 threads
22828 @tab
22830 SJLJ
22832 @item
22834 Mac OS
22836 @tab
22838 rts-native
22840 @tab
22842 pthread library
22844 @tab
22848 @end multitable
22851 @node Specifying a Run-Time Library,GNU/Linux Topics,Run-Time Libraries,Platform-Specific Information
22852 @anchor{gnat_ugn/platform_specific_information id4}@anchor{1ba}@anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{1bb}
22853 @section Specifying a Run-Time Library
22856 The @code{adainclude} subdirectory containing the sources of the GNAT
22857 run-time library, and the @code{adalib} subdirectory containing the
22858 @code{ALI} files and the static and/or shared GNAT library, are located
22859 in the gcc target-dependent area:
22861 @quotation
22863 @example
22864 target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
22865 @end example
22866 @end quotation
22868 As indicated above, on some platforms several run-time libraries are supplied.
22869 These libraries are installed in the target dependent area and
22870 contain a complete source and binary subdirectory. The detailed description
22871 below explains the differences between the different libraries in terms of
22872 their thread support.
22874 The default run-time library (when GNAT is installed) is `rts-native'.
22875 This default run-time is selected by the means of soft links.
22876 For example on x86-linux:
22878 @c --
22879 @c --  $(target-dir)
22880 @c --      |
22881 @c --      +--- adainclude----------+
22882 @c --      |                        |
22883 @c --      +--- adalib-----------+  |
22884 @c --      |                     |  |
22885 @c --      +--- rts-native       |  |
22886 @c --      |    |                |  |
22887 @c --      |    +--- adainclude <---+
22888 @c --      |    |                |
22889 @c --      |    +--- adalib <----+
22890 @c --      |
22891 @c --      +--- rts-sjlj
22892 @c --           |
22893 @c --           +--- adainclude
22894 @c --           |
22895 @c --           +--- adalib
22898 @example
22899                $(target-dir)
22900               __/ /      \ \___
22901       _______/   /        \    \_________________
22902      /          /          \                     \
22903     /          /            \                     \
22904 ADAINCLUDE  ADALIB      rts-native             rts-sjlj
22905    :          :            /    \                 /   \
22906    :          :           /      \               /     \
22907    :          :          /        \             /       \
22908    :          :         /          \           /         \
22909    +-------------> adainclude     adalib   adainclude   adalib
22910               :                     ^
22911               :                     :
22912               +---------------------+
22914               Run-Time Library Directory Structure
22915    (Upper-case names and dotted/dashed arrows represent soft links)
22916 @end example
22918 If the `rts-sjlj' library is to be selected on a permanent basis,
22919 these soft links can be modified with the following commands:
22921 @quotation
22923 @example
22924 $ cd $target
22925 $ rm -f adainclude adalib
22926 $ ln -s rts-sjlj/adainclude adainclude
22927 $ ln -s rts-sjlj/adalib adalib
22928 @end example
22929 @end quotation
22931 Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
22932 @code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
22933 @code{$target/ada_object_path}.
22935 @geindex --RTS option
22937 Selecting another run-time library temporarily can be
22938 achieved by using the @code{--RTS} switch, e.g., @code{--RTS=sjlj}
22940 @geindex Linux
22942 @geindex GNU/Linux
22944 @node GNU/Linux Topics,Microsoft Windows Topics,Specifying a Run-Time Library,Platform-Specific Information
22945 @anchor{gnat_ugn/platform_specific_information gnu-linux-topics}@anchor{1bc}@anchor{gnat_ugn/platform_specific_information id5}@anchor{1bd}
22946 @section GNU/Linux Topics
22949 This section describes topics that are specific to GNU/Linux platforms.
22951 @menu
22952 * Required Packages on GNU/Linux:: 
22953 * Position Independent Executable (PIE) Enabled by Default on Linux: Position Independent Executable PIE Enabled by Default on Linux. 
22954 * Choosing the Scheduling Policy with GNU/Linux:: 
22955 * A GNU/Linux Debug Quirk:: 
22957 @end menu
22959 @node Required Packages on GNU/Linux,Position Independent Executable PIE Enabled by Default on Linux,,GNU/Linux Topics
22960 @anchor{gnat_ugn/platform_specific_information id6}@anchor{1be}@anchor{gnat_ugn/platform_specific_information required-packages-on-gnu-linux}@anchor{1bf}
22961 @subsection Required Packages on GNU/Linux
22964 GNAT requires the C library developer’s package to be installed.
22965 The name of of that package depends on your GNU/Linux distribution:
22968 @itemize *
22970 @item 
22971 RedHat, SUSE: @code{glibc-devel};
22973 @item 
22974 Debian, Ubuntu: @code{libc6-dev} (normally installed by default).
22975 @end itemize
22977 If using the 32-bit version of GNAT on a 64-bit version of GNU/Linux,
22978 you’ll need the 32-bit version of the following packages:
22981 @itemize *
22983 @item 
22984 RedHat, SUSE: @code{glibc.i686}, @code{glibc-devel.i686}, @code{ncurses-libs.i686}
22986 @item 
22987 SUSE: @code{glibc-locale-base-32bit}
22989 @item 
22990 Debian, Ubuntu: @code{libc6:i386}, @code{libc6-dev:i386}, @code{lib32ncursesw5}
22991 @end itemize
22993 Other GNU/Linux distributions might be choosing a different name
22994 for those packages.
22996 @node Position Independent Executable PIE Enabled by Default on Linux,Choosing the Scheduling Policy with GNU/Linux,Required Packages on GNU/Linux,GNU/Linux Topics
22997 @anchor{gnat_ugn/platform_specific_information pie-enabled-by-default-on-linux}@anchor{1c0}@anchor{gnat_ugn/platform_specific_information position-independent-executable-pie-enabled-by-default-on-linux}@anchor{1c1}
22998 @subsection Position Independent Executable (PIE) Enabled by Default on Linux
23001 GNAT generates Position Independent Executable (PIE) code by default.
23002 PIE binaries are loaded into random memory locations, introducing
23003 an additional layer of protection against attacks.
23005 Building PIE binaries requires that all of their dependencies also be
23006 built as Position Independent. If the link of your project fails with
23007 an error like:
23009 @example
23010 /[...]/ld: /path/to/object/file: relocation R_X86_64_32S against symbol
23011 `symbol name' can not be used when making a PIE object;
23012 recompile with -fPIE
23013 @end example
23015 it means the identified object file has not been built as Position
23016 Independent.
23018 If you are not interested in building PIE binaries, you can simply
23019 turn this feature off by first compiling your code with @code{-fno-pie}
23020 and then by linking with @code{-no-pie} (note the subtle but important
23021 difference in the names of the options – the linker option does `not'
23022 have an @cite{f} after the dash!). When using gprbuild, this is
23023 achieved by updating the `Required_Switches' attribute in package @cite{Compiler}
23024 and, depending on your type of project, either attribute `Switches'
23025 or attribute `Library_Options' in package @cite{Linker}.
23027 On the other hand, if you would like to build PIE binaries and you are
23028 getting the error above, a quick and easy workaround to allow linking
23029 to succeed again is to disable PIE during the link, thus temporarily
23030 lifting the requirement that all dependencies also be Position
23031 Independent code. To do so, you simply need to add @code{-no-pie} to
23032 the list of switches passed to the linker. As part of this workaround,
23033 there is no need to adjust the compiler switches.
23035 From there, to be able to link your binaries with PIE and therefore
23036 drop the @code{-no-pie} workaround, you’ll need to get the identified
23037 dependencies rebuilt with PIE enabled (compiled with @code{-fPIE}
23038 and linked with @code{-pie}).
23039 @anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy-with-gnu-linux}@anchor{1c2}
23040 @geindex SCHED_FIFO scheduling policy
23042 @geindex SCHED_RR scheduling policy
23044 @geindex SCHED_OTHER scheduling policy
23046 @node Choosing the Scheduling Policy with GNU/Linux,A GNU/Linux Debug Quirk,Position Independent Executable PIE Enabled by Default on Linux,GNU/Linux Topics
23047 @anchor{gnat_ugn/platform_specific_information id7}@anchor{1c3}
23048 @subsection Choosing the Scheduling Policy with GNU/Linux
23051 When using a POSIX threads implementation, you have a choice of several
23052 scheduling policies: @code{SCHED_FIFO}, @code{SCHED_RR} and @code{SCHED_OTHER}.
23054 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
23055 or @code{SCHED_RR} requires special (e.g., root) privileges.
23057 @geindex pragma Time_Slice
23059 @geindex -T0 option
23061 @geindex pragma Task_Dispatching_Policy
23063 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
23064 @code{SCHED_FIFO},
23065 you can use one of the following:
23068 @itemize *
23070 @item 
23071 @code{pragma Time_Slice (0.0)}
23073 @item 
23074 the corresponding binder option @code{-T0}
23076 @item 
23077 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23078 @end itemize
23080 To specify @code{SCHED_RR},
23081 you should use @code{pragma Time_Slice} with a
23082 value greater than 0.0, or else use the corresponding @code{-T}
23083 binder option.
23085 To make sure a program is running as root, you can put something like
23086 this in a library package body in your application:
23088 @quotation
23090 @example
23091 function geteuid return Integer;
23092 pragma Import (C, geteuid, "geteuid");
23093 Ignore : constant Boolean :=
23094   (if geteuid = 0 then True else raise Program_Error with "must be root");
23095 @end example
23096 @end quotation
23098 It gets the effective user id, and if it’s not 0 (i.e. root), it raises
23099 Program_Error. Note that if you re running the code in a container, this may
23100 not be sufficient, as you may have sufficient priviledge on the container,
23101 but not on the host machine running the container, so check that you also
23102 have sufficient priviledge for running the container image.
23104 @node A GNU/Linux Debug Quirk,,Choosing the Scheduling Policy with GNU/Linux,GNU/Linux Topics
23105 @anchor{gnat_ugn/platform_specific_information a-gnu-linux-debug-quirk}@anchor{1c4}@anchor{gnat_ugn/platform_specific_information id8}@anchor{1c5}
23106 @subsection A GNU/Linux Debug Quirk
23109 On SuSE 15, some kernels have a defect causing issues when debugging
23110 programs using threads or Ada tasks. Due to the lack of documentation
23111 found regarding this kernel issue, we can only provide limited
23112 information about which kernels are impacted: kernel version 5.3.18 is
23113 known to be impacted, and kernels in the 5.14 range or newer are
23114 believed to fix this problem.
23116 The bug affects the debugging of 32-bit processes on a 64-bit system.
23117 Symptoms can vary: Unexpected @code{SIGABRT} signals being received by
23118 the program, “The futex facility returned an unexpected error code”
23119 error message, and inferior programs hanging indefinitely range among
23120 the symptoms most commonly observed.
23122 @geindex Windows
23124 @node Microsoft Windows Topics,Mac OS Topics,GNU/Linux Topics,Platform-Specific Information
23125 @anchor{gnat_ugn/platform_specific_information id9}@anchor{1c6}@anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{1c7}
23126 @section Microsoft Windows Topics
23129 This section describes topics that are specific to the Microsoft Windows
23130 platforms.
23133 @menu
23134 * Using GNAT on Windows:: 
23135 * Using a network installation of GNAT:: 
23136 * CONSOLE and WINDOWS subsystems:: 
23137 * Temporary Files:: 
23138 * Disabling Command Line Argument Expansion:: 
23139 * Choosing the Scheduling Policy with Windows:: 
23140 * Windows Socket Timeouts:: 
23141 * Mixed-Language Programming on Windows:: 
23142 * Windows Specific Add-Ons:: 
23144 @end menu
23146 @node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
23147 @anchor{gnat_ugn/platform_specific_information id10}@anchor{1c8}@anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{1c9}
23148 @subsection Using GNAT on Windows
23151 One of the strengths of the GNAT technology is that its tool set
23152 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
23153 @code{gdb} debugger, etc.) is used in the same way regardless of the
23154 platform.
23156 On Windows this tool set is complemented by a number of Microsoft-specific
23157 tools that have been provided to facilitate interoperability with Windows
23158 when this is required. With these tools:
23161 @itemize *
23163 @item 
23164 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
23165 subsystems.
23167 @item 
23168 You can use any Dynamically Linked Library (DLL) in your Ada code (both
23169 relocatable and non-relocatable DLLs are supported).
23171 @item 
23172 You can build Ada DLLs for use in other applications. These applications
23173 can be written in a language other than Ada (e.g., C, C++, etc). Again both
23174 relocatable and non-relocatable Ada DLLs are supported.
23176 @item 
23177 You can include Windows resources in your Ada application.
23179 @item 
23180 You can use or create COM/DCOM objects.
23181 @end itemize
23183 Immediately below are listed all known general GNAT-for-Windows restrictions.
23184 Other restrictions about specific features like Windows Resources and DLLs
23185 are listed in separate sections below.
23188 @itemize *
23190 @item 
23191 It is not possible to use @code{GetLastError} and @code{SetLastError}
23192 when tasking, protected records, or exceptions are used. In these
23193 cases, in order to implement Ada semantics, the GNAT run-time system
23194 calls certain Win32 routines that set the last error variable to 0 upon
23195 success. It should be possible to use @code{GetLastError} and
23196 @code{SetLastError} when tasking, protected record, and exception
23197 features are not used, but it is not guaranteed to work.
23199 @item 
23200 It is not possible to link against Microsoft C++ libraries except for
23201 import libraries. Interfacing must be done by the mean of DLLs.
23203 @item 
23204 It is possible to link against Microsoft C libraries. Yet the preferred
23205 solution is to use C/C++ compiler that comes with GNAT, since it
23206 doesn’t require having two different development environments and makes the
23207 inter-language debugging experience smoother.
23209 @item 
23210 When the compilation environment is located on FAT32 drives, users may
23211 experience recompilations of the source files that have not changed if
23212 Daylight Saving Time (DST) state has changed since the last time files
23213 were compiled. NTFS drives do not have this problem.
23215 @item 
23216 No components of the GNAT toolset use any entries in the Windows
23217 registry. The only entries that can be created are file associations and
23218 PATH settings, provided the user has chosen to create them at installation
23219 time, as well as some minimal book-keeping information needed to correctly
23220 uninstall or integrate different GNAT products.
23221 @end itemize
23223 @node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
23224 @anchor{gnat_ugn/platform_specific_information id11}@anchor{1ca}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{1cb}
23225 @subsection Using a network installation of GNAT
23228 Make sure the system on which GNAT is installed is accessible from the
23229 current machine, i.e., the install location is shared over the network.
23230 Shared resources are accessed on Windows by means of UNC paths, which
23231 have the format @code{\\\\server\\sharename\\path}
23233 In order to use such a network installation, simply add the UNC path of the
23234 @code{bin} directory of your GNAT installation in front of your PATH. For
23235 example, if GNAT is installed in @code{\GNAT} directory of a share location
23236 called @code{c-drive} on a machine @code{LOKI}, the following command will
23237 make it available:
23239 @quotation
23241 @example
23242 $ path \\loki\c-drive\gnat\bin;%path%`
23243 @end example
23244 @end quotation
23246 Be aware that every compilation using the network installation results in the
23247 transfer of large amounts of data across the network and will likely cause
23248 serious performance penalty.
23250 @node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
23251 @anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{1cc}@anchor{gnat_ugn/platform_specific_information id12}@anchor{1cd}
23252 @subsection CONSOLE and WINDOWS subsystems
23255 @geindex CONSOLE Subsystem
23257 @geindex WINDOWS Subsystem
23259 @geindex -mwindows
23261 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
23262 (which is the default subsystem) will always create a console when
23263 launching the application. This is not something desirable when the
23264 application has a Windows GUI. To get rid of this console the
23265 application must be using the @code{WINDOWS} subsystem. To do so
23266 the @code{-mwindows} linker option must be specified.
23268 @quotation
23270 @example
23271 $ gnatmake winprog -largs -mwindows
23272 @end example
23273 @end quotation
23275 @node Temporary Files,Disabling Command Line Argument Expansion,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
23276 @anchor{gnat_ugn/platform_specific_information id13}@anchor{1ce}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{1cf}
23277 @subsection Temporary Files
23280 @geindex Temporary files
23282 It is possible to control where temporary files gets created by setting
23283 the 
23284 @geindex TMP
23285 @geindex environment variable; TMP
23286 @code{TMP} environment variable. The file will be created:
23289 @itemize *
23291 @item 
23292 Under the directory pointed to by the 
23293 @geindex TMP
23294 @geindex environment variable; TMP
23295 @code{TMP} environment variable if
23296 this directory exists.
23298 @item 
23299 Under @code{c:\temp}, if the 
23300 @geindex TMP
23301 @geindex environment variable; TMP
23302 @code{TMP} environment variable is not
23303 set (or not pointing to a directory) and if this directory exists.
23305 @item 
23306 Under the current working directory otherwise.
23307 @end itemize
23309 This allows you to determine exactly where the temporary
23310 file will be created. This is particularly useful in networked
23311 environments where you may not have write access to some
23312 directories.
23314 @node Disabling Command Line Argument Expansion,Choosing the Scheduling Policy with Windows,Temporary Files,Microsoft Windows Topics
23315 @anchor{gnat_ugn/platform_specific_information disabling-command-line-argument-expansion}@anchor{1d0}
23316 @subsection Disabling Command Line Argument Expansion
23319 @geindex Command Line Argument Expansion
23321 By default, an executable compiled for the Windows platform will do
23322 the following postprocessing on the arguments passed on the command
23323 line:
23326 @itemize *
23328 @item 
23329 If the argument contains the characters @code{*} and/or @code{?}, then
23330 file expansion will be attempted. For example, if the current directory
23331 contains @code{a.txt} and @code{b.txt}, then when calling:
23333 @example
23334 $ my_ada_program *.txt
23335 @end example
23337 The following arguments will effectively be passed to the main program
23338 (for example when using @code{Ada.Command_Line.Argument}):
23340 @example
23341 Ada.Command_Line.Argument (1) -> "a.txt"
23342 Ada.Command_Line.Argument (2) -> "b.txt"
23343 @end example
23345 @item 
23346 Filename expansion can be disabled for a given argument by using single
23347 quotes. Thus, calling:
23349 @example
23350 $ my_ada_program '*.txt'
23351 @end example
23353 will result in:
23355 @example
23356 Ada.Command_Line.Argument (1) -> "*.txt"
23357 @end example
23358 @end itemize
23360 Note that if the program is launched from a shell such as Cygwin Bash
23361 then quote removal might be performed by the shell.
23363 In some contexts it might be useful to disable this feature (for example if
23364 the program performs its own argument expansion). In order to do this, a C
23365 symbol needs to be defined and set to @code{0}. You can do this by
23366 adding the following code fragment in one of your Ada units:
23368 @example
23369 Do_Argv_Expansion : Integer := 0;
23370 pragma Export (C, Do_Argv_Expansion, "__gnat_do_argv_expansion");
23371 @end example
23373 The results of previous examples will be respectively:
23375 @example
23376 Ada.Command_Line.Argument (1) -> "*.txt"
23377 @end example
23379 and:
23381 @example
23382 Ada.Command_Line.Argument (1) -> "'*.txt'"
23383 @end example
23385 @node Choosing the Scheduling Policy with Windows,Windows Socket Timeouts,Disabling Command Line Argument Expansion,Microsoft Windows Topics
23386 @anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy-with-windows}@anchor{1d1}@anchor{gnat_ugn/platform_specific_information id14}@anchor{1d2}
23387 @subsection Choosing the Scheduling Policy with Windows
23390 Under Windows, the standard 31 priorities of the Ada model are mapped onto
23391 Window’s seven standard priority levels by default: Idle, Lowest, Below Normal,
23392 Normal, Above Normal,
23394 When using the @code{FIFO_Within_Priorities} task dispatching policy, GNAT
23395 will assign the @code{REALTIME_PRIORITY_CLASS} priority class to the application
23396 and map the Ada priority range to the sixteen priorities made available under
23397 @code{REALTIME_PRIORITY_CLASS}.
23399 For details on the values of the different priority mappings, see declarations
23400 in @code{system.ads}. For more information about Windows priorities, please
23401 refer to Microsoft’s documentation.
23403 @node Windows Socket Timeouts,Mixed-Language Programming on Windows,Choosing the Scheduling Policy with Windows,Microsoft Windows Topics
23404 @anchor{gnat_ugn/platform_specific_information windows-socket-timeouts}@anchor{1d3}
23405 @subsection Windows Socket Timeouts
23408 Microsoft Windows desktops older than @code{8.0} and Microsoft Windows Servers
23409 older than @code{2019} set a socket timeout 500 milliseconds longer than the value
23410 set by setsockopt with @code{SO_RCVTIMEO} and @code{SO_SNDTIMEO} options. The GNAT
23411 runtime makes a correction for the difference in the corresponding Windows
23412 versions. For Windows Server starting with version @code{2019}, the user must
23413 provide a manifest file for the GNAT runtime to be able to recognize that
23414 the Windows version does not need the timeout correction. The manifest file
23415 should be located in the same directory as the executable file, and its file
23416 name must match the executable name suffixed by @code{.manifest}. For example,
23417 if the executable name is @code{sock_wto.exe}, then the manifest file name
23418 has to be @code{sock_wto.exe.manifest}. The manifest file must contain at
23419 least the following data:
23421 @example
23422 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
23423 <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
23424 <compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
23425 <application>
23426    <!-- Windows Vista -->
23427    <supportedOS Id="@{e2011457-1546-43c5-a5fe-008deee3d3f0@}"/>
23428    <!-- Windows 7 -->
23429    <supportedOS Id="@{35138b9a-5d96-4fbd-8e2d-a2440225f93a@}"/>
23430    <!-- Windows 8 -->
23431    <supportedOS Id="@{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38@}"/>
23432    <!-- Windows 8.1 -->
23433    <supportedOS Id="@{1f676c76-80e1-4239-95bb-83d0f6d0da78@}"/>
23434    <!-- Windows 10 -->
23435    <supportedOS Id="@{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a@}"/>
23436 </application>
23437 </compatibility>
23438 </assembly>
23439 @end example
23441 Without the manifest file, the socket timeout is going to be overcorrected on
23442 these Windows Server versions and the actual time is going to be 500
23443 milliseconds shorter than what was set with GNAT.Sockets.Set_Socket_Option.
23444 Note that on Microsoft Windows versions where correction is necessary, there
23445 is no way to set a socket timeout shorter than 500 ms. If a socket timeout
23446 shorter than 500 ms is needed on these Windows versions, a call to
23447 Check_Selector should be added before any socket read or write operations.
23449 @node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Windows Socket Timeouts,Microsoft Windows Topics
23450 @anchor{gnat_ugn/platform_specific_information id15}@anchor{1d4}@anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{1d5}
23451 @subsection Mixed-Language Programming on Windows
23454 Developing pure Ada applications on Windows is no different than on
23455 other GNAT-supported platforms. However, when developing or porting an
23456 application that contains a mix of Ada and C/C++, the choice of your
23457 Windows C/C++ development environment conditions your overall
23458 interoperability strategy.
23460 If you use @code{gcc} or Microsoft C to compile the non-Ada part of
23461 your application, there are no Windows-specific restrictions that
23462 affect the overall interoperability with your Ada code. If you do want
23463 to use the Microsoft tools for your C++ code, you have two choices:
23466 @itemize *
23468 @item 
23469 Encapsulate your C++ code in a DLL to be linked with your Ada
23470 application. In this case, use the Microsoft or whatever environment to
23471 build the DLL and use GNAT to build your executable
23472 (@ref{1d6,,Using DLLs with GNAT}).
23474 @item 
23475 Or you can encapsulate your Ada code in a DLL to be linked with the
23476 other part of your application. In this case, use GNAT to build the DLL
23477 (@ref{1d7,,Building DLLs with GNAT Project files}) and use the Microsoft
23478 or whatever environment to build your executable.
23479 @end itemize
23481 In addition to the description about C main in
23482 @ref{2c,,Mixed Language Programming} section, if the C main uses a
23483 stand-alone library it is required on x86-windows to
23484 setup the SEH context. For this the C main must looks like this:
23486 @quotation
23488 @example
23489 /* main.c */
23490 extern void adainit (void);
23491 extern void adafinal (void);
23492 extern void __gnat_initialize(void*);
23493 extern void call_to_ada (void);
23495 int main (int argc, char *argv[])
23497   int SEH [2];
23499   /* Initialize the SEH context */
23500   __gnat_initialize (&SEH);
23502   adainit();
23504   /* Then call Ada services in the stand-alone library */
23506   call_to_ada();
23508   adafinal();
23510 @end example
23511 @end quotation
23513 Note that this is not needed on x86_64-windows where the Windows
23514 native SEH support is used.
23516 @menu
23517 * Windows Calling Conventions:: 
23518 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
23519 * Using DLLs with GNAT:: 
23520 * Building DLLs with GNAT Project files:: 
23521 * Building DLLs with GNAT:: 
23522 * Building DLLs with gnatdll:: 
23523 * Ada DLLs and Finalization:: 
23524 * Creating a Spec for Ada DLLs:: 
23525 * GNAT and Windows Resources:: 
23526 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
23527 * Debugging a DLL:: 
23528 * Setting Stack Size from gnatlink:: 
23529 * Setting Heap Size from gnatlink:: 
23531 @end menu
23533 @node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
23534 @anchor{gnat_ugn/platform_specific_information id16}@anchor{1d8}@anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{1d9}
23535 @subsubsection Windows Calling Conventions
23538 @geindex Stdcall
23540 @geindex APIENTRY
23542 This section pertain only to Win32. On Win64 there is a single native
23543 calling convention. All convention specifiers are ignored on this
23544 platform.
23546 When a subprogram @code{F} (caller) calls a subprogram @code{G}
23547 (callee), there are several ways to push @code{G}‘s parameters on the
23548 stack and there are several possible scenarios to clean up the stack
23549 upon @code{G}‘s return. A calling convention is an agreed upon software
23550 protocol whereby the responsibilities between the caller (@code{F}) and
23551 the callee (@code{G}) are clearly defined. Several calling conventions
23552 are available for Windows:
23555 @itemize *
23557 @item 
23558 @code{C} (Microsoft defined)
23560 @item 
23561 @code{Stdcall} (Microsoft defined)
23563 @item 
23564 @code{Win32} (GNAT specific)
23566 @item 
23567 @code{DLL} (GNAT specific)
23568 @end itemize
23570 @menu
23571 * C Calling Convention:: 
23572 * Stdcall Calling Convention:: 
23573 * Win32 Calling Convention:: 
23574 * DLL Calling Convention:: 
23576 @end menu
23578 @node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
23579 @anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{1da}@anchor{gnat_ugn/platform_specific_information id17}@anchor{1db}
23580 @subsubsection @code{C} Calling Convention
23583 This is the default calling convention used when interfacing to C/C++
23584 routines compiled with either @code{gcc} or Microsoft Visual C++.
23586 In the @code{C} calling convention subprogram parameters are pushed on the
23587 stack by the caller from right to left. The caller itself is in charge of
23588 cleaning up the stack after the call. In addition, the name of a routine
23589 with @code{C} calling convention is mangled by adding a leading underscore.
23591 The name to use on the Ada side when importing (or exporting) a routine
23592 with @code{C} calling convention is the name of the routine. For
23593 instance the C function:
23595 @quotation
23597 @example
23598 int get_val (long);
23599 @end example
23600 @end quotation
23602 should be imported from Ada as follows:
23604 @quotation
23606 @example
23607 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23608 pragma Import (C, Get_Val, External_Name => "get_val");
23609 @end example
23610 @end quotation
23612 Note that in this particular case the @code{External_Name} parameter could
23613 have been omitted since, when missing, this parameter is taken to be the
23614 name of the Ada entity in lower case. When the @code{Link_Name} parameter
23615 is missing, as in the above example, this parameter is set to be the
23616 @code{External_Name} with a leading underscore.
23618 When importing a variable defined in C, you should always use the @code{C}
23619 calling convention unless the object containing the variable is part of a
23620 DLL (in which case you should use the @code{Stdcall} calling
23621 convention, @ref{1dc,,Stdcall Calling Convention}).
23623 @node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
23624 @anchor{gnat_ugn/platform_specific_information id18}@anchor{1dd}@anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{1dc}
23625 @subsubsection @code{Stdcall} Calling Convention
23628 This convention, which was the calling convention used for Pascal
23629 programs, is used by Microsoft for all the routines in the Win32 API for
23630 efficiency reasons. It must be used to import any routine for which this
23631 convention was specified.
23633 In the @code{Stdcall} calling convention subprogram parameters are pushed
23634 on the stack by the caller from right to left. The callee (and not the
23635 caller) is in charge of cleaning the stack on routine exit. In addition,
23636 the name of a routine with @code{Stdcall} calling convention is mangled by
23637 adding a leading underscore (as for the @code{C} calling convention) and a
23638 trailing @code{@@@var{nn}}, where @code{nn} is the overall size (in
23639 bytes) of the parameters passed to the routine.
23641 The name to use on the Ada side when importing a C routine with a
23642 @code{Stdcall} calling convention is the name of the C routine. The leading
23643 underscore and trailing @code{@@@var{nn}} are added automatically by
23644 the compiler. For instance the Win32 function:
23646 @quotation
23648 @example
23649 APIENTRY int get_val (long);
23650 @end example
23651 @end quotation
23653 should be imported from Ada as follows:
23655 @quotation
23657 @example
23658 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23659 pragma Import (Stdcall, Get_Val);
23660 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
23661 @end example
23662 @end quotation
23664 As for the @code{C} calling convention, when the @code{External_Name}
23665 parameter is missing, it is taken to be the name of the Ada entity in lower
23666 case. If instead of writing the above import pragma you write:
23668 @quotation
23670 @example
23671 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23672 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
23673 @end example
23674 @end quotation
23676 then the imported routine is @code{_retrieve_val@@4}. However, if instead
23677 of specifying the @code{External_Name} parameter you specify the
23678 @code{Link_Name} as in the following example:
23680 @quotation
23682 @example
23683 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
23684 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
23685 @end example
23686 @end quotation
23688 then the imported routine is @code{retrieve_val}, that is, there is no
23689 decoration at all. No leading underscore and no Stdcall suffix
23690 @code{@@@var{nn}}.
23692 This is especially important as in some special cases a DLL’s entry
23693 point name lacks a trailing @code{@@@var{nn}} while the exported
23694 name generated for a call has it.
23696 It is also possible to import variables defined in a DLL by using an
23697 import pragma for a variable. As an example, if a DLL contains a
23698 variable defined as:
23700 @quotation
23702 @example
23703 int my_var;
23704 @end example
23705 @end quotation
23707 then, to access this variable from Ada you should write:
23709 @quotation
23711 @example
23712 My_Var : Interfaces.C.int;
23713 pragma Import (Stdcall, My_Var);
23714 @end example
23715 @end quotation
23717 Note that to ease building cross-platform bindings this convention
23718 will be handled as a @code{C} calling convention on non-Windows platforms.
23720 @node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
23721 @anchor{gnat_ugn/platform_specific_information id19}@anchor{1de}@anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{1df}
23722 @subsubsection @code{Win32} Calling Convention
23725 This convention, which is GNAT-specific is fully equivalent to the
23726 @code{Stdcall} calling convention described above.
23728 @node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
23729 @anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{1e0}@anchor{gnat_ugn/platform_specific_information id20}@anchor{1e1}
23730 @subsubsection @code{DLL} Calling Convention
23733 This convention, which is GNAT-specific is fully equivalent to the
23734 @code{Stdcall} calling convention described above.
23736 @node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
23737 @anchor{gnat_ugn/platform_specific_information id21}@anchor{1e2}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{1e3}
23738 @subsubsection Introduction to Dynamic Link Libraries (DLLs)
23741 @geindex DLL
23743 A Dynamically Linked Library (DLL) is a library that can be shared by
23744 several applications running under Windows. A DLL can contain any number of
23745 routines and variables.
23747 One advantage of DLLs is that you can change and enhance them without
23748 forcing all the applications that depend on them to be relinked or
23749 recompiled. However, you should be aware than all calls to DLL routines are
23750 slower since, as you will understand below, such calls are indirect.
23752 To illustrate the remainder of this section, suppose that an application
23753 wants to use the services of a DLL @code{API.dll}. To use the services
23754 provided by @code{API.dll} you must statically link against the DLL or
23755 an import library which contains a jump table with an entry for each
23756 routine and variable exported by the DLL. In the Microsoft world this
23757 import library is called @code{API.lib}. When using GNAT this import
23758 library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
23759 @code{libAPI.a} or @code{libapi.a} (names are case insensitive).
23761 After you have linked your application with the DLL or the import library
23762 and you run your application, here is what happens:
23765 @itemize *
23767 @item 
23768 Your application is loaded into memory.
23770 @item 
23771 The DLL @code{API.dll} is mapped into the address space of your
23772 application. This means that:
23775 @itemize -
23777 @item 
23778 The DLL will use the stack of the calling thread.
23780 @item 
23781 The DLL will use the virtual address space of the calling process.
23783 @item 
23784 The DLL will allocate memory from the virtual address space of the calling
23785 process.
23787 @item 
23788 Handles (pointers) can be safely exchanged between routines in the DLL
23789 routines and routines in the application using the DLL.
23790 @end itemize
23792 @item 
23793 The entries in the jump table (from the import library @code{libAPI.dll.a}
23794 or @code{API.lib} or automatically created when linking against a DLL)
23795 which is part of your application are initialized with the addresses
23796 of the routines and variables in @code{API.dll}.
23798 @item 
23799 If present in @code{API.dll}, routines @code{DllMain} or
23800 @code{DllMainCRTStartup} are invoked. These routines typically contain
23801 the initialization code needed for the well-being of the routines and
23802 variables exported by the DLL.
23803 @end itemize
23805 There is an additional point which is worth mentioning. In the Windows
23806 world there are two kind of DLLs: relocatable and non-relocatable
23807 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
23808 in the target application address space. If the addresses of two
23809 non-relocatable DLLs overlap and these happen to be used by the same
23810 application, a conflict will occur and the application will run
23811 incorrectly. Hence, when possible, it is always preferable to use and
23812 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
23813 supported by GNAT. Note that the @code{-s} linker option (see GNU Linker
23814 User’s Guide) removes the debugging symbols from the DLL but the DLL can
23815 still be relocated.
23817 As a side note, an interesting difference between Microsoft DLLs and
23818 Unix shared libraries, is the fact that on most Unix systems all public
23819 routines are exported by default in a Unix shared library, while under
23820 Windows it is possible (but not required) to list exported routines in
23821 a definition file (see @ref{1e4,,The Definition File}).
23823 @node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
23824 @anchor{gnat_ugn/platform_specific_information id22}@anchor{1e5}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{1d6}
23825 @subsubsection Using DLLs with GNAT
23828 To use the services of a DLL, say @code{API.dll}, in your Ada application
23829 you must have:
23832 @itemize *
23834 @item 
23835 The Ada spec for the routines and/or variables you want to access in
23836 @code{API.dll}. If not available this Ada spec must be built from the C/C++
23837 header files provided with the DLL.
23839 @item 
23840 The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
23841 mentioned an import library is a statically linked library containing the
23842 import table which will be filled at load time to point to the actual
23843 @code{API.dll} routines. Sometimes you don’t have an import library for the
23844 DLL you want to use. The following sections will explain how to build
23845 one. Note that this is optional.
23847 @item 
23848 The actual DLL, @code{API.dll}.
23849 @end itemize
23851 Once you have all the above, to compile an Ada application that uses the
23852 services of @code{API.dll} and whose main subprogram is @code{My_Ada_App},
23853 you simply issue the command
23855 @quotation
23857 @example
23858 $ gnatmake my_ada_app -largs -lAPI
23859 @end example
23860 @end quotation
23862 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
23863 tells the GNAT linker to look for an import library. The linker will
23864 look for a library name in this specific order:
23867 @itemize *
23869 @item 
23870 @code{libAPI.dll.a}
23872 @item 
23873 @code{API.dll.a}
23875 @item 
23876 @code{libAPI.a}
23878 @item 
23879 @code{API.lib}
23881 @item 
23882 @code{libAPI.dll}
23884 @item 
23885 @code{API.dll}
23886 @end itemize
23888 The first three are the GNU style import libraries. The third is the
23889 Microsoft style import libraries. The last two are the actual DLL names.
23891 Note that if the Ada package spec for @code{API.dll} contains the
23892 following pragma
23894 @quotation
23896 @example
23897 pragma Linker_Options ("-lAPI");
23898 @end example
23899 @end quotation
23901 you do not have to add @code{-largs -lAPI} at the end of the
23902 @code{gnatmake} command.
23904 If any one of the items above is missing you will have to create it
23905 yourself. The following sections explain how to do so using as an
23906 example a fictitious DLL called @code{API.dll}.
23908 @menu
23909 * Creating an Ada Spec for the DLL Services:: 
23910 * Creating an Import Library:: 
23912 @end menu
23914 @node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
23915 @anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{1e6}@anchor{gnat_ugn/platform_specific_information id23}@anchor{1e7}
23916 @subsubsection Creating an Ada Spec for the DLL Services
23919 A DLL typically comes with a C/C++ header file which provides the
23920 definitions of the routines and variables exported by the DLL. The Ada
23921 equivalent of this header file is a package spec that contains definitions
23922 for the imported entities. If the DLL you intend to use does not come with
23923 an Ada spec you have to generate one such spec yourself. For example if
23924 the header file of @code{API.dll} is a file @code{api.h} containing the
23925 following two definitions:
23927 @quotation
23929 @example
23930 int some_var;
23931 int get (char *);
23932 @end example
23933 @end quotation
23935 then the equivalent Ada spec could be:
23937 @quotation
23939 @example
23940 with Interfaces.C.Strings;
23941 package API is
23942    use Interfaces;
23944    Some_Var : C.int;
23945    function Get (Str : C.Strings.Chars_Ptr) return C.int;
23947 private
23948    pragma Import (C, Get);
23949    pragma Import (DLL, Some_Var);
23950 end API;
23951 @end example
23952 @end quotation
23954 @node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
23955 @anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{1e8}@anchor{gnat_ugn/platform_specific_information id24}@anchor{1e9}
23956 @subsubsection Creating an Import Library
23959 @geindex Import library
23961 If a Microsoft-style import library @code{API.lib} or a GNAT-style
23962 import library @code{libAPI.dll.a} or @code{libAPI.a} is available
23963 with @code{API.dll} you can skip this section. You can also skip this
23964 section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
23965 as in this case it is possible to link directly against the
23966 DLL. Otherwise read on.
23968 @geindex Definition file
23969 @anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{1e4}
23970 @subsubheading The Definition File
23973 As previously mentioned, and unlike Unix systems, the list of symbols
23974 that are exported from a DLL must be provided explicitly in Windows.
23975 The main goal of a definition file is precisely that: list the symbols
23976 exported by a DLL. A definition file (usually a file with a @code{.def}
23977 suffix) has the following structure:
23979 @quotation
23981 @example
23982 [LIBRARY `@w{`}name`@w{`}]
23983 [DESCRIPTION `@w{`}string`@w{`}]
23984 EXPORTS
23985    `@w{`}symbol1`@w{`}
23986    `@w{`}symbol2`@w{`}
23987    ...
23988 @end example
23989 @end quotation
23992 @table @asis
23994 @item `LIBRARY name'
23996 This section, which is optional, gives the name of the DLL.
23998 @item `DESCRIPTION string'
24000 This section, which is optional, gives a description string that will be
24001 embedded in the import library.
24003 @item `EXPORTS'
24005 This section gives the list of exported symbols (procedures, functions or
24006 variables). For instance in the case of @code{API.dll} the @code{EXPORTS}
24007 section of @code{API.def} looks like:
24009 @example
24010 EXPORTS
24011    some_var
24012    get
24013 @end example
24014 @end table
24016 Note that you must specify the correct suffix (@code{@@@var{nn}})
24017 (see @ref{1d9,,Windows Calling Conventions}) for a Stdcall
24018 calling convention function in the exported symbols list.
24020 There can actually be other sections in a definition file, but these
24021 sections are not relevant to the discussion at hand.
24022 @anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{1ea}
24023 @subsubheading Creating a Definition File Automatically
24026 You can automatically create the definition file @code{API.def}
24027 (see @ref{1e4,,The Definition File}) from a DLL.
24028 For that use the @code{dlltool} program as follows:
24030 @quotation
24032 @example
24033 $ dlltool API.dll -z API.def --export-all-symbols
24034 @end example
24036 Note that if some routines in the DLL have the @code{Stdcall} convention
24037 (@ref{1d9,,Windows Calling Conventions}) with stripped @code{@@@var{nn}}
24038 suffix then you’ll have to edit @code{api.def} to add it, and specify
24039 @code{-k} to @code{gnatdll} when creating the import library.
24041 Here are some hints to find the right @code{@@@var{nn}} suffix.
24044 @itemize -
24046 @item 
24047 If you have the Microsoft import library (.lib), it is possible to get
24048 the right symbols by using Microsoft @code{dumpbin} tool (see the
24049 corresponding Microsoft documentation for further details).
24051 @example
24052 $ dumpbin /exports api.lib
24053 @end example
24055 @item 
24056 If you have a message about a missing symbol at link time the compiler
24057 tells you what symbol is expected. You just have to go back to the
24058 definition file and add the right suffix.
24059 @end itemize
24060 @end quotation
24061 @anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{1eb}
24062 @subsubheading GNAT-Style Import Library
24065 To create a static import library from @code{API.dll} with the GNAT tools
24066 you should create the .def file, then use @code{gnatdll} tool
24067 (see @ref{1ec,,Using gnatdll}) as follows:
24069 @quotation
24071 @example
24072 $ gnatdll -e API.def -d API.dll
24073 @end example
24075 @code{gnatdll} takes as input a definition file @code{API.def} and the
24076 name of the DLL containing the services listed in the definition file
24077 @code{API.dll}. The name of the static import library generated is
24078 computed from the name of the definition file as follows: if the
24079 definition file name is @code{xyz.def}, the import library name will
24080 be @code{libxyz.a}. Note that in the previous example option
24081 @code{-e} could have been removed because the name of the definition
24082 file (before the @code{.def} suffix) is the same as the name of the
24083 DLL (@ref{1ec,,Using gnatdll} for more information about @code{gnatdll}).
24084 @end quotation
24085 @anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{1ed}
24086 @subsubheading Microsoft-Style Import Library
24089 A Microsoft import library is needed only if you plan to make an
24090 Ada DLL available to applications developed with Microsoft
24091 tools (@ref{1d5,,Mixed-Language Programming on Windows}).
24093 To create a Microsoft-style import library for @code{API.dll} you
24094 should create the .def file, then build the actual import library using
24095 Microsoft’s @code{lib} utility:
24097 @quotation
24099 @example
24100 $ lib -machine:IX86 -def:API.def -out:API.lib
24101 @end example
24103 If you use the above command the definition file @code{API.def} must
24104 contain a line giving the name of the DLL:
24106 @example
24107 LIBRARY      "API"
24108 @end example
24110 See the Microsoft documentation for further details about the usage of
24111 @code{lib}.
24112 @end quotation
24114 @node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
24115 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{1d7}@anchor{gnat_ugn/platform_specific_information id25}@anchor{1ee}
24116 @subsubsection Building DLLs with GNAT Project files
24119 @geindex DLLs
24120 @geindex building
24122 There is nothing specific to Windows in the build process.
24123 See the `Library Projects' section in the `GNAT Project Manager'
24124 chapter of the `GPRbuild User’s Guide'.
24126 Due to a system limitation, it is not possible under Windows to create threads
24127 when inside the @code{DllMain} routine which is used for auto-initialization
24128 of shared libraries, so it is not possible to have library level tasks in SALs.
24130 @node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
24131 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{1ef}@anchor{gnat_ugn/platform_specific_information id26}@anchor{1f0}
24132 @subsubsection Building DLLs with GNAT
24135 @geindex DLLs
24136 @geindex building
24138 This section explain how to build DLLs using the GNAT built-in DLL
24139 support. With the following procedure it is straight forward to build
24140 and use DLLs with GNAT.
24143 @itemize *
24145 @item 
24146 Building object files.
24147 The first step is to build all objects files that are to be included
24148 into the DLL. This is done by using the standard @code{gnatmake} tool.
24150 @item 
24151 Building the DLL.
24152 To build the DLL you must use the @code{gcc} @code{-shared} and
24153 @code{-shared-libgcc} options. It is quite simple to use this method:
24155 @example
24156 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
24157 @end example
24159 It is important to note that in this case all symbols found in the
24160 object files are automatically exported. It is possible to restrict
24161 the set of symbols to export by passing to @code{gcc} a definition
24162 file (see @ref{1e4,,The Definition File}).
24163 For example:
24165 @example
24166 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
24167 @end example
24169 If you use a definition file you must export the elaboration procedures
24170 for every package that required one. Elaboration procedures are named
24171 using the package name followed by “_E”.
24173 @item 
24174 Preparing DLL to be used.
24175 For the DLL to be used by client programs the bodies must be hidden
24176 from it and the .ali set with read-only attribute. This is very important
24177 otherwise GNAT will recompile all packages and will not actually use
24178 the code in the DLL. For example:
24180 @example
24181 $ mkdir apilib
24182 $ copy *.ads *.ali api.dll apilib
24183 $ attrib +R apilib\\*.ali
24184 @end example
24185 @end itemize
24187 At this point it is possible to use the DLL by directly linking
24188 against it. Note that you must use the GNAT shared runtime when using
24189 GNAT shared libraries. This is achieved by using the @code{-shared} binder
24190 option.
24192 @quotation
24194 @example
24195 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
24196 @end example
24197 @end quotation
24199 @node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
24200 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{1f1}@anchor{gnat_ugn/platform_specific_information id27}@anchor{1f2}
24201 @subsubsection Building DLLs with gnatdll
24204 @geindex DLLs
24205 @geindex building
24207 Note that it is preferred to use GNAT Project files
24208 (@ref{1d7,,Building DLLs with GNAT Project files}) or the built-in GNAT
24209 DLL support (@ref{1ef,,Building DLLs with GNAT}) or to build DLLs.
24211 This section explains how to build DLLs containing Ada code using
24212 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
24213 remainder of this section.
24215 The steps required to build an Ada DLL that is to be used by Ada as well as
24216 non-Ada applications are as follows:
24219 @itemize *
24221 @item 
24222 You need to mark each Ada entity exported by the DLL with a @code{C} or
24223 @code{Stdcall} calling convention to avoid any Ada name mangling for the
24224 entities exported by the DLL
24225 (see @ref{1f3,,Exporting Ada Entities}). You can
24226 skip this step if you plan to use the Ada DLL only from Ada applications.
24228 @item 
24229 Your Ada code must export an initialization routine which calls the routine
24230 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
24231 the Ada code in the DLL (@ref{1f4,,Ada DLLs and Elaboration}). The initialization
24232 routine exported by the Ada DLL must be invoked by the clients of the DLL
24233 to initialize the DLL.
24235 @item 
24236 When useful, the DLL should also export a finalization routine which calls
24237 routine @code{adafinal} generated by @code{gnatbind} to perform the
24238 finalization of the Ada code in the DLL (@ref{1f5,,Ada DLLs and Finalization}).
24239 The finalization routine exported by the Ada DLL must be invoked by the
24240 clients of the DLL when the DLL services are no further needed.
24242 @item 
24243 You must provide a spec for the services exported by the Ada DLL in each
24244 of the programming languages to which you plan to make the DLL available.
24246 @item 
24247 You must provide a definition file listing the exported entities
24248 (@ref{1e4,,The Definition File}).
24250 @item 
24251 Finally you must use @code{gnatdll} to produce the DLL and the import
24252 library (@ref{1ec,,Using gnatdll}).
24253 @end itemize
24255 Note that a relocatable DLL stripped using the @code{strip}
24256 binutils tool will not be relocatable anymore. To build a DLL without
24257 debug information pass @code{-largs -s} to @code{gnatdll}. This
24258 restriction does not apply to a DLL built using a Library Project.
24259 See the `Library Projects' section in the `GNAT Project Manager'
24260 chapter of the `GPRbuild User’s Guide'.
24262 @c Limitations_When_Using_Ada_DLLs_from Ada:
24264 @menu
24265 * Limitations When Using Ada DLLs from Ada:: 
24266 * Exporting Ada Entities:: 
24267 * Ada DLLs and Elaboration:: 
24269 @end menu
24271 @node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
24272 @anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{1f6}
24273 @subsubsection Limitations When Using Ada DLLs from Ada
24276 When using Ada DLLs from Ada applications there is a limitation users
24277 should be aware of. Because on Windows the GNAT run-time is not in a DLL of
24278 its own, each Ada DLL includes a part of the GNAT run-time. Specifically,
24279 each Ada DLL includes the services of the GNAT run-time that are necessary
24280 to the Ada code inside the DLL. As a result, when an Ada program uses an
24281 Ada DLL there are two independent GNAT run-times: one in the Ada DLL and
24282 one in the main program.
24284 It is therefore not possible to exchange GNAT run-time objects between the
24285 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
24286 handles (e.g., @code{Text_IO.File_Type}), tasks types, protected objects
24287 types, etc.
24289 It is completely safe to exchange plain elementary, array or record types,
24290 Windows object handles, etc.
24292 @node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
24293 @anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{1f3}@anchor{gnat_ugn/platform_specific_information id28}@anchor{1f7}
24294 @subsubsection Exporting Ada Entities
24297 @geindex Export table
24299 Building a DLL is a way to encapsulate a set of services usable from any
24300 application. As a result, the Ada entities exported by a DLL should be
24301 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
24302 any Ada name mangling. As an example here is an Ada package
24303 @code{API}, spec and body, exporting two procedures, a function, and a
24304 variable:
24306 @quotation
24308 @example
24309 with Interfaces.C; use Interfaces;
24310 package API is
24311    Count : C.int := 0;
24312    function Factorial (Val : C.int) return C.int;
24314    procedure Initialize_API;
24315    procedure Finalize_API;
24316    --  Initialization & Finalization routines. More in the next section.
24317 private
24318    pragma Export (C, Initialize_API);
24319    pragma Export (C, Finalize_API);
24320    pragma Export (C, Count);
24321    pragma Export (C, Factorial);
24322 end API;
24323 @end example
24325 @example
24326 package body API is
24327    function Factorial (Val : C.int) return C.int is
24328       Fact : C.int := 1;
24329    begin
24330       Count := Count + 1;
24331       for K in 1 .. Val loop
24332          Fact := Fact * K;
24333       end loop;
24334       return Fact;
24335    end Factorial;
24337    procedure Initialize_API is
24338       procedure Adainit;
24339       pragma Import (C, Adainit);
24340    begin
24341       Adainit;
24342    end Initialize_API;
24344    procedure Finalize_API is
24345       procedure Adafinal;
24346       pragma Import (C, Adafinal);
24347    begin
24348       Adafinal;
24349    end Finalize_API;
24350 end API;
24351 @end example
24352 @end quotation
24354 If the Ada DLL you are building will only be used by Ada applications
24355 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
24356 convention. As an example, the previous package could be written as
24357 follows:
24359 @quotation
24361 @example
24362 package API is
24363    Count : Integer := 0;
24364    function Factorial (Val : Integer) return Integer;
24366    procedure Initialize_API;
24367    procedure Finalize_API;
24368    --  Initialization and Finalization routines.
24369 end API;
24370 @end example
24372 @example
24373 package body API is
24374    function Factorial (Val : Integer) return Integer is
24375       Fact : Integer := 1;
24376    begin
24377       Count := Count + 1;
24378       for K in 1 .. Val loop
24379          Fact := Fact * K;
24380       end loop;
24381       return Fact;
24382    end Factorial;
24384    ...
24385    --  The remainder of this package body is unchanged.
24386 end API;
24387 @end example
24388 @end quotation
24390 Note that if you do not export the Ada entities with a @code{C} or
24391 @code{Stdcall} convention you will have to provide the mangled Ada names
24392 in the definition file of the Ada DLL
24393 (@ref{1f8,,Creating the Definition File}).
24395 @node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
24396 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{1f4}@anchor{gnat_ugn/platform_specific_information id29}@anchor{1f9}
24397 @subsubsection Ada DLLs and Elaboration
24400 @geindex DLLs and elaboration
24402 The DLL that you are building contains your Ada code as well as all the
24403 routines in the Ada library that are needed by it. The first thing a
24404 user of your DLL must do is elaborate the Ada code
24405 (@ref{f,,Elaboration Order Handling in GNAT}).
24407 To achieve this you must export an initialization routine
24408 (@code{Initialize_API} in the previous example), which must be invoked
24409 before using any of the DLL services. This elaboration routine must call
24410 the Ada elaboration routine @code{adainit} generated by the GNAT binder
24411 (@ref{7e,,Binding with Non-Ada Main Programs}). See the body of
24412 @code{Initialize_Api} for an example. Note that the GNAT binder is
24413 automatically invoked during the DLL build process by the @code{gnatdll}
24414 tool (@ref{1ec,,Using gnatdll}).
24416 When a DLL is loaded, Windows systematically invokes a routine called
24417 @code{DllMain}. It would therefore be possible to call @code{adainit}
24418 directly from @code{DllMain} without having to provide an explicit
24419 initialization routine. Unfortunately, it is not possible to call
24420 @code{adainit} from the @code{DllMain} if your program has library level
24421 tasks because access to the @code{DllMain} entry point is serialized by
24422 the system (that is, only a single thread can execute ‘through’ it at a
24423 time), which means that the GNAT run-time will deadlock waiting for the
24424 newly created task to complete its initialization.
24426 @node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
24427 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{1f5}@anchor{gnat_ugn/platform_specific_information id30}@anchor{1fa}
24428 @subsubsection Ada DLLs and Finalization
24431 @geindex DLLs and finalization
24433 When the services of an Ada DLL are no longer needed, the client code should
24434 invoke the DLL finalization routine, if available. The DLL finalization
24435 routine is in charge of releasing all resources acquired by the DLL. In the
24436 case of the Ada code contained in the DLL, this is achieved by calling
24437 routine @code{adafinal} generated by the GNAT binder
24438 (@ref{7e,,Binding with Non-Ada Main Programs}).
24439 See the body of @code{Finalize_Api} for an
24440 example. As already pointed out the GNAT binder is automatically invoked
24441 during the DLL build process by the @code{gnatdll} tool
24442 (@ref{1ec,,Using gnatdll}).
24444 @node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
24445 @anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{1fb}@anchor{gnat_ugn/platform_specific_information id31}@anchor{1fc}
24446 @subsubsection Creating a Spec for Ada DLLs
24449 To use the services exported by the Ada DLL from another programming
24450 language (e.g., C), you have to translate the specs of the exported Ada
24451 entities in that language. For instance in the case of @code{API.dll},
24452 the corresponding C header file could look like:
24454 @quotation
24456 @example
24457 extern int *_imp__count;
24458 #define count (*_imp__count)
24459 int factorial (int);
24460 @end example
24461 @end quotation
24463 It is important to understand that when building an Ada DLL to be used by
24464 other Ada applications, you need two different specs for the packages
24465 contained in the DLL: one for building the DLL and the other for using
24466 the DLL. This is because the @code{DLL} calling convention is needed to
24467 use a variable defined in a DLL, but when building the DLL, the variable
24468 must have either the @code{Ada} or @code{C} calling convention. As an
24469 example consider a DLL comprising the following package @code{API}:
24471 @quotation
24473 @example
24474 package API is
24475    Count : Integer := 0;
24476    ...
24477    --  Remainder of the package omitted.
24478 end API;
24479 @end example
24480 @end quotation
24482 After producing a DLL containing package @code{API}, the spec that
24483 must be used to import @code{API.Count} from Ada code outside of the
24484 DLL is:
24486 @quotation
24488 @example
24489 package API is
24490    Count : Integer;
24491    pragma Import (DLL, Count);
24492 end API;
24493 @end example
24494 @end quotation
24496 @menu
24497 * Creating the Definition File:: 
24498 * Using gnatdll:: 
24500 @end menu
24502 @node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
24503 @anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{1f8}@anchor{gnat_ugn/platform_specific_information id32}@anchor{1fd}
24504 @subsubsection Creating the Definition File
24507 The definition file is the last file needed to build the DLL. It lists
24508 the exported symbols. As an example, the definition file for a DLL
24509 containing only package @code{API} (where all the entities are exported
24510 with a @code{C} calling convention) is:
24512 @quotation
24514 @example
24515 EXPORTS
24516     count
24517     factorial
24518     finalize_api
24519     initialize_api
24520 @end example
24521 @end quotation
24523 If the @code{C} calling convention is missing from package @code{API},
24524 then the definition file contains the mangled Ada names of the above
24525 entities, which in this case are:
24527 @quotation
24529 @example
24530 EXPORTS
24531     api__count
24532     api__factorial
24533     api__finalize_api
24534     api__initialize_api
24535 @end example
24536 @end quotation
24538 @node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
24539 @anchor{gnat_ugn/platform_specific_information id33}@anchor{1fe}@anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{1ec}
24540 @subsubsection Using @code{gnatdll}
24543 @geindex gnatdll
24545 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
24546 and non-Ada sources that make up your DLL have been compiled.
24547 @code{gnatdll} is actually in charge of two distinct tasks: build the
24548 static import library for the DLL and the actual DLL. The form of the
24549 @code{gnatdll} command is
24551 @quotation
24553 @example
24554 $ gnatdll [ switches ] list-of-files [ -largs opts ]
24555 @end example
24556 @end quotation
24558 where @code{list-of-files} is a list of ALI and object files. The object
24559 file list must be the exact list of objects corresponding to the non-Ada
24560 sources whose services are to be included in the DLL. The ALI file list
24561 must be the exact list of ALI files for the corresponding Ada sources
24562 whose services are to be included in the DLL. If @code{list-of-files} is
24563 missing, only the static import library is generated.
24565 You may specify any of the following switches to @code{gnatdll}:
24567 @quotation
24569 @geindex -a (gnatdll)
24570 @end quotation
24573 @table @asis
24575 @item @code{-a[`address']}
24577 Build a non-relocatable DLL at @code{address}. If @code{address} is not
24578 specified the default address @code{0x11000000} will be used. By default,
24579 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
24580 advise the reader to build relocatable DLL.
24582 @geindex -b (gnatdll)
24584 @item @code{-b `address'}
24586 Set the relocatable DLL base address. By default the address is
24587 @code{0x11000000}.
24589 @geindex -bargs (gnatdll)
24591 @item @code{-bargs `opts'}
24593 Binder options. Pass @code{opts} to the binder.
24595 @geindex -d (gnatdll)
24597 @item @code{-d `dllfile'}
24599 @code{dllfile} is the name of the DLL. This switch must be present for
24600 @code{gnatdll} to do anything. The name of the generated import library is
24601 obtained algorithmically from @code{dllfile} as shown in the following
24602 example: if @code{dllfile} is @code{xyz.dll}, the import library name is
24603 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
24604 by option @code{-e}) is obtained algorithmically from @code{dllfile}
24605 as shown in the following example:
24606 if @code{dllfile} is @code{xyz.dll}, the definition
24607 file used is @code{xyz.def}.
24609 @geindex -e (gnatdll)
24611 @item @code{-e `deffile'}
24613 @code{deffile} is the name of the definition file.
24615 @geindex -g (gnatdll)
24617 @item @code{-g}
24619 Generate debugging information. This information is stored in the object
24620 file and copied from there to the final DLL file by the linker,
24621 where it can be read by the debugger. You must use the
24622 @code{-g} switch if you plan on using the debugger or the symbolic
24623 stack traceback.
24625 @geindex -h (gnatdll)
24627 @item @code{-h}
24629 Help mode. Displays @code{gnatdll} switch usage information.
24631 @geindex -I (gnatdll)
24633 @item @code{-I`dir'}
24635 Direct @code{gnatdll} to search the @code{dir} directory for source and
24636 object files needed to build the DLL.
24637 (@ref{73,,Search Paths and the Run-Time Library (RTL)}).
24639 @geindex -k (gnatdll)
24641 @item @code{-k}
24643 Removes the @code{@@@var{nn}} suffix from the import library’s exported
24644 names, but keeps them for the link names. You must specify this
24645 option if you want to use a @code{Stdcall} function in a DLL for which
24646 the @code{@@@var{nn}} suffix has been removed. This is the case for most
24647 of the Windows NT DLL for example. This option has no effect when
24648 @code{-n} option is specified.
24650 @geindex -l (gnatdll)
24652 @item @code{-l `file'}
24654 The list of ALI and object files used to build the DLL are listed in
24655 @code{file}, instead of being given in the command line. Each line in
24656 @code{file} contains the name of an ALI or object file.
24658 @geindex -n (gnatdll)
24660 @item @code{-n}
24662 No Import. Do not create the import library.
24664 @geindex -q (gnatdll)
24666 @item @code{-q}
24668 Quiet mode. Do not display unnecessary messages.
24670 @geindex -v (gnatdll)
24672 @item @code{-v}
24674 Verbose mode. Display extra information.
24676 @geindex -largs (gnatdll)
24678 @item @code{-largs `opts'}
24680 Linker options. Pass @code{opts} to the linker.
24681 @end table
24683 @subsubheading @code{gnatdll} Example
24686 As an example the command to build a relocatable DLL from @code{api.adb}
24687 once @code{api.adb} has been compiled and @code{api.def} created is
24689 @quotation
24691 @example
24692 $ gnatdll -d api.dll api.ali
24693 @end example
24694 @end quotation
24696 The above command creates two files: @code{libapi.dll.a} (the import
24697 library) and @code{api.dll} (the actual DLL). If you want to create
24698 only the DLL, just type:
24700 @quotation
24702 @example
24703 $ gnatdll -d api.dll -n api.ali
24704 @end example
24705 @end quotation
24707 Alternatively if you want to create just the import library, type:
24709 @quotation
24711 @example
24712 $ gnatdll -d api.dll
24713 @end example
24714 @end quotation
24716 @subsubheading @code{gnatdll} behind the Scenes
24719 This section details the steps involved in creating a DLL. @code{gnatdll}
24720 does these steps for you. Unless you are interested in understanding what
24721 goes on behind the scenes, you should skip this section.
24723 We use the previous example of a DLL containing the Ada package @code{API},
24724 to illustrate the steps necessary to build a DLL. The starting point is a
24725 set of objects that will make up the DLL and the corresponding ALI
24726 files. In the case of this example this means that @code{api.o} and
24727 @code{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
24728 the following:
24731 @itemize *
24733 @item 
24734 @code{gnatdll} builds the base file (@code{api.base}). A base file gives
24735 the information necessary to generate relocation information for the
24736 DLL.
24738 @example
24739 $ gnatbind -n api
24740 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
24741 @end example
24743 In addition to the base file, the @code{gnatlink} command generates an
24744 output file @code{api.jnk} which can be discarded. The @code{-mdll} switch
24745 asks @code{gnatlink} to generate the routines @code{DllMain} and
24746 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
24747 is loaded into memory.
24749 @item 
24750 @code{gnatdll} uses @code{dlltool} (see @ref{1ff,,Using dlltool}) to build the
24751 export table (@code{api.exp}). The export table contains the relocation
24752 information in a form which can be used during the final link to ensure
24753 that the Windows loader is able to place the DLL anywhere in memory.
24755 @example
24756 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
24757           --output-exp api.exp
24758 @end example
24760 @item 
24761 @code{gnatdll} builds the base file using the new export table. Note that
24762 @code{gnatbind} must be called once again since the binder generated file
24763 has been deleted during the previous call to @code{gnatlink}.
24765 @example
24766 $ gnatbind -n api
24767 $ gnatlink api -o api.jnk api.exp -mdll
24768       -Wl,--base-file,api.base
24769 @end example
24771 @item 
24772 @code{gnatdll} builds the new export table using the new base file and
24773 generates the DLL import library @code{libAPI.dll.a}.
24775 @example
24776 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
24777           --output-exp api.exp --output-lib libAPI.a
24778 @end example
24780 @item 
24781 Finally @code{gnatdll} builds the relocatable DLL using the final export
24782 table.
24784 @example
24785 $ gnatbind -n api
24786 $ gnatlink api api.exp -o api.dll -mdll
24787 @end example
24788 @end itemize
24789 @anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{1ff}
24790 @subsubheading Using @code{dlltool}
24793 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
24794 DLLs and static import libraries. This section summarizes the most
24795 common @code{dlltool} switches. The form of the @code{dlltool} command
24798 @quotation
24800 @example
24801 $ dlltool [`switches`]
24802 @end example
24803 @end quotation
24805 @code{dlltool} switches include:
24807 @geindex --base-file (dlltool)
24810 @table @asis
24812 @item @code{--base-file `basefile'}
24814 Read the base file @code{basefile} generated by the linker. This switch
24815 is used to create a relocatable DLL.
24816 @end table
24818 @geindex --def (dlltool)
24821 @table @asis
24823 @item @code{--def `deffile'}
24825 Read the definition file.
24826 @end table
24828 @geindex --dllname (dlltool)
24831 @table @asis
24833 @item @code{--dllname `name'}
24835 Gives the name of the DLL. This switch is used to embed the name of the
24836 DLL in the static import library generated by @code{dlltool} with switch
24837 @code{--output-lib}.
24838 @end table
24840 @geindex -k (dlltool)
24843 @table @asis
24845 @item @code{-k}
24847 Kill @code{@@@var{nn}} from exported names
24848 (@ref{1d9,,Windows Calling Conventions}
24849 for a discussion about @code{Stdcall}-style symbols).
24850 @end table
24852 @geindex --help (dlltool)
24855 @table @asis
24857 @item @code{--help}
24859 Prints the @code{dlltool} switches with a concise description.
24860 @end table
24862 @geindex --output-exp (dlltool)
24865 @table @asis
24867 @item @code{--output-exp `exportfile'}
24869 Generate an export file @code{exportfile}. The export file contains the
24870 export table (list of symbols in the DLL) and is used to create the DLL.
24871 @end table
24873 @geindex --output-lib (dlltool)
24876 @table @asis
24878 @item @code{--output-lib `libfile'}
24880 Generate a static import library @code{libfile}.
24881 @end table
24883 @geindex -v (dlltool)
24886 @table @asis
24888 @item @code{-v}
24890 Verbose mode.
24891 @end table
24893 @geindex --as (dlltool)
24896 @table @asis
24898 @item @code{--as `assembler-name'}
24900 Use @code{assembler-name} as the assembler. The default is @code{as}.
24901 @end table
24903 @node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
24904 @anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{200}@anchor{gnat_ugn/platform_specific_information id34}@anchor{201}
24905 @subsubsection GNAT and Windows Resources
24908 @geindex Resources
24909 @geindex windows
24911 Resources are an easy way to add Windows specific objects to your
24912 application. The objects that can be added as resources include:
24915 @itemize *
24917 @item 
24918 menus
24920 @item 
24921 accelerators
24923 @item 
24924 dialog boxes
24926 @item 
24927 string tables
24929 @item 
24930 bitmaps
24932 @item 
24933 cursors
24935 @item 
24936 icons
24938 @item 
24939 fonts
24941 @item 
24942 version information
24943 @end itemize
24945 For example, a version information resource can be defined as follow and
24946 embedded into an executable or DLL:
24948 A version information resource can be used to embed information into an
24949 executable or a DLL. These information can be viewed using the file properties
24950 from the Windows Explorer. Here is an example of a version information
24951 resource:
24953 @quotation
24955 @example
24956 1 VERSIONINFO
24957 FILEVERSION     1,0,0,0
24958 PRODUCTVERSION  1,0,0,0
24959 BEGIN
24960   BLOCK "StringFileInfo"
24961   BEGIN
24962     BLOCK "080904E4"
24963     BEGIN
24964       VALUE "CompanyName", "My Company Name"
24965       VALUE "FileDescription", "My application"
24966       VALUE "FileVersion", "1.0"
24967       VALUE "InternalName", "my_app"
24968       VALUE "LegalCopyright", "My Name"
24969       VALUE "OriginalFilename", "my_app.exe"
24970       VALUE "ProductName", "My App"
24971       VALUE "ProductVersion", "1.0"
24972     END
24973   END
24975   BLOCK "VarFileInfo"
24976   BEGIN
24977     VALUE "Translation", 0x809, 1252
24978   END
24980 @end example
24981 @end quotation
24983 The value @code{0809} (langID) is for the U.K English language and
24984 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
24985 multilingual.
24987 This section explains how to build, compile and use resources. Note that this
24988 section does not cover all resource objects, for a complete description see
24989 the corresponding Microsoft documentation.
24991 @menu
24992 * Building Resources:: 
24993 * Compiling Resources:: 
24994 * Using Resources:: 
24996 @end menu
24998 @node Building Resources,Compiling Resources,,GNAT and Windows Resources
24999 @anchor{gnat_ugn/platform_specific_information building-resources}@anchor{202}@anchor{gnat_ugn/platform_specific_information id35}@anchor{203}
25000 @subsubsection Building Resources
25003 @geindex Resources
25004 @geindex building
25006 A resource file is an ASCII file. By convention resource files have an
25007 @code{.rc} extension.
25008 The easiest way to build a resource file is to use Microsoft tools
25009 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
25010 @code{dlgedit.exe} to build dialogs.
25011 It is always possible to build an @code{.rc} file yourself by writing a
25012 resource script.
25014 It is not our objective to explain how to write a resource file. A
25015 complete description of the resource script language can be found in the
25016 Microsoft documentation.
25018 @node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
25019 @anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{204}@anchor{gnat_ugn/platform_specific_information id36}@anchor{205}
25020 @subsubsection Compiling Resources
25023 @geindex rc
25025 @geindex windres
25027 @geindex Resources
25028 @geindex compiling
25030 This section describes how to build a GNAT-compatible (COFF) object file
25031 containing the resources. This is done using the Resource Compiler
25032 @code{windres} as follows:
25034 @quotation
25036 @example
25037 $ windres -i myres.rc -o myres.o
25038 @end example
25039 @end quotation
25041 By default @code{windres} will run @code{gcc} to preprocess the @code{.rc}
25042 file. You can specify an alternate preprocessor (usually named
25043 @code{cpp.exe}) using the @code{windres} @code{--preprocessor}
25044 parameter. A list of all possible options may be obtained by entering
25045 the command @code{windres} @code{--help}.
25047 It is also possible to use the Microsoft resource compiler @code{rc.exe}
25048 to produce a @code{.res} file (binary resource file). See the
25049 corresponding Microsoft documentation for further details. In this case
25050 you need to use @code{windres} to translate the @code{.res} file to a
25051 GNAT-compatible object file as follows:
25053 @quotation
25055 @example
25056 $ windres -i myres.res -o myres.o
25057 @end example
25058 @end quotation
25060 @node Using Resources,,Compiling Resources,GNAT and Windows Resources
25061 @anchor{gnat_ugn/platform_specific_information id37}@anchor{206}@anchor{gnat_ugn/platform_specific_information using-resources}@anchor{207}
25062 @subsubsection Using Resources
25065 @geindex Resources
25066 @geindex using
25068 To include the resource file in your program just add the
25069 GNAT-compatible object file for the resource(s) to the linker
25070 arguments. With @code{gnatmake} this is done by using the @code{-largs}
25071 option:
25073 @quotation
25075 @example
25076 $ gnatmake myprog -largs myres.o
25077 @end example
25078 @end quotation
25080 @node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
25081 @anchor{gnat_ugn/platform_specific_information using-gnat-dll-from-msvs}@anchor{208}@anchor{gnat_ugn/platform_specific_information using-gnat-dlls-from-microsoft-visual-studio-applications}@anchor{209}
25082 @subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
25085 @geindex Microsoft Visual Studio
25086 @geindex use with GNAT DLLs
25088 This section describes a common case of mixed GNAT/Microsoft Visual Studio
25089 application development, where the main program is developed using MSVS, and
25090 is linked with a DLL developed using GNAT. Such a mixed application should
25091 be developed following the general guidelines outlined above; below is the
25092 cookbook-style sequence of steps to follow:
25095 @enumerate 
25097 @item 
25098 First develop and build the GNAT shared library using a library project
25099 (let’s assume the project is @code{mylib.gpr}, producing the library @code{libmylib.dll}):
25100 @end enumerate
25102 @quotation
25104 @example
25105 $ gprbuild -p mylib.gpr
25106 @end example
25107 @end quotation
25110 @enumerate 2
25112 @item 
25113 Produce a .def file for the symbols you need to interface with, either by
25114 hand or automatically with possibly some manual adjustments
25115 (see @ref{1ea,,Creating Definition File Automatically}):
25116 @end enumerate
25118 @quotation
25120 @example
25121 $ dlltool libmylib.dll -z libmylib.def --export-all-symbols
25122 @end example
25123 @end quotation
25126 @enumerate 3
25128 @item 
25129 Make sure that MSVS command-line tools are accessible on the path.
25131 @item 
25132 Create the Microsoft-style import library (see @ref{1ed,,MSVS-Style Import Library}):
25133 @end enumerate
25135 @quotation
25137 @example
25138 $ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
25139 @end example
25140 @end quotation
25142 If you are using a 64-bit toolchain, the above becomes…
25144 @quotation
25146 @example
25147 $ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
25148 @end example
25149 @end quotation
25152 @enumerate 5
25154 @item 
25155 Build the C main
25156 @end enumerate
25158 @quotation
25160 @example
25161 $ cl /O2 /MD main.c libmylib.lib
25162 @end example
25163 @end quotation
25166 @enumerate 6
25168 @item 
25169 Before running the executable, make sure you have set the PATH to the DLL,
25170 or copy the DLL into into the directory containing the .exe.
25171 @end enumerate
25173 @node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
25174 @anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{20a}@anchor{gnat_ugn/platform_specific_information id38}@anchor{20b}
25175 @subsubsection Debugging a DLL
25178 @geindex DLL debugging
25180 Debugging a DLL is similar to debugging a standard program. But
25181 we have to deal with two different executable parts: the DLL and the
25182 program that uses it. We have the following four possibilities:
25185 @itemize *
25187 @item 
25188 The program and the DLL are built with GCC/GNAT.
25190 @item 
25191 The program is built with foreign tools and the DLL is built with
25192 GCC/GNAT.
25194 @item 
25195 The program is built with GCC/GNAT and the DLL is built with
25196 foreign tools.
25197 @end itemize
25199 In this section we address only cases one and two above.
25200 There is no point in trying to debug
25201 a DLL with GNU/GDB, if there is no GDB-compatible debugging
25202 information in it. To do so you must use a debugger compatible with the
25203 tools suite used to build the DLL.
25205 @menu
25206 * Program and DLL Both Built with GCC/GNAT:: 
25207 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
25209 @end menu
25211 @node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
25212 @anchor{gnat_ugn/platform_specific_information id39}@anchor{20c}@anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{20d}
25213 @subsubsection Program and DLL Both Built with GCC/GNAT
25216 This is the simplest case. Both the DLL and the program have @code{GDB}
25217 compatible debugging information. It is then possible to break anywhere in
25218 the process. Let’s suppose here that the main procedure is named
25219 @code{ada_main} and that in the DLL there is an entry point named
25220 @code{ada_dll}.
25222 The DLL (@ref{1e3,,Introduction to Dynamic Link Libraries (DLLs)}) and
25223 program must have been built with the debugging information (see GNAT -g
25224 switch). Here are the step-by-step instructions for debugging it:
25227 @itemize *
25229 @item 
25230 Launch @code{GDB} on the main program.
25232 @example
25233 $ gdb -nw ada_main
25234 @end example
25236 @item 
25237 Start the program and stop at the beginning of the main procedure
25239 @example
25240 (gdb) start
25241 @end example
25243 This step is required to be able to set a breakpoint inside the DLL. As long
25244 as the program is not run, the DLL is not loaded. This has the
25245 consequence that the DLL debugging information is also not loaded, so it is not
25246 possible to set a breakpoint in the DLL.
25248 @item 
25249 Set a breakpoint inside the DLL
25251 @example
25252 (gdb) break ada_dll
25253 (gdb) cont
25254 @end example
25255 @end itemize
25257 At this stage a breakpoint is set inside the DLL. From there on
25258 you can use the standard approach to debug the whole program
25259 (@ref{150,,Running and Debugging Ada Programs}).
25261 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
25262 @anchor{gnat_ugn/platform_specific_information id40}@anchor{20e}@anchor{gnat_ugn/platform_specific_information program-built-with-foreign-tools-and-dll-built-with-gcc-gnat}@anchor{20f}
25263 @subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
25266 In this case things are slightly more complex because it is not possible to
25267 start the main program and then break at the beginning to load the DLL and the
25268 associated DLL debugging information. It is not possible to break at the
25269 beginning of the program because there is no @code{GDB} debugging information,
25270 and therefore there is no direct way of getting initial control. This
25271 section addresses this issue by describing some methods that can be used
25272 to break somewhere in the DLL to debug it.
25274 First suppose that the main procedure is named @code{main} (this is for
25275 example some C code built with Microsoft Visual C) and that there is a
25276 DLL named @code{test.dll} containing an Ada entry point named
25277 @code{ada_dll}.
25279 The DLL (see @ref{1e3,,Introduction to Dynamic Link Libraries (DLLs)}) must have
25280 been built with debugging information (see the GNAT @code{-g} option).
25282 @subsubheading Debugging the DLL Directly
25286 @itemize *
25288 @item 
25289 Find out the executable starting address
25291 @example
25292 $ objdump --file-header main.exe
25293 @end example
25295 The starting address is reported on the last line. For example:
25297 @example
25298 main.exe:     file format pei-i386
25299 architecture: i386, flags 0x0000010a:
25300 EXEC_P, HAS_DEBUG, D_PAGED
25301 start address 0x00401010
25302 @end example
25304 @item 
25305 Launch the debugger on the executable.
25307 @example
25308 $ gdb main.exe
25309 @end example
25311 @item 
25312 Set a breakpoint at the starting address, and launch the program.
25314 @example
25315 $ (gdb) break *0x00401010
25316 $ (gdb) run
25317 @end example
25319 The program will stop at the given address.
25321 @item 
25322 Set a breakpoint on a DLL subroutine.
25324 @example
25325 (gdb) break ada_dll.adb:45
25326 @end example
25328 Or if you want to break using a symbol on the DLL, you need first to
25329 select the Ada language (language used by the DLL).
25331 @example
25332 (gdb) set language ada
25333 (gdb) break ada_dll
25334 @end example
25336 @item 
25337 Continue the program.
25339 @example
25340 (gdb) cont
25341 @end example
25343 This will run the program until it reaches the breakpoint that has been
25344 set. From that point you can use the standard way to debug a program
25345 as described in (@ref{150,,Running and Debugging Ada Programs}).
25346 @end itemize
25348 It is also possible to debug the DLL by attaching to a running process.
25350 @subsubheading Attaching to a Running Process
25353 @geindex DLL debugging
25354 @geindex attach to process
25356 With @code{GDB} it is always possible to debug a running process by
25357 attaching to it. It is possible to debug a DLL this way. The limitation
25358 of this approach is that the DLL must run long enough to perform the
25359 attach operation. It may be useful for instance to insert a time wasting
25360 loop in the code of the DLL to meet this criterion.
25363 @itemize *
25365 @item 
25366 Launch the main program @code{main.exe}.
25368 @example
25369 $ main
25370 @end example
25372 @item 
25373 Use the Windows `Task Manager' to find the process ID. Let’s say
25374 that the process PID for @code{main.exe} is 208.
25376 @item 
25377 Launch gdb.
25379 @example
25380 $ gdb
25381 @end example
25383 @item 
25384 Attach to the running process to be debugged.
25386 @example
25387 (gdb) attach 208
25388 @end example
25390 @item 
25391 Load the process debugging information.
25393 @example
25394 (gdb) symbol-file main.exe
25395 @end example
25397 @item 
25398 Break somewhere in the DLL.
25400 @example
25401 (gdb) break ada_dll
25402 @end example
25404 @item 
25405 Continue process execution.
25407 @example
25408 (gdb) cont
25409 @end example
25410 @end itemize
25412 This last step will resume the process execution, and stop at
25413 the breakpoint we have set. From there you can use the standard
25414 approach to debug a program as described in
25415 @ref{150,,Running and Debugging Ada Programs}.
25417 @node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
25418 @anchor{gnat_ugn/platform_specific_information id41}@anchor{210}@anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{12a}
25419 @subsubsection Setting Stack Size from @code{gnatlink}
25422 It is possible to specify the program stack size at link time. On modern
25423 versions of Windows, starting with XP, this is mostly useful to set the size of
25424 the main stack (environment task). The other task stacks are set with pragma
25425 Storage_Size or with the `gnatbind -d' command.
25427 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
25428 reserve size of individual tasks, the link-time stack size applies to all
25429 tasks, and pragma Storage_Size has no effect.
25430 In particular, Stack Overflow checks are made against this
25431 link-time specified size.
25433 This setting can be done with @code{gnatlink} using either of the following:
25436 @itemize *
25438 @item 
25439 @code{-Xlinker} linker option
25441 @example
25442 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
25443 @end example
25445 This sets the stack reserve size to 0x10000 bytes and the stack commit
25446 size to 0x1000 bytes.
25448 @item 
25449 @code{-Wl} linker option
25451 @example
25452 $ gnatlink hello -Wl,--stack=0x1000000
25453 @end example
25455 This sets the stack reserve size to 0x1000000 bytes. Note that with
25456 @code{-Wl} option it is not possible to set the stack commit size
25457 because the comma is a separator for this option.
25458 @end itemize
25460 @node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
25461 @anchor{gnat_ugn/platform_specific_information id42}@anchor{211}@anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{12b}
25462 @subsubsection Setting Heap Size from @code{gnatlink}
25465 Under Windows systems, it is possible to specify the program heap size from
25466 @code{gnatlink} using either of the following:
25469 @itemize *
25471 @item 
25472 @code{-Xlinker} linker option
25474 @example
25475 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
25476 @end example
25478 This sets the heap reserve size to 0x10000 bytes and the heap commit
25479 size to 0x1000 bytes.
25481 @item 
25482 @code{-Wl} linker option
25484 @example
25485 $ gnatlink hello -Wl,--heap=0x1000000
25486 @end example
25488 This sets the heap reserve size to 0x1000000 bytes. Note that with
25489 @code{-Wl} option it is not possible to set the heap commit size
25490 because the comma is a separator for this option.
25491 @end itemize
25493 @node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
25494 @anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{212}@anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{213}
25495 @subsection Windows Specific Add-Ons
25498 This section describes the Windows specific add-ons.
25500 @menu
25501 * Win32Ada:: 
25502 * wPOSIX:: 
25504 @end menu
25506 @node Win32Ada,wPOSIX,,Windows Specific Add-Ons
25507 @anchor{gnat_ugn/platform_specific_information id43}@anchor{214}@anchor{gnat_ugn/platform_specific_information win32ada}@anchor{215}
25508 @subsubsection Win32Ada
25511 Win32Ada is a binding for the Microsoft Win32 API. This binding can be
25512 easily installed from the provided installer. To use the Win32Ada
25513 binding you need to use a project file, and adding a single with_clause
25514 will give you full access to the Win32Ada binding sources and ensure
25515 that the proper libraries are passed to the linker.
25517 @quotation
25519 @example
25520 with "win32ada";
25521 project P is
25522    for Sources use ...;
25523 end P;
25524 @end example
25525 @end quotation
25527 To build the application you just need to call gprbuild for the
25528 application’s project, here p.gpr:
25530 @quotation
25532 @example
25533 gprbuild p.gpr
25534 @end example
25535 @end quotation
25537 @node wPOSIX,,Win32Ada,Windows Specific Add-Ons
25538 @anchor{gnat_ugn/platform_specific_information id44}@anchor{216}@anchor{gnat_ugn/platform_specific_information wposix}@anchor{217}
25539 @subsubsection wPOSIX
25542 wPOSIX is a minimal POSIX binding whose goal is to help with building
25543 cross-platforms applications. This binding is not complete though, as
25544 the Win32 API does not provide the necessary support for all POSIX APIs.
25546 To use the wPOSIX binding you need to use a project file, and adding
25547 a single with_clause will give you full access to the wPOSIX binding
25548 sources and ensure that the proper libraries are passed to the linker.
25550 @quotation
25552 @example
25553 with "wposix";
25554 project P is
25555    for Sources use ...;
25556 end P;
25557 @end example
25558 @end quotation
25560 To build the application you just need to call gprbuild for the
25561 application’s project, here p.gpr:
25563 @quotation
25565 @example
25566 gprbuild p.gpr
25567 @end example
25568 @end quotation
25570 @node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
25571 @anchor{gnat_ugn/platform_specific_information id45}@anchor{218}@anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{219}
25572 @section Mac OS Topics
25575 @geindex OS X
25577 This section describes topics that are specific to Apple’s OS X
25578 platform.
25580 @menu
25581 * Codesigning the Debugger:: 
25583 @end menu
25585 @node Codesigning the Debugger,,,Mac OS Topics
25586 @anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{21a}
25587 @subsection Codesigning the Debugger
25590 The Darwin Kernel requires the debugger to have special permissions
25591 before it is allowed to control other processes. These permissions
25592 are granted by codesigning the GDB executable. Without these
25593 permissions, the debugger will report error messages such as:
25595 @example
25596 Starting program: /x/y/foo
25597 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
25598 (please check gdb is codesigned - see taskgated(8))
25599 @end example
25601 Codesigning requires a certificate.  The following procedure explains
25602 how to create one:
25605 @itemize *
25607 @item 
25608 Start the Keychain Access application (in
25609 /Applications/Utilities/Keychain Access.app)
25611 @item 
25612 Select the Keychain Access -> Certificate Assistant ->
25613 Create a Certificate… menu
25615 @item 
25616 Then:
25619 @itemize *
25621 @item 
25622 Choose a name for the new certificate (this procedure will use
25623 “gdb-cert” as an example)
25625 @item 
25626 Set “Identity Type” to “Self Signed Root”
25628 @item 
25629 Set “Certificate Type” to “Code Signing”
25631 @item 
25632 Activate the “Let me override defaults” option
25633 @end itemize
25635 @item 
25636 Click several times on “Continue” until the “Specify a Location
25637 For The Certificate” screen appears, then set “Keychain” to “System”
25639 @item 
25640 Click on “Continue” until the certificate is created
25642 @item 
25643 Finally, in the view, double-click on the new certificate,
25644 and set “When using this certificate” to “Always Trust”
25646 @item 
25647 Exit the Keychain Access application and restart the computer
25648 (this is unfortunately required)
25649 @end itemize
25651 Once a certificate has been created, the debugger can be codesigned
25652 as follow. In a Terminal, run the following command:
25654 @quotation
25656 @example
25657 $ codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
25658 @end example
25659 @end quotation
25661 where “gdb-cert” should be replaced by the actual certificate
25662 name chosen above, and <gnat_install_prefix> should be replaced by
25663 the location where you installed GNAT.  Also, be sure that users are
25664 in the Unix group @code{_developer}.
25666 @node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
25667 @anchor{gnat_ugn/example_of_binder_output doc}@anchor{21b}@anchor{gnat_ugn/example_of_binder_output example-of-binder-output-file}@anchor{e}@anchor{gnat_ugn/example_of_binder_output id1}@anchor{21c}
25668 @chapter Example of Binder Output File
25671 @geindex Binder output (example)
25673 This Appendix displays the source code for the output file
25674 generated by `gnatbind' for a simple ‘Hello World’ program.
25675 Comments have been added for clarification purposes.
25677 @example
25678 --  The package is called Ada_Main unless this name is actually used
25679 --  as a unit name in the partition, in which case some other unique
25680 --  name is used.
25682 pragma Ada_95;
25683 with System;
25684 package ada_main is
25685    pragma Warnings (Off);
25687    --  The main program saves the parameters (argument count,
25688    --  argument values, environment pointer) in global variables
25689    --  for later access by other units including
25690    --  Ada.Command_Line.
25692    gnat_argc : Integer;
25693    gnat_argv : System.Address;
25694    gnat_envp : System.Address;
25696    --  The actual variables are stored in a library routine. This
25697    --  is useful for some shared library situations, where there
25698    --  are problems if variables are not in the library.
25700    pragma Import (C, gnat_argc);
25701    pragma Import (C, gnat_argv);
25702    pragma Import (C, gnat_envp);
25704    --  The exit status is similarly an external location
25706    gnat_exit_status : Integer;
25707    pragma Import (C, gnat_exit_status);
25709    GNAT_Version : constant String :=
25710                     "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
25711    pragma Export (C, GNAT_Version, "__gnat_version");
25713    Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
25714    pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
25716    --  This is the generated adainit routine that performs
25717    --  initialization at the start of execution. In the case
25718    --  where Ada is the main program, this main program makes
25719    --  a call to adainit at program startup.
25721    procedure adainit;
25722    pragma Export (C, adainit, "adainit");
25724    --  This is the generated adafinal routine that performs
25725    --  finalization at the end of execution. In the case where
25726    --  Ada is the main program, this main program makes a call
25727    --  to adafinal at program termination.
25729    procedure adafinal;
25730    pragma Export (C, adafinal, "adafinal");
25732    --  This routine is called at the start of execution. It is
25733    --  a dummy routine that is used by the debugger to breakpoint
25734    --  at the start of execution.
25736    --  This is the actual generated main program (it would be
25737    --  suppressed if the no main program switch were used). As
25738    --  required by standard system conventions, this program has
25739    --  the external name main.
25741    function main
25742      (argc : Integer;
25743       argv : System.Address;
25744       envp : System.Address)
25745       return Integer;
25746    pragma Export (C, main, "main");
25748    --  The following set of constants give the version
25749    --  identification values for every unit in the bound
25750    --  partition. This identification is computed from all
25751    --  dependent semantic units, and corresponds to the
25752    --  string that would be returned by use of the
25753    --  Body_Version or Version attributes.
25755    --  The following Export pragmas export the version numbers
25756    --  with symbolic names ending in B (for body) or S
25757    --  (for spec) so that they can be located in a link. The
25758    --  information provided here is sufficient to track down
25759    --  the exact versions of units used in a given build.
25761    type Version_32 is mod 2 ** 32;
25762    u00001 : constant Version_32 := 16#8ad6e54a#;
25763    pragma Export (C, u00001, "helloB");
25764    u00002 : constant Version_32 := 16#fbff4c67#;
25765    pragma Export (C, u00002, "system__standard_libraryB");
25766    u00003 : constant Version_32 := 16#1ec6fd90#;
25767    pragma Export (C, u00003, "system__standard_libraryS");
25768    u00004 : constant Version_32 := 16#3ffc8e18#;
25769    pragma Export (C, u00004, "adaS");
25770    u00005 : constant Version_32 := 16#28f088c2#;
25771    pragma Export (C, u00005, "ada__text_ioB");
25772    u00006 : constant Version_32 := 16#f372c8ac#;
25773    pragma Export (C, u00006, "ada__text_ioS");
25774    u00007 : constant Version_32 := 16#2c143749#;
25775    pragma Export (C, u00007, "ada__exceptionsB");
25776    u00008 : constant Version_32 := 16#f4f0cce8#;
25777    pragma Export (C, u00008, "ada__exceptionsS");
25778    u00009 : constant Version_32 := 16#a46739c0#;
25779    pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
25780    u00010 : constant Version_32 := 16#3aac8c92#;
25781    pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
25782    u00011 : constant Version_32 := 16#1d274481#;
25783    pragma Export (C, u00011, "systemS");
25784    u00012 : constant Version_32 := 16#a207fefe#;
25785    pragma Export (C, u00012, "system__soft_linksB");
25786    u00013 : constant Version_32 := 16#467d9556#;
25787    pragma Export (C, u00013, "system__soft_linksS");
25788    u00014 : constant Version_32 := 16#b01dad17#;
25789    pragma Export (C, u00014, "system__parametersB");
25790    u00015 : constant Version_32 := 16#630d49fe#;
25791    pragma Export (C, u00015, "system__parametersS");
25792    u00016 : constant Version_32 := 16#b19b6653#;
25793    pragma Export (C, u00016, "system__secondary_stackB");
25794    u00017 : constant Version_32 := 16#b6468be8#;
25795    pragma Export (C, u00017, "system__secondary_stackS");
25796    u00018 : constant Version_32 := 16#39a03df9#;
25797    pragma Export (C, u00018, "system__storage_elementsB");
25798    u00019 : constant Version_32 := 16#30e40e85#;
25799    pragma Export (C, u00019, "system__storage_elementsS");
25800    u00020 : constant Version_32 := 16#41837d1e#;
25801    pragma Export (C, u00020, "system__stack_checkingB");
25802    u00021 : constant Version_32 := 16#93982f69#;
25803    pragma Export (C, u00021, "system__stack_checkingS");
25804    u00022 : constant Version_32 := 16#393398c1#;
25805    pragma Export (C, u00022, "system__exception_tableB");
25806    u00023 : constant Version_32 := 16#b33e2294#;
25807    pragma Export (C, u00023, "system__exception_tableS");
25808    u00024 : constant Version_32 := 16#ce4af020#;
25809    pragma Export (C, u00024, "system__exceptionsB");
25810    u00025 : constant Version_32 := 16#75442977#;
25811    pragma Export (C, u00025, "system__exceptionsS");
25812    u00026 : constant Version_32 := 16#37d758f1#;
25813    pragma Export (C, u00026, "system__exceptions__machineS");
25814    u00027 : constant Version_32 := 16#b895431d#;
25815    pragma Export (C, u00027, "system__exceptions_debugB");
25816    u00028 : constant Version_32 := 16#aec55d3f#;
25817    pragma Export (C, u00028, "system__exceptions_debugS");
25818    u00029 : constant Version_32 := 16#570325c8#;
25819    pragma Export (C, u00029, "system__img_intB");
25820    u00030 : constant Version_32 := 16#1ffca443#;
25821    pragma Export (C, u00030, "system__img_intS");
25822    u00031 : constant Version_32 := 16#b98c3e16#;
25823    pragma Export (C, u00031, "system__tracebackB");
25824    u00032 : constant Version_32 := 16#831a9d5a#;
25825    pragma Export (C, u00032, "system__tracebackS");
25826    u00033 : constant Version_32 := 16#9ed49525#;
25827    pragma Export (C, u00033, "system__traceback_entriesB");
25828    u00034 : constant Version_32 := 16#1d7cb2f1#;
25829    pragma Export (C, u00034, "system__traceback_entriesS");
25830    u00035 : constant Version_32 := 16#8c33a517#;
25831    pragma Export (C, u00035, "system__wch_conB");
25832    u00036 : constant Version_32 := 16#065a6653#;
25833    pragma Export (C, u00036, "system__wch_conS");
25834    u00037 : constant Version_32 := 16#9721e840#;
25835    pragma Export (C, u00037, "system__wch_stwB");
25836    u00038 : constant Version_32 := 16#2b4b4a52#;
25837    pragma Export (C, u00038, "system__wch_stwS");
25838    u00039 : constant Version_32 := 16#92b797cb#;
25839    pragma Export (C, u00039, "system__wch_cnvB");
25840    u00040 : constant Version_32 := 16#09eddca0#;
25841    pragma Export (C, u00040, "system__wch_cnvS");
25842    u00041 : constant Version_32 := 16#6033a23f#;
25843    pragma Export (C, u00041, "interfacesS");
25844    u00042 : constant Version_32 := 16#ece6fdb6#;
25845    pragma Export (C, u00042, "system__wch_jisB");
25846    u00043 : constant Version_32 := 16#899dc581#;
25847    pragma Export (C, u00043, "system__wch_jisS");
25848    u00044 : constant Version_32 := 16#10558b11#;
25849    pragma Export (C, u00044, "ada__streamsB");
25850    u00045 : constant Version_32 := 16#2e6701ab#;
25851    pragma Export (C, u00045, "ada__streamsS");
25852    u00046 : constant Version_32 := 16#db5c917c#;
25853    pragma Export (C, u00046, "ada__io_exceptionsS");
25854    u00047 : constant Version_32 := 16#12c8cd7d#;
25855    pragma Export (C, u00047, "ada__tagsB");
25856    u00048 : constant Version_32 := 16#ce72c228#;
25857    pragma Export (C, u00048, "ada__tagsS");
25858    u00049 : constant Version_32 := 16#c3335bfd#;
25859    pragma Export (C, u00049, "system__htableB");
25860    u00050 : constant Version_32 := 16#99e5f76b#;
25861    pragma Export (C, u00050, "system__htableS");
25862    u00051 : constant Version_32 := 16#089f5cd0#;
25863    pragma Export (C, u00051, "system__string_hashB");
25864    u00052 : constant Version_32 := 16#3bbb9c15#;
25865    pragma Export (C, u00052, "system__string_hashS");
25866    u00053 : constant Version_32 := 16#807fe041#;
25867    pragma Export (C, u00053, "system__unsigned_typesS");
25868    u00054 : constant Version_32 := 16#d27be59e#;
25869    pragma Export (C, u00054, "system__val_lluB");
25870    u00055 : constant Version_32 := 16#fa8db733#;
25871    pragma Export (C, u00055, "system__val_lluS");
25872    u00056 : constant Version_32 := 16#27b600b2#;
25873    pragma Export (C, u00056, "system__val_utilB");
25874    u00057 : constant Version_32 := 16#b187f27f#;
25875    pragma Export (C, u00057, "system__val_utilS");
25876    u00058 : constant Version_32 := 16#d1060688#;
25877    pragma Export (C, u00058, "system__case_utilB");
25878    u00059 : constant Version_32 := 16#392e2d56#;
25879    pragma Export (C, u00059, "system__case_utilS");
25880    u00060 : constant Version_32 := 16#84a27f0d#;
25881    pragma Export (C, u00060, "interfaces__c_streamsB");
25882    u00061 : constant Version_32 := 16#8bb5f2c0#;
25883    pragma Export (C, u00061, "interfaces__c_streamsS");
25884    u00062 : constant Version_32 := 16#6db6928f#;
25885    pragma Export (C, u00062, "system__crtlS");
25886    u00063 : constant Version_32 := 16#4e6a342b#;
25887    pragma Export (C, u00063, "system__file_ioB");
25888    u00064 : constant Version_32 := 16#ba56a5e4#;
25889    pragma Export (C, u00064, "system__file_ioS");
25890    u00065 : constant Version_32 := 16#b7ab275c#;
25891    pragma Export (C, u00065, "ada__finalizationB");
25892    u00066 : constant Version_32 := 16#19f764ca#;
25893    pragma Export (C, u00066, "ada__finalizationS");
25894    u00067 : constant Version_32 := 16#95817ed8#;
25895    pragma Export (C, u00067, "system__finalization_rootB");
25896    u00068 : constant Version_32 := 16#52d53711#;
25897    pragma Export (C, u00068, "system__finalization_rootS");
25898    u00069 : constant Version_32 := 16#769e25e6#;
25899    pragma Export (C, u00069, "interfaces__cB");
25900    u00070 : constant Version_32 := 16#4a38bedb#;
25901    pragma Export (C, u00070, "interfaces__cS");
25902    u00071 : constant Version_32 := 16#07e6ee66#;
25903    pragma Export (C, u00071, "system__os_libB");
25904    u00072 : constant Version_32 := 16#d7b69782#;
25905    pragma Export (C, u00072, "system__os_libS");
25906    u00073 : constant Version_32 := 16#1a817b8e#;
25907    pragma Export (C, u00073, "system__stringsB");
25908    u00074 : constant Version_32 := 16#639855e7#;
25909    pragma Export (C, u00074, "system__stringsS");
25910    u00075 : constant Version_32 := 16#e0b8de29#;
25911    pragma Export (C, u00075, "system__file_control_blockS");
25912    u00076 : constant Version_32 := 16#b5b2aca1#;
25913    pragma Export (C, u00076, "system__finalization_mastersB");
25914    u00077 : constant Version_32 := 16#69316dc1#;
25915    pragma Export (C, u00077, "system__finalization_mastersS");
25916    u00078 : constant Version_32 := 16#57a37a42#;
25917    pragma Export (C, u00078, "system__address_imageB");
25918    u00079 : constant Version_32 := 16#bccbd9bb#;
25919    pragma Export (C, u00079, "system__address_imageS");
25920    u00080 : constant Version_32 := 16#7268f812#;
25921    pragma Export (C, u00080, "system__img_boolB");
25922    u00081 : constant Version_32 := 16#e8fe356a#;
25923    pragma Export (C, u00081, "system__img_boolS");
25924    u00082 : constant Version_32 := 16#d7aac20c#;
25925    pragma Export (C, u00082, "system__ioB");
25926    u00083 : constant Version_32 := 16#8365b3ce#;
25927    pragma Export (C, u00083, "system__ioS");
25928    u00084 : constant Version_32 := 16#6d4d969a#;
25929    pragma Export (C, u00084, "system__storage_poolsB");
25930    u00085 : constant Version_32 := 16#e87cc305#;
25931    pragma Export (C, u00085, "system__storage_poolsS");
25932    u00086 : constant Version_32 := 16#e34550ca#;
25933    pragma Export (C, u00086, "system__pool_globalB");
25934    u00087 : constant Version_32 := 16#c88d2d16#;
25935    pragma Export (C, u00087, "system__pool_globalS");
25936    u00088 : constant Version_32 := 16#9d39c675#;
25937    pragma Export (C, u00088, "system__memoryB");
25938    u00089 : constant Version_32 := 16#445a22b5#;
25939    pragma Export (C, u00089, "system__memoryS");
25940    u00090 : constant Version_32 := 16#6a859064#;
25941    pragma Export (C, u00090, "system__storage_pools__subpoolsB");
25942    u00091 : constant Version_32 := 16#e3b008dc#;
25943    pragma Export (C, u00091, "system__storage_pools__subpoolsS");
25944    u00092 : constant Version_32 := 16#63f11652#;
25945    pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
25946    u00093 : constant Version_32 := 16#fe2f4b3a#;
25947    pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
25949    --  BEGIN ELABORATION ORDER
25950    --  ada%s
25951    --  interfaces%s
25952    --  system%s
25953    --  system.case_util%s
25954    --  system.case_util%b
25955    --  system.htable%s
25956    --  system.img_bool%s
25957    --  system.img_bool%b
25958    --  system.img_int%s
25959    --  system.img_int%b
25960    --  system.io%s
25961    --  system.io%b
25962    --  system.parameters%s
25963    --  system.parameters%b
25964    --  system.crtl%s
25965    --  interfaces.c_streams%s
25966    --  interfaces.c_streams%b
25967    --  system.standard_library%s
25968    --  system.exceptions_debug%s
25969    --  system.exceptions_debug%b
25970    --  system.storage_elements%s
25971    --  system.storage_elements%b
25972    --  system.stack_checking%s
25973    --  system.stack_checking%b
25974    --  system.string_hash%s
25975    --  system.string_hash%b
25976    --  system.htable%b
25977    --  system.strings%s
25978    --  system.strings%b
25979    --  system.os_lib%s
25980    --  system.traceback_entries%s
25981    --  system.traceback_entries%b
25982    --  ada.exceptions%s
25983    --  system.soft_links%s
25984    --  system.unsigned_types%s
25985    --  system.val_llu%s
25986    --  system.val_util%s
25987    --  system.val_util%b
25988    --  system.val_llu%b
25989    --  system.wch_con%s
25990    --  system.wch_con%b
25991    --  system.wch_cnv%s
25992    --  system.wch_jis%s
25993    --  system.wch_jis%b
25994    --  system.wch_cnv%b
25995    --  system.wch_stw%s
25996    --  system.wch_stw%b
25997    --  ada.exceptions.last_chance_handler%s
25998    --  ada.exceptions.last_chance_handler%b
25999    --  system.address_image%s
26000    --  system.exception_table%s
26001    --  system.exception_table%b
26002    --  ada.io_exceptions%s
26003    --  ada.tags%s
26004    --  ada.streams%s
26005    --  ada.streams%b
26006    --  interfaces.c%s
26007    --  system.exceptions%s
26008    --  system.exceptions%b
26009    --  system.exceptions.machine%s
26010    --  system.finalization_root%s
26011    --  system.finalization_root%b
26012    --  ada.finalization%s
26013    --  ada.finalization%b
26014    --  system.storage_pools%s
26015    --  system.storage_pools%b
26016    --  system.finalization_masters%s
26017    --  system.storage_pools.subpools%s
26018    --  system.storage_pools.subpools.finalization%s
26019    --  system.storage_pools.subpools.finalization%b
26020    --  system.memory%s
26021    --  system.memory%b
26022    --  system.standard_library%b
26023    --  system.pool_global%s
26024    --  system.pool_global%b
26025    --  system.file_control_block%s
26026    --  system.file_io%s
26027    --  system.secondary_stack%s
26028    --  system.file_io%b
26029    --  system.storage_pools.subpools%b
26030    --  system.finalization_masters%b
26031    --  interfaces.c%b
26032    --  ada.tags%b
26033    --  system.soft_links%b
26034    --  system.os_lib%b
26035    --  system.secondary_stack%b
26036    --  system.address_image%b
26037    --  system.traceback%s
26038    --  ada.exceptions%b
26039    --  system.traceback%b
26040    --  ada.text_io%s
26041    --  ada.text_io%b
26042    --  hello%b
26043    --  END ELABORATION ORDER
26045 end ada_main;
26046 @end example
26048 @example
26049 pragma Ada_95;
26050 --  The following source file name pragmas allow the generated file
26051 --  names to be unique for different main programs. They are needed
26052 --  since the package name will always be Ada_Main.
26054 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26055 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26057 pragma Suppress (Overflow_Check);
26058 with Ada.Exceptions;
26060 --  Generated package body for Ada_Main starts here
26062 package body ada_main is
26063    pragma Warnings (Off);
26065    --  These values are reference counter associated to units which have
26066    --  been elaborated. It is also used to avoid elaborating the
26067    --  same unit twice.
26069    E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
26070    E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
26071    E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
26072    E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
26073    E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
26074    E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
26075    E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
26076    E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
26077    E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
26078    E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
26079    E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
26080    E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
26081    E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
26082    E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
26083    E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
26084    E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
26085    E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
26086    E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
26088    Local_Priority_Specific_Dispatching : constant String := "";
26089    Local_Interrupt_States : constant String := "";
26091    Is_Elaborated : Boolean := False;
26093    procedure finalize_library is
26094    begin
26095       E06 := E06 - 1;
26096       declare
26097          procedure F1;
26098          pragma Import (Ada, F1, "ada__text_io__finalize_spec");
26099       begin
26100          F1;
26101       end;
26102       E77 := E77 - 1;
26103       E91 := E91 - 1;
26104       declare
26105          procedure F2;
26106          pragma Import (Ada, F2, "system__file_io__finalize_body");
26107       begin
26108          E64 := E64 - 1;
26109          F2;
26110       end;
26111       declare
26112          procedure F3;
26113          pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
26114       begin
26115          E75 := E75 - 1;
26116          F3;
26117       end;
26118       E87 := E87 - 1;
26119       declare
26120          procedure F4;
26121          pragma Import (Ada, F4, "system__pool_global__finalize_spec");
26122       begin
26123          F4;
26124       end;
26125       declare
26126          procedure F5;
26127          pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
26128       begin
26129          F5;
26130       end;
26131       declare
26132          procedure F6;
26133          pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
26134       begin
26135          F6;
26136       end;
26137       declare
26138          procedure Reraise_Library_Exception_If_Any;
26139          pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
26140       begin
26141          Reraise_Library_Exception_If_Any;
26142       end;
26143    end finalize_library;
26145    -------------
26146    -- adainit --
26147    -------------
26149    procedure adainit is
26151       Main_Priority : Integer;
26152       pragma Import (C, Main_Priority, "__gl_main_priority");
26153       Time_Slice_Value : Integer;
26154       pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
26155       WC_Encoding : Character;
26156       pragma Import (C, WC_Encoding, "__gl_wc_encoding");
26157       Locking_Policy : Character;
26158       pragma Import (C, Locking_Policy, "__gl_locking_policy");
26159       Queuing_Policy : Character;
26160       pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
26161       Task_Dispatching_Policy : Character;
26162       pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
26163       Priority_Specific_Dispatching : System.Address;
26164       pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
26165       Num_Specific_Dispatching : Integer;
26166       pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
26167       Main_CPU : Integer;
26168       pragma Import (C, Main_CPU, "__gl_main_cpu");
26169       Interrupt_States : System.Address;
26170       pragma Import (C, Interrupt_States, "__gl_interrupt_states");
26171       Num_Interrupt_States : Integer;
26172       pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
26173       Unreserve_All_Interrupts : Integer;
26174       pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
26175       Detect_Blocking : Integer;
26176       pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
26177       Default_Stack_Size : Integer;
26178       pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
26179       Leap_Seconds_Support : Integer;
26180       pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
26182       procedure Runtime_Initialize;
26183       pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
26185       Finalize_Library_Objects : No_Param_Proc;
26186       pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
26188    --  Start of processing for adainit
26190    begin
26192       --  Record various information for this partition.  The values
26193       --  are derived by the binder from information stored in the ali
26194       --  files by the compiler.
26196       if Is_Elaborated then
26197          return;
26198       end if;
26199       Is_Elaborated := True;
26200       Main_Priority := -1;
26201       Time_Slice_Value := -1;
26202       WC_Encoding := 'b';
26203       Locking_Policy := ' ';
26204       Queuing_Policy := ' ';
26205       Task_Dispatching_Policy := ' ';
26206       Priority_Specific_Dispatching :=
26207         Local_Priority_Specific_Dispatching'Address;
26208       Num_Specific_Dispatching := 0;
26209       Main_CPU := -1;
26210       Interrupt_States := Local_Interrupt_States'Address;
26211       Num_Interrupt_States := 0;
26212       Unreserve_All_Interrupts := 0;
26213       Detect_Blocking := 0;
26214       Default_Stack_Size := -1;
26215       Leap_Seconds_Support := 0;
26217       Runtime_Initialize;
26219       Finalize_Library_Objects := finalize_library'access;
26221       --  Now we have the elaboration calls for all units in the partition.
26222       --  The Elab_Spec and Elab_Body attributes generate references to the
26223       --  implicit elaboration procedures generated by the compiler for
26224       --  each unit that requires elaboration. Increment a counter of
26225       --  reference for each unit.
26227       System.Soft_Links'Elab_Spec;
26228       System.Exception_Table'Elab_Body;
26229       E23 := E23 + 1;
26230       Ada.Io_Exceptions'Elab_Spec;
26231       E46 := E46 + 1;
26232       Ada.Tags'Elab_Spec;
26233       Ada.Streams'Elab_Spec;
26234       E45 := E45 + 1;
26235       Interfaces.C'Elab_Spec;
26236       System.Exceptions'Elab_Spec;
26237       E25 := E25 + 1;
26238       System.Finalization_Root'Elab_Spec;
26239       E68 := E68 + 1;
26240       Ada.Finalization'Elab_Spec;
26241       E66 := E66 + 1;
26242       System.Storage_Pools'Elab_Spec;
26243       E85 := E85 + 1;
26244       System.Finalization_Masters'Elab_Spec;
26245       System.Storage_Pools.Subpools'Elab_Spec;
26246       System.Pool_Global'Elab_Spec;
26247       E87 := E87 + 1;
26248       System.File_Control_Block'Elab_Spec;
26249       E75 := E75 + 1;
26250       System.File_Io'Elab_Body;
26251       E64 := E64 + 1;
26252       E91 := E91 + 1;
26253       System.Finalization_Masters'Elab_Body;
26254       E77 := E77 + 1;
26255       E70 := E70 + 1;
26256       Ada.Tags'Elab_Body;
26257       E48 := E48 + 1;
26258       System.Soft_Links'Elab_Body;
26259       E13 := E13 + 1;
26260       System.Os_Lib'Elab_Body;
26261       E72 := E72 + 1;
26262       System.Secondary_Stack'Elab_Body;
26263       E17 := E17 + 1;
26264       Ada.Text_Io'Elab_Spec;
26265       Ada.Text_Io'Elab_Body;
26266       E06 := E06 + 1;
26267    end adainit;
26269    --------------
26270    -- adafinal --
26271    --------------
26273    procedure adafinal is
26274       procedure s_stalib_adafinal;
26275       pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
26277       procedure Runtime_Finalize;
26278       pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
26280    begin
26281       if not Is_Elaborated then
26282          return;
26283       end if;
26284       Is_Elaborated := False;
26285       Runtime_Finalize;
26286       s_stalib_adafinal;
26287    end adafinal;
26289    --  We get to the main program of the partition by using
26290    --  pragma Import because if we try to with the unit and
26291    --  call it Ada style, then not only do we waste time
26292    --  recompiling it, but also, we don't really know the right
26293    --  switches (e.g.@@: identifier character set) to be used
26294    --  to compile it.
26296    procedure Ada_Main_Program;
26297    pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26299    ----------
26300    -- main --
26301    ----------
26303    --  main is actually a function, as in the ANSI C standard,
26304    --  defined to return the exit status. The three parameters
26305    --  are the argument count, argument values and environment
26306    --  pointer.
26308    function main
26309      (argc : Integer;
26310       argv : System.Address;
26311       envp : System.Address)
26312       return Integer
26313    is
26314       --  The initialize routine performs low level system
26315       --  initialization using a standard library routine which
26316       --  sets up signal handling and performs any other
26317       --  required setup. The routine can be found in file
26318       --  a-init.c.
26320       procedure initialize;
26321       pragma Import (C, initialize, "__gnat_initialize");
26323       --  The finalize routine performs low level system
26324       --  finalization using a standard library routine. The
26325       --  routine is found in file a-final.c and in the standard
26326       --  distribution is a dummy routine that does nothing, so
26327       --  really this is a hook for special user finalization.
26329       procedure finalize;
26330       pragma Import (C, finalize, "__gnat_finalize");
26332       --  The following is to initialize the SEH exceptions
26334       SEH : aliased array (1 .. 2) of Integer;
26336       Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
26337       pragma Volatile (Ensure_Reference);
26339    --  Start of processing for main
26341    begin
26342       --  Save global variables
26344       gnat_argc := argc;
26345       gnat_argv := argv;
26346       gnat_envp := envp;
26348       --  Call low level system initialization
26350       Initialize (SEH'Address);
26352       --  Call our generated Ada initialization routine
26354       adainit;
26356       --  Now we call the main program of the partition
26358       Ada_Main_Program;
26360       --  Perform Ada finalization
26362       adafinal;
26364       --  Perform low level system finalization
26366       Finalize;
26368       --  Return the proper exit status
26369       return (gnat_exit_status);
26370    end;
26372 --  This section is entirely comments, so it has no effect on the
26373 --  compilation of the Ada_Main package. It provides the list of
26374 --  object files and linker options, as well as some standard
26375 --  libraries needed for the link. The gnatlink utility parses
26376 --  this b~hello.adb file to read these comment lines to generate
26377 --  the appropriate command line arguments for the call to the
26378 --  system linker. The BEGIN/END lines are used for sentinels for
26379 --  this parsing operation.
26381 --  The exact file names will of course depend on the environment,
26382 --  host/target and location of files on the host system.
26384 -- BEGIN Object file/option list
26385    --   ./hello.o
26386    --   -L./
26387    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
26388    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
26389 -- END Object file/option list
26391 end ada_main;
26392 @end example
26394 The Ada code in the above example is exactly what is generated by the
26395 binder. We have added comments to more clearly indicate the function
26396 of each part of the generated @code{Ada_Main} package.
26398 The code is standard Ada in all respects, and can be processed by any
26399 tools that handle Ada. In particular, it is possible to use the debugger
26400 in Ada mode to debug the generated @code{Ada_Main} package. For example,
26401 suppose that for reasons that you do not understand, your program is crashing
26402 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
26403 you can place a breakpoint on the call:
26405 @quotation
26407 @example
26408 Ada.Text_Io'Elab_Body;
26409 @end example
26410 @end quotation
26412 and trace the elaboration routine for this package to find out where
26413 the problem might be (more usually of course you would be debugging
26414 elaboration code in your own application).
26416 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
26418 @node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
26419 @anchor{gnat_ugn/elaboration_order_handling_in_gnat doc}@anchor{21d}@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{21e}
26420 @chapter Elaboration Order Handling in GNAT
26423 @geindex Order of elaboration
26425 @geindex Elaboration control
26427 This appendix describes the handling of elaboration code in Ada and GNAT, and
26428 discusses how the order of elaboration of program units can be controlled in
26429 GNAT, either automatically or with explicit programming features.
26431 @menu
26432 * Elaboration Code:: 
26433 * Elaboration Order:: 
26434 * Checking the Elaboration Order:: 
26435 * Controlling the Elaboration Order in Ada:: 
26436 * Controlling the Elaboration Order in GNAT:: 
26437 * Mixing Elaboration Models:: 
26438 * ABE Diagnostics:: 
26439 * SPARK Diagnostics:: 
26440 * Elaboration Circularities:: 
26441 * Resolving Elaboration Circularities:: 
26442 * Elaboration-related Compiler Switches:: 
26443 * Summary of Procedures for Elaboration Control:: 
26444 * Inspecting the Chosen Elaboration Order:: 
26446 @end menu
26448 @node Elaboration Code,Elaboration Order,,Elaboration Order Handling in GNAT
26449 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{21f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{220}
26450 @section Elaboration Code
26453 Ada defines the term `execution' as the process by which a construct achieves
26454 its run-time effect. This process is also referred to as `elaboration' for
26455 declarations and `evaluation' for expressions.
26457 The execution model in Ada allows for certain sections of an Ada program to be
26458 executed prior to execution of the program itself, primarily with the intent of
26459 initializing data. These sections are referred to as `elaboration code'.
26460 Elaboration code is executed as follows:
26463 @itemize *
26465 @item 
26466 All partitions of an Ada program are executed in parallel with one another,
26467 possibly in a separate address space, and possibly on a separate computer.
26469 @item 
26470 The execution of a partition involves running the environment task for that
26471 partition.
26473 @item 
26474 The environment task executes all elaboration code (if available) for all
26475 units within that partition. This code is said to be executed at
26476 `elaboration time'.
26478 @item 
26479 The environment task executes the Ada program (if available) for that
26480 partition.
26481 @end itemize
26483 In addition to the Ada terminology, this appendix defines the following terms:
26486 @itemize *
26488 @item 
26489 `Invocation'
26491 The act of calling a subprogram, instantiating a generic, or activating a
26492 task.
26494 @item 
26495 `Scenario'
26497 A construct that is elaborated or invoked by elaboration code is referred to
26498 as an `elaboration scenario' or simply a `scenario'. GNAT recognizes the
26499 following scenarios:
26502 @itemize -
26504 @item 
26505 @code{'Access} of entries, operators, and subprograms
26507 @item 
26508 Activation of tasks
26510 @item 
26511 Calls to entries, operators, and subprograms
26513 @item 
26514 Instantiations of generic templates
26515 @end itemize
26517 @item 
26518 `Target'
26520 A construct elaborated by a scenario is referred to as `elaboration target'
26521 or simply `target'. GNAT recognizes the following targets:
26524 @itemize -
26526 @item 
26527 For @code{'Access} of entries, operators, and subprograms, the target is the
26528 entry, operator, or subprogram being aliased.
26530 @item 
26531 For activation of tasks, the target is the task body
26533 @item 
26534 For calls to entries, operators, and subprograms, the target is the entry,
26535 operator, or subprogram being invoked.
26537 @item 
26538 For instantiations of generic templates, the target is the generic template
26539 being instantiated.
26540 @end itemize
26541 @end itemize
26543 Elaboration code may appear in two distinct contexts:
26546 @itemize *
26548 @item 
26549 `Library level'
26551 A scenario appears at the library level when it is encapsulated by a package
26552 [body] compilation unit, ignoring any other package [body] declarations in
26553 between.
26555 @example
26556 with Server;
26557 package Client is
26558    procedure Proc;
26560    package Nested is
26561       Val : ... := Server.Func;
26562    end Nested;
26563 end Client;
26564 @end example
26566 In the example above, the call to @code{Server.Func} is an elaboration scenario
26567 because it appears at the library level of package @code{Client}. Note that the
26568 declaration of package @code{Nested} is ignored according to the definition
26569 given above. As a result, the call to @code{Server.Func} will be invoked when
26570 the spec of unit @code{Client} is elaborated.
26572 @item 
26573 `Package body statements'
26575 A scenario appears within the statement sequence of a package body when it is
26576 bounded by the region starting from the @code{begin} keyword of the package body
26577 and ending at the @code{end} keyword of the package body.
26579 @example
26580 package body Client is
26581    procedure Proc is
26582    begin
26583       ...
26584    end Proc;
26585 begin
26586    Proc;
26587 end Client;
26588 @end example
26590 In the example above, the call to @code{Proc} is an elaboration scenario because
26591 it appears within the statement sequence of package body @code{Client}. As a
26592 result, the call to @code{Proc} will be invoked when the body of @code{Client} is
26593 elaborated.
26594 @end itemize
26596 @node Elaboration Order,Checking the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
26597 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order}@anchor{221}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{222}
26598 @section Elaboration Order
26601 The sequence by which the elaboration code of all units within a partition is
26602 executed is referred to as `elaboration order'.
26604 Within a single unit, elaboration code is executed in sequential order.
26606 @quotation
26608 @example
26609 package body Client is
26610    Result : ... := Server.Func;
26612    procedure Proc is
26613       package Inst is new Server.Gen;
26614    begin
26615       Inst.Eval (Result);
26616    end Proc;
26617 begin
26618    Proc;
26619 end Client;
26620 @end example
26621 @end quotation
26623 In the example above, the elaboration order within package body @code{Client} is
26624 as follows:
26627 @enumerate 
26629 @item 
26630 The object declaration of @code{Result} is elaborated.
26633 @itemize *
26635 @item 
26636 Function @code{Server.Func} is invoked.
26637 @end itemize
26639 @item 
26640 The subprogram body of @code{Proc} is elaborated.
26642 @item 
26643 Procedure @code{Proc} is invoked.
26646 @itemize *
26648 @item 
26649 Generic unit @code{Server.Gen} is instantiated as @code{Inst}.
26651 @item 
26652 Instance @code{Inst} is elaborated.
26654 @item 
26655 Procedure @code{Inst.Eval} is invoked.
26656 @end itemize
26657 @end enumerate
26659 The elaboration order of all units within a partition depends on the following
26660 factors:
26663 @itemize *
26665 @item 
26666 `with'ed units
26668 @item 
26669 parent units
26671 @item 
26672 purity of units
26674 @item 
26675 preelaborability of units
26677 @item 
26678 presence of elaboration-control pragmas
26680 @item 
26681 invocations performed in elaboration code
26682 @end itemize
26684 A program may have several elaboration orders depending on its structure.
26686 @quotation
26688 @example
26689 package Server is
26690    function Func (Index : Integer) return Integer;
26691 end Server;
26692 @end example
26694 @example
26695 package body Server is
26696    Results : array (1 .. 5) of Integer := (1, 2, 3, 4, 5);
26698    function Func (Index : Integer) return Integer is
26699    begin
26700       return Results (Index);
26701    end Func;
26702 end Server;
26703 @end example
26705 @example
26706 with Server;
26707 package Client is
26708    Val : constant Integer := Server.Func (3);
26709 end Client;
26710 @end example
26712 @example
26713 with Client;
26714 procedure Main is begin null; end Main;
26715 @end example
26716 @end quotation
26718 The following elaboration order exhibits a fundamental problem referred to as
26719 `access-before-elaboration' or simply `ABE'.
26721 @quotation
26723 @example
26724 spec of Server
26725 spec of Client
26726 body of Server
26727 body of Main
26728 @end example
26729 @end quotation
26731 The elaboration of @code{Server}’s spec materializes function @code{Func}, making it
26732 callable. The elaboration of @code{Client}’s spec elaborates the declaration of
26733 @code{Val}. This invokes function @code{Server.Func}, however the body of
26734 @code{Server.Func} has not been elaborated yet because @code{Server}’s body comes
26735 after @code{Client}’s spec in the elaboration order. As a result, the value of
26736 constant @code{Val} is now undefined.
26738 Without any guarantees from the language, an undetected ABE problem may hinder
26739 proper initialization of data, which in turn may lead to undefined behavior at
26740 run time. To prevent such ABE problems, Ada employs dynamic checks in the same
26741 vein as index or null exclusion checks. A failed ABE check raises exception
26742 @code{Program_Error}.
26744 The following elaboration order avoids the ABE problem and the program can be
26745 successfully elaborated.
26747 @quotation
26749 @example
26750 spec of Server
26751 body of Server
26752 spec of Client
26753 body of Main
26754 @end example
26755 @end quotation
26757 Ada states that a total elaboration order must exist, but it does not define
26758 what this order is. A compiler is thus tasked with choosing a suitable
26759 elaboration order which satisfies the dependencies imposed by `with' clauses,
26760 unit categorization, elaboration-control pragmas, and invocations performed in
26761 elaboration code. Ideally an order that avoids ABE problems should be chosen,
26762 however a compiler may not always find such an order due to complications with
26763 respect to control and data flow.
26765 @node Checking the Elaboration Order,Controlling the Elaboration Order in Ada,Elaboration Order,Elaboration Order Handling in GNAT
26766 @anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{223}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{224}
26767 @section Checking the Elaboration Order
26770 To avoid placing the entire elaboration-order burden on the programmer, Ada
26771 provides three lines of defense:
26774 @itemize *
26776 @item 
26777 `Static semantics'
26779 Static semantic rules restrict the possible choice of elaboration order. For
26780 instance, if unit Client `with's unit Server, then the spec of Server is
26781 always elaborated prior to Client. The same principle applies to child units
26782 - the spec of a parent unit is always elaborated prior to the child unit.
26784 @item 
26785 `Dynamic semantics'
26787 Dynamic checks are performed at run time, to ensure that a target is
26788 elaborated prior to a scenario that invokes it, thus avoiding ABE problems.
26789 A failed run-time check raises exception @code{Program_Error}. The following
26790 restrictions apply:
26793 @itemize -
26795 @item 
26796 `Restrictions on calls'
26798 An entry, operator, or subprogram can be called from elaboration code only
26799 when the corresponding body has been elaborated.
26801 @item 
26802 `Restrictions on instantiations'
26804 A generic unit can be instantiated by elaboration code only when the
26805 corresponding body has been elaborated.
26807 @item 
26808 `Restrictions on task activation'
26810 A task can be activated by elaboration code only when the body of the
26811 associated task type has been elaborated.
26812 @end itemize
26814 The restrictions above can be summarized by the following rule:
26816 `If a target has a body, then this body must be elaborated prior to the
26817 scenario that invokes the target.'
26819 @item 
26820 `Elaboration control'
26822 Pragmas are provided for the programmer to specify the desired elaboration
26823 order.
26824 @end itemize
26826 @node Controlling the Elaboration Order in Ada,Controlling the Elaboration Order in GNAT,Checking the Elaboration Order,Elaboration Order Handling in GNAT
26827 @anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-ada}@anchor{225}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{226}
26828 @section Controlling the Elaboration Order in Ada
26831 Ada provides several idioms and pragmas to aid the programmer with specifying
26832 the desired elaboration order and avoiding ABE problems altogether.
26835 @itemize *
26837 @item 
26838 `Packages without a body'
26840 A library package which does not require a completing body does not suffer
26841 from ABE problems.
26843 @example
26844 package Pack is
26845    generic
26846       type Element is private;
26847    package Containers is
26848       type Element_Array is array (1 .. 10) of Element;
26849    end Containers;
26850 end Pack;
26851 @end example
26853 In the example above, package @code{Pack} does not require a body because it
26854 does not contain any constructs which require completion in a body. As a
26855 result, generic @code{Pack.Containers} can be instantiated without encountering
26856 any ABE problems.
26857 @end itemize
26859 @geindex pragma Pure
26862 @itemize *
26864 @item 
26865 `pragma Pure'
26867 Pragma @code{Pure} places sufficient restrictions on a unit to guarantee that no
26868 scenario within the unit can result in an ABE problem.
26869 @end itemize
26871 @geindex pragma Preelaborate
26874 @itemize *
26876 @item 
26877 `pragma Preelaborate'
26879 Pragma @code{Preelaborate} is slightly less restrictive than pragma @code{Pure},
26880 but still strong enough to prevent ABE problems within a unit.
26881 @end itemize
26883 @geindex pragma Elaborate_Body
26886 @itemize *
26888 @item 
26889 `pragma Elaborate_Body'
26891 Pragma @code{Elaborate_Body} requires that the body of a unit is elaborated
26892 immediately after its spec. This restriction guarantees that no client
26893 scenario can invoke a server target before the target body has been
26894 elaborated because the spec and body are effectively “glued” together.
26896 @example
26897 package Server is
26898    pragma Elaborate_Body;
26900    function Func return Integer;
26901 end Server;
26902 @end example
26904 @example
26905 package body Server is
26906    function Func return Integer is
26907    begin
26908       ...
26909    end Func;
26910 end Server;
26911 @end example
26913 @example
26914 with Server;
26915 package Client is
26916    Val : constant Integer := Server.Func;
26917 end Client;
26918 @end example
26920 In the example above, pragma @code{Elaborate_Body} guarantees the following
26921 elaboration order:
26923 @example
26924 spec of Server
26925 body of Server
26926 spec of Client
26927 @end example
26929 because the spec of @code{Server} must be elaborated prior to @code{Client} by
26930 virtue of the `with' clause, and in addition the body of @code{Server} must be
26931 elaborated immediately after the spec of @code{Server}.
26933 Removing pragma @code{Elaborate_Body} could result in the following incorrect
26934 elaboration order:
26936 @example
26937 spec of Server
26938 spec of Client
26939 body of Server
26940 @end example
26942 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func} has
26943 not been elaborated yet.
26944 @end itemize
26946 The pragmas outlined above allow a server unit to guarantee safe elaboration
26947 use by client units. Thus it is a good rule to mark units as @code{Pure} or
26948 @code{Preelaborate}, and if this is not possible, mark them as @code{Elaborate_Body}.
26950 There are however situations where @code{Pure}, @code{Preelaborate}, and
26951 @code{Elaborate_Body} are not applicable. Ada provides another set of pragmas for
26952 use by client units to help ensure the elaboration safety of server units they
26953 depend on.
26955 @geindex pragma Elaborate (Unit)
26958 @itemize *
26960 @item 
26961 `pragma Elaborate (Unit)'
26963 Pragma @code{Elaborate} can be placed in the context clauses of a unit, after a
26964 `with' clause. It guarantees that both the spec and body of its argument will
26965 be elaborated prior to the unit with the pragma. Note that other unrelated
26966 units may be elaborated in between the spec and the body.
26968 @example
26969 package Server is
26970    function Func return Integer;
26971 end Server;
26972 @end example
26974 @example
26975 package body Server is
26976    function Func return Integer is
26977    begin
26978       ...
26979    end Func;
26980 end Server;
26981 @end example
26983 @example
26984 with Server;
26985 pragma Elaborate (Server);
26986 package Client is
26987    Val : constant Integer := Server.Func;
26988 end Client;
26989 @end example
26991 In the example above, pragma @code{Elaborate} guarantees the following
26992 elaboration order:
26994 @example
26995 spec of Server
26996 body of Server
26997 spec of Client
26998 @end example
27000 Removing pragma @code{Elaborate} could result in the following incorrect
27001 elaboration order:
27003 @example
27004 spec of Server
27005 spec of Client
27006 body of Server
27007 @end example
27009 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func}
27010 has not been elaborated yet.
27011 @end itemize
27013 @geindex pragma Elaborate_All (Unit)
27016 @itemize *
27018 @item 
27019 `pragma Elaborate_All (Unit)'
27021 Pragma @code{Elaborate_All} is placed in the context clauses of a unit, after
27022 a `with' clause. It guarantees that both the spec and body of its argument
27023 will be elaborated prior to the unit with the pragma, as well as all units
27024 `with'ed by the spec and body of the argument, recursively. Note that other
27025 unrelated units may be elaborated in between the spec and the body.
27027 @example
27028 package Math is
27029    function Factorial (Val : Natural) return Natural;
27030 end Math;
27031 @end example
27033 @example
27034 package body Math is
27035    function Factorial (Val : Natural) return Natural is
27036    begin
27037       ...;
27038    end Factorial;
27039 end Math;
27040 @end example
27042 @example
27043 package Computer is
27044    type Operation_Kind is (None, Op_Factorial);
27046    function Compute
27047      (Val : Natural;
27048       Op  : Operation_Kind) return Natural;
27049 end Computer;
27050 @end example
27052 @example
27053 with Math;
27054 package body Computer is
27055    function Compute
27056      (Val : Natural;
27057       Op  : Operation_Kind) return Natural
27058    is
27059       if Op = Op_Factorial then
27060          return Math.Factorial (Val);
27061       end if;
27063       return 0;
27064    end Compute;
27065 end Computer;
27066 @end example
27068 @example
27069 with Computer;
27070 pragma Elaborate_All (Computer);
27071 package Client is
27072    Val : constant Natural :=
27073            Computer.Compute (123, Computer.Op_Factorial);
27074 end Client;
27075 @end example
27077 In the example above, pragma @code{Elaborate_All} can result in the following
27078 elaboration order:
27080 @example
27081 spec of Math
27082 body of Math
27083 spec of Computer
27084 body of Computer
27085 spec of Client
27086 @end example
27088 Note that there are several allowable suborders for the specs and bodies of
27089 @code{Math} and @code{Computer}, but the point is that these specs and bodies will
27090 be elaborated prior to @code{Client}.
27092 Removing pragma @code{Elaborate_All} could result in the following incorrect
27093 elaboration order:
27095 @example
27096 spec of Math
27097 spec of Computer
27098 body of Computer
27099 spec of Client
27100 body of Math
27101 @end example
27103 where @code{Client} invokes @code{Computer.Compute}, which in turn invokes
27104 @code{Math.Factorial}, but the body of @code{Math.Factorial} has not been
27105 elaborated yet.
27106 @end itemize
27108 All pragmas shown above can be summarized by the following rule:
27110 `If a client unit elaborates a server target directly or indirectly, then if
27111 the server unit requires a body and does not have pragma Pure, Preelaborate,
27112 or Elaborate_Body, then the client unit should have pragma Elaborate or
27113 Elaborate_All for the server unit.'
27115 If the rule outlined above is not followed, then a program may fall in one of
27116 the following states:
27119 @itemize *
27121 @item 
27122 `No elaboration order exists'
27124 In this case a compiler must diagnose the situation, and refuse to build an
27125 executable program.
27127 @item 
27128 `One or more incorrect elaboration orders exist'
27130 In this case a compiler can build an executable program, but
27131 @code{Program_Error} will be raised when the program is run.
27133 @item 
27134 `Several elaboration orders exist, some correct, some incorrect'
27136 In this case the programmer has not controlled the elaboration order. As a
27137 result, a compiler may or may not pick one of the correct orders, and the
27138 program may or may not raise @code{Program_Error} when it is run. This is the
27139 worst possible state because the program may fail on another compiler, or
27140 even another version of the same compiler.
27142 @item 
27143 `One or more correct orders exist'
27145 In this case a compiler can build an executable program, and the program is
27146 run successfully. This state may be guaranteed by following the outlined
27147 rules, or may be the result of good program architecture.
27148 @end itemize
27150 Note that one additional advantage of using @code{Elaborate} and @code{Elaborate_All}
27151 is that the program continues to stay in the last state (one or more correct
27152 orders exist) even if maintenance changes the bodies of targets.
27154 @node Controlling the Elaboration Order in GNAT,Mixing Elaboration Models,Controlling the Elaboration Order in Ada,Elaboration Order Handling in GNAT
27155 @anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-gnat}@anchor{227}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{228}
27156 @section Controlling the Elaboration Order in GNAT
27159 In addition to Ada semantics and rules synthesized from them, GNAT offers
27160 three elaboration models to aid the programmer with specifying the correct
27161 elaboration order and to diagnose elaboration problems.
27163 @geindex Dynamic elaboration model
27166 @itemize *
27168 @item 
27169 `Dynamic elaboration model'
27171 This is the most permissive of the three elaboration models and emulates the
27172 behavior specified by the Ada Reference Manual. When the dynamic model is in
27173 effect, GNAT makes the following assumptions:
27176 @itemize -
27178 @item 
27179 All code within all units in a partition is considered to be elaboration
27180 code.
27182 @item 
27183 Some of the invocations in elaboration code may not take place at run time
27184 due to conditional execution.
27185 @end itemize
27187 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
27188 that invoke internal targets. In addition, GNAT generates run-time checks for
27189 all external targets and for all scenarios that may exhibit ABE problems.
27191 The elaboration order is obtained by honoring all `with' clauses, purity and
27192 preelaborability of units, and elaboration-control pragmas. The dynamic model
27193 attempts to take all invocations in elaboration code into account. If an
27194 invocation leads to a circularity, GNAT ignores the invocation based on the
27195 assumptions stated above. An order obtained using the dynamic model may fail
27196 an ABE check at run time when GNAT ignored an invocation.
27198 The dynamic model is enabled with compiler switch @code{-gnatE}.
27199 @end itemize
27201 @geindex Static elaboration model
27204 @itemize *
27206 @item 
27207 `Static elaboration model'
27209 This is the middle ground of the three models. When the static model is in
27210 effect, GNAT makes the following assumptions:
27213 @itemize -
27215 @item 
27216 Only code at the library level and in package body statements within all
27217 units in a partition is considered to be elaboration code.
27219 @item 
27220 All invocations in elaboration will take place at run time, regardless of
27221 conditional execution.
27222 @end itemize
27224 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
27225 that invoke internal targets. In addition, GNAT generates run-time checks for
27226 all external targets and for all scenarios that may exhibit ABE problems.
27228 The elaboration order is obtained by honoring all `with' clauses, purity and
27229 preelaborability of units, presence of elaboration-control pragmas, and all
27230 invocations in elaboration code. An order obtained using the static model is
27231 guaranteed to be ABE problem-free, excluding dispatching calls and
27232 access-to-subprogram types.
27234 The static model is the default model in GNAT.
27235 @end itemize
27237 @geindex SPARK elaboration model
27240 @itemize *
27242 @item 
27243 `SPARK elaboration model'
27245 This is the most conservative of the three models and enforces the SPARK
27246 rules of elaboration as defined in the SPARK Reference Manual, section 7.7.
27247 The SPARK model is in effect only when a scenario and a target reside in a
27248 region subject to @code{SPARK_Mode On}, otherwise the dynamic or static model
27249 is in effect.
27251 The SPARK model is enabled with compiler switch @code{-gnatd.v}.
27252 @end itemize
27254 @geindex Legacy elaboration models
27257 @itemize *
27259 @item 
27260 `Legacy elaboration models'
27262 In addition to the three elaboration models outlined above, GNAT provides the
27263 following legacy models:
27266 @itemize -
27268 @item 
27269 @cite{Legacy elaboration-checking model} available in pre-18.x versions of GNAT.
27270 This model is enabled with compiler switch @code{-gnatH}.
27272 @item 
27273 @cite{Legacy elaboration-order model} available in pre-20.x versions of GNAT.
27274 This model is enabled with binder switch @code{-H}.
27275 @end itemize
27276 @end itemize
27278 @geindex Relaxed elaboration mode
27280 The dynamic, legacy, and static models can be relaxed using compiler switch
27281 @code{-gnatJ}, making them more permissive. Note that in this mode, GNAT
27282 may not diagnose certain elaboration issues or install run-time checks.
27284 @node Mixing Elaboration Models,ABE Diagnostics,Controlling the Elaboration Order in GNAT,Elaboration Order Handling in GNAT
27285 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{229}@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{22a}
27286 @section Mixing Elaboration Models
27289 It is possible to mix units compiled with a different elaboration model,
27290 however the following rules must be observed:
27293 @itemize *
27295 @item 
27296 A client unit compiled with the dynamic model can only `with' a server unit
27297 that meets at least one of the following criteria:
27300 @itemize -
27302 @item 
27303 The server unit is compiled with the dynamic model.
27305 @item 
27306 The server unit is a GNAT implementation unit from the @code{Ada}, @code{GNAT},
27307 @code{Interfaces}, or @code{System} hierarchies.
27309 @item 
27310 The server unit has pragma @code{Pure} or @code{Preelaborate}.
27312 @item 
27313 The client unit has an explicit @code{Elaborate_All} pragma for the server
27314 unit.
27315 @end itemize
27316 @end itemize
27318 These rules ensure that elaboration checks are not omitted. If the rules are
27319 violated, the binder emits a warning:
27321 @quotation
27323 @example
27324 warning: "x.ads" has dynamic elaboration checks and with's
27325 warning:   "y.ads" which has static elaboration checks
27326 @end example
27327 @end quotation
27329 The warnings can be suppressed by binder switch @code{-ws}.
27331 @node ABE Diagnostics,SPARK Diagnostics,Mixing Elaboration Models,Elaboration Order Handling in GNAT
27332 @anchor{gnat_ugn/elaboration_order_handling_in_gnat abe-diagnostics}@anchor{22b}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{22c}
27333 @section ABE Diagnostics
27336 GNAT performs extensive diagnostics on a unit-by-unit basis for all scenarios
27337 that invoke internal targets, regardless of whether the dynamic, SPARK, or
27338 static model is in effect.
27340 Note that GNAT emits warnings rather than hard errors whenever it encounters an
27341 elaboration problem. This is because the elaboration model in effect may be too
27342 conservative, or a particular scenario may not be invoked due conditional
27343 execution. The warnings can be suppressed selectively with @code{pragma Warnings
27344 (Off)} or globally with compiler switch @code{-gnatwL}.
27346 A `guaranteed ABE' arises when the body of a target is not elaborated early
27347 enough, and causes `all' scenarios that directly invoke the target to fail.
27349 @quotation
27351 @example
27352 package body Guaranteed_ABE is
27353    function ABE return Integer;
27355    Val : constant Integer := ABE;
27357    function ABE return Integer is
27358    begin
27359      ...
27360    end ABE;
27361 end Guaranteed_ABE;
27362 @end example
27363 @end quotation
27365 In the example above, the elaboration of @code{Guaranteed_ABE}’s body elaborates
27366 the declaration of @code{Val}. This invokes function @code{ABE}, however the body of
27367 @code{ABE} has not been elaborated yet. GNAT emits the following diagnostic:
27369 @quotation
27371 @example
27372 4.    Val : constant Integer := ABE;
27373                                 |
27374    >>> warning: cannot call "ABE" before body seen
27375    >>> warning: Program_Error will be raised at run time
27376 @end example
27377 @end quotation
27379 A `conditional ABE' arises when the body of a target is not elaborated early
27380 enough, and causes `some' scenarios that directly invoke the target to fail.
27382 @quotation
27384 @example
27385  1. package body Conditional_ABE is
27386  2.    procedure Force_Body is null;
27387  3.
27388  4.    generic
27389  5.       with function Func return Integer;
27390  6.    package Gen is
27391  7.       Val : constant Integer := Func;
27392  8.    end Gen;
27393  9.
27394 10.    function ABE return Integer;
27396 12.    function Cause_ABE return Boolean is
27397 13.       package Inst is new Gen (ABE);
27398 14.    begin
27399 15.       ...
27400 16.    end Cause_ABE;
27402 18.    Val : constant Boolean := Cause_ABE;
27404 20.    function ABE return Integer is
27405 21.    begin
27406 22.       ...
27407 23.    end ABE;
27409 25.    Safe : constant Boolean := Cause_ABE;
27410 26. end Conditional_ABE;
27411 @end example
27412 @end quotation
27414 In the example above, the elaboration of package body @code{Conditional_ABE}
27415 elaborates the declaration of @code{Val}. This invokes function @code{Cause_ABE},
27416 which instantiates generic unit @code{Gen} as @code{Inst}. The elaboration of
27417 @code{Inst} invokes function @code{ABE}, however the body of @code{ABE} has not been
27418 elaborated yet. GNAT emits the following diagnostic:
27420 @quotation
27422 @example
27423 13.       package Inst is new Gen (ABE);
27424           |
27425     >>> warning: in instantiation at line 7
27426     >>> warning: cannot call "ABE" before body seen
27427     >>> warning: Program_Error may be raised at run time
27428     >>> warning:   body of unit "Conditional_ABE" elaborated
27429     >>> warning:   function "Cause_ABE" called at line 18
27430     >>> warning:   function "ABE" called at line 7, instance at line 13
27431 @end example
27432 @end quotation
27434 Note that the same ABE problem does not occur with the elaboration of
27435 declaration @code{Safe} because the body of function @code{ABE} has already been
27436 elaborated at that point.
27438 @node SPARK Diagnostics,Elaboration Circularities,ABE Diagnostics,Elaboration Order Handling in GNAT
27439 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{22d}@anchor{gnat_ugn/elaboration_order_handling_in_gnat spark-diagnostics}@anchor{22e}
27440 @section SPARK Diagnostics
27443 GNAT enforces the SPARK rules of elaboration as defined in the SPARK Reference
27444 Manual section 7.7 when compiler switch @code{-gnatd.v} is in effect. Note
27445 that GNAT emits hard errors whenever it encounters a violation of the SPARK
27446 rules.
27448 @quotation
27450 @example
27451 1. with Server;
27452 2. package body SPARK_Diagnostics with SPARK_Mode is
27453 3.    Val : constant Integer := Server.Func;
27454                                       |
27455    >>> call to "Func" during elaboration in SPARK
27456    >>> unit "SPARK_Diagnostics" requires pragma "Elaborate_All" for "Server"
27457    >>>   body of unit "SPARK_Model" elaborated
27458    >>>   function "Func" called at line 3
27460 4. end SPARK_Diagnostics;
27461 @end example
27462 @end quotation
27464 @node Elaboration Circularities,Resolving Elaboration Circularities,SPARK Diagnostics,Elaboration Order Handling in GNAT
27465 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-circularities}@anchor{22f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{230}
27466 @section Elaboration Circularities
27469 An `elaboration circularity' occurs whenever the elaboration of a set of
27470 units enters a deadlocked state, where each unit is waiting for another unit
27471 to be elaborated. This situation may be the result of improper use of `with'
27472 clauses, elaboration-control pragmas, or invocations in elaboration code.
27474 The following example exhibits an elaboration circularity.
27476 @quotation
27478 @example
27479 with B; pragma Elaborate (B);
27480 package A is
27481 end A;
27482 @end example
27484 @example
27485 package B is
27486    procedure Force_Body;
27487 end B;
27488 @end example
27490 @example
27491 with C;
27492 package body B is
27493    procedure Force_Body is null;
27495    Elab : constant Integer := C.Func;
27496 end B;
27497 @end example
27499 @example
27500 package C is
27501    function Func return Integer;
27502 end C;
27503 @end example
27505 @example
27506 with A;
27507 package body C is
27508    function Func return Integer is
27509    begin
27510       ...
27511    end Func;
27512 end C;
27513 @end example
27514 @end quotation
27516 The binder emits the following diagnostic:
27518 @quotation
27520 @example
27521 error: Elaboration circularity detected
27522 info:
27523 info:    Reason:
27524 info:
27525 info:      unit "a (spec)" depends on its own elaboration
27526 info:
27527 info:    Circularity:
27528 info:
27529 info:      unit "a (spec)" has with clause and pragma Elaborate for unit "b (spec)"
27530 info:      unit "b (body)" is in the closure of pragma Elaborate
27531 info:      unit "b (body)" invokes a construct of unit "c (body)" at elaboration time
27532 info:      unit "c (body)" has with clause for unit "a (spec)"
27533 info:
27534 info:    Suggestions:
27535 info:
27536 info:      remove pragma Elaborate for unit "b (body)" in unit "a (spec)"
27537 info:      use the dynamic elaboration model (compiler switch -gnatE)
27538 @end example
27539 @end quotation
27541 The diagnostic consist of the following sections:
27544 @itemize *
27546 @item 
27547 Reason
27549 This section provides a short explanation describing why the set of units
27550 could not be ordered.
27552 @item 
27553 Circularity
27555 This section enumerates the units comprising the deadlocked set, along with
27556 their interdependencies.
27558 @item 
27559 Suggestions
27561 This section enumerates various tactics for eliminating the circularity.
27562 @end itemize
27564 @node Resolving Elaboration Circularities,Elaboration-related Compiler Switches,Elaboration Circularities,Elaboration Order Handling in GNAT
27565 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{231}@anchor{gnat_ugn/elaboration_order_handling_in_gnat resolving-elaboration-circularities}@anchor{232}
27566 @section Resolving Elaboration Circularities
27569 The most desirable option from the point of view of long-term maintenance is to
27570 rearrange the program so that the elaboration problems are avoided. One useful
27571 technique is to place the elaboration code into separate child packages.
27572 Another is to move some of the initialization code to explicitly invoked
27573 subprograms, where the program controls the order of initialization explicitly.
27574 Although this is the most desirable option, it may be impractical and involve
27575 too much modification, especially in the case of complex legacy code.
27577 When faced with an elaboration circularity, the programmer should also consider
27578 the tactics given in the suggestions section of the circularity diagnostic.
27579 Depending on the units involved in the circularity, their `with' clauses,
27580 purity, preelaborability, presence of elaboration-control pragmas and
27581 invocations at elaboration time, the binder may suggest one or more of the
27582 following tactics to eliminate the circularity:
27585 @itemize *
27587 @item 
27588 Pragma Elaborate elimination
27590 @example
27591 remove pragma Elaborate for unit "..." in unit "..."
27592 @end example
27594 This tactic is suggested when the binder has determined that pragma
27595 @code{Elaborate}:
27598 @itemize -
27600 @item 
27601 Prevents a set of units from being elaborated.
27603 @item 
27604 The removal of the pragma will not eliminate the semantic effects of the
27605 pragma. In other words, the argument of the pragma will still be elaborated
27606 prior to the unit containing the pragma.
27608 @item 
27609 The removal of the pragma will enable the successful ordering of the units.
27610 @end itemize
27612 The programmer should remove the pragma as advised, and rebuild the program.
27614 @item 
27615 Pragma Elaborate_All elimination
27617 @example
27618 remove pragma Elaborate_All for unit "..." in unit "..."
27619 @end example
27621 This tactic is suggested when the binder has determined that pragma
27622 @code{Elaborate_All}:
27625 @itemize -
27627 @item 
27628 Prevents a set of units from being elaborated.
27630 @item 
27631 The removal of the pragma will not eliminate the semantic effects of the
27632 pragma. In other words, the argument of the pragma along with its `with'
27633 closure will still be elaborated prior to the unit containing the pragma.
27635 @item 
27636 The removal of the pragma will enable the successful ordering of the units.
27637 @end itemize
27639 The programmer should remove the pragma as advised, and rebuild the program.
27641 @item 
27642 Pragma Elaborate_All downgrade
27644 @example
27645 change pragma Elaborate_All for unit "..." to Elaborate in unit "..."
27646 @end example
27648 This tactic is always suggested with the pragma @code{Elaborate_All} elimination
27649 tactic. It offers a different alternative of guaranteeing that the argument
27650 of the pragma will still be elaborated prior to the unit containing the
27651 pragma.
27653 The programmer should update the pragma as advised, and rebuild the program.
27655 @item 
27656 Pragma Elaborate_Body elimination
27658 @example
27659 remove pragma Elaborate_Body in unit "..."
27660 @end example
27662 This tactic is suggested when the binder has determined that pragma
27663 @code{Elaborate_Body}:
27666 @itemize -
27668 @item 
27669 Prevents a set of units from being elaborated.
27671 @item 
27672 The removal of the pragma will enable the successful ordering of the units.
27673 @end itemize
27675 Note that the binder cannot determine whether the pragma is required for
27676 other purposes, such as guaranteeing the initialization of a variable
27677 declared in the spec by elaboration code in the body.
27679 The programmer should remove the pragma as advised, and rebuild the program.
27681 @item 
27682 Use of pragma Restrictions
27684 @example
27685 use pragma Restrictions (No_Entry_Calls_In_Elaboration_Code)
27686 @end example
27688 This tactic is suggested when the binder has determined that a task
27689 activation at elaboration time:
27692 @itemize -
27694 @item 
27695 Prevents a set of units from being elaborated.
27696 @end itemize
27698 Note that the binder cannot determine with certainty whether the task will
27699 block at elaboration time.
27701 The programmer should create a configuration file, place the pragma within,
27702 update the general compilation arguments, and rebuild the program.
27704 @item 
27705 Use of dynamic elaboration model
27707 @example
27708 use the dynamic elaboration model (compiler switch -gnatE)
27709 @end example
27711 This tactic is suggested when the binder has determined that an invocation at
27712 elaboration time:
27715 @itemize -
27717 @item 
27718 Prevents a set of units from being elaborated.
27720 @item 
27721 The use of the dynamic model will enable the successful ordering of the
27722 units.
27723 @end itemize
27725 The programmer has two options:
27728 @itemize -
27730 @item 
27731 Determine the units involved in the invocation using the detailed
27732 invocation information, and add compiler switch @code{-gnatE} to the
27733 compilation arguments of selected files only. This approach will yield
27734 safer elaboration orders compared to the other option because it will
27735 minimize the opportunities presented to the dynamic model for ignoring
27736 invocations.
27738 @item 
27739 Add compiler switch @code{-gnatE} to the general compilation arguments.
27740 @end itemize
27742 @item 
27743 Use of detailed invocation information
27745 @example
27746 use detailed invocation information (compiler switch -gnatd_F)
27747 @end example
27749 This tactic is always suggested with the use of the dynamic model tactic. It
27750 causes the circularity section of the circularity diagnostic to describe the
27751 flow of elaboration code from a unit to a unit, enumerating all such paths in
27752 the process.
27754 The programmer should analyze this information to determine which units
27755 should be compiled with the dynamic model.
27757 @item 
27758 Forced-dependency elimination
27760 @example
27761 remove the dependency of unit "..." on unit "..." from the argument of switch -f
27762 @end example
27764 This tactic is suggested when the binder has determined that a dependency
27765 present in the forced-elaboration-order file indicated by binder switch
27766 @code{-f}:
27769 @itemize -
27771 @item 
27772 Prevents a set of units from being elaborated.
27774 @item 
27775 The removal of the dependency will enable the successful ordering of the
27776 units.
27777 @end itemize
27779 The programmer should edit the forced-elaboration-order file, remove the
27780 dependency, and rebind the program.
27782 @item 
27783 All forced-dependency elimination
27785 @example
27786 remove switch -f
27787 @end example
27789 This tactic is suggested in case editing the forced-elaboration-order file is
27790 not an option.
27792 The programmer should remove binder switch @code{-f} from the binder
27793 arguments, and rebind.
27795 @item 
27796 Multiple-circularities diagnostic
27798 @example
27799 diagnose all circularities (binder switch -d_C)
27800 @end example
27802 By default, the binder will diagnose only the highest-precedence circularity.
27803 If the program contains multiple circularities, the binder will suggest the
27804 use of binder switch @code{-d_C} in order to obtain the diagnostics of all
27805 circularities.
27807 The programmer should add binder switch @code{-d_C} to the binder
27808 arguments, and rebind.
27809 @end itemize
27811 If none of the tactics suggested by the binder eliminate the elaboration
27812 circularity, the programmer should consider using one of the legacy elaboration
27813 models, in the following order:
27816 @itemize *
27818 @item 
27819 Use the pre-20.x legacy elaboration-order model, with binder switch
27820 @code{-H}.
27822 @item 
27823 Use both pre-18.x and pre-20.x legacy elaboration models, with compiler
27824 switch @code{-gnatH} and binder switch @code{-H}.
27826 @item 
27827 Use the relaxed static-elaboration model, with compiler switches
27828 @code{-gnatH} @code{-gnatJ} and binder switch @code{-H}.
27830 @item 
27831 Use the relaxed dynamic-elaboration model, with compiler switches
27832 @code{-gnatH} @code{-gnatJ} @code{-gnatE} and binder switch
27833 @code{-H}.
27834 @end itemize
27836 @node Elaboration-related Compiler Switches,Summary of Procedures for Elaboration Control,Resolving Elaboration Circularities,Elaboration Order Handling in GNAT
27837 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-related-compiler-switches}@anchor{233}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{234}
27838 @section Elaboration-related Compiler Switches
27841 GNAT has several switches that affect the elaboration model and consequently
27842 the elaboration order chosen by the binder.
27844 @geindex -gnatE (gnat)
27847 @table @asis
27849 @item @code{-gnatE}
27851 Dynamic elaboration checking mode enabled
27853 When this switch is in effect, GNAT activates the dynamic model.
27854 @end table
27856 @geindex -gnatel (gnat)
27859 @table @asis
27861 @item @code{-gnatel}
27863 Turn on info messages on generated Elaborate[_All] pragmas
27865 This switch is only applicable to the pre-20.x legacy elaboration models.
27866 The post-20.x elaboration model no longer relies on implicitly generated
27867 @code{Elaborate} and @code{Elaborate_All} pragmas to order units.
27869 When this switch is in effect, GNAT will emit the following supplementary
27870 information depending on the elaboration model in effect.
27873 @itemize -
27875 @item 
27876 `Dynamic model'
27878 GNAT will indicate missing @code{Elaborate} and @code{Elaborate_All} pragmas for
27879 all library-level scenarios within the partition.
27881 @item 
27882 `Static model'
27884 GNAT will indicate all scenarios invoked during elaboration. In addition,
27885 it will provide detailed traceback when an implicit @code{Elaborate} or
27886 @code{Elaborate_All} pragma is generated.
27888 @item 
27889 `SPARK model'
27891 GNAT will indicate how an elaboration requirement is met by the context of
27892 a unit. This diagnostic requires compiler switch @code{-gnatd.v}.
27894 @example
27895 1. with Server; pragma Elaborate_All (Server);
27896 2. package Client with SPARK_Mode is
27897 3.    Val : constant Integer := Server.Func;
27898                                       |
27899    >>> info: call to "Func" during elaboration in SPARK
27900    >>> info: "Elaborate_All" requirement for unit "Server" met by pragma at line 1
27902 4. end Client;
27903 @end example
27904 @end itemize
27905 @end table
27907 @geindex -gnatH (gnat)
27910 @table @asis
27912 @item @code{-gnatH}
27914 Legacy elaboration checking mode enabled
27916 When this switch is in effect, GNAT will utilize the pre-18.x elaboration
27917 model.
27918 @end table
27920 @geindex -gnatJ (gnat)
27923 @table @asis
27925 @item @code{-gnatJ}
27927 Relaxed elaboration checking mode enabled
27929 When this switch is in effect, GNAT will not process certain scenarios,
27930 resulting in a more permissive elaboration model. Note that this may
27931 eliminate some diagnostics and run-time checks.
27932 @end table
27934 @geindex -gnatw.f (gnat)
27937 @table @asis
27939 @item @code{-gnatw.f}
27941 Turn on warnings for suspicious Subp’Access
27943 When this switch is in effect, GNAT will treat @code{'Access} of an entry,
27944 operator, or subprogram as a potential call to the target and issue warnings:
27946 @example
27947  1. package body Attribute_Call is
27948  2.    function Func return Integer;
27949  3.    type Func_Ptr is access function return Integer;
27950  4.
27951  5.    Ptr : constant Func_Ptr := Func'Access;
27952                                       |
27953     >>> warning: "Access" attribute of "Func" before body seen
27954     >>> warning: possible Program_Error on later references
27955     >>> warning:   body of unit "Attribute_Call" elaborated
27956     >>> warning:   "Access" of "Func" taken at line 5
27958  6.
27959  7.    function Func return Integer is
27960  8.    begin
27961  9.       ...
27962 10.    end Func;
27963 11. end Attribute_Call;
27964 @end example
27966 In the example above, the elaboration of declaration @code{Ptr} is assigned
27967 @code{Func'Access} before the body of @code{Func} has been elaborated.
27968 @end table
27970 @geindex -gnatwl (gnat)
27973 @table @asis
27975 @item @code{-gnatwl}
27977 Turn on warnings for elaboration problems
27979 When this switch is in effect, GNAT emits diagnostics in the form of warnings
27980 concerning various elaboration problems. The warnings are enabled by default.
27981 The switch is provided in case all warnings are suppressed, but elaboration
27982 warnings are still desired.
27984 @item @code{-gnatwL}
27986 Turn off warnings for elaboration problems
27988 When this switch is in effect, GNAT no longer emits any diagnostics in the
27989 form of warnings. Selective suppression of elaboration problems is possible
27990 using @code{pragma Warnings (Off)}.
27992 @example
27993  1. package body Selective_Suppression is
27994  2.    function ABE return Integer;
27995  3.
27996  4.    Val_1 : constant Integer := ABE;
27997                                    |
27998     >>> warning: cannot call "ABE" before body seen
27999     >>> warning: Program_Error will be raised at run time
28001  5.
28002  6.    pragma Warnings (Off);
28003  7.    Val_2 : constant Integer := ABE;
28004  8.    pragma Warnings (On);
28005  9.
28006 10.    function ABE return Integer is
28007 11.    begin
28008 12.       ...
28009 13.    end ABE;
28010 14. end Selective_Suppression;
28011 @end example
28013 Note that suppressing elaboration warnings does not eliminate run-time
28014 checks. The example above will still fail at run time with an ABE.
28015 @end table
28017 @node Summary of Procedures for Elaboration Control,Inspecting the Chosen Elaboration Order,Elaboration-related Compiler Switches,Elaboration Order Handling in GNAT
28018 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{235}@anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{236}
28019 @section Summary of Procedures for Elaboration Control
28022 A programmer should first compile the program with the default options, using
28023 none of the binder or compiler switches. If the binder succeeds in finding an
28024 elaboration order, then apart from possible cases involving dispatching calls
28025 and access-to-subprogram types, the program is free of elaboration errors.
28027 If it is important for the program to be portable to compilers other than GNAT,
28028 then the programmer should use compiler switch @code{-gnatel} and consider
28029 the messages about missing or implicitly created @code{Elaborate} and
28030 @code{Elaborate_All} pragmas.
28032 If the binder reports an elaboration circularity, the programmer has several
28033 options:
28036 @itemize *
28038 @item 
28039 Ensure that elaboration warnings are enabled. This will allow the static
28040 model to output trace information of elaboration issues. The trace
28041 information could shed light on previously unforeseen dependencies, as well
28042 as their origins. Elaboration warnings are enabled with compiler switch
28043 @code{-gnatwl}.
28045 @item 
28046 Cosider the tactics given in the suggestions section of the circularity
28047 diagnostic.
28049 @item 
28050 If none of the steps outlined above resolve the circularity, use a more
28051 permissive elaboration model, in the following order:
28054 @itemize -
28056 @item 
28057 Use the pre-20.x legacy elaboration-order model, with binder switch
28058 @code{-H}.
28060 @item 
28061 Use both pre-18.x and pre-20.x legacy elaboration models, with compiler
28062 switch @code{-gnatH} and binder switch @code{-H}.
28064 @item 
28065 Use the relaxed static elaboration model, with compiler switches
28066 @code{-gnatH} @code{-gnatJ} and binder switch @code{-H}.
28068 @item 
28069 Use the relaxed dynamic elaboration model, with compiler switches
28070 @code{-gnatH} @code{-gnatJ} @code{-gnatE} and binder switch
28071 @code{-H}.
28072 @end itemize
28073 @end itemize
28075 @node Inspecting the Chosen Elaboration Order,,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
28076 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{237}@anchor{gnat_ugn/elaboration_order_handling_in_gnat inspecting-the-chosen-elaboration-order}@anchor{238}
28077 @section Inspecting the Chosen Elaboration Order
28080 To see the elaboration order chosen by the binder, inspect the contents of file
28081 @cite{b~xxx.adb}. On certain targets, this file appears as @cite{b_xxx.adb}. The
28082 elaboration order appears as a sequence of calls to @code{Elab_Body} and
28083 @code{Elab_Spec}, interspersed with assignments to @cite{Exxx} which indicates that a
28084 particular unit is elaborated. For example:
28086 @quotation
28088 @example
28089 System.Soft_Links'Elab_Body;
28090 E14 := True;
28091 System.Secondary_Stack'Elab_Body;
28092 E18 := True;
28093 System.Exception_Table'Elab_Body;
28094 E24 := True;
28095 Ada.Io_Exceptions'Elab_Spec;
28096 E67 := True;
28097 Ada.Tags'Elab_Spec;
28098 Ada.Streams'Elab_Spec;
28099 E43 := True;
28100 Interfaces.C'Elab_Spec;
28101 E69 := True;
28102 System.Finalization_Root'Elab_Spec;
28103 E60 := True;
28104 System.Os_Lib'Elab_Body;
28105 E71 := True;
28106 System.Finalization_Implementation'Elab_Spec;
28107 System.Finalization_Implementation'Elab_Body;
28108 E62 := True;
28109 Ada.Finalization'Elab_Spec;
28110 E58 := True;
28111 Ada.Finalization.List_Controller'Elab_Spec;
28112 E76 := True;
28113 System.File_Control_Block'Elab_Spec;
28114 E74 := True;
28115 System.File_Io'Elab_Body;
28116 E56 := True;
28117 Ada.Tags'Elab_Body;
28118 E45 := True;
28119 Ada.Text_Io'Elab_Spec;
28120 Ada.Text_Io'Elab_Body;
28121 E07 := True;
28122 @end example
28123 @end quotation
28125 Note also binder switch @code{-l}, which outputs the chosen elaboration
28126 order and provides a more readable form of the above:
28128 @quotation
28130 @example
28131 ada (spec)
28132 interfaces (spec)
28133 system (spec)
28134 system.case_util (spec)
28135 system.case_util (body)
28136 system.concat_2 (spec)
28137 system.concat_2 (body)
28138 system.concat_3 (spec)
28139 system.concat_3 (body)
28140 system.htable (spec)
28141 system.parameters (spec)
28142 system.parameters (body)
28143 system.crtl (spec)
28144 interfaces.c_streams (spec)
28145 interfaces.c_streams (body)
28146 system.restrictions (spec)
28147 system.restrictions (body)
28148 system.standard_library (spec)
28149 system.exceptions (spec)
28150 system.exceptions (body)
28151 system.storage_elements (spec)
28152 system.storage_elements (body)
28153 system.secondary_stack (spec)
28154 system.stack_checking (spec)
28155 system.stack_checking (body)
28156 system.string_hash (spec)
28157 system.string_hash (body)
28158 system.htable (body)
28159 system.strings (spec)
28160 system.strings (body)
28161 system.traceback (spec)
28162 system.traceback (body)
28163 system.traceback_entries (spec)
28164 system.traceback_entries (body)
28165 ada.exceptions (spec)
28166 ada.exceptions.last_chance_handler (spec)
28167 system.soft_links (spec)
28168 system.soft_links (body)
28169 ada.exceptions.last_chance_handler (body)
28170 system.secondary_stack (body)
28171 system.exception_table (spec)
28172 system.exception_table (body)
28173 ada.io_exceptions (spec)
28174 ada.tags (spec)
28175 ada.streams (spec)
28176 interfaces.c (spec)
28177 interfaces.c (body)
28178 system.finalization_root (spec)
28179 system.finalization_root (body)
28180 system.memory (spec)
28181 system.memory (body)
28182 system.standard_library (body)
28183 system.os_lib (spec)
28184 system.os_lib (body)
28185 system.unsigned_types (spec)
28186 system.stream_attributes (spec)
28187 system.stream_attributes (body)
28188 system.finalization_implementation (spec)
28189 system.finalization_implementation (body)
28190 ada.finalization (spec)
28191 ada.finalization (body)
28192 ada.finalization.list_controller (spec)
28193 ada.finalization.list_controller (body)
28194 system.file_control_block (spec)
28195 system.file_io (spec)
28196 system.file_io (body)
28197 system.val_uns (spec)
28198 system.val_util (spec)
28199 system.val_util (body)
28200 system.val_uns (body)
28201 system.wch_con (spec)
28202 system.wch_con (body)
28203 system.wch_cnv (spec)
28204 system.wch_jis (spec)
28205 system.wch_jis (body)
28206 system.wch_cnv (body)
28207 system.wch_stw (spec)
28208 system.wch_stw (body)
28209 ada.tags (body)
28210 ada.exceptions (body)
28211 ada.text_io (spec)
28212 ada.text_io (body)
28213 text_io (spec)
28214 gdbstr (body)
28215 @end example
28216 @end quotation
28218 @node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
28219 @anchor{gnat_ugn/inline_assembler doc}@anchor{239}@anchor{gnat_ugn/inline_assembler id1}@anchor{23a}@anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{10}
28220 @chapter Inline Assembler
28223 @geindex Inline Assembler
28225 If you need to write low-level software that interacts directly
28226 with the hardware, Ada provides two ways to incorporate assembly
28227 language code into your program.  First, you can import and invoke
28228 external routines written in assembly language, an Ada feature fully
28229 supported by GNAT.  However, for small sections of code it may be simpler
28230 or more efficient to include assembly language statements directly
28231 in your Ada source program, using the facilities of the implementation-defined
28232 package @code{System.Machine_Code}, which incorporates the gcc
28233 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
28234 including the following:
28237 @itemize *
28239 @item 
28240 No need to use non-Ada tools
28242 @item 
28243 Consistent interface over different targets
28245 @item 
28246 Automatic usage of the proper calling conventions
28248 @item 
28249 Access to Ada constants and variables
28251 @item 
28252 Definition of intrinsic routines
28254 @item 
28255 Possibility of inlining a subprogram comprising assembler code
28257 @item 
28258 Code optimizer can take Inline Assembler code into account
28259 @end itemize
28261 This appendix presents a series of examples to show you how to use
28262 the Inline Assembler.  Although it focuses on the Intel x86,
28263 the general approach applies also to other processors.
28264 It is assumed that you are familiar with Ada
28265 and with assembly language programming.
28267 @menu
28268 * Basic Assembler Syntax:: 
28269 * A Simple Example of Inline Assembler:: 
28270 * Output Variables in Inline Assembler:: 
28271 * Input Variables in Inline Assembler:: 
28272 * Inlining Inline Assembler Code:: 
28273 * Other Asm Functionality:: 
28275 @end menu
28277 @node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
28278 @anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{23b}@anchor{gnat_ugn/inline_assembler id2}@anchor{23c}
28279 @section Basic Assembler Syntax
28282 The assembler used by GNAT and gcc is based not on the Intel assembly
28283 language, but rather on a language that descends from the AT&T Unix
28284 assembler @code{as} (and which is often referred to as ‘AT&T syntax’).
28285 The following table summarizes the main features of @code{as} syntax
28286 and points out the differences from the Intel conventions.
28287 See the gcc @code{as} and @code{gas} (an @code{as} macro
28288 pre-processor) documentation for further information.
28291 @display
28292 `Register names'@w{ }
28293 @display
28294 gcc / @code{as}: Prefix with ‘%’; for example @code{%eax}@w{ }
28295 Intel: No extra punctuation; for example @code{eax}@w{ }
28296 @end display
28297 @end display
28302 @display
28303 `Immediate operand'@w{ }
28304 @display
28305 gcc / @code{as}: Prefix with ‘$’; for example @code{$4}@w{ }
28306 Intel: No extra punctuation; for example @code{4}@w{ }
28307 @end display
28308 @end display
28313 @display
28314 `Address'@w{ }
28315 @display
28316 gcc / @code{as}: Prefix with ‘$’; for example @code{$loc}@w{ }
28317 Intel: No extra punctuation; for example @code{loc}@w{ }
28318 @end display
28319 @end display
28324 @display
28325 `Memory contents'@w{ }
28326 @display
28327 gcc / @code{as}: No extra punctuation; for example @code{loc}@w{ }
28328 Intel: Square brackets; for example @code{[loc]}@w{ }
28329 @end display
28330 @end display
28335 @display
28336 `Register contents'@w{ }
28337 @display
28338 gcc / @code{as}: Parentheses; for example @code{(%eax)}@w{ }
28339 Intel: Square brackets; for example @code{[eax]}@w{ }
28340 @end display
28341 @end display
28346 @display
28347 `Hexadecimal numbers'@w{ }
28348 @display
28349 gcc / @code{as}: Leading ‘0x’ (C language syntax); for example @code{0xA0}@w{ }
28350 Intel: Trailing ‘h’; for example @code{A0h}@w{ }
28351 @end display
28352 @end display
28357 @display
28358 `Operand size'@w{ }
28359 @display
28360 gcc / @code{as}: Explicit in op code; for example @code{movw} to move a 16-bit word@w{ }
28361 Intel: Implicit, deduced by assembler; for example @code{mov}@w{ }
28362 @end display
28363 @end display
28368 @display
28369 `Instruction repetition'@w{ }
28370 @display
28371 gcc / @code{as}: Split into two lines; for example@w{ }
28372 @display
28373 @code{rep}@w{ }
28374 @code{stosl}@w{ }
28375 @end display
28376 Intel: Keep on one line; for example @code{rep stosl}@w{ }
28377 @end display
28378 @end display
28383 @display
28384 `Order of operands'@w{ }
28385 @display
28386 gcc / @code{as}: Source first; for example @code{movw $4, %eax}@w{ }
28387 Intel: Destination first; for example @code{mov eax, 4}@w{ }
28388 @end display
28389 @end display
28393 @node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
28394 @anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{23d}@anchor{gnat_ugn/inline_assembler id3}@anchor{23e}
28395 @section A Simple Example of Inline Assembler
28398 The following example will generate a single assembly language statement,
28399 @code{nop}, which does nothing.  Despite its lack of run-time effect,
28400 the example will be useful in illustrating the basics of
28401 the Inline Assembler facility.
28403 @quotation
28405 @example
28406 with System.Machine_Code; use System.Machine_Code;
28407 procedure Nothing is
28408 begin
28409    Asm ("nop");
28410 end Nothing;
28411 @end example
28412 @end quotation
28414 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
28415 here it takes one parameter, a `template string' that must be a static
28416 expression and that will form the generated instruction.
28417 @code{Asm} may be regarded as a compile-time procedure that parses
28418 the template string and additional parameters (none here),
28419 from which it generates a sequence of assembly language instructions.
28421 The examples in this chapter will illustrate several of the forms
28422 for invoking @code{Asm}; a complete specification of the syntax
28423 is found in the @code{Machine_Code_Insertions} section of the
28424 @cite{GNAT Reference Manual}.
28426 Under the standard GNAT conventions, the @code{Nothing} procedure
28427 should be in a file named @code{nothing.adb}.
28428 You can build the executable in the usual way:
28430 @quotation
28432 @example
28433 $ gnatmake nothing
28434 @end example
28435 @end quotation
28437 However, the interesting aspect of this example is not its run-time behavior
28438 but rather the generated assembly code.
28439 To see this output, invoke the compiler as follows:
28441 @quotation
28443 @example
28444 $ gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
28445 @end example
28446 @end quotation
28448 where the options are:
28451 @itemize *
28453 @item 
28455 @table @asis
28457 @item @code{-c}
28459 compile only (no bind or link)
28460 @end table
28462 @item 
28464 @table @asis
28466 @item @code{-S}
28468 generate assembler listing
28469 @end table
28471 @item 
28473 @table @asis
28475 @item @code{-fomit-frame-pointer}
28477 do not set up separate stack frames
28478 @end table
28480 @item 
28482 @table @asis
28484 @item @code{-gnatp}
28486 do not add runtime checks
28487 @end table
28488 @end itemize
28490 This gives a human-readable assembler version of the code. The resulting
28491 file will have the same name as the Ada source file, but with a @code{.s}
28492 extension. In our example, the file @code{nothing.s} has the following
28493 contents:
28495 @quotation
28497 @example
28498 .file "nothing.adb"
28499 gcc2_compiled.:
28500 ___gnu_compiled_ada:
28501 .text
28502    .align 4
28503 .globl __ada_nothing
28504 __ada_nothing:
28505 #APP
28506    nop
28507 #NO_APP
28508    jmp L1
28509    .align 2,0x90
28511    ret
28512 @end example
28513 @end quotation
28515 The assembly code you included is clearly indicated by
28516 the compiler, between the @code{#APP} and @code{#NO_APP}
28517 delimiters. The character before the ‘APP’ and ‘NOAPP’
28518 can differ on different targets. For example, GNU/Linux uses ‘#APP’ while
28519 on NT you will see ‘/APP’.
28521 If you make a mistake in your assembler code (such as using the
28522 wrong size modifier, or using a wrong operand for the instruction) GNAT
28523 will report this error in a temporary file, which will be deleted when
28524 the compilation is finished.  Generating an assembler file will help
28525 in such cases, since you can assemble this file separately using the
28526 @code{as} assembler that comes with gcc.
28528 Assembling the file using the command
28530 @quotation
28532 @example
28533 $ as nothing.s
28534 @end example
28535 @end quotation
28537 will give you error messages whose lines correspond to the assembler
28538 input file, so you can easily find and correct any mistakes you made.
28539 If there are no errors, @code{as} will generate an object file
28540 @code{nothing.out}.
28542 @node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
28543 @anchor{gnat_ugn/inline_assembler id4}@anchor{23f}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{240}
28544 @section Output Variables in Inline Assembler
28547 The examples in this section, showing how to access the processor flags,
28548 illustrate how to specify the destination operands for assembly language
28549 statements.
28551 @quotation
28553 @example
28554 with Interfaces; use Interfaces;
28555 with Ada.Text_IO; use Ada.Text_IO;
28556 with System.Machine_Code; use System.Machine_Code;
28557 procedure Get_Flags is
28558    Flags : Unsigned_32;
28559    use ASCII;
28560 begin
28561    Asm ("pushfl"          & LF & HT & -- push flags on stack
28562         "popl %%eax"      & LF & HT & -- load eax with flags
28563         "movl %%eax, %0",             -- store flags in variable
28564         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28565    Put_Line ("Flags register:" & Flags'Img);
28566 end Get_Flags;
28567 @end example
28568 @end quotation
28570 In order to have a nicely aligned assembly listing, we have separated
28571 multiple assembler statements in the Asm template string with linefeed
28572 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28573 The resulting section of the assembly output file is:
28575 @quotation
28577 @example
28578 #APP
28579    pushfl
28580    popl %eax
28581    movl %eax, -40(%ebp)
28582 #NO_APP
28583 @end example
28584 @end quotation
28586 It would have been legal to write the Asm invocation as:
28588 @quotation
28590 @example
28591 Asm ("pushfl popl %%eax movl %%eax, %0")
28592 @end example
28593 @end quotation
28595 but in the generated assembler file, this would come out as:
28597 @quotation
28599 @example
28600 #APP
28601    pushfl popl %eax movl %eax, -40(%ebp)
28602 #NO_APP
28603 @end example
28604 @end quotation
28606 which is not so convenient for the human reader.
28608 We use Ada comments
28609 at the end of each line to explain what the assembler instructions
28610 actually do.  This is a useful convention.
28612 When writing Inline Assembler instructions, you need to precede each register
28613 and variable name with a percent sign.  Since the assembler already requires
28614 a percent sign at the beginning of a register name, you need two consecutive
28615 percent signs for such names in the Asm template string, thus @code{%%eax}.
28616 In the generated assembly code, one of the percent signs will be stripped off.
28618 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28619 variables: operands you later define using @code{Input} or @code{Output}
28620 parameters to @code{Asm}.
28621 An output variable is illustrated in
28622 the third statement in the Asm template string:
28624 @quotation
28626 @example
28627 movl %%eax, %0
28628 @end example
28629 @end quotation
28631 The intent is to store the contents of the eax register in a variable that can
28632 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
28633 necessarily work, since the compiler might optimize by using a register
28634 to hold Flags, and the expansion of the @code{movl} instruction would not be
28635 aware of this optimization.  The solution is not to store the result directly
28636 but rather to advise the compiler to choose the correct operand form;
28637 that is the purpose of the @code{%0} output variable.
28639 Information about the output variable is supplied in the @code{Outputs}
28640 parameter to @code{Asm}:
28642 @quotation
28644 @example
28645 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28646 @end example
28647 @end quotation
28649 The output is defined by the @code{Asm_Output} attribute of the target type;
28650 the general format is
28652 @quotation
28654 @example
28655 Type'Asm_Output (constraint_string, variable_name)
28656 @end example
28657 @end quotation
28659 The constraint string directs the compiler how
28660 to store/access the associated variable.  In the example
28662 @quotation
28664 @example
28665 Unsigned_32'Asm_Output ("=m", Flags);
28666 @end example
28667 @end quotation
28669 the @code{"m"} (memory) constraint tells the compiler that the variable
28670 @code{Flags} should be stored in a memory variable, thus preventing
28671 the optimizer from keeping it in a register.  In contrast,
28673 @quotation
28675 @example
28676 Unsigned_32'Asm_Output ("=r", Flags);
28677 @end example
28678 @end quotation
28680 uses the @code{"r"} (register) constraint, telling the compiler to
28681 store the variable in a register.
28683 If the constraint is preceded by the equal character ‘=’, it tells
28684 the compiler that the variable will be used to store data into it.
28686 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28687 allowing the optimizer to choose whatever it deems best.
28689 There are a fairly large number of constraints, but the ones that are
28690 most useful (for the Intel x86 processor) are the following:
28692 @quotation
28695 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
28696 @item
28700 @tab
28702 output constraint
28704 @item
28708 @tab
28710 global (i.e., can be stored anywhere)
28712 @item
28716 @tab
28718 in memory
28720 @item
28724 @tab
28726 a constant
28728 @item
28732 @tab
28734 use eax
28736 @item
28740 @tab
28742 use ebx
28744 @item
28748 @tab
28750 use ecx
28752 @item
28756 @tab
28758 use edx
28760 @item
28764 @tab
28766 use esi
28768 @item
28772 @tab
28774 use edi
28776 @item
28780 @tab
28782 use one of eax, ebx, ecx or edx
28784 @item
28788 @tab
28790 use one of eax, ebx, ecx, edx, esi or edi
28792 @end multitable
28794 @end quotation
28796 The full set of constraints is described in the gcc and @code{as}
28797 documentation; note that it is possible to combine certain constraints
28798 in one constraint string.
28800 You specify the association of an output variable with an assembler operand
28801 through the @code{%@var{n}} notation, where `n' is a non-negative
28802 integer.  Thus in
28804 @quotation
28806 @example
28807 Asm ("pushfl"          & LF & HT & -- push flags on stack
28808      "popl %%eax"      & LF & HT & -- load eax with flags
28809      "movl %%eax, %0",             -- store flags in variable
28810      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28811 @end example
28812 @end quotation
28814 @code{%0} will be replaced in the expanded code by the appropriate operand,
28815 whatever
28816 the compiler decided for the @code{Flags} variable.
28818 In general, you may have any number of output variables:
28821 @itemize *
28823 @item 
28824 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28826 @item 
28827 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28828 of @code{Asm_Output} attributes
28829 @end itemize
28831 For example:
28833 @quotation
28835 @example
28836 Asm ("movl %%eax, %0" & LF & HT &
28837      "movl %%ebx, %1" & LF & HT &
28838      "movl %%ecx, %2",
28839      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
28840                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
28841                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
28842 @end example
28843 @end quotation
28845 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28846 in the Ada program.
28848 As a variation on the @code{Get_Flags} example, we can use the constraints
28849 string to direct the compiler to store the eax register into the @code{Flags}
28850 variable, instead of including the store instruction explicitly in the
28851 @code{Asm} template string:
28853 @quotation
28855 @example
28856 with Interfaces; use Interfaces;
28857 with Ada.Text_IO; use Ada.Text_IO;
28858 with System.Machine_Code; use System.Machine_Code;
28859 procedure Get_Flags_2 is
28860    Flags : Unsigned_32;
28861    use ASCII;
28862 begin
28863    Asm ("pushfl"      & LF & HT & -- push flags on stack
28864         "popl %%eax",             -- save flags in eax
28865         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28866    Put_Line ("Flags register:" & Flags'Img);
28867 end Get_Flags_2;
28868 @end example
28869 @end quotation
28871 The @code{"a"} constraint tells the compiler that the @code{Flags}
28872 variable will come from the eax register. Here is the resulting code:
28874 @quotation
28876 @example
28877 #APP
28878    pushfl
28879    popl %eax
28880 #NO_APP
28881    movl %eax,-40(%ebp)
28882 @end example
28883 @end quotation
28885 The compiler generated the store of eax into Flags after
28886 expanding the assembler code.
28888 Actually, there was no need to pop the flags into the eax register;
28889 more simply, we could just pop the flags directly into the program variable:
28891 @quotation
28893 @example
28894 with Interfaces; use Interfaces;
28895 with Ada.Text_IO; use Ada.Text_IO;
28896 with System.Machine_Code; use System.Machine_Code;
28897 procedure Get_Flags_3 is
28898    Flags : Unsigned_32;
28899    use ASCII;
28900 begin
28901    Asm ("pushfl"  & LF & HT & -- push flags on stack
28902         "pop %0",             -- save flags in Flags
28903         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28904    Put_Line ("Flags register:" & Flags'Img);
28905 end Get_Flags_3;
28906 @end example
28907 @end quotation
28909 @node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
28910 @anchor{gnat_ugn/inline_assembler id5}@anchor{241}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{242}
28911 @section Input Variables in Inline Assembler
28914 The example in this section illustrates how to specify the source operands
28915 for assembly language statements.
28916 The program simply increments its input value by 1:
28918 @quotation
28920 @example
28921 with Interfaces; use Interfaces;
28922 with Ada.Text_IO; use Ada.Text_IO;
28923 with System.Machine_Code; use System.Machine_Code;
28924 procedure Increment is
28926    function Incr (Value : Unsigned_32) return Unsigned_32 is
28927       Result : Unsigned_32;
28928    begin
28929       Asm ("incl %0",
28930            Outputs => Unsigned_32'Asm_Output ("=a", Result),
28931            Inputs  => Unsigned_32'Asm_Input ("a", Value));
28932       return Result;
28933    end Incr;
28935    Value : Unsigned_32;
28937 begin
28938    Value := 5;
28939    Put_Line ("Value before is" & Value'Img);
28940    Value := Incr (Value);
28941   Put_Line ("Value after is" & Value'Img);
28942 end Increment;
28943 @end example
28944 @end quotation
28946 The @code{Outputs} parameter to @code{Asm} specifies
28947 that the result will be in the eax register and that it is to be stored
28948 in the @code{Result} variable.
28950 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28951 but with an @code{Asm_Input} attribute.
28952 The @code{"="} constraint, indicating an output value, is not present.
28954 You can have multiple input variables, in the same way that you can have more
28955 than one output variable.
28957 The parameter count (%0, %1) etc, still starts at the first output statement,
28958 and continues with the input statements.
28960 Just as the @code{Outputs} parameter causes the register to be stored into the
28961 target variable after execution of the assembler statements, so does the
28962 @code{Inputs} parameter cause its variable to be loaded into the register
28963 before execution of the assembler statements.
28965 Thus the effect of the @code{Asm} invocation is:
28968 @itemize *
28970 @item 
28971 load the 32-bit value of @code{Value} into eax
28973 @item 
28974 execute the @code{incl %eax} instruction
28976 @item 
28977 store the contents of eax into the @code{Result} variable
28978 @end itemize
28980 The resulting assembler file (with @code{-O2} optimization) contains:
28982 @quotation
28984 @example
28985 _increment__incr.1:
28986    subl $4,%esp
28987    movl 8(%esp),%eax
28988 #APP
28989    incl %eax
28990 #NO_APP
28991    movl %eax,%edx
28992    movl %ecx,(%esp)
28993    addl $4,%esp
28994    ret
28995 @end example
28996 @end quotation
28998 @node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
28999 @anchor{gnat_ugn/inline_assembler id6}@anchor{243}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{244}
29000 @section Inlining Inline Assembler Code
29003 For a short subprogram such as the @code{Incr} function in the previous
29004 section, the overhead of the call and return (creating / deleting the stack
29005 frame) can be significant, compared to the amount of code in the subprogram
29006 body.  A solution is to apply Ada’s @code{Inline} pragma to the subprogram,
29007 which directs the compiler to expand invocations of the subprogram at the
29008 point(s) of call, instead of setting up a stack frame for out-of-line calls.
29009 Here is the resulting program:
29011 @quotation
29013 @example
29014 with Interfaces; use Interfaces;
29015 with Ada.Text_IO; use Ada.Text_IO;
29016 with System.Machine_Code; use System.Machine_Code;
29017 procedure Increment_2 is
29019    function Incr (Value : Unsigned_32) return Unsigned_32 is
29020       Result : Unsigned_32;
29021    begin
29022       Asm ("incl %0",
29023            Outputs => Unsigned_32'Asm_Output ("=a", Result),
29024            Inputs  => Unsigned_32'Asm_Input ("a", Value));
29025       return Result;
29026    end Incr;
29027    pragma Inline (Increment);
29029    Value : Unsigned_32;
29031 begin
29032    Value := 5;
29033    Put_Line ("Value before is" & Value'Img);
29034    Value := Increment (Value);
29035    Put_Line ("Value after is" & Value'Img);
29036 end Increment_2;
29037 @end example
29038 @end quotation
29040 Compile the program with both optimization (@code{-O2}) and inlining
29041 (@code{-gnatn}) enabled.
29043 The @code{Incr} function is still compiled as usual, but at the
29044 point in @code{Increment} where our function used to be called:
29046 @quotation
29048 @example
29049 pushl %edi
29050 call _increment__incr.1
29051 @end example
29052 @end quotation
29054 the code for the function body directly appears:
29056 @quotation
29058 @example
29059 movl %esi,%eax
29060 #APP
29061    incl %eax
29062 #NO_APP
29063    movl %eax,%edx
29064 @end example
29065 @end quotation
29067 thus saving the overhead of stack frame setup and an out-of-line call.
29069 @node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
29070 @anchor{gnat_ugn/inline_assembler id7}@anchor{245}@anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{246}
29071 @section Other @code{Asm} Functionality
29074 This section describes two important parameters to the @code{Asm}
29075 procedure: @code{Clobber}, which identifies register usage;
29076 and @code{Volatile}, which inhibits unwanted optimizations.
29078 @menu
29079 * The Clobber Parameter:: 
29080 * The Volatile Parameter:: 
29082 @end menu
29084 @node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
29085 @anchor{gnat_ugn/inline_assembler id8}@anchor{247}@anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{248}
29086 @subsection The @code{Clobber} Parameter
29089 One of the dangers of intermixing assembly language and a compiled language
29090 such as Ada is that the compiler needs to be aware of which registers are
29091 being used by the assembly code.  In some cases, such as the earlier examples,
29092 the constraint string is sufficient to indicate register usage (e.g.,
29093 @code{"a"} for
29094 the eax register).  But more generally, the compiler needs an explicit
29095 identification of the registers that are used by the Inline Assembly
29096 statements.
29098 Using a register that the compiler doesn’t know about
29099 could be a side effect of an instruction (like @code{mull}
29100 storing its result in both eax and edx).
29101 It can also arise from explicit register usage in your
29102 assembly code; for example:
29104 @quotation
29106 @example
29107 Asm ("movl %0, %%ebx" & LF & HT &
29108      "movl %%ebx, %1",
29109      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29110      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
29111 @end example
29112 @end quotation
29114 where the compiler (since it does not analyze the @code{Asm} template string)
29115 does not know you are using the ebx register.
29117 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
29118 to identify the registers that will be used by your assembly code:
29120 @quotation
29122 @example
29123 Asm ("movl %0, %%ebx" & LF & HT &
29124      "movl %%ebx, %1",
29125      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29126      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
29127      Clobber => "ebx");
29128 @end example
29129 @end quotation
29131 The Clobber parameter is a static string expression specifying the
29132 register(s) you are using.  Note that register names are `not' prefixed
29133 by a percent sign. Also, if more than one register is used then their names
29134 are separated by commas; e.g., @code{"eax, ebx"}
29136 The @code{Clobber} parameter has several additional uses:
29139 @itemize *
29141 @item 
29142 Use ‘register’ name @code{cc} to indicate that flags might have changed
29144 @item 
29145 Use ‘register’ name @code{memory} if you changed a memory location
29146 @end itemize
29148 @node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
29149 @anchor{gnat_ugn/inline_assembler id9}@anchor{249}@anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{24a}
29150 @subsection The @code{Volatile} Parameter
29153 @geindex Volatile parameter
29155 Compiler optimizations in the presence of Inline Assembler may sometimes have
29156 unwanted effects.  For example, when an @code{Asm} invocation with an input
29157 variable is inside a loop, the compiler might move the loading of the input
29158 variable outside the loop, regarding it as a one-time initialization.
29160 If this effect is not desired, you can disable such optimizations by setting
29161 the @code{Volatile} parameter to @code{True}; for example:
29163 @quotation
29165 @example
29166 Asm ("movl %0, %%ebx" & LF & HT &
29167      "movl %%ebx, %1",
29168      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
29169      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
29170      Clobber  => "ebx",
29171      Volatile => True);
29172 @end example
29173 @end quotation
29175 By default, @code{Volatile} is set to @code{False} unless there is no
29176 @code{Outputs} parameter.
29178 Although setting @code{Volatile} to @code{True} prevents unwanted
29179 optimizations, it will also disable other optimizations that might be
29180 important for efficiency. In general, you should set @code{Volatile}
29181 to @code{True} only if the compiler’s optimizations have created
29182 problems.
29184 @node GNU Free Documentation License,Index,Inline Assembler,Top
29185 @anchor{share/gnu_free_documentation_license doc}@anchor{24b}@anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{24c}
29186 @chapter GNU Free Documentation License
29189 Version 1.3, 3 November 2008
29191 Copyright  2000, 2001, 2002, 2007, 2008  Free Software Foundation, Inc
29192 @indicateurl{https://fsf.org/}
29194 Everyone is permitted to copy and distribute verbatim copies of this
29195 license document, but changing it is not allowed.
29197 `Preamble'
29199 The purpose of this License is to make a manual, textbook, or other
29200 functional and useful document “free” in the sense of freedom: to
29201 assure everyone the effective freedom to copy and redistribute it,
29202 with or without modifying it, either commercially or noncommercially.
29203 Secondarily, this License preserves for the author and publisher a way
29204 to get credit for their work, while not being considered responsible
29205 for modifications made by others.
29207 This License is a kind of “copyleft”, which means that derivative
29208 works of the document must themselves be free in the same sense.  It
29209 complements the GNU General Public License, which is a copyleft
29210 license designed for free software.
29212 We have designed this License in order to use it for manuals for free
29213 software, because free software needs free documentation: a free
29214 program should come with manuals providing the same freedoms that the
29215 software does.  But this License is not limited to software manuals;
29216 it can be used for any textual work, regardless of subject matter or
29217 whether it is published as a printed book.  We recommend this License
29218 principally for works whose purpose is instruction or reference.
29220 `1. APPLICABILITY AND DEFINITIONS'
29222 This License applies to any manual or other work, in any medium, that
29223 contains a notice placed by the copyright holder saying it can be
29224 distributed under the terms of this License.  Such a notice grants a
29225 world-wide, royalty-free license, unlimited in duration, to use that
29226 work under the conditions stated herein.  The `Document', below,
29227 refers to any such manual or work.  Any member of the public is a
29228 licensee, and is addressed as “`you'”.  You accept the license if you
29229 copy, modify or distribute the work in a way requiring permission
29230 under copyright law.
29232 A “`Modified Version'” of the Document means any work containing the
29233 Document or a portion of it, either copied verbatim, or with
29234 modifications and/or translated into another language.
29236 A “`Secondary Section'” is a named appendix or a front-matter section of
29237 the Document that deals exclusively with the relationship of the
29238 publishers or authors of the Document to the Document’s overall subject
29239 (or to related matters) and contains nothing that could fall directly
29240 within that overall subject.  (Thus, if the Document is in part a
29241 textbook of mathematics, a Secondary Section may not explain any
29242 mathematics.)  The relationship could be a matter of historical
29243 connection with the subject or with related matters, or of legal,
29244 commercial, philosophical, ethical or political position regarding
29245 them.
29247 The “`Invariant Sections'” are certain Secondary Sections whose titles
29248 are designated, as being those of Invariant Sections, in the notice
29249 that says that the Document is released under this License.  If a
29250 section does not fit the above definition of Secondary then it is not
29251 allowed to be designated as Invariant.  The Document may contain zero
29252 Invariant Sections.  If the Document does not identify any Invariant
29253 Sections then there are none.
29255 The “`Cover Texts'” are certain short passages of text that are listed,
29256 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
29257 the Document is released under this License.  A Front-Cover Text may
29258 be at most 5 words, and a Back-Cover Text may be at most 25 words.
29260 A “`Transparent'” copy of the Document means a machine-readable copy,
29261 represented in a format whose specification is available to the
29262 general public, that is suitable for revising the document
29263 straightforwardly with generic text editors or (for images composed of
29264 pixels) generic paint programs or (for drawings) some widely available
29265 drawing editor, and that is suitable for input to text formatters or
29266 for automatic translation to a variety of formats suitable for input
29267 to text formatters.  A copy made in an otherwise Transparent file
29268 format whose markup, or absence of markup, has been arranged to thwart
29269 or discourage subsequent modification by readers is not Transparent.
29270 An image format is not Transparent if used for any substantial amount
29271 of text.  A copy that is not “Transparent” is called `Opaque'.
29273 Examples of suitable formats for Transparent copies include plain
29274 ASCII without markup, Texinfo input format, LaTeX input format, SGML
29275 or XML using a publicly available DTD, and standard-conforming simple
29276 HTML, PostScript or PDF designed for human modification.  Examples of
29277 transparent image formats include PNG, XCF and JPG.  Opaque formats
29278 include proprietary formats that can be read and edited only by
29279 proprietary word processors, SGML or XML for which the DTD and/or
29280 processing tools are not generally available, and the
29281 machine-generated HTML, PostScript or PDF produced by some word
29282 processors for output purposes only.
29284 The “`Title Page'” means, for a printed book, the title page itself,
29285 plus such following pages as are needed to hold, legibly, the material
29286 this License requires to appear in the title page.  For works in
29287 formats which do not have any title page as such, “Title Page” means
29288 the text near the most prominent appearance of the work’s title,
29289 preceding the beginning of the body of the text.
29291 The “`publisher'” means any person or entity that distributes
29292 copies of the Document to the public.
29294 A section “`Entitled XYZ'” means a named subunit of the Document whose
29295 title either is precisely XYZ or contains XYZ in parentheses following
29296 text that translates XYZ in another language.  (Here XYZ stands for a
29297 specific section name mentioned below, such as “`Acknowledgements'”,
29298 “`Dedications'”, “`Endorsements'”, or “`History'”.)
29299 To “`Preserve the Title'”
29300 of such a section when you modify the Document means that it remains a
29301 section “Entitled XYZ” according to this definition.
29303 The Document may include Warranty Disclaimers next to the notice which
29304 states that this License applies to the Document.  These Warranty
29305 Disclaimers are considered to be included by reference in this
29306 License, but only as regards disclaiming warranties: any other
29307 implication that these Warranty Disclaimers may have is void and has
29308 no effect on the meaning of this License.
29310 `2. VERBATIM COPYING'
29312 You may copy and distribute the Document in any medium, either
29313 commercially or noncommercially, provided that this License, the
29314 copyright notices, and the license notice saying this License applies
29315 to the Document are reproduced in all copies, and that you add no other
29316 conditions whatsoever to those of this License.  You may not use
29317 technical measures to obstruct or control the reading or further
29318 copying of the copies you make or distribute.  However, you may accept
29319 compensation in exchange for copies.  If you distribute a large enough
29320 number of copies you must also follow the conditions in section 3.
29322 You may also lend copies, under the same conditions stated above, and
29323 you may publicly display copies.
29325 `3. COPYING IN QUANTITY'
29327 If you publish printed copies (or copies in media that commonly have
29328 printed covers) of the Document, numbering more than 100, and the
29329 Document’s license notice requires Cover Texts, you must enclose the
29330 copies in covers that carry, clearly and legibly, all these Cover
29331 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
29332 the back cover.  Both covers must also clearly and legibly identify
29333 you as the publisher of these copies.  The front cover must present
29334 the full title with all words of the title equally prominent and
29335 visible.  You may add other material on the covers in addition.
29336 Copying with changes limited to the covers, as long as they preserve
29337 the title of the Document and satisfy these conditions, can be treated
29338 as verbatim copying in other respects.
29340 If the required texts for either cover are too voluminous to fit
29341 legibly, you should put the first ones listed (as many as fit
29342 reasonably) on the actual cover, and continue the rest onto adjacent
29343 pages.
29345 If you publish or distribute Opaque copies of the Document numbering
29346 more than 100, you must either include a machine-readable Transparent
29347 copy along with each Opaque copy, or state in or with each Opaque copy
29348 a computer-network location from which the general network-using
29349 public has access to download using public-standard network protocols
29350 a complete Transparent copy of the Document, free of added material.
29351 If you use the latter option, you must take reasonably prudent steps,
29352 when you begin distribution of Opaque copies in quantity, to ensure
29353 that this Transparent copy will remain thus accessible at the stated
29354 location until at least one year after the last time you distribute an
29355 Opaque copy (directly or through your agents or retailers) of that
29356 edition to the public.
29358 It is requested, but not required, that you contact the authors of the
29359 Document well before redistributing any large number of copies, to give
29360 them a chance to provide you with an updated version of the Document.
29362 `4. MODIFICATIONS'
29364 You may copy and distribute a Modified Version of the Document under
29365 the conditions of sections 2 and 3 above, provided that you release
29366 the Modified Version under precisely this License, with the Modified
29367 Version filling the role of the Document, thus licensing distribution
29368 and modification of the Modified Version to whoever possesses a copy
29369 of it.  In addition, you must do these things in the Modified Version:
29372 @enumerate A
29374 @item 
29375 Use in the Title Page (and on the covers, if any) a title distinct
29376 from that of the Document, and from those of previous versions
29377 (which should, if there were any, be listed in the History section
29378 of the Document).  You may use the same title as a previous version
29379 if the original publisher of that version gives permission.
29381 @item 
29382 List on the Title Page, as authors, one or more persons or entities
29383 responsible for authorship of the modifications in the Modified
29384 Version, together with at least five of the principal authors of the
29385 Document (all of its principal authors, if it has fewer than five),
29386 unless they release you from this requirement.
29388 @item 
29389 State on the Title page the name of the publisher of the
29390 Modified Version, as the publisher.
29392 @item 
29393 Preserve all the copyright notices of the Document.
29395 @item 
29396 Add an appropriate copyright notice for your modifications
29397 adjacent to the other copyright notices.
29399 @item 
29400 Include, immediately after the copyright notices, a license notice
29401 giving the public permission to use the Modified Version under the
29402 terms of this License, in the form shown in the Addendum below.
29404 @item 
29405 Preserve in that license notice the full lists of Invariant Sections
29406 and required Cover Texts given in the Document’s license notice.
29408 @item 
29409 Include an unaltered copy of this License.
29411 @item 
29412 Preserve the section Entitled “History”, Preserve its Title, and add
29413 to it an item stating at least the title, year, new authors, and
29414 publisher of the Modified Version as given on the Title Page.  If
29415 there is no section Entitled “History” in the Document, create one
29416 stating the title, year, authors, and publisher of the Document as
29417 given on its Title Page, then add an item describing the Modified
29418 Version as stated in the previous sentence.
29420 @item 
29421 Preserve the network location, if any, given in the Document for
29422 public access to a Transparent copy of the Document, and likewise
29423 the network locations given in the Document for previous versions
29424 it was based on.  These may be placed in the “History” section.
29425 You may omit a network location for a work that was published at
29426 least four years before the Document itself, or if the original
29427 publisher of the version it refers to gives permission.
29429 @item 
29430 For any section Entitled “Acknowledgements” or “Dedications”,
29431 Preserve the Title of the section, and preserve in the section all
29432 the substance and tone of each of the contributor acknowledgements
29433 and/or dedications given therein.
29435 @item 
29436 Preserve all the Invariant Sections of the Document,
29437 unaltered in their text and in their titles.  Section numbers
29438 or the equivalent are not considered part of the section titles.
29440 @item 
29441 Delete any section Entitled “Endorsements”.  Such a section
29442 may not be included in the Modified Version.
29444 @item 
29445 Do not retitle any existing section to be Entitled “Endorsements”
29446 or to conflict in title with any Invariant Section.
29448 @item 
29449 Preserve any Warranty Disclaimers.
29450 @end enumerate
29452 If the Modified Version includes new front-matter sections or
29453 appendices that qualify as Secondary Sections and contain no material
29454 copied from the Document, you may at your option designate some or all
29455 of these sections as invariant.  To do this, add their titles to the
29456 list of Invariant Sections in the Modified Version’s license notice.
29457 These titles must be distinct from any other section titles.
29459 You may add a section Entitled “Endorsements”, provided it contains
29460 nothing but endorsements of your Modified Version by various
29461 parties—for example, statements of peer review or that the text has
29462 been approved by an organization as the authoritative definition of a
29463 standard.
29465 You may add a passage of up to five words as a Front-Cover Text, and a
29466 passage of up to 25 words as a Back-Cover Text, to the end of the list
29467 of Cover Texts in the Modified Version.  Only one passage of
29468 Front-Cover Text and one of Back-Cover Text may be added by (or
29469 through arrangements made by) any one entity.  If the Document already
29470 includes a cover text for the same cover, previously added by you or
29471 by arrangement made by the same entity you are acting on behalf of,
29472 you may not add another; but you may replace the old one, on explicit
29473 permission from the previous publisher that added the old one.
29475 The author(s) and publisher(s) of the Document do not by this License
29476 give permission to use their names for publicity for or to assert or
29477 imply endorsement of any Modified Version.
29479 `5. COMBINING DOCUMENTS'
29481 You may combine the Document with other documents released under this
29482 License, under the terms defined in section 4 above for modified
29483 versions, provided that you include in the combination all of the
29484 Invariant Sections of all of the original documents, unmodified, and
29485 list them all as Invariant Sections of your combined work in its
29486 license notice, and that you preserve all their Warranty Disclaimers.
29488 The combined work need only contain one copy of this License, and
29489 multiple identical Invariant Sections may be replaced with a single
29490 copy.  If there are multiple Invariant Sections with the same name but
29491 different contents, make the title of each such section unique by
29492 adding at the end of it, in parentheses, the name of the original
29493 author or publisher of that section if known, or else a unique number.
29494 Make the same adjustment to the section titles in the list of
29495 Invariant Sections in the license notice of the combined work.
29497 In the combination, you must combine any sections Entitled “History”
29498 in the various original documents, forming one section Entitled
29499 “History”; likewise combine any sections Entitled “Acknowledgements”,
29500 and any sections Entitled “Dedications”.  You must delete all sections
29501 Entitled “Endorsements”.
29503 `6. COLLECTIONS OF DOCUMENTS'
29505 You may make a collection consisting of the Document and other documents
29506 released under this License, and replace the individual copies of this
29507 License in the various documents with a single copy that is included in
29508 the collection, provided that you follow the rules of this License for
29509 verbatim copying of each of the documents in all other respects.
29511 You may extract a single document from such a collection, and distribute
29512 it individually under this License, provided you insert a copy of this
29513 License into the extracted document, and follow this License in all
29514 other respects regarding verbatim copying of that document.
29516 `7. AGGREGATION WITH INDEPENDENT WORKS'
29518 A compilation of the Document or its derivatives with other separate
29519 and independent documents or works, in or on a volume of a storage or
29520 distribution medium, is called an “aggregate” if the copyright
29521 resulting from the compilation is not used to limit the legal rights
29522 of the compilation’s users beyond what the individual works permit.
29523 When the Document is included in an aggregate, this License does not
29524 apply to the other works in the aggregate which are not themselves
29525 derivative works of the Document.
29527 If the Cover Text requirement of section 3 is applicable to these
29528 copies of the Document, then if the Document is less than one half of
29529 the entire aggregate, the Document’s Cover Texts may be placed on
29530 covers that bracket the Document within the aggregate, or the
29531 electronic equivalent of covers if the Document is in electronic form.
29532 Otherwise they must appear on printed covers that bracket the whole
29533 aggregate.
29535 `8. TRANSLATION'
29537 Translation is considered a kind of modification, so you may
29538 distribute translations of the Document under the terms of section 4.
29539 Replacing Invariant Sections with translations requires special
29540 permission from their copyright holders, but you may include
29541 translations of some or all Invariant Sections in addition to the
29542 original versions of these Invariant Sections.  You may include a
29543 translation of this License, and all the license notices in the
29544 Document, and any Warranty Disclaimers, provided that you also include
29545 the original English version of this License and the original versions
29546 of those notices and disclaimers.  In case of a disagreement between
29547 the translation and the original version of this License or a notice
29548 or disclaimer, the original version will prevail.
29550 If a section in the Document is Entitled “Acknowledgements”,
29551 “Dedications”, or “History”, the requirement (section 4) to Preserve
29552 its Title (section 1) will typically require changing the actual
29553 title.
29555 `9. TERMINATION'
29557 You may not copy, modify, sublicense, or distribute the Document
29558 except as expressly provided under this License.  Any attempt
29559 otherwise to copy, modify, sublicense, or distribute it is void, and
29560 will automatically terminate your rights under this License.
29562 However, if you cease all violation of this License, then your license
29563 from a particular copyright holder is reinstated (a) provisionally,
29564 unless and until the copyright holder explicitly and finally
29565 terminates your license, and (b) permanently, if the copyright holder
29566 fails to notify you of the violation by some reasonable means prior to
29567 60 days after the cessation.
29569 Moreover, your license from a particular copyright holder is
29570 reinstated permanently if the copyright holder notifies you of the
29571 violation by some reasonable means, this is the first time you have
29572 received notice of violation of this License (for any work) from that
29573 copyright holder, and you cure the violation prior to 30 days after
29574 your receipt of the notice.
29576 Termination of your rights under this section does not terminate the
29577 licenses of parties who have received copies or rights from you under
29578 this License.  If your rights have been terminated and not permanently
29579 reinstated, receipt of a copy of some or all of the same material does
29580 not give you any rights to use it.
29582 `10. FUTURE REVISIONS OF THIS LICENSE'
29584 The Free Software Foundation may publish new, revised versions
29585 of the GNU Free Documentation License from time to time.  Such new
29586 versions will be similar in spirit to the present version, but may
29587 differ in detail to address new problems or concerns.  See
29588 @indicateurl{https://www.gnu.org/copyleft/}.
29590 Each version of the License is given a distinguishing version number.
29591 If the Document specifies that a particular numbered version of this
29592 License “or any later version” applies to it, you have the option of
29593 following the terms and conditions either of that specified version or
29594 of any later version that has been published (not as a draft) by the
29595 Free Software Foundation.  If the Document does not specify a version
29596 number of this License, you may choose any version ever published (not
29597 as a draft) by the Free Software Foundation.  If the Document
29598 specifies that a proxy can decide which future versions of this
29599 License can be used, that proxy’s public statement of acceptance of a
29600 version permanently authorizes you to choose that version for the
29601 Document.
29603 `11. RELICENSING'
29605 “Massive Multiauthor Collaboration Site” (or “MMC Site”) means any
29606 World Wide Web server that publishes copyrightable works and also
29607 provides prominent facilities for anybody to edit those works.  A
29608 public wiki that anybody can edit is an example of such a server.  A
29609 “Massive Multiauthor Collaboration” (or “MMC”) contained in the
29610 site means any set of copyrightable works thus published on the MMC
29611 site.
29613 “CC-BY-SA” means the Creative Commons Attribution-Share Alike 3.0
29614 license published by Creative Commons Corporation, a not-for-profit
29615 corporation with a principal place of business in San Francisco,
29616 California, as well as future copyleft versions of that license
29617 published by that same organization.
29619 “Incorporate” means to publish or republish a Document, in whole or
29620 in part, as part of another Document.
29622 An MMC is “eligible for relicensing” if it is licensed under this
29623 License, and if all works that were first published under this License
29624 somewhere other than this MMC, and subsequently incorporated in whole
29625 or in part into the MMC, (1) had no cover texts or invariant sections,
29626 and (2) were thus incorporated prior to November 1, 2008.
29628 The operator of an MMC Site may republish an MMC contained in the site
29629 under CC-BY-SA on the same site at any time before August 1, 2009,
29630 provided the MMC is eligible for relicensing.
29632 `ADDENDUM: How to use this License for your documents'
29634 To use this License in a document you have written, include a copy of
29635 the License in the document and put the following copyright and
29636 license notices just after the title page:
29638 @quotation
29640 Copyright © YEAR  YOUR NAME.
29641 Permission is granted to copy, distribute and/or modify this document
29642 under the terms of the GNU Free Documentation License, Version 1.3
29643 or any later version published by the Free Software Foundation;
29644 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
29645 A copy of the license is included in the section entitled “GNU
29646 Free Documentation License”.
29647 @end quotation
29649 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
29650 replace the “with … Texts.” line with this:
29652 @quotation
29654 with the Invariant Sections being LIST THEIR TITLES, with the
29655 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
29656 @end quotation
29658 If you have Invariant Sections without Cover Texts, or some other
29659 combination of the three, merge those two alternatives to suit the
29660 situation.
29662 If your document contains nontrivial examples of program code, we
29663 recommend releasing these examples in parallel under your choice of
29664 free software license, such as the GNU General Public License,
29665 to permit their use in free software.
29667 @node Index,,GNU Free Documentation License,Top
29668 @unnumbered Index
29671 @printindex ge
29673 @anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{                              }
29674 @anchor{d1}@w{                              }
29676 @c %**end of body
29677 @bye