* tree-vect-loop-manip.c (vect_do_peeling): Do not use
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob05fdf4c84d079b4b62e62043e8f129d0c55157f5
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 1.4.6.@*
7 @end ifinfo
8 @settitle GNAT User's Guide for Native Platforms
9 @defindex ge
10 @paragraphindent 0
11 @exampleindent 4
12 @finalout
13 @dircategory GNU Ada Tools 
14 @direntry
15 * gnat_ugn: (gnat_ugn.info). gnat_ugn
16 @end direntry
18 @definfoenclose strong,`,'
19 @definfoenclose emph,`,'
20 @c %**end of header
22 @copying
23 @quotation
24 GNAT User's Guide for Native Platforms , Nov 09, 2017
26 AdaCore
28 Copyright @copyright{} 2008-2017, Free Software Foundation
29 @end quotation
31 @end copying
33 @titlepage
34 @title GNAT User's Guide for Native Platforms
35 @insertcopying
36 @end titlepage
37 @contents
39 @c %** start of user preamble
41 @c %** end of user preamble
43 @ifnottex
44 @node Top
45 @top GNAT User's Guide for Native Platforms
46 @insertcopying
47 @end ifnottex
49 @c %**start of body
50 @anchor{gnat_ugn doc}@anchor{0}
51 @emph{GNAT, The GNU Ada Development Environment}
54 @include gcc-common.texi
55 GCC version @value{version-GCC}@*
56 AdaCore
58 Permission is granted to copy, distribute and/or modify this document
59 under the terms of the GNU Free Documentation License, Version 1.3 or
60 any later version published by the Free Software Foundation; with no
61 Invariant Sections, with the Front-Cover Texts being
62 "GNAT User's Guide for Native Platforms",
63 and with no Back-Cover Texts.  A copy of the license is
64 included in the section entitled @ref{1,,GNU Free Documentation License}.
66 @menu
67 * About This Guide:: 
68 * Getting Started with GNAT:: 
69 * The GNAT Compilation Model:: 
70 * Building Executable Programs with GNAT:: 
71 * GNAT Utility Programs:: 
72 * GNAT and Program Execution:: 
73 * Platform-Specific Information:: 
74 * Example of Binder Output File:: 
75 * Elaboration Order Handling in GNAT:: 
76 * Inline Assembler:: 
77 * GNU Free Documentation License:: 
78 * Index:: 
80 @detailmenu
81  --- The Detailed Node Listing ---
83 About This Guide
85 * What This Guide Contains:: 
86 * What You Should Know before Reading This Guide:: 
87 * Related Information:: 
88 * A Note to Readers of Previous Versions of the Manual:: 
89 * Conventions:: 
91 Getting Started with GNAT
93 * Running GNAT:: 
94 * Running a Simple Ada Program:: 
95 * Running a Program with Multiple Units:: 
96 * Using the gnatmake Utility:: 
98 The GNAT Compilation Model
100 * Source Representation:: 
101 * Foreign Language Representation:: 
102 * File Naming Topics and Utilities:: 
103 * Configuration Pragmas:: 
104 * Generating Object Files:: 
105 * Source Dependencies:: 
106 * The Ada Library Information Files:: 
107 * Binding an Ada Program:: 
108 * GNAT and Libraries:: 
109 * Conditional Compilation:: 
110 * Mixed Language Programming:: 
111 * GNAT and Other Compilation Models:: 
112 * Using GNAT Files with External Tools:: 
114 Foreign Language Representation
116 * Latin-1:: 
117 * Other 8-Bit Codes:: 
118 * Wide_Character Encodings:: 
119 * Wide_Wide_Character Encodings:: 
121 File Naming Topics and Utilities
123 * File Naming Rules:: 
124 * Using Other File Names:: 
125 * Alternative File Naming Schemes:: 
126 * Handling Arbitrary File Naming Conventions with gnatname:: 
127 * File Name Krunching with gnatkr:: 
128 * Renaming Files with gnatchop:: 
130 Handling Arbitrary File Naming Conventions with gnatname
132 * Arbitrary File Naming Conventions:: 
133 * Running gnatname:: 
134 * Switches for gnatname:: 
135 * Examples of gnatname Usage:: 
137 File Name Krunching with gnatkr
139 * About gnatkr:: 
140 * Using gnatkr:: 
141 * Krunching Method:: 
142 * Examples of gnatkr Usage:: 
144 Renaming Files with gnatchop
146 * Handling Files with Multiple Units:: 
147 * Operating gnatchop in Compilation Mode:: 
148 * Command Line for gnatchop:: 
149 * Switches for gnatchop:: 
150 * Examples of gnatchop Usage:: 
152 Configuration Pragmas
154 * Handling of Configuration Pragmas:: 
155 * The Configuration Pragmas Files:: 
157 GNAT and Libraries
159 * Introduction to Libraries in GNAT:: 
160 * General Ada Libraries:: 
161 * Stand-alone Ada Libraries:: 
162 * Rebuilding the GNAT Run-Time Library:: 
164 General Ada Libraries
166 * Building a library:: 
167 * Installing a library:: 
168 * Using a library:: 
170 Stand-alone Ada Libraries
172 * Introduction to Stand-alone Libraries:: 
173 * Building a Stand-alone Library:: 
174 * Creating a Stand-alone Library to be used in a non-Ada context:: 
175 * Restrictions in Stand-alone Libraries:: 
177 Conditional Compilation
179 * Modeling Conditional Compilation in Ada:: 
180 * Preprocessing with gnatprep:: 
181 * Integrated Preprocessing:: 
183 Modeling Conditional Compilation in Ada
185 * Use of Boolean Constants:: 
186 * Debugging - A Special Case:: 
187 * Conditionalizing Declarations:: 
188 * Use of Alternative Implementations:: 
189 * Preprocessing:: 
191 Preprocessing with gnatprep
193 * Preprocessing Symbols:: 
194 * Using gnatprep:: 
195 * Switches for gnatprep:: 
196 * Form of Definitions File:: 
197 * Form of Input Text for gnatprep:: 
199 Mixed Language Programming
201 * Interfacing to C:: 
202 * Calling Conventions:: 
203 * Building Mixed Ada and C++ Programs:: 
204 * Generating Ada Bindings for C and C++ headers:: 
205 * Generating C Headers for Ada Specifications:: 
207 Building Mixed Ada and C++ Programs
209 * Interfacing to C++:: 
210 * Linking a Mixed C++ & Ada Program:: 
211 * A Simple Example:: 
212 * Interfacing with C++ constructors:: 
213 * Interfacing with C++ at the Class Level:: 
215 Generating Ada Bindings for C and C++ headers
217 * Running the Binding Generator:: 
218 * Generating Bindings for C++ Headers:: 
219 * Switches:: 
221 Generating C Headers for Ada Specifications
223 * Running the C Header Generator:: 
225 GNAT and Other Compilation Models
227 * Comparison between GNAT and C/C++ Compilation Models:: 
228 * Comparison between GNAT and Conventional Ada Library Models:: 
230 Using GNAT Files with External Tools
232 * Using Other Utility Programs with GNAT:: 
233 * The External Symbol Naming Scheme of GNAT:: 
235 Building Executable Programs with GNAT
237 * Building with gnatmake:: 
238 * Compiling with gcc:: 
239 * Compiler Switches:: 
240 * Linker Switches:: 
241 * Binding with gnatbind:: 
242 * Linking with gnatlink:: 
243 * Using the GNU make Utility:: 
245 Building with gnatmake
247 * Running gnatmake:: 
248 * Switches for gnatmake:: 
249 * Mode Switches for gnatmake:: 
250 * Notes on the Command Line:: 
251 * How gnatmake Works:: 
252 * Examples of gnatmake Usage:: 
254 Compiling with gcc
256 * Compiling Programs:: 
257 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
258 * Order of Compilation Issues:: 
259 * Examples:: 
261 Compiler Switches
263 * Alphabetical List of All Switches:: 
264 * Output and Error Message Control:: 
265 * Warning Message Control:: 
266 * Debugging and Assertion Control:: 
267 * Validity Checking:: 
268 * Style Checking:: 
269 * Run-Time Checks:: 
270 * Using gcc for Syntax Checking:: 
271 * Using gcc for Semantic Checking:: 
272 * Compiling Different Versions of Ada:: 
273 * Character Set Control:: 
274 * File Naming Control:: 
275 * Subprogram Inlining Control:: 
276 * Auxiliary Output Control:: 
277 * Debugging Control:: 
278 * Exception Handling Control:: 
279 * Units to Sources Mapping Files:: 
280 * Code Generation Control:: 
282 Binding with gnatbind
284 * Running gnatbind:: 
285 * Switches for gnatbind:: 
286 * Command-Line Access:: 
287 * Search Paths for gnatbind:: 
288 * Examples of gnatbind Usage:: 
290 Switches for gnatbind
292 * Consistency-Checking Modes:: 
293 * Binder Error Message Control:: 
294 * Elaboration Control:: 
295 * Output Control:: 
296 * Dynamic Allocation Control:: 
297 * Binding with Non-Ada Main Programs:: 
298 * Binding Programs with No Main Subprogram:: 
300 Linking with gnatlink
302 * Running gnatlink:: 
303 * Switches for gnatlink:: 
305 Using the GNU make Utility
307 * Using gnatmake in a Makefile:: 
308 * Automatically Creating a List of Directories:: 
309 * Generating the Command Line Switches:: 
310 * Overcoming Command Line Length Limits:: 
312 GNAT Utility Programs
314 * The File Cleanup Utility gnatclean:: 
315 * The GNAT Library Browser gnatls:: 
316 * The Cross-Referencing Tools gnatxref and gnatfind:: 
317 * The Ada to HTML Converter gnathtml:: 
319 The File Cleanup Utility gnatclean
321 * Running gnatclean:: 
322 * Switches for gnatclean:: 
324 The GNAT Library Browser gnatls
326 * Running gnatls:: 
327 * Switches for gnatls:: 
328 * Example of gnatls Usage:: 
330 The Cross-Referencing Tools gnatxref and gnatfind
332 * gnatxref Switches:: 
333 * gnatfind Switches:: 
334 * Configuration Files for gnatxref and gnatfind:: 
335 * Regular Expressions in gnatfind and gnatxref:: 
336 * Examples of gnatxref Usage:: 
337 * Examples of gnatfind Usage:: 
339 Examples of gnatxref Usage
341 * General Usage:: 
342 * Using gnatxref with vi:: 
344 The Ada to HTML Converter gnathtml
346 * Invoking gnathtml:: 
347 * Installing gnathtml:: 
349 GNAT and Program Execution
351 * Running and Debugging Ada Programs:: 
352 * Code Coverage and Profiling:: 
353 * Improving Performance:: 
354 * Overflow Check Handling in GNAT:: 
355 * Performing Dimensionality Analysis in GNAT:: 
356 * Stack Related Facilities:: 
357 * Memory Management Issues:: 
359 Running and Debugging Ada Programs
361 * The GNAT Debugger GDB:: 
362 * Running GDB:: 
363 * Introduction to GDB Commands:: 
364 * Using Ada Expressions:: 
365 * Calling User-Defined Subprograms:: 
366 * Using the next Command in a Function:: 
367 * Stopping When Ada Exceptions Are Raised:: 
368 * Ada Tasks:: 
369 * Debugging Generic Units:: 
370 * Remote Debugging with gdbserver:: 
371 * GNAT Abnormal Termination or Failure to Terminate:: 
372 * Naming Conventions for GNAT Source Files:: 
373 * Getting Internal Debugging Information:: 
374 * Stack Traceback:: 
375 * Pretty-Printers for the GNAT runtime:: 
377 Stack Traceback
379 * Non-Symbolic Traceback:: 
380 * Symbolic Traceback:: 
382 Code Coverage and Profiling
384 * Code Coverage of Ada Programs with gcov:: 
385 * Profiling an Ada Program with gprof:: 
387 Code Coverage of Ada Programs with gcov
389 * Quick startup guide:: 
390 * GNAT specifics:: 
392 Profiling an Ada Program with gprof
394 * Compilation for profiling:: 
395 * Program execution:: 
396 * Running gprof:: 
397 * Interpretation of profiling results:: 
399 Improving Performance
401 * Performance Considerations:: 
402 * Text_IO Suggestions:: 
403 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
405 Performance Considerations
407 * Controlling Run-Time Checks:: 
408 * Use of Restrictions:: 
409 * Optimization Levels:: 
410 * Debugging Optimized Code:: 
411 * Inlining of Subprograms:: 
412 * Floating_Point_Operations:: 
413 * Vectorization of loops:: 
414 * Other Optimization Switches:: 
415 * Optimization and Strict Aliasing:: 
416 * Aliased Variables and Optimization:: 
417 * Atomic Variables and Optimization:: 
418 * Passive Task Optimization:: 
420 Reducing Size of Executables with Unused Subprogram/Data Elimination
422 * About unused subprogram/data elimination:: 
423 * Compilation options:: 
424 * Example of unused subprogram/data elimination:: 
426 Overflow Check Handling in GNAT
428 * Background:: 
429 * Management of Overflows in GNAT:: 
430 * Specifying the Desired Mode:: 
431 * Default Settings:: 
432 * Implementation Notes:: 
434 Stack Related Facilities
436 * Stack Overflow Checking:: 
437 * Static Stack Usage Analysis:: 
438 * Dynamic Stack Usage Analysis:: 
440 Memory Management Issues
442 * Some Useful Memory Pools:: 
443 * The GNAT Debug Pool Facility:: 
445 Platform-Specific Information
447 * Run-Time Libraries:: 
448 * Specifying a Run-Time Library:: 
449 * GNU/Linux Topics:: 
450 * Microsoft Windows Topics:: 
451 * Mac OS Topics:: 
453 Run-Time Libraries
455 * Summary of Run-Time Configurations:: 
457 Specifying a Run-Time Library
459 * Choosing the Scheduling Policy:: 
461 GNU/Linux Topics
463 * Required Packages on GNU/Linux;: Required Packages on GNU/Linux. 
465 Microsoft Windows Topics
467 * Using GNAT on Windows:: 
468 * Using a network installation of GNAT:: 
469 * CONSOLE and WINDOWS subsystems:: 
470 * Temporary Files:: 
471 * Disabling Command Line Argument Expansion:: 
472 * Mixed-Language Programming on Windows:: 
473 * Windows Specific Add-Ons:: 
475 Mixed-Language Programming on Windows
477 * Windows Calling Conventions:: 
478 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
479 * Using DLLs with GNAT:: 
480 * Building DLLs with GNAT Project files:: 
481 * Building DLLs with GNAT:: 
482 * Building DLLs with gnatdll:: 
483 * Ada DLLs and Finalization:: 
484 * Creating a Spec for Ada DLLs:: 
485 * GNAT and Windows Resources:: 
486 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
487 * Debugging a DLL:: 
488 * Setting Stack Size from gnatlink:: 
489 * Setting Heap Size from gnatlink:: 
491 Windows Calling Conventions
493 * C Calling Convention:: 
494 * Stdcall Calling Convention:: 
495 * Win32 Calling Convention:: 
496 * DLL Calling Convention:: 
498 Using DLLs with GNAT
500 * Creating an Ada Spec for the DLL Services:: 
501 * Creating an Import Library:: 
503 Building DLLs with gnatdll
505 * Limitations When Using Ada DLLs from Ada:: 
506 * Exporting Ada Entities:: 
507 * Ada DLLs and Elaboration:: 
509 Creating a Spec for Ada DLLs
511 * Creating the Definition File:: 
512 * Using gnatdll:: 
514 GNAT and Windows Resources
516 * Building Resources:: 
517 * Compiling Resources:: 
518 * Using Resources:: 
520 Debugging a DLL
522 * Program and DLL Both Built with GCC/GNAT:: 
523 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
525 Windows Specific Add-Ons
527 * Win32Ada:: 
528 * wPOSIX:: 
530 Mac OS Topics
532 * Codesigning the Debugger:: 
534 Elaboration Order Handling in GNAT
536 * Elaboration Code:: 
537 * Elaboration Order:: 
538 * Checking the Elaboration Order:: 
539 * Controlling the Elaboration Order in Ada:: 
540 * Controlling the Elaboration Order in GNAT:: 
541 * Common Elaboration-model Traits:: 
542 * Dynamic Elaboration Model in GNAT:: 
543 * Static Elaboration Model in GNAT:: 
544 * SPARK Elaboration Model in GNAT:: 
545 * Mixing Elaboration Models:: 
546 * Elaboration Circularities:: 
547 * Resolving Elaboration Circularities:: 
548 * Resolving Task Issues:: 
549 * Elaboration-related Compiler Switches:: 
550 * Summary of Procedures for Elaboration Control:: 
551 * Inspecting the Chosen Elaboration Order:: 
553 Inline Assembler
555 * Basic Assembler Syntax:: 
556 * A Simple Example of Inline Assembler:: 
557 * Output Variables in Inline Assembler:: 
558 * Input Variables in Inline Assembler:: 
559 * Inlining Inline Assembler Code:: 
560 * Other Asm Functionality:: 
562 Other Asm Functionality
564 * The Clobber Parameter:: 
565 * The Volatile Parameter:: 
567 @end detailmenu
568 @end menu
570 @node About This Guide,Getting Started with GNAT,Top,Top
571 @anchor{gnat_ugn/about_this_guide about-this-guide}@anchor{2}@anchor{gnat_ugn/about_this_guide doc}@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}
572 @chapter About This Guide
576 This guide describes the use of GNAT,
577 a compiler and software development
578 toolset for the full Ada programming language.
579 It documents the features of the compiler and tools, and explains
580 how to use them to build Ada applications.
582 GNAT implements Ada 95, Ada 2005 and Ada 2012, and it may also be
583 invoked in Ada 83 compatibility mode.
584 By default, GNAT assumes Ada 2012, but you can override with a
585 compiler switch (@ref{6,,Compiling Different Versions of Ada})
586 to explicitly specify the language version.
587 Throughout this manual, references to 'Ada' without a year suffix
588 apply to all Ada 95/2005/2012 versions of the language.
590 @menu
591 * What This Guide Contains:: 
592 * What You Should Know before Reading This Guide:: 
593 * Related Information:: 
594 * A Note to Readers of Previous Versions of the Manual:: 
595 * Conventions:: 
597 @end menu
599 @node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
600 @anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
601 @section What This Guide Contains
604 This guide contains the following chapters:
607 @itemize *
609 @item 
610 @ref{8,,Getting Started with GNAT} describes how to get started compiling
611 and running Ada programs with the GNAT Ada programming environment.
613 @item 
614 @ref{9,,The GNAT Compilation Model} describes the compilation model used
615 by GNAT.
617 @item 
618 @ref{a,,Building Executable Programs with GNAT} describes how to use the
619 main GNAT tools to build executable programs, and it also gives examples of
620 using the GNU make utility with GNAT.
622 @item 
623 @ref{b,,GNAT Utility Programs} explains the various utility programs that
624 are included in the GNAT environment
626 @item 
627 @ref{c,,GNAT and Program Execution} covers a number of topics related to
628 running, debugging, and tuning the performace of programs developed
629 with GNAT
630 @end itemize
632 Appendices cover several additional topics:
635 @itemize *
637 @item 
638 @ref{d,,Platform-Specific Information} describes the different run-time
639 library implementations and also presents information on how to use
640 GNAT on several specific platforms
642 @item 
643 @ref{e,,Example of Binder Output File} shows the source code for the binder
644 output file for a sample program.
646 @item 
647 @ref{f,,Elaboration Order Handling in GNAT} describes how GNAT helps
648 you deal with elaboration order issues.
650 @item 
651 @ref{10,,Inline Assembler} shows how to use the inline assembly facility
652 in an Ada program.
653 @end itemize
655 @node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
656 @anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{11}
657 @section What You Should Know before Reading This Guide
660 @geindex Ada 95 Language Reference Manual
662 @geindex Ada 2005 Language Reference Manual
664 This guide assumes a basic familiarity with the Ada 95 language, as
665 described in the International Standard ANSI/ISO/IEC-8652:1995, January
666 1995.
667 It does not require knowledge of the features introduced by Ada 2005
668 or Ada 2012.
669 Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
670 the GNAT documentation package.
672 @node Related Information,A Note to Readers of Previous Versions of the Manual,What You Should Know before Reading This Guide,About This Guide
673 @anchor{gnat_ugn/about_this_guide related-information}@anchor{12}
674 @section Related Information
677 For further information about Ada and related tools, please refer to the
678 following documents:
681 @itemize *
683 @item 
684 @cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
685 @cite{Ada 2012 Reference Manual}, which contain reference
686 material for the several revisions of the Ada language standard.
688 @item 
689 @cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
690 implementation of Ada.
692 @item 
693 @cite{Using the GNAT Programming Studio}, which describes the GPS
694 Integrated Development Environment.
696 @item 
697 @cite{GNAT Programming Studio Tutorial}, which introduces the
698 main GPS features through examples.
700 @item 
701 @cite{Debugging with GDB},
702 for all details on the use of the GNU source-level debugger.
704 @item 
705 @cite{GNU Emacs Manual},
706 for full information on the extensible editor and programming
707 environment Emacs.
708 @end itemize
710 @node A Note to Readers of Previous Versions of the Manual,Conventions,Related Information,About This Guide
711 @anchor{gnat_ugn/about_this_guide a-note-to-readers-of-previous-versions-of-the-manual}@anchor{13}
712 @section A Note to Readers of Previous Versions of the Manual
715 In early 2015 the GNAT manuals were transitioned to the
716 reStructuredText (rst) / Sphinx documentation generator technology.
717 During that process the @cite{GNAT User's Guide} was reorganized
718 so that related topics would be described together in the same chapter
719 or appendix.  Here's a summary of the major changes realized in
720 the new document structure.
723 @itemize *
725 @item 
726 @ref{9,,The GNAT Compilation Model} has been extended so that it now covers
727 the following material:
730 @itemize -
732 @item 
733 The @code{gnatname}, @code{gnatkr}, and @code{gnatchop} tools
735 @item 
736 @ref{14,,Configuration Pragmas}
738 @item 
739 @ref{15,,GNAT and Libraries}
741 @item 
742 @ref{16,,Conditional Compilation} including @ref{17,,Preprocessing with gnatprep}
743 and @ref{18,,Integrated Preprocessing}
745 @item 
746 @ref{19,,Generating Ada Bindings for C and C++ headers}
748 @item 
749 @ref{1a,,Using GNAT Files with External Tools}
750 @end itemize
752 @item 
753 @ref{a,,Building Executable Programs with GNAT} is a new chapter consolidating
754 the following content:
757 @itemize -
759 @item 
760 @ref{1b,,Building with gnatmake}
762 @item 
763 @ref{1c,,Compiling with gcc}
765 @item 
766 @ref{1d,,Binding with gnatbind}
768 @item 
769 @ref{1e,,Linking with gnatlink}
771 @item 
772 @ref{1f,,Using the GNU make Utility}
773 @end itemize
775 @item 
776 @ref{b,,GNAT Utility Programs} is a new chapter consolidating the information about several
777 GNAT tools:
781 @itemize -
783 @item 
784 @ref{20,,The File Cleanup Utility gnatclean}
786 @item 
787 @ref{21,,The GNAT Library Browser gnatls}
789 @item 
790 @ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
792 @item 
793 @ref{23,,The Ada to HTML Converter gnathtml}
794 @end itemize
796 @item 
797 @ref{c,,GNAT and Program Execution} is a new chapter consolidating the following:
800 @itemize -
802 @item 
803 @ref{24,,Running and Debugging Ada Programs}
805 @item 
806 @ref{25,,Code Coverage and Profiling}
808 @item 
809 @ref{26,,Improving Performance}
811 @item 
812 @ref{27,,Overflow Check Handling in GNAT}
814 @item 
815 @ref{28,,Performing Dimensionality Analysis in GNAT}
817 @item 
818 @ref{29,,Stack Related Facilities}
820 @item 
821 @ref{2a,,Memory Management Issues}
822 @end itemize
824 @item 
825 @ref{d,,Platform-Specific Information} is a new appendix consolidating the following:
828 @itemize -
830 @item 
831 @ref{2b,,Run-Time Libraries}
833 @item 
834 @ref{2c,,Microsoft Windows Topics}
836 @item 
837 @ref{2d,,Mac OS Topics}
838 @end itemize
840 @item 
841 The @emph{Compatibility and Porting Guide} appendix has been moved to the
842 @cite{GNAT Reference Manual}. It now includes a section
843 @emph{Writing Portable Fixed-Point Declarations} which was previously
844 a separate chapter in the @cite{GNAT User's Guide}.
845 @end itemize
847 @node Conventions,,A Note to Readers of Previous Versions of the Manual,About This Guide
848 @anchor{gnat_ugn/about_this_guide conventions}@anchor{2e}
849 @section Conventions
852 @geindex Conventions
853 @geindex typographical
855 @geindex Typographical conventions
857 Following are examples of the typographical and graphic conventions used
858 in this guide:
861 @itemize *
863 @item 
864 @code{Functions}, @code{utility program names}, @code{standard names},
865 and @code{classes}.
867 @item 
868 @code{Option flags}
870 @item 
871 @code{File names}
873 @item 
874 @code{Variables}
876 @item 
877 @emph{Emphasis}
879 @item 
880 [optional information or parameters]
882 @item 
883 Examples are described by text
885 @example
886 and then shown this way.
887 @end example
889 @item 
890 Commands that are entered by the user are shown as preceded by a prompt string
891 comprising the @code{$} character followed by a space.
893 @item 
894 Full file names are shown with the '/' character
895 as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
896 If you are using GNAT on a Windows platform, please note that
897 the '\' character should be used instead.
898 @end itemize
900 @node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
901 @anchor{gnat_ugn/getting_started_with_gnat getting-started-with-gnat}@anchor{8}@anchor{gnat_ugn/getting_started_with_gnat doc}@anchor{2f}@anchor{gnat_ugn/getting_started_with_gnat id1}@anchor{30}
902 @chapter Getting Started with GNAT
905 This chapter describes how to use GNAT's command line interface to build
906 executable Ada programs.
907 On most platforms a visually oriented Integrated Development Environment
908 is also available, the GNAT Programming Studio (GPS).
909 GPS offers a graphical "look and feel", support for development in
910 other programming languages, comprehensive browsing features, and
911 many other capabilities.
912 For information on GPS please refer to
913 @cite{Using the GNAT Programming Studio}.
915 @menu
916 * Running GNAT:: 
917 * Running a Simple Ada Program:: 
918 * Running a Program with Multiple Units:: 
919 * Using the gnatmake Utility:: 
921 @end menu
923 @node Running GNAT,Running a Simple Ada Program,,Getting Started with GNAT
924 @anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{31}@anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{32}
925 @section Running GNAT
928 Three steps are needed to create an executable file from an Ada source
929 file:
932 @itemize *
934 @item 
935 The source file(s) must be compiled.
937 @item 
938 The file(s) must be bound using the GNAT binder.
940 @item 
941 All appropriate object files must be linked to produce an executable.
942 @end itemize
944 All three steps are most commonly handled by using the @code{gnatmake}
945 utility program that, given the name of the main program, automatically
946 performs the necessary compilation, binding and linking steps.
948 @node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
949 @anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{33}@anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{34}
950 @section Running a Simple Ada Program
953 Any text editor may be used to prepare an Ada program.
954 (If Emacs is used, the optional Ada mode may be helpful in laying out the
955 program.)
956 The program text is a normal text file. We will assume in our initial
957 example that you have used your editor to prepare the following
958 standard format text file:
960 @example
961 with Ada.Text_IO; use Ada.Text_IO;
962 procedure Hello is
963 begin
964    Put_Line ("Hello WORLD!");
965 end Hello;
966 @end example
968 This file should be named @code{hello.adb}.
969 With the normal default file naming conventions, GNAT requires
970 that each file
971 contain a single compilation unit whose file name is the
972 unit name,
973 with periods replaced by hyphens; the
974 extension is @code{ads} for a
975 spec and @code{adb} for a body.
976 You can override this default file naming convention by use of the
977 special pragma @code{Source_File_Name} (for further information please
978 see @ref{35,,Using Other File Names}).
979 Alternatively, if you want to rename your files according to this default
980 convention, which is probably more convenient if you will be using GNAT
981 for all your compilations, then the @code{gnatchop} utility
982 can be used to generate correctly-named source files
983 (see @ref{36,,Renaming Files with gnatchop}).
985 You can compile the program using the following command (@code{$} is used
986 as the command prompt in the examples in this document):
988 @example
989 $ gcc -c hello.adb
990 @end example
992 @code{gcc} is the command used to run the compiler. This compiler is
993 capable of compiling programs in several languages, including Ada and
994 C. It assumes that you have given it an Ada program if the file extension is
995 either @code{.ads} or @code{.adb}, and it will then call
996 the GNAT compiler to compile the specified file.
998 The @code{-c} switch is required. It tells @code{gcc} to only do a
999 compilation. (For C programs, @code{gcc} can also do linking, but this
1000 capability is not used directly for Ada programs, so the @code{-c}
1001 switch must always be present.)
1003 This compile command generates a file
1004 @code{hello.o}, which is the object
1005 file corresponding to your Ada program. It also generates
1006 an 'Ada Library Information' file @code{hello.ali},
1007 which contains additional information used to check
1008 that an Ada program is consistent.
1009 To build an executable file,
1010 use @code{gnatbind} to bind the program
1011 and @code{gnatlink} to link it. The
1012 argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1013 @code{ALI} file, but the default extension of @code{.ali} can
1014 be omitted. This means that in the most common case, the argument
1015 is simply the name of the main program:
1017 @example
1018 $ gnatbind hello
1019 $ gnatlink hello
1020 @end example
1022 A simpler method of carrying out these steps is to use @code{gnatmake},
1023 a master program that invokes all the required
1024 compilation, binding and linking tools in the correct order. In particular,
1025 @code{gnatmake} automatically recompiles any sources that have been
1026 modified since they were last compiled, or sources that depend
1027 on such modified sources, so that 'version skew' is avoided.
1029 @geindex Version skew (avoided by `@w{`}gnatmake`@w{`})
1031 @example
1032 $ gnatmake hello.adb
1033 @end example
1035 The result is an executable program called @code{hello}, which can be
1036 run by entering:
1038 @example
1039 $ hello
1040 @end example
1042 assuming that the current directory is on the search path
1043 for executable programs.
1045 and, if all has gone well, you will see:
1047 @example
1048 Hello WORLD!
1049 @end example
1051 appear in response to this command.
1053 @node Running a Program with Multiple Units,Using the gnatmake Utility,Running a Simple Ada Program,Getting Started with GNAT
1054 @anchor{gnat_ugn/getting_started_with_gnat id4}@anchor{37}@anchor{gnat_ugn/getting_started_with_gnat running-a-program-with-multiple-units}@anchor{38}
1055 @section Running a Program with Multiple Units
1058 Consider a slightly more complicated example that has three files: a
1059 main program, and the spec and body of a package:
1061 @example
1062 package Greetings is
1063    procedure Hello;
1064    procedure Goodbye;
1065 end Greetings;
1067 with Ada.Text_IO; use Ada.Text_IO;
1068 package body Greetings is
1069    procedure Hello is
1070    begin
1071       Put_Line ("Hello WORLD!");
1072    end Hello;
1074    procedure Goodbye is
1075    begin
1076       Put_Line ("Goodbye WORLD!");
1077    end Goodbye;
1078 end Greetings;
1080 with Greetings;
1081 procedure Gmain is
1082 begin
1083    Greetings.Hello;
1084    Greetings.Goodbye;
1085 end Gmain;
1086 @end example
1088 Following the one-unit-per-file rule, place this program in the
1089 following three separate files:
1092 @table @asis
1094 @item @emph{greetings.ads}
1096 spec of package @code{Greetings}
1098 @item @emph{greetings.adb}
1100 body of package @code{Greetings}
1102 @item @emph{gmain.adb}
1104 body of main program
1105 @end table
1107 To build an executable version of
1108 this program, we could use four separate steps to compile, bind, and link
1109 the program, as follows:
1111 @example
1112 $ gcc -c gmain.adb
1113 $ gcc -c greetings.adb
1114 $ gnatbind gmain
1115 $ gnatlink gmain
1116 @end example
1118 Note that there is no required order of compilation when using GNAT.
1119 In particular it is perfectly fine to compile the main program first.
1120 Also, it is not necessary to compile package specs in the case where
1121 there is an accompanying body; you only need to compile the body. If you want
1122 to submit these files to the compiler for semantic checking and not code
1123 generation, then use the @code{-gnatc} switch:
1125 @example
1126 $ gcc -c greetings.ads -gnatc
1127 @end example
1129 Although the compilation can be done in separate steps as in the
1130 above example, in practice it is almost always more convenient
1131 to use the @code{gnatmake} tool. All you need to know in this case
1132 is the name of the main program's source file. The effect of the above four
1133 commands can be achieved with a single one:
1135 @example
1136 $ gnatmake gmain.adb
1137 @end example
1139 In the next section we discuss the advantages of using @code{gnatmake} in
1140 more detail.
1142 @node Using the gnatmake Utility,,Running a Program with Multiple Units,Getting Started with GNAT
1143 @anchor{gnat_ugn/getting_started_with_gnat using-the-gnatmake-utility}@anchor{39}@anchor{gnat_ugn/getting_started_with_gnat id5}@anchor{3a}
1144 @section Using the @code{gnatmake} Utility
1147 If you work on a program by compiling single components at a time using
1148 @code{gcc}, you typically keep track of the units you modify. In order to
1149 build a consistent system, you compile not only these units, but also any
1150 units that depend on the units you have modified.
1151 For example, in the preceding case,
1152 if you edit @code{gmain.adb}, you only need to recompile that file. But if
1153 you edit @code{greetings.ads}, you must recompile both
1154 @code{greetings.adb} and @code{gmain.adb}, because both files contain
1155 units that depend on @code{greetings.ads}.
1157 @code{gnatbind} will warn you if you forget one of these compilation
1158 steps, so that it is impossible to generate an inconsistent program as a
1159 result of forgetting to do a compilation. Nevertheless it is tedious and
1160 error-prone to keep track of dependencies among units.
1161 One approach to handle the dependency-bookkeeping is to use a
1162 makefile. However, makefiles present maintenance problems of their own:
1163 if the dependencies change as you change the program, you must make
1164 sure that the makefile is kept up-to-date manually, which is also an
1165 error-prone process.
1167 The @code{gnatmake} utility takes care of these details automatically.
1168 Invoke it using either one of the following forms:
1170 @example
1171 $ gnatmake gmain.adb
1172 $ gnatmake gmain
1173 @end example
1175 The argument is the name of the file containing the main program;
1176 you may omit the extension. @code{gnatmake}
1177 examines the environment, automatically recompiles any files that need
1178 recompiling, and binds and links the resulting set of object files,
1179 generating the executable file, @code{gmain}.
1180 In a large program, it
1181 can be extremely helpful to use @code{gnatmake}, because working out by hand
1182 what needs to be recompiled can be difficult.
1184 Note that @code{gnatmake} takes into account all the Ada rules that
1185 establish dependencies among units. These include dependencies that result
1186 from inlining subprogram bodies, and from
1187 generic instantiation. Unlike some other
1188 Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1189 found by the compiler on a previous compilation, which may possibly
1190 be wrong when sources change. @code{gnatmake} determines the exact set of
1191 dependencies from scratch each time it is run.
1193 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
1195 @node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
1196 @anchor{gnat_ugn/the_gnat_compilation_model doc}@anchor{3b}@anchor{gnat_ugn/the_gnat_compilation_model the-gnat-compilation-model}@anchor{9}@anchor{gnat_ugn/the_gnat_compilation_model id1}@anchor{3c}
1197 @chapter The GNAT Compilation Model
1200 @geindex GNAT compilation model
1202 @geindex Compilation model
1204 This chapter describes the compilation model used by GNAT. Although
1205 similar to that used by other languages such as C and C++, this model
1206 is substantially different from the traditional Ada compilation models,
1207 which are based on a centralized program library. The chapter covers
1208 the following material:
1211 @itemize *
1213 @item 
1214 Topics related to source file makeup and naming
1217 @itemize *
1219 @item 
1220 @ref{3d,,Source Representation}
1222 @item 
1223 @ref{3e,,Foreign Language Representation}
1225 @item 
1226 @ref{3f,,File Naming Topics and Utilities}
1227 @end itemize
1229 @item 
1230 @ref{14,,Configuration Pragmas}
1232 @item 
1233 @ref{40,,Generating Object Files}
1235 @item 
1236 @ref{41,,Source Dependencies}
1238 @item 
1239 @ref{42,,The Ada Library Information Files}
1241 @item 
1242 @ref{43,,Binding an Ada Program}
1244 @item 
1245 @ref{15,,GNAT and Libraries}
1247 @item 
1248 @ref{16,,Conditional Compilation}
1250 @item 
1251 @ref{44,,Mixed Language Programming}
1253 @item 
1254 @ref{45,,GNAT and Other Compilation Models}
1256 @item 
1257 @ref{1a,,Using GNAT Files with External Tools}
1258 @end itemize
1260 @menu
1261 * Source Representation:: 
1262 * Foreign Language Representation:: 
1263 * File Naming Topics and Utilities:: 
1264 * Configuration Pragmas:: 
1265 * Generating Object Files:: 
1266 * Source Dependencies:: 
1267 * The Ada Library Information Files:: 
1268 * Binding an Ada Program:: 
1269 * GNAT and Libraries:: 
1270 * Conditional Compilation:: 
1271 * Mixed Language Programming:: 
1272 * GNAT and Other Compilation Models:: 
1273 * Using GNAT Files with External Tools:: 
1275 @end menu
1277 @node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1278 @anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{3d}@anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{46}
1279 @section Source Representation
1282 @geindex Latin-1
1284 @geindex VT
1285 @geindex HT
1286 @geindex CR
1287 @geindex LF
1288 @geindex FF
1290 Ada source programs are represented in standard text files, using
1291 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1292 7-bit ASCII set, plus additional characters used for
1293 representing foreign languages (see @ref{3e,,Foreign Language Representation}
1294 for support of non-USA character sets). The format effector characters
1295 are represented using their standard ASCII encodings, as follows:
1297 @quotation
1300 @multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxx} 
1301 @item
1303 Character
1305 @tab
1307 Effect
1309 @tab
1311 Code
1313 @item
1315 @code{VT}
1317 @tab
1319 Vertical tab
1321 @tab
1323 @code{16#0B#}
1325 @item
1327 @code{HT}
1329 @tab
1331 Horizontal tab
1333 @tab
1335 @code{16#09#}
1337 @item
1339 @code{CR}
1341 @tab
1343 Carriage return
1345 @tab
1347 @code{16#0D#}
1349 @item
1351 @code{LF}
1353 @tab
1355 Line feed
1357 @tab
1359 @code{16#0A#}
1361 @item
1363 @code{FF}
1365 @tab
1367 Form feed
1369 @tab
1371 @code{16#0C#}
1373 @end multitable
1375 @end quotation
1377 Source files are in standard text file format. In addition, GNAT will
1378 recognize a wide variety of stream formats, in which the end of
1379 physical lines is marked by any of the following sequences:
1380 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1381 in accommodating files that are imported from other operating systems.
1383 @geindex End of source file; Source file@comma{} end
1385 @geindex SUB (control character)
1387 The end of a source file is normally represented by the physical end of
1388 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1389 recognized as signalling the end of the source file. Again, this is
1390 provided for compatibility with other operating systems where this
1391 code is used to represent the end of file.
1393 @geindex spec (definition)
1394 @geindex compilation (definition)
1396 Each file contains a single Ada compilation unit, including any pragmas
1397 associated with the unit. For example, this means you must place a
1398 package declaration (a package @emph{spec}) and the corresponding body in
1399 separate files. An Ada @emph{compilation} (which is a sequence of
1400 compilation units) is represented using a sequence of files. Similarly,
1401 you will place each subunit or child unit in a separate file.
1403 @node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1404 @anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{3e}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{47}
1405 @section Foreign Language Representation
1408 GNAT supports the standard character sets defined in Ada as well as
1409 several other non-standard character sets for use in localized versions
1410 of the compiler (@ref{48,,Character Set Control}).
1412 @menu
1413 * Latin-1:: 
1414 * Other 8-Bit Codes:: 
1415 * Wide_Character Encodings:: 
1416 * Wide_Wide_Character Encodings:: 
1418 @end menu
1420 @node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1421 @anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{49}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{4a}
1422 @subsection Latin-1
1425 @geindex Latin-1
1427 The basic character set is Latin-1. This character set is defined by ISO
1428 standard 8859, part 1. The lower half (character codes @code{16#00#}
1429 ... @code{16#7F#)} is identical to standard ASCII coding, but the upper
1430 half is used to represent additional characters. These include extended letters
1431 used by European languages, such as French accents, the vowels with umlauts
1432 used in German, and the extra letter A-ring used in Swedish.
1434 @geindex Ada.Characters.Latin_1
1436 For a complete list of Latin-1 codes and their encodings, see the source
1437 file of library unit @code{Ada.Characters.Latin_1} in file
1438 @code{a-chlat1.ads}.
1439 You may use any of these extended characters freely in character or
1440 string literals. In addition, the extended characters that represent
1441 letters can be used in identifiers.
1443 @node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1444 @anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{4b}@anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{4c}
1445 @subsection Other 8-Bit Codes
1448 GNAT also supports several other 8-bit coding schemes:
1450 @geindex Latin-2
1452 @geindex ISO 8859-2
1455 @table @asis
1457 @item @emph{ISO 8859-2 (Latin-2)}
1459 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1460 equivalence.
1461 @end table
1463 @geindex Latin-3
1465 @geindex ISO 8859-3
1468 @table @asis
1470 @item @emph{ISO 8859-3 (Latin-3)}
1472 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1473 equivalence.
1474 @end table
1476 @geindex Latin-4
1478 @geindex ISO 8859-4
1481 @table @asis
1483 @item @emph{ISO 8859-4 (Latin-4)}
1485 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1486 equivalence.
1487 @end table
1489 @geindex ISO 8859-5
1491 @geindex Cyrillic
1494 @table @asis
1496 @item @emph{ISO 8859-5 (Cyrillic)}
1498 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1499 lowercase equivalence.
1500 @end table
1502 @geindex ISO 8859-15
1504 @geindex Latin-9
1507 @table @asis
1509 @item @emph{ISO 8859-15 (Latin-9)}
1511 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1512 lowercase equivalence
1513 @end table
1515 @geindex code page 437 (IBM PC)
1518 @table @asis
1520 @item @emph{IBM PC (code page 437)}
1522 This code page is the normal default for PCs in the U.S. It corresponds
1523 to the original IBM PC character set. This set has some, but not all, of
1524 the extended Latin-1 letters, but these letters do not have the same
1525 encoding as Latin-1. In this mode, these letters are allowed in
1526 identifiers with uppercase and lowercase equivalence.
1527 @end table
1529 @geindex code page 850 (IBM PC)
1532 @table @asis
1534 @item @emph{IBM PC (code page 850)}
1536 This code page is a modification of 437 extended to include all the
1537 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1538 mode, all these letters are allowed in identifiers with uppercase and
1539 lowercase equivalence.
1541 @item @emph{Full Upper 8-bit}
1543 Any character in the range 80-FF allowed in identifiers, and all are
1544 considered distinct. In other words, there are no uppercase and lowercase
1545 equivalences in this range. This is useful in conjunction with
1546 certain encoding schemes used for some foreign character sets (e.g.,
1547 the typical method of representing Chinese characters on the PC).
1549 @item @emph{No Upper-Half}
1551 No upper-half characters in the range 80-FF are allowed in identifiers.
1552 This gives Ada 83 compatibility for identifier names.
1553 @end table
1555 For precise data on the encodings permitted, and the uppercase and lowercase
1556 equivalences that are recognized, see the file @code{csets.adb} in
1557 the GNAT compiler sources. You will need to obtain a full source release
1558 of GNAT to obtain this file.
1560 @node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1561 @anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{4d}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{4e}
1562 @subsection Wide_Character Encodings
1565 GNAT allows wide character codes to appear in character and string
1566 literals, and also optionally in identifiers, by means of the following
1567 possible encoding schemes:
1570 @table @asis
1572 @item @emph{Hex Coding}
1574 In this encoding, a wide character is represented by the following five
1575 character sequence:
1577 @example
1578 ESC a b c d
1579 @end example
1581 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1582 characters (using uppercase letters) of the wide character code. For
1583 example, ESC A345 is used to represent the wide character with code
1584 @code{16#A345#}.
1585 This scheme is compatible with use of the full Wide_Character set.
1587 @item @emph{Upper-Half Coding}
1589 @geindex Upper-Half Coding
1591 The wide character with encoding @code{16#abcd#} where the upper bit is on
1592 (in other words, 'a' is in the range 8-F) is represented as two bytes,
1593 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1594 character, but is not required to be in the upper half. This method can
1595 be also used for shift-JIS or EUC, where the internal coding matches the
1596 external coding.
1598 @item @emph{Shift JIS Coding}
1600 @geindex Shift JIS Coding
1602 A wide character is represented by a two-character sequence,
1603 @code{16#ab#} and
1604 @code{16#cd#}, with the restrictions described for upper-half encoding as
1605 described above. The internal character code is the corresponding JIS
1606 character according to the standard algorithm for Shift-JIS
1607 conversion. Only characters defined in the JIS code set table can be
1608 used with this encoding method.
1610 @item @emph{EUC Coding}
1612 @geindex EUC Coding
1614 A wide character is represented by a two-character sequence
1615 @code{16#ab#} and
1616 @code{16#cd#}, with both characters being in the upper half. The internal
1617 character code is the corresponding JIS character according to the EUC
1618 encoding algorithm. Only characters defined in the JIS code set table
1619 can be used with this encoding method.
1621 @item @emph{UTF-8 Coding}
1623 A wide character is represented using
1624 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1625 10646-1/Am.2. Depending on the character value, the representation
1626 is a one, two, or three byte sequence:
1628 @example
1629 16#0000#-16#007f#: 2#0xxxxxxx#
1630 16#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
1631 16#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1632 @end example
1634 where the @code{xxx} bits correspond to the left-padded bits of the
1635 16-bit character value. Note that all lower half ASCII characters
1636 are represented as ASCII bytes and all upper half characters and
1637 other wide characters are represented as sequences of upper-half
1638 (The full UTF-8 scheme allows for encoding 31-bit characters as
1639 6-byte sequences, and in the following section on wide wide
1640 characters, the use of these sequences is documented).
1642 @item @emph{Brackets Coding}
1644 In this encoding, a wide character is represented by the following eight
1645 character sequence:
1647 @example
1648 [ " a b c d " ]
1649 @end example
1651 where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1652 characters (using uppercase letters) of the wide character code. For
1653 example, ['A345'] is used to represent the wide character with code
1654 @code{16#A345#}. It is also possible (though not required) to use the
1655 Brackets coding for upper half characters. For example, the code
1656 @code{16#A3#} can be represented as @code{['A3']}.
1658 This scheme is compatible with use of the full Wide_Character set,
1659 and is also the method used for wide character encoding in some standard
1660 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1661 @end table
1663 @cartouche
1664 @quotation Note 
1665 Some of these coding schemes do not permit the full use of the
1666 Ada character set. For example, neither Shift JIS nor EUC allow the
1667 use of the upper half of the Latin-1 set.
1668 @end quotation
1669 @end cartouche
1671 @node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1672 @anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{4f}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{50}
1673 @subsection Wide_Wide_Character Encodings
1676 GNAT allows wide wide character codes to appear in character and string
1677 literals, and also optionally in identifiers, by means of the following
1678 possible encoding schemes:
1681 @table @asis
1683 @item @emph{UTF-8 Coding}
1685 A wide character is represented using
1686 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1687 10646-1/Am.2. Depending on the character value, the representation
1688 of character codes with values greater than 16#FFFF# is a
1689 is a four, five, or six byte sequence:
1691 @example
1692 16#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1693                              10xxxxxx
1694 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1695                              10xxxxxx 10xxxxxx
1696 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1697                              10xxxxxx 10xxxxxx 10xxxxxx
1698 @end example
1700 where the @code{xxx} bits correspond to the left-padded bits of the
1701 32-bit character value.
1703 @item @emph{Brackets Coding}
1705 In this encoding, a wide wide character is represented by the following ten or
1706 twelve byte character sequence:
1708 @example
1709 [ " a b c d e f " ]
1710 [ " a b c d e f g h " ]
1711 @end example
1713 where @code{a-h} are the six or eight hexadecimal
1714 characters (using uppercase letters) of the wide wide character code. For
1715 example, ["1F4567"] is used to represent the wide wide character with code
1716 @code{16#001F_4567#}.
1718 This scheme is compatible with use of the full Wide_Wide_Character set,
1719 and is also the method used for wide wide character encoding in some standard
1720 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1721 @end table
1723 @node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1724 @anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{3f}
1725 @section File Naming Topics and Utilities
1728 GNAT has a default file naming scheme and also provides the user with
1729 a high degree of control over how the names and extensions of the
1730 source files correspond to the Ada compilation units that they contain.
1732 @menu
1733 * File Naming Rules:: 
1734 * Using Other File Names:: 
1735 * Alternative File Naming Schemes:: 
1736 * Handling Arbitrary File Naming Conventions with gnatname:: 
1737 * File Name Krunching with gnatkr:: 
1738 * Renaming Files with gnatchop:: 
1740 @end menu
1742 @node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1743 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{52}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{53}
1744 @subsection File Naming Rules
1747 The default file name is determined by the name of the unit that the
1748 file contains. The name is formed by taking the full expanded name of
1749 the unit and replacing the separating dots with hyphens and using
1750 lowercase for all letters.
1752 An exception arises if the file name generated by the above rules starts
1753 with one of the characters
1754 @code{a}, @code{g}, @code{i}, or @code{s}, and the second character is a
1755 minus. In this case, the character tilde is used in place
1756 of the minus. The reason for this special rule is to avoid clashes with
1757 the standard names for child units of the packages System, Ada,
1758 Interfaces, and GNAT, which use the prefixes
1759 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
1760 respectively.
1762 The file extension is @code{.ads} for a spec and
1763 @code{.adb} for a body. The following table shows some
1764 examples of these rules.
1766 @quotation
1769 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
1770 @item
1772 Source File
1774 @tab
1776 Ada Compilation Unit
1778 @item
1780 @code{main.ads}
1782 @tab
1784 Main (spec)
1786 @item
1788 @code{main.adb}
1790 @tab
1792 Main (body)
1794 @item
1796 @code{arith_functions.ads}
1798 @tab
1800 Arith_Functions (package spec)
1802 @item
1804 @code{arith_functions.adb}
1806 @tab
1808 Arith_Functions (package body)
1810 @item
1812 @code{func-spec.ads}
1814 @tab
1816 Func.Spec (child package spec)
1818 @item
1820 @code{func-spec.adb}
1822 @tab
1824 Func.Spec (child package body)
1826 @item
1828 @code{main-sub.adb}
1830 @tab
1832 Sub (subunit of Main)
1834 @item
1836 @code{a~bad.adb}
1838 @tab
1840 A.Bad (child package body)
1842 @end multitable
1844 @end quotation
1846 Following these rules can result in excessively long
1847 file names if corresponding
1848 unit names are long (for example, if child units or subunits are
1849 heavily nested). An option is available to shorten such long file names
1850 (called file name 'krunching'). This may be particularly useful when
1851 programs being developed with GNAT are to be used on operating systems
1852 with limited file name lengths. @ref{54,,Using gnatkr}.
1854 Of course, no file shortening algorithm can guarantee uniqueness over
1855 all possible unit names; if file name krunching is used, it is your
1856 responsibility to ensure no name clashes occur. Alternatively you
1857 can specify the exact file names that you want used, as described
1858 in the next section. Finally, if your Ada programs are migrating from a
1859 compiler with a different naming convention, you can use the gnatchop
1860 utility to produce source files that follow the GNAT naming conventions.
1861 (For details see @ref{36,,Renaming Files with gnatchop}.)
1863 Note: in the case of Windows or Mac OS operating systems, case is not
1864 significant. So for example on Windows if the canonical name is
1865 @code{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1866 However, case is significant for other operating systems, so for example,
1867 if you want to use other than canonically cased file names on a Unix system,
1868 you need to follow the procedures described in the next section.
1870 @node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1871 @anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{55}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{35}
1872 @subsection Using Other File Names
1875 @geindex File names
1877 In the previous section, we have described the default rules used by
1878 GNAT to determine the file name in which a given unit resides. It is
1879 often convenient to follow these default rules, and if you follow them,
1880 the compiler knows without being explicitly told where to find all
1881 the files it needs.
1883 @geindex Source_File_Name pragma
1885 However, in some cases, particularly when a program is imported from
1886 another Ada compiler environment, it may be more convenient for the
1887 programmer to specify which file names contain which units. GNAT allows
1888 arbitrary file names to be used by means of the Source_File_Name pragma.
1889 The form of this pragma is as shown in the following examples:
1891 @example
1892 pragma Source_File_Name (My_Utilities.Stacks,
1893   Spec_File_Name => "myutilst_a.ada");
1894 pragma Source_File_name (My_Utilities.Stacks,
1895   Body_File_Name => "myutilst.ada");
1896 @end example
1898 As shown in this example, the first argument for the pragma is the unit
1899 name (in this example a child unit). The second argument has the form
1900 of a named association. The identifier
1901 indicates whether the file name is for a spec or a body;
1902 the file name itself is given by a string literal.
1904 The source file name pragma is a configuration pragma, which means that
1905 normally it will be placed in the @code{gnat.adc}
1906 file used to hold configuration
1907 pragmas that apply to a complete compilation environment.
1908 For more details on how the @code{gnat.adc} file is created and used
1909 see @ref{56,,Handling of Configuration Pragmas}.
1911 @geindex gnat.adc
1913 GNAT allows completely arbitrary file names to be specified using the
1914 source file name pragma. However, if the file name specified has an
1915 extension other than @code{.ads} or @code{.adb} it is necessary to use
1916 a special syntax when compiling the file. The name in this case must be
1917 preceded by the special sequence @code{-x} followed by a space and the name
1918 of the language, here @code{ada}, as in:
1920 @example
1921 $ gcc -c -x ada peculiar_file_name.sim
1922 @end example
1924 @code{gnatmake} handles non-standard file names in the usual manner (the
1925 non-standard file name for the main program is simply used as the
1926 argument to gnatmake). Note that if the extension is also non-standard,
1927 then it must be included in the @code{gnatmake} command, it may not
1928 be omitted.
1930 @node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
1931 @anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{57}@anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{58}
1932 @subsection Alternative File Naming Schemes
1935 @geindex File naming schemes
1936 @geindex alternative
1938 @geindex File names
1940 The previous section described the use of the @code{Source_File_Name}
1941 pragma to allow arbitrary names to be assigned to individual source files.
1942 However, this approach requires one pragma for each file, and especially in
1943 large systems can result in very long @code{gnat.adc} files, and also create
1944 a maintenance problem.
1946 @geindex Source_File_Name pragma
1948 GNAT also provides a facility for specifying systematic file naming schemes
1949 other than the standard default naming scheme previously described. An
1950 alternative scheme for naming is specified by the use of
1951 @code{Source_File_Name} pragmas having the following format:
1953 @example
1954 pragma Source_File_Name (
1955    Spec_File_Name  => FILE_NAME_PATTERN
1956  [ , Casing          => CASING_SPEC]
1957  [ , Dot_Replacement => STRING_LITERAL ] );
1959 pragma Source_File_Name (
1960    Body_File_Name  => FILE_NAME_PATTERN
1961  [ , Casing          => CASING_SPEC ]
1962  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1964 pragma Source_File_Name (
1965    Subunit_File_Name  => FILE_NAME_PATTERN
1966  [ , Casing          => CASING_SPEC ]
1967  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1969 FILE_NAME_PATTERN ::= STRING_LITERAL
1970 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1971 @end example
1973 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1974 It contains a single asterisk character, and the unit name is substituted
1975 systematically for this asterisk. The optional parameter
1976 @code{Casing} indicates
1977 whether the unit name is to be all upper-case letters, all lower-case letters,
1978 or mixed-case. If no
1979 @code{Casing} parameter is used, then the default is all
1980 lower-case.
1982 The optional @code{Dot_Replacement} string is used to replace any periods
1983 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1984 argument is used then separating dots appear unchanged in the resulting
1985 file name.
1986 Although the above syntax indicates that the
1987 @code{Casing} argument must appear
1988 before the @code{Dot_Replacement} argument, but it
1989 is also permissible to write these arguments in the opposite order.
1991 As indicated, it is possible to specify different naming schemes for
1992 bodies, specs, and subunits. Quite often the rule for subunits is the
1993 same as the rule for bodies, in which case, there is no need to give
1994 a separate @code{Subunit_File_Name} rule, and in this case the
1995 @code{Body_File_name} rule is used for subunits as well.
1997 The separate rule for subunits can also be used to implement the rather
1998 unusual case of a compilation environment (e.g., a single directory) which
1999 contains a subunit and a child unit with the same unit name. Although
2000 both units cannot appear in the same partition, the Ada Reference Manual
2001 allows (but does not require) the possibility of the two units coexisting
2002 in the same environment.
2004 The file name translation works in the following steps:
2007 @itemize *
2009 @item 
2010 If there is a specific @code{Source_File_Name} pragma for the given unit,
2011 then this is always used, and any general pattern rules are ignored.
2013 @item 
2014 If there is a pattern type @code{Source_File_Name} pragma that applies to
2015 the unit, then the resulting file name will be used if the file exists. If
2016 more than one pattern matches, the latest one will be tried first, and the
2017 first attempt resulting in a reference to a file that exists will be used.
2019 @item 
2020 If no pattern type @code{Source_File_Name} pragma that applies to the unit
2021 for which the corresponding file exists, then the standard GNAT default
2022 naming rules are used.
2023 @end itemize
2025 As an example of the use of this mechanism, consider a commonly used scheme
2026 in which file names are all lower case, with separating periods copied
2027 unchanged to the resulting file name, and specs end with @code{.1.ada}, and
2028 bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
2029 two pragmas appear:
2031 @example
2032 pragma Source_File_Name
2033   (Spec_File_Name => ".1.ada");
2034 pragma Source_File_Name
2035   (Body_File_Name => ".2.ada");
2036 @end example
2038 The default GNAT scheme is actually implemented by providing the following
2039 default pragmas internally:
2041 @example
2042 pragma Source_File_Name
2043   (Spec_File_Name => ".ads", Dot_Replacement => "-");
2044 pragma Source_File_Name
2045   (Body_File_Name => ".adb", Dot_Replacement => "-");
2046 @end example
2048 Our final example implements a scheme typically used with one of the
2049 Ada 83 compilers, where the separator character for subunits was '__'
2050 (two underscores), specs were identified by adding @code{_.ADA}, bodies
2051 by adding @code{.ADA}, and subunits by
2052 adding @code{.SEP}. All file names were
2053 upper case. Child units were not present of course since this was an
2054 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2055 the same double underscore separator for child units.
2057 @example
2058 pragma Source_File_Name
2059   (Spec_File_Name => "_.ADA",
2060    Dot_Replacement => "__",
2061    Casing = Uppercase);
2062 pragma Source_File_Name
2063   (Body_File_Name => ".ADA",
2064    Dot_Replacement => "__",
2065    Casing = Uppercase);
2066 pragma Source_File_Name
2067   (Subunit_File_Name => ".SEP",
2068    Dot_Replacement => "__",
2069    Casing = Uppercase);
2070 @end example
2072 @geindex gnatname
2074 @node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
2075 @anchor{gnat_ugn/the_gnat_compilation_model handling-arbitrary-file-naming-conventions-with-gnatname}@anchor{59}@anchor{gnat_ugn/the_gnat_compilation_model id12}@anchor{5a}
2076 @subsection Handling Arbitrary File Naming Conventions with @code{gnatname}
2079 @geindex File Naming Conventions
2081 @menu
2082 * Arbitrary File Naming Conventions:: 
2083 * Running gnatname:: 
2084 * Switches for gnatname:: 
2085 * Examples of gnatname Usage:: 
2087 @end menu
2089 @node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
2090 @anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{5b}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{5c}
2091 @subsubsection Arbitrary File Naming Conventions
2094 The GNAT compiler must be able to know the source file name of a compilation
2095 unit.  When using the standard GNAT default file naming conventions
2096 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
2097 does not need additional information.
2099 When the source file names do not follow the standard GNAT default file naming
2100 conventions, the GNAT compiler must be given additional information through
2101 a configuration pragmas file (@ref{14,,Configuration Pragmas})
2102 or a project file.
2103 When the non-standard file naming conventions are well-defined,
2104 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
2105 (@ref{58,,Alternative File Naming Schemes}) may be sufficient. However,
2106 if the file naming conventions are irregular or arbitrary, a number
2107 of pragma @code{Source_File_Name} for individual compilation units
2108 must be defined.
2109 To help maintain the correspondence between compilation unit names and
2110 source file names within the compiler,
2111 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
2112 set of files.
2114 @node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
2115 @anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{5d}@anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{5e}
2116 @subsubsection Running @code{gnatname}
2119 The usual form of the @code{gnatname} command is:
2121 @example
2122 $ gnatname [ switches ]  naming_pattern  [ naming_patterns ]
2123     [--and [ switches ]  naming_pattern  [ naming_patterns ]]
2124 @end example
2126 All of the arguments are optional. If invoked without any argument,
2127 @code{gnatname} will display its usage.
2129 When used with at least one naming pattern, @code{gnatname} will attempt to
2130 find all the compilation units in files that follow at least one of the
2131 naming patterns. To find these compilation units,
2132 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
2133 regular files.
2135 One or several Naming Patterns may be given as arguments to @code{gnatname}.
2136 Each Naming Pattern is enclosed between double quotes (or single
2137 quotes on Windows).
2138 A Naming Pattern is a regular expression similar to the wildcard patterns
2139 used in file names by the Unix shells or the DOS prompt.
2141 @code{gnatname} may be called with several sections of directories/patterns.
2142 Sections are separated by the switch @code{--and}. In each section, there must be
2143 at least one pattern. If no directory is specified in a section, the current
2144 directory (or the project directory if @code{-P} is used) is implied.
2145 The options other that the directory switches and the patterns apply globally
2146 even if they are in different sections.
2148 Examples of Naming Patterns are:
2150 @example
2151 "*.[12].ada"
2152 "*.ad[sb]*"
2153 "body_*"    "spec_*"
2154 @end example
2156 For a more complete description of the syntax of Naming Patterns,
2157 see the second kind of regular expressions described in @code{g-regexp.ads}
2158 (the 'Glob' regular expressions).
2160 When invoked without the switch @code{-P}, @code{gnatname} will create a
2161 configuration pragmas file @code{gnat.adc} in the current working directory,
2162 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
2163 unit.
2165 @node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
2166 @anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{5f}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{60}
2167 @subsubsection Switches for @code{gnatname}
2170 Switches for @code{gnatname} must precede any specified Naming Pattern.
2172 You may specify any of the following switches to @code{gnatname}:
2174 @geindex --version (gnatname)
2177 @table @asis
2179 @item @code{--version}
2181 Display Copyright and version, then exit disregarding all other options.
2182 @end table
2184 @geindex --help (gnatname)
2187 @table @asis
2189 @item @code{--help}
2191 If @code{--version} was not used, display usage, then exit disregarding
2192 all other options.
2194 @item @code{--subdirs=@emph{dir}}
2196 Real object, library or exec directories are subdirectories <dir> of the
2197 specified ones.
2199 @item @code{--no-backup}
2201 Do not create a backup copy of an existing project file.
2203 @item @code{--and}
2205 Start another section of directories/patterns.
2206 @end table
2208 @geindex -c (gnatname)
2211 @table @asis
2213 @item @code{-c@emph{filename}}
2215 Create a configuration pragmas file @code{filename} (instead of the default
2216 @code{gnat.adc}).
2217 There may be zero, one or more space between @code{-c} and
2218 @code{filename}.
2219 @code{filename} may include directory information. @code{filename} must be
2220 writable. There may be only one switch @code{-c}.
2221 When a switch @code{-c} is
2222 specified, no switch @code{-P} may be specified (see below).
2223 @end table
2225 @geindex -d (gnatname)
2228 @table @asis
2230 @item @code{-d@emph{dir}}
2232 Look for source files in directory @code{dir}. There may be zero, one or more
2233 spaces between @code{-d} and @code{dir}.
2234 @code{dir} may end with @code{/**}, that is it may be of the form
2235 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
2236 subdirectories, recursively, have to be searched for sources.
2237 When a switch @code{-d}
2238 is specified, the current working directory will not be searched for source
2239 files, unless it is explicitly specified with a @code{-d}
2240 or @code{-D} switch.
2241 Several switches @code{-d} may be specified.
2242 If @code{dir} is a relative path, it is relative to the directory of
2243 the configuration pragmas file specified with switch
2244 @code{-c},
2245 or to the directory of the project file specified with switch
2246 @code{-P} or,
2247 if neither switch @code{-c}
2248 nor switch @code{-P} are specified, it is relative to the
2249 current working directory. The directory
2250 specified with switch @code{-d} must exist and be readable.
2251 @end table
2253 @geindex -D (gnatname)
2256 @table @asis
2258 @item @code{-D@emph{filename}}
2260 Look for source files in all directories listed in text file @code{filename}.
2261 There may be zero, one or more spaces between @code{-D}
2262 and @code{filename}.
2263 @code{filename} must be an existing, readable text file.
2264 Each nonempty line in @code{filename} must be a directory.
2265 Specifying switch @code{-D} is equivalent to specifying as many
2266 switches @code{-d} as there are nonempty lines in
2267 @code{file}.
2269 @item @code{-eL}
2271 Follow symbolic links when processing project files.
2273 @geindex -f (gnatname)
2275 @item @code{-f@emph{pattern}}
2277 Foreign patterns. Using this switch, it is possible to add sources of languages
2278 other than Ada to the list of sources of a project file.
2279 It is only useful if a -P switch is used.
2280 For example,
2282 @example
2283 gnatname -Pprj -f"*.c" "*.ada"
2284 @end example
2286 will look for Ada units in all files with the @code{.ada} extension,
2287 and will add to the list of file for project @code{prj.gpr} the C files
2288 with extension @code{.c}.
2290 @geindex -h (gnatname)
2292 @item @code{-h}
2294 Output usage (help) information. The output is written to @code{stdout}.
2296 @geindex -P (gnatname)
2298 @item @code{-P@emph{proj}}
2300 Create or update project file @code{proj}. There may be zero, one or more space
2301 between @code{-P} and @code{proj}. @code{proj} may include directory
2302 information. @code{proj} must be writable.
2303 There may be only one switch @code{-P}.
2304 When a switch @code{-P} is specified,
2305 no switch @code{-c} may be specified.
2306 On all platforms, except on VMS, when @code{gnatname} is invoked for an
2307 existing project file <proj>.gpr, a backup copy of the project file is created
2308 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
2309 non negative number that makes this backup copy a new file.
2311 @geindex -v (gnatname)
2313 @item @code{-v}
2315 Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2316 This includes name of the file written, the name of the directories to search
2317 and, for each file in those directories whose name matches at least one of
2318 the Naming Patterns, an indication of whether the file contains a unit,
2319 and if so the name of the unit.
2320 @end table
2322 @geindex -v -v (gnatname)
2325 @table @asis
2327 @item @code{-v -v}
2329 Very Verbose mode. In addition to the output produced in verbose mode,
2330 for each file in the searched directories whose name matches none of
2331 the Naming Patterns, an indication is given that there is no match.
2333 @geindex -x (gnatname)
2335 @item @code{-x@emph{pattern}}
2337 Excluded patterns. Using this switch, it is possible to exclude some files
2338 that would match the name patterns. For example,
2340 @example
2341 gnatname -x "*_nt.ada" "*.ada"
2342 @end example
2344 will look for Ada units in all files with the @code{.ada} extension,
2345 except those whose names end with @code{_nt.ada}.
2346 @end table
2348 @node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2349 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{61}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{62}
2350 @subsubsection Examples of @code{gnatname} Usage
2353 @example
2354 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2355 @end example
2357 In this example, the directory @code{/home/me} must already exist
2358 and be writable. In addition, the directory
2359 @code{/home/me/sources} (specified by
2360 @code{-d sources}) must exist and be readable.
2362 Note the optional spaces after @code{-c} and @code{-d}.
2364 @example
2365 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
2366 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2367 @end example
2369 Note that several switches @code{-d} may be used,
2370 even in conjunction with one or several switches
2371 @code{-D}. Several Naming Patterns and one excluded pattern
2372 are used in this example.
2374 @node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2375 @anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{63}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{64}
2376 @subsection File Name Krunching with @code{gnatkr}
2379 @geindex gnatkr
2381 This section discusses the method used by the compiler to shorten
2382 the default file names chosen for Ada units so that they do not
2383 exceed the maximum length permitted. It also describes the
2384 @code{gnatkr} utility that can be used to determine the result of
2385 applying this shortening.
2387 @menu
2388 * About gnatkr:: 
2389 * Using gnatkr:: 
2390 * Krunching Method:: 
2391 * Examples of gnatkr Usage:: 
2393 @end menu
2395 @node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2396 @anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{66}
2397 @subsubsection About @code{gnatkr}
2400 The default file naming rule in GNAT
2401 is that the file name must be derived from
2402 the unit name. The exact default rule is as follows:
2405 @itemize *
2407 @item 
2408 Take the unit name and replace all dots by hyphens.
2410 @item 
2411 If such a replacement occurs in the
2412 second character position of a name, and the first character is
2413 @code{a}, @code{g}, @code{s}, or @code{i},
2414 then replace the dot by the character
2415 @code{~} (tilde)
2416 instead of a minus.
2418 The reason for this exception is to avoid clashes
2419 with the standard names for children of System, Ada, Interfaces,
2420 and GNAT, which use the prefixes
2421 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
2422 respectively.
2423 @end itemize
2425 The @code{-gnatk@emph{nn}}
2426 switch of the compiler activates a 'krunching'
2427 circuit that limits file names to nn characters (where nn is a decimal
2428 integer).
2430 The @code{gnatkr} utility can be used to determine the krunched name for
2431 a given file, when krunched to a specified maximum length.
2433 @node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2434 @anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{67}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{54}
2435 @subsubsection Using @code{gnatkr}
2438 The @code{gnatkr} command has the form:
2440 @example
2441 $ gnatkr name [ length ]
2442 @end example
2444 @code{name} is the uncrunched file name, derived from the name of the unit
2445 in the standard manner described in the previous section (i.e., in particular
2446 all dots are replaced by hyphens). The file name may or may not have an
2447 extension (defined as a suffix of the form period followed by arbitrary
2448 characters other than period). If an extension is present then it will
2449 be preserved in the output. For example, when krunching @code{hellofile.ads}
2450 to eight characters, the result will be hellofil.ads.
2452 Note: for compatibility with previous versions of @code{gnatkr} dots may
2453 appear in the name instead of hyphens, but the last dot will always be
2454 taken as the start of an extension. So if @code{gnatkr} is given an argument
2455 such as @code{Hello.World.adb} it will be treated exactly as if the first
2456 period had been a hyphen, and for example krunching to eight characters
2457 gives the result @code{hellworl.adb}.
2459 Note that the result is always all lower case.
2460 Characters of the other case are folded as required.
2462 @code{length} represents the length of the krunched name. The default
2463 when no argument is given is 8 characters. A length of zero stands for
2464 unlimited, in other words do not chop except for system files where the
2465 implied crunching length is always eight characters.
2467 The output is the krunched name. The output has an extension only if the
2468 original argument was a file name with an extension.
2470 @node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2471 @anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{68}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{69}
2472 @subsubsection Krunching Method
2475 The initial file name is determined by the name of the unit that the file
2476 contains. The name is formed by taking the full expanded name of the
2477 unit and replacing the separating dots with hyphens and
2478 using lowercase
2479 for all letters, except that a hyphen in the second character position is
2480 replaced by a tilde if the first character is
2481 @code{a}, @code{i}, @code{g}, or @code{s}.
2482 The extension is @code{.ads} for a
2483 spec and @code{.adb} for a body.
2484 Krunching does not affect the extension, but the file name is shortened to
2485 the specified length by following these rules:
2488 @itemize *
2490 @item 
2491 The name is divided into segments separated by hyphens, tildes or
2492 underscores and all hyphens, tildes, and underscores are
2493 eliminated. If this leaves the name short enough, we are done.
2495 @item 
2496 If the name is too long, the longest segment is located (left-most
2497 if there are two of equal length), and shortened by dropping
2498 its last character. This is repeated until the name is short enough.
2500 As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2501 to fit the name into 8 characters as required by some operating systems:
2503 @example
2504 our-strings-wide_fixed 22
2505 our strings wide fixed 19
2506 our string  wide fixed 18
2507 our strin   wide fixed 17
2508 our stri    wide fixed 16
2509 our stri    wide fixe  15
2510 our str     wide fixe  14
2511 our str     wid  fixe  13
2512 our str     wid  fix   12
2513 ou  str     wid  fix   11
2514 ou  st      wid  fix   10
2515 ou  st      wi   fix   9
2516 ou  st      wi   fi    8
2517 Final file name: oustwifi.adb
2518 @end example
2520 @item 
2521 The file names for all predefined units are always krunched to eight
2522 characters. The krunching of these predefined units uses the following
2523 special prefix replacements:
2526 @multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
2527 @item
2529 Prefix
2531 @tab
2533 Replacement
2535 @item
2537 @code{ada-}
2539 @tab
2541 @code{a-}
2543 @item
2545 @code{gnat-}
2547 @tab
2549 @code{g-}
2551 @item
2553 @code{interfac es-}
2555 @tab
2557 @code{i-}
2559 @item
2561 @code{system-}
2563 @tab
2565 @code{s-}
2567 @end multitable
2570 These system files have a hyphen in the second character position. That
2571 is why normal user files replace such a character with a
2572 tilde, to avoid confusion with system file names.
2574 As an example of this special rule, consider
2575 @code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2577 @example
2578 ada-strings-wide_fixed 22
2579 a-  strings wide fixed 18
2580 a-  string  wide fixed 17
2581 a-  strin   wide fixed 16
2582 a-  stri    wide fixed 15
2583 a-  stri    wide fixe  14
2584 a-  str     wide fixe  13
2585 a-  str     wid  fixe  12
2586 a-  str     wid  fix   11
2587 a-  st      wid  fix   10
2588 a-  st      wi   fix   9
2589 a-  st      wi   fi    8
2590 Final file name: a-stwifi.adb
2591 @end example
2592 @end itemize
2594 Of course no file shortening algorithm can guarantee uniqueness over all
2595 possible unit names, and if file name krunching is used then it is your
2596 responsibility to ensure that no name clashes occur. The utility
2597 program @code{gnatkr} is supplied for conveniently determining the
2598 krunched name of a file.
2600 @node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2601 @anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{6a}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{6b}
2602 @subsubsection Examples of @code{gnatkr} Usage
2605 @example
2606 $ gnatkr very_long_unit_name.ads      --> velounna.ads
2607 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
2608 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2609 $ gnatkr grandparent-parent-child     --> grparchi
2610 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2611 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2612 @end example
2614 @node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2615 @anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{36}
2616 @subsection Renaming Files with @code{gnatchop}
2619 @geindex gnatchop
2621 This section discusses how to handle files with multiple units by using
2622 the @code{gnatchop} utility. This utility is also useful in renaming
2623 files to meet the standard GNAT default file naming conventions.
2625 @menu
2626 * Handling Files with Multiple Units:: 
2627 * Operating gnatchop in Compilation Mode:: 
2628 * Command Line for gnatchop:: 
2629 * Switches for gnatchop:: 
2630 * Examples of gnatchop Usage:: 
2632 @end menu
2634 @node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2635 @anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{6d}@anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{6e}
2636 @subsubsection Handling Files with Multiple Units
2639 The basic compilation model of GNAT requires that a file submitted to the
2640 compiler have only one unit and there be a strict correspondence
2641 between the file name and the unit name.
2643 The @code{gnatchop} utility allows both of these rules to be relaxed,
2644 allowing GNAT to process files which contain multiple compilation units
2645 and files with arbitrary file names. @code{gnatchop}
2646 reads the specified file and generates one or more output files,
2647 containing one unit per file. The unit and the file name correspond,
2648 as required by GNAT.
2650 If you want to permanently restructure a set of 'foreign' files so that
2651 they match the GNAT rules, and do the remaining development using the
2652 GNAT structure, you can simply use @code{gnatchop} once, generate the
2653 new set of files and work with them from that point on.
2655 Alternatively, if you want to keep your files in the 'foreign' format,
2656 perhaps to maintain compatibility with some other Ada compilation
2657 system, you can set up a procedure where you use @code{gnatchop} each
2658 time you compile, regarding the source files that it writes as temporary
2659 files that you throw away.
2661 Note that if your file containing multiple units starts with a byte order
2662 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2663 will each start with a copy of this BOM, meaning that they can be compiled
2664 automatically in UTF-8 mode without needing to specify an explicit encoding.
2666 @node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2667 @anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{6f}@anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{70}
2668 @subsubsection Operating gnatchop in Compilation Mode
2671 The basic function of @code{gnatchop} is to take a file with multiple units
2672 and split it into separate files. The boundary between files is reasonably
2673 clear, except for the issue of comments and pragmas. In default mode, the
2674 rule is that any pragmas between units belong to the previous unit, except
2675 that configuration pragmas always belong to the following unit. Any comments
2676 belong to the following unit. These rules
2677 almost always result in the right choice of
2678 the split point without needing to mark it explicitly and most users will
2679 find this default to be what they want. In this default mode it is incorrect to
2680 submit a file containing only configuration pragmas, or one that ends in
2681 configuration pragmas, to @code{gnatchop}.
2683 However, using a special option to activate 'compilation mode',
2684 @code{gnatchop}
2685 can perform another function, which is to provide exactly the semantics
2686 required by the RM for handling of configuration pragmas in a compilation.
2687 In the absence of configuration pragmas (at the main file level), this
2688 option has no effect, but it causes such configuration pragmas to be handled
2689 in a quite different manner.
2691 First, in compilation mode, if @code{gnatchop} is given a file that consists of
2692 only configuration pragmas, then this file is appended to the
2693 @code{gnat.adc} file in the current directory. This behavior provides
2694 the required behavior described in the RM for the actions to be taken
2695 on submitting such a file to the compiler, namely that these pragmas
2696 should apply to all subsequent compilations in the same compilation
2697 environment. Using GNAT, the current directory, possibly containing a
2698 @code{gnat.adc} file is the representation
2699 of a compilation environment. For more information on the
2700 @code{gnat.adc} file, see @ref{56,,Handling of Configuration Pragmas}.
2702 Second, in compilation mode, if @code{gnatchop}
2703 is given a file that starts with
2704 configuration pragmas, and contains one or more units, then these
2705 configuration pragmas are prepended to each of the chopped files. This
2706 behavior provides the required behavior described in the RM for the
2707 actions to be taken on compiling such a file, namely that the pragmas
2708 apply to all units in the compilation, but not to subsequently compiled
2709 units.
2711 Finally, if configuration pragmas appear between units, they are appended
2712 to the previous unit. This results in the previous unit being illegal,
2713 since the compiler does not accept configuration pragmas that follow
2714 a unit. This provides the required RM behavior that forbids configuration
2715 pragmas other than those preceding the first compilation unit of a
2716 compilation.
2718 For most purposes, @code{gnatchop} will be used in default mode. The
2719 compilation mode described above is used only if you need exactly
2720 accurate behavior with respect to compilations, and you have files
2721 that contain multiple units and configuration pragmas. In this
2722 circumstance the use of @code{gnatchop} with the compilation mode
2723 switch provides the required behavior, and is for example the mode
2724 in which GNAT processes the ACVC tests.
2726 @node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2727 @anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{72}
2728 @subsubsection Command Line for @code{gnatchop}
2731 The @code{gnatchop} command has the form:
2733 @example
2734 $ gnatchop switches file_name [file_name ...]
2735       [directory]
2736 @end example
2738 The only required argument is the file name of the file to be chopped.
2739 There are no restrictions on the form of this file name. The file itself
2740 contains one or more Ada units, in normal GNAT format, concatenated
2741 together. As shown, more than one file may be presented to be chopped.
2743 When run in default mode, @code{gnatchop} generates one output file in
2744 the current directory for each unit in each of the files.
2746 @code{directory}, if specified, gives the name of the directory to which
2747 the output files will be written. If it is not specified, all files are
2748 written to the current directory.
2750 For example, given a
2751 file called @code{hellofiles} containing
2753 @example
2754 procedure Hello;
2756 with Ada.Text_IO; use Ada.Text_IO;
2757 procedure Hello is
2758 begin
2759    Put_Line ("Hello");
2760 end Hello;
2761 @end example
2763 the command
2765 @example
2766 $ gnatchop hellofiles
2767 @end example
2769 generates two files in the current directory, one called
2770 @code{hello.ads} containing the single line that is the procedure spec,
2771 and the other called @code{hello.adb} containing the remaining text. The
2772 original file is not affected. The generated files can be compiled in
2773 the normal manner.
2775 When gnatchop is invoked on a file that is empty or that contains only empty
2776 lines and/or comments, gnatchop will not fail, but will not produce any
2777 new sources.
2779 For example, given a
2780 file called @code{toto.txt} containing
2782 @example
2783 --  Just a comment
2784 @end example
2786 the command
2788 @example
2789 $ gnatchop toto.txt
2790 @end example
2792 will not produce any new file and will result in the following warnings:
2794 @example
2795 toto.txt:1:01: warning: empty file, contains no compilation units
2796 no compilation units found
2797 no source files written
2798 @end example
2800 @node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2801 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{73}@anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{74}
2802 @subsubsection Switches for @code{gnatchop}
2805 @code{gnatchop} recognizes the following switches:
2807 @geindex --version (gnatchop)
2810 @table @asis
2812 @item @code{--version}
2814 Display Copyright and version, then exit disregarding all other options.
2815 @end table
2817 @geindex --help (gnatchop)
2820 @table @asis
2822 @item @code{--help}
2824 If @code{--version} was not used, display usage, then exit disregarding
2825 all other options.
2826 @end table
2828 @geindex -c (gnatchop)
2831 @table @asis
2833 @item @code{-c}
2835 Causes @code{gnatchop} to operate in compilation mode, in which
2836 configuration pragmas are handled according to strict RM rules. See
2837 previous section for a full description of this mode.
2839 @item @code{-gnat@emph{xxx}}
2841 This passes the given @code{-gnat@emph{xxx}} switch to @code{gnat} which is
2842 used to parse the given file. Not all @emph{xxx} options make sense,
2843 but for example, the use of @code{-gnati2} allows @code{gnatchop} to
2844 process a source file that uses Latin-2 coding for identifiers.
2846 @item @code{-h}
2848 Causes @code{gnatchop} to generate a brief help summary to the standard
2849 output file showing usage information.
2850 @end table
2852 @geindex -k (gnatchop)
2855 @table @asis
2857 @item @code{-k@emph{mm}}
2859 Limit generated file names to the specified number @code{mm}
2860 of characters.
2861 This is useful if the
2862 resulting set of files is required to be interoperable with systems
2863 which limit the length of file names.
2864 No space is allowed between the @code{-k} and the numeric value. The numeric
2865 value may be omitted in which case a default of @code{-k8},
2866 suitable for use
2867 with DOS-like file systems, is used. If no @code{-k} switch
2868 is present then
2869 there is no limit on the length of file names.
2870 @end table
2872 @geindex -p (gnatchop)
2875 @table @asis
2877 @item @code{-p}
2879 Causes the file modification time stamp of the input file to be
2880 preserved and used for the time stamp of the output file(s). This may be
2881 useful for preserving coherency of time stamps in an environment where
2882 @code{gnatchop} is used as part of a standard build process.
2883 @end table
2885 @geindex -q (gnatchop)
2888 @table @asis
2890 @item @code{-q}
2892 Causes output of informational messages indicating the set of generated
2893 files to be suppressed. Warnings and error messages are unaffected.
2894 @end table
2896 @geindex -r (gnatchop)
2898 @geindex Source_Reference pragmas
2901 @table @asis
2903 @item @code{-r}
2905 Generate @code{Source_Reference} pragmas. Use this switch if the output
2906 files are regarded as temporary and development is to be done in terms
2907 of the original unchopped file. This switch causes
2908 @code{Source_Reference} pragmas to be inserted into each of the
2909 generated files to refers back to the original file name and line number.
2910 The result is that all error messages refer back to the original
2911 unchopped file.
2912 In addition, the debugging information placed into the object file (when
2913 the @code{-g} switch of @code{gcc} or @code{gnatmake} is
2914 specified)
2915 also refers back to this original file so that tools like profilers and
2916 debuggers will give information in terms of the original unchopped file.
2918 If the original file to be chopped itself contains
2919 a @code{Source_Reference}
2920 pragma referencing a third file, then gnatchop respects
2921 this pragma, and the generated @code{Source_Reference} pragmas
2922 in the chopped file refer to the original file, with appropriate
2923 line numbers. This is particularly useful when @code{gnatchop}
2924 is used in conjunction with @code{gnatprep} to compile files that
2925 contain preprocessing statements and multiple units.
2926 @end table
2928 @geindex -v (gnatchop)
2931 @table @asis
2933 @item @code{-v}
2935 Causes @code{gnatchop} to operate in verbose mode. The version
2936 number and copyright notice are output, as well as exact copies of
2937 the gnat1 commands spawned to obtain the chop control information.
2938 @end table
2940 @geindex -w (gnatchop)
2943 @table @asis
2945 @item @code{-w}
2947 Overwrite existing file names. Normally @code{gnatchop} regards it as a
2948 fatal error if there is already a file with the same name as a
2949 file it would otherwise output, in other words if the files to be
2950 chopped contain duplicated units. This switch bypasses this
2951 check, and causes all but the last instance of such duplicated
2952 units to be skipped.
2953 @end table
2955 @geindex --GCC= (gnatchop)
2958 @table @asis
2960 @item @code{--GCC=@emph{xxxx}}
2962 Specify the path of the GNAT parser to be used. When this switch is used,
2963 no attempt is made to add the prefix to the GNAT parser executable.
2964 @end table
2966 @node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
2967 @anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{75}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{76}
2968 @subsubsection Examples of @code{gnatchop} Usage
2971 @example
2972 $ gnatchop -w hello_s.ada prerelease/files
2973 @end example
2975 Chops the source file @code{hello_s.ada}. The output files will be
2976 placed in the directory @code{prerelease/files},
2977 overwriting any
2978 files with matching names in that directory (no files in the current
2979 directory are modified).
2981 @example
2982 $ gnatchop archive
2983 @end example
2985 Chops the source file @code{archive}
2986 into the current directory. One
2987 useful application of @code{gnatchop} is in sending sets of sources
2988 around, for example in email messages. The required sources are simply
2989 concatenated (for example, using a Unix @code{cat}
2990 command), and then
2991 @code{gnatchop} is used at the other end to reconstitute the original
2992 file names.
2994 @example
2995 $ gnatchop file1 file2 file3 direc
2996 @end example
2998 Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
2999 the resulting files in the directory @code{direc}. Note that if any units
3000 occur more than once anywhere within this set of files, an error message
3001 is generated, and no files are written. To override this check, use the
3002 @code{-w} switch,
3003 in which case the last occurrence in the last file will
3004 be the one that is output, and earlier duplicate occurrences for a given
3005 unit will be skipped.
3007 @node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
3008 @anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{14}
3009 @section Configuration Pragmas
3012 @geindex Configuration pragmas
3014 @geindex Pragmas
3015 @geindex configuration
3017 Configuration pragmas include those pragmas described as
3018 such in the Ada Reference Manual, as well as
3019 implementation-dependent pragmas that are configuration pragmas.
3020 See the @code{Implementation_Defined_Pragmas} chapter in the
3021 @cite{GNAT_Reference_Manual} for details on these
3022 additional GNAT-specific configuration pragmas.
3023 Most notably, the pragma @code{Source_File_Name}, which allows
3024 specifying non-default names for source files, is a configuration
3025 pragma. The following is a complete list of configuration pragmas
3026 recognized by GNAT:
3028 @example
3029 Ada_83
3030 Ada_95
3031 Ada_05
3032 Ada_2005
3033 Ada_12
3034 Ada_2012
3035 Allow_Integer_Address
3036 Annotate
3037 Assertion_Policy
3038 Assume_No_Invalid_Values
3039 C_Pass_By_Copy
3040 Check_Float_Overflow
3041 Check_Name
3042 Check_Policy
3043 Compile_Time_Error
3044 Compile_Time_Warning
3045 Compiler_Unit
3046 Compiler_Unit_Warning
3047 Component_Alignment
3048 Convention_Identifier
3049 Debug_Policy
3050 Detect_Blocking
3051 Default_Scalar_Storage_Order
3052 Default_Storage_Pool
3053 Disable_Atomic_Synchronization
3054 Discard_Names
3055 Elaboration_Checks
3056 Eliminate
3057 Enable_Atomic_Synchronization
3058 Extend_System
3059 Extensions_Allowed
3060 External_Name_Casing
3061 Fast_Math
3062 Favor_Top_Level
3063 Ignore_Pragma
3064 Implicit_Packing
3065 Initialize_Scalars
3066 Interrupt_State
3067 License
3068 Locking_Policy
3069 No_Component_Reordering
3070 No_Heap_Finalization
3071 No_Run_Time
3072 No_Strict_Aliasing
3073 Normalize_Scalars
3074 Optimize_Alignment
3075 Overflow_Mode
3076 Overriding_Renamings
3077 Partition_Elaboration_Policy
3078 Persistent_BSS
3079 Polling
3080 Prefix_Exception_Messages
3081 Priority_Specific_Dispatching
3082 Profile
3083 Profile_Warnings
3084 Propagate_Exceptions
3085 Queuing_Policy
3086 Rational
3087 Ravenscar
3088 Rename_Pragma
3089 Restricted_Run_Time
3090 Restrictions
3091 Restrictions_Warnings
3092 Reviewable
3093 Short_Circuit_And_Or
3094 Short_Descriptors
3095 Source_File_Name
3096 Source_File_Name_Project
3097 SPARK_Mode
3098 Style_Checks
3099 Suppress
3100 Suppress_Exception_Locations
3101 Task_Dispatching_Policy
3102 Unevaluated_Use_Of_Old
3103 Universal_Data
3104 Unsuppress
3105 Use_VADS_Size
3106 Validity_Checks
3107 Warning_As_Error
3108 Warnings
3109 Wide_Character_Encoding
3110 @end example
3112 @menu
3113 * Handling of Configuration Pragmas:: 
3114 * The Configuration Pragmas Files:: 
3116 @end menu
3118 @node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
3119 @anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{78}@anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{56}
3120 @subsection Handling of Configuration Pragmas
3123 Configuration pragmas may either appear at the start of a compilation
3124 unit, or they can appear in a configuration pragma file to apply to
3125 all compilations performed in a given compilation environment.
3127 GNAT also provides the @code{gnatchop} utility to provide an automatic
3128 way to handle configuration pragmas following the semantics for
3129 compilations (that is, files with multiple units), described in the RM.
3130 See @ref{6f,,Operating gnatchop in Compilation Mode} for details.
3131 However, for most purposes, it will be more convenient to edit the
3132 @code{gnat.adc} file that contains configuration pragmas directly,
3133 as described in the following section.
3135 In the case of @code{Restrictions} pragmas appearing as configuration
3136 pragmas in individual compilation units, the exact handling depends on
3137 the type of restriction.
3139 Restrictions that require partition-wide consistency (like
3140 @code{No_Tasking}) are
3141 recognized wherever they appear
3142 and can be freely inherited, e.g. from a @emph{with}ed unit to the @emph{with}ing
3143 unit. This makes sense since the binder will in any case insist on seeing
3144 consistent use, so any unit not conforming to any restrictions that are
3145 anywhere in the partition will be rejected, and you might as well find
3146 that out at compile time rather than at bind time.
3148 For restrictions that do not require partition-wide consistency, e.g.
3149 SPARK or No_Implementation_Attributes, in general the restriction applies
3150 only to the unit in which the pragma appears, and not to any other units.
3152 The exception is No_Elaboration_Code which always applies to the entire
3153 object file from a compilation, i.e. to the body, spec, and all subunits.
3154 This restriction can be specified in a configuration pragma file, or it
3155 can be on the body and/or the spec (in eithe case it applies to all the
3156 relevant units). It can appear on a subunit only if it has previously
3157 appeared in the body of spec.
3159 @node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
3160 @anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{79}@anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{7a}
3161 @subsection The Configuration Pragmas Files
3164 @geindex gnat.adc
3166 In GNAT a compilation environment is defined by the current
3167 directory at the time that a compile command is given. This current
3168 directory is searched for a file whose name is @code{gnat.adc}. If
3169 this file is present, it is expected to contain one or more
3170 configuration pragmas that will be applied to the current compilation.
3171 However, if the switch @code{-gnatA} is used, @code{gnat.adc} is not
3172 considered. When taken into account, @code{gnat.adc} is added to the
3173 dependencies, so that if @code{gnat.adc} is modified later, an invocation of
3174 @code{gnatmake} will recompile the source.
3176 Configuration pragmas may be entered into the @code{gnat.adc} file
3177 either by running @code{gnatchop} on a source file that consists only of
3178 configuration pragmas, or more conveniently by direct editing of the
3179 @code{gnat.adc} file, which is a standard format source file.
3181 Besides @code{gnat.adc}, additional files containing configuration
3182 pragmas may be applied to the current compilation using the switch
3183 @code{-gnatec=@emph{path}} where @code{path} must designate an existing file that
3184 contains only configuration pragmas. These configuration pragmas are
3185 in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
3186 is present and switch @code{-gnatA} is not used).
3188 It is allowable to specify several switches @code{-gnatec=}, all of which
3189 will be taken into account.
3191 Files containing configuration pragmas specified with switches
3192 @code{-gnatec=} are added to the dependencies, unless they are
3193 temporary files. A file is considered temporary if its name ends in
3194 @code{.tmp} or @code{.TMP}. Certain tools follow this naming
3195 convention because they pass information to @code{gcc} via
3196 temporary files that are immediately deleted; it doesn't make sense to
3197 depend on a file that no longer exists. Such tools include
3198 @code{gprbuild}, @code{gnatmake}, and @code{gnatcheck}.
3200 If you are using project file, a separate mechanism is provided using
3201 project attributes.
3203 @c --Comment
3204 @c See :ref:`Specifying_Configuration_Pragmas` for more details.
3206 @node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
3207 @anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{7b}
3208 @section Generating Object Files
3211 An Ada program consists of a set of source files, and the first step in
3212 compiling the program is to generate the corresponding object files.
3213 These are generated by compiling a subset of these source files.
3214 The files you need to compile are the following:
3217 @itemize *
3219 @item 
3220 If a package spec has no body, compile the package spec to produce the
3221 object file for the package.
3223 @item 
3224 If a package has both a spec and a body, compile the body to produce the
3225 object file for the package. The source file for the package spec need
3226 not be compiled in this case because there is only one object file, which
3227 contains the code for both the spec and body of the package.
3229 @item 
3230 For a subprogram, compile the subprogram body to produce the object file
3231 for the subprogram. The spec, if one is present, is as usual in a
3232 separate file, and need not be compiled.
3233 @end itemize
3235 @geindex Subunits
3238 @itemize *
3240 @item 
3241 In the case of subunits, only compile the parent unit. A single object
3242 file is generated for the entire subunit tree, which includes all the
3243 subunits.
3245 @item 
3246 Compile child units independently of their parent units
3247 (though, of course, the spec of all the ancestor unit must be present in order
3248 to compile a child unit).
3250 @geindex Generics
3252 @item 
3253 Compile generic units in the same manner as any other units. The object
3254 files in this case are small dummy files that contain at most the
3255 flag used for elaboration checking. This is because GNAT always handles generic
3256 instantiation by means of macro expansion. However, it is still necessary to
3257 compile generic units, for dependency checking and elaboration purposes.
3258 @end itemize
3260 The preceding rules describe the set of files that must be compiled to
3261 generate the object files for a program. Each object file has the same
3262 name as the corresponding source file, except that the extension is
3263 @code{.o} as usual.
3265 You may wish to compile other files for the purpose of checking their
3266 syntactic and semantic correctness. For example, in the case where a
3267 package has a separate spec and body, you would not normally compile the
3268 spec. However, it is convenient in practice to compile the spec to make
3269 sure it is error-free before compiling clients of this spec, because such
3270 compilations will fail if there is an error in the spec.
3272 GNAT provides an option for compiling such files purely for the
3273 purposes of checking correctness; such compilations are not required as
3274 part of the process of building a program. To compile a file in this
3275 checking mode, use the @code{-gnatc} switch.
3277 @node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3278 @anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{7c}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{41}
3279 @section Source Dependencies
3282 A given object file clearly depends on the source file which is compiled
3283 to produce it. Here we are using "depends" in the sense of a typical
3284 @code{make} utility; in other words, an object file depends on a source
3285 file if changes to the source file require the object file to be
3286 recompiled.
3287 In addition to this basic dependency, a given object may depend on
3288 additional source files as follows:
3291 @itemize *
3293 @item 
3294 If a file being compiled @emph{with}s a unit @code{X}, the object file
3295 depends on the file containing the spec of unit @code{X}. This includes
3296 files that are @emph{with}ed implicitly either because they are parents
3297 of @emph{with}ed child units or they are run-time units required by the
3298 language constructs used in a particular unit.
3300 @item 
3301 If a file being compiled instantiates a library level generic unit, the
3302 object file depends on both the spec and body files for this generic
3303 unit.
3305 @item 
3306 If a file being compiled instantiates a generic unit defined within a
3307 package, the object file depends on the body file for the package as
3308 well as the spec file.
3309 @end itemize
3311 @geindex Inline
3313 @geindex -gnatn switch
3316 @itemize *
3318 @item 
3319 If a file being compiled contains a call to a subprogram for which
3320 pragma @code{Inline} applies and inlining is activated with the
3321 @code{-gnatn} switch, the object file depends on the file containing the
3322 body of this subprogram as well as on the file containing the spec. Note
3323 that for inlining to actually occur as a result of the use of this switch,
3324 it is necessary to compile in optimizing mode.
3326 @geindex -gnatN switch
3328 The use of @code{-gnatN} activates  inlining optimization
3329 that is performed by the front end of the compiler. This inlining does
3330 not require that the code generation be optimized. Like @code{-gnatn},
3331 the use of this switch generates additional dependencies.
3333 When using a gcc-based back end (in practice this means using any version
3334 of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of
3335 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
3336 Historically front end inlining was more extensive than the gcc back end
3337 inlining, but that is no longer the case.
3339 @item 
3340 If an object file @code{O} depends on the proper body of a subunit through
3341 inlining or instantiation, it depends on the parent unit of the subunit.
3342 This means that any modification of the parent unit or one of its subunits
3343 affects the compilation of @code{O}.
3345 @item 
3346 The object file for a parent unit depends on all its subunit body files.
3348 @item 
3349 The previous two rules meant that for purposes of computing dependencies and
3350 recompilation, a body and all its subunits are treated as an indivisible whole.
3352 These rules are applied transitively: if unit @code{A} @emph{with}s
3353 unit @code{B}, whose elaboration calls an inlined procedure in package
3354 @code{C}, the object file for unit @code{A} will depend on the body of
3355 @code{C}, in file @code{c.adb}.
3357 The set of dependent files described by these rules includes all the
3358 files on which the unit is semantically dependent, as dictated by the
3359 Ada language standard. However, it is a superset of what the
3360 standard describes, because it includes generic, inline, and subunit
3361 dependencies.
3363 An object file must be recreated by recompiling the corresponding source
3364 file if any of the source files on which it depends are modified. For
3365 example, if the @code{make} utility is used to control compilation,
3366 the rule for an Ada object file must mention all the source files on
3367 which the object file depends, according to the above definition.
3368 The determination of the necessary
3369 recompilations is done automatically when one uses @code{gnatmake}.
3370 @end itemize
3372 @node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3373 @anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{7d}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{42}
3374 @section The Ada Library Information Files
3377 @geindex Ada Library Information files
3379 @geindex ALI files
3381 Each compilation actually generates two output files. The first of these
3382 is the normal object file that has a @code{.o} extension. The second is a
3383 text file containing full dependency information. It has the same
3384 name as the source file, but an @code{.ali} extension.
3385 This file is known as the Ada Library Information (@code{ALI}) file.
3386 The following information is contained in the @code{ALI} file.
3389 @itemize *
3391 @item 
3392 Version information (indicates which version of GNAT was used to compile
3393 the unit(s) in question)
3395 @item 
3396 Main program information (including priority and time slice settings,
3397 as well as the wide character encoding used during compilation).
3399 @item 
3400 List of arguments used in the @code{gcc} command for the compilation
3402 @item 
3403 Attributes of the unit, including configuration pragmas used, an indication
3404 of whether the compilation was successful, exception model used etc.
3406 @item 
3407 A list of relevant restrictions applying to the unit (used for consistency)
3408 checking.
3410 @item 
3411 Categorization information (e.g., use of pragma @code{Pure}).
3413 @item 
3414 Information on all @emph{with}ed units, including presence of
3415 @code{Elaborate} or @code{Elaborate_All} pragmas.
3417 @item 
3418 Information from any @code{Linker_Options} pragmas used in the unit
3420 @item 
3421 Information on the use of @code{Body_Version} or @code{Version}
3422 attributes in the unit.
3424 @item 
3425 Dependency information. This is a list of files, together with
3426 time stamp and checksum information. These are files on which
3427 the unit depends in the sense that recompilation is required
3428 if any of these units are modified.
3430 @item 
3431 Cross-reference data. Contains information on all entities referenced
3432 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
3433 provide cross-reference information.
3434 @end itemize
3436 For a full detailed description of the format of the @code{ALI} file,
3437 see the source of the body of unit @code{Lib.Writ}, contained in file
3438 @code{lib-writ.adb} in the GNAT compiler sources.
3440 @node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3441 @anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{7e}@anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{43}
3442 @section Binding an Ada Program
3445 When using languages such as C and C++, once the source files have been
3446 compiled the only remaining step in building an executable program
3447 is linking the object modules together. This means that it is possible to
3448 link an inconsistent version of a program, in which two units have
3449 included different versions of the same header.
3451 The rules of Ada do not permit such an inconsistent program to be built.
3452 For example, if two clients have different versions of the same package,
3453 it is illegal to build a program containing these two clients.
3454 These rules are enforced by the GNAT binder, which also determines an
3455 elaboration order consistent with the Ada rules.
3457 The GNAT binder is run after all the object files for a program have
3458 been created. It is given the name of the main program unit, and from
3459 this it determines the set of units required by the program, by reading the
3460 corresponding ALI files. It generates error messages if the program is
3461 inconsistent or if no valid order of elaboration exists.
3463 If no errors are detected, the binder produces a main program, in Ada by
3464 default, that contains calls to the elaboration procedures of those
3465 compilation unit that require them, followed by
3466 a call to the main program. This Ada program is compiled to generate the
3467 object file for the main program. The name of
3468 the Ada file is @code{b~xxx}.adb` (with the corresponding spec
3469 @code{b~xxx}.ads`) where @code{xxx} is the name of the
3470 main program unit.
3472 Finally, the linker is used to build the resulting executable program,
3473 using the object from the main program from the bind step as well as the
3474 object files for the Ada units of the program.
3476 @node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3477 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{15}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{7f}
3478 @section GNAT and Libraries
3481 @geindex Library building and using
3483 This section describes how to build and use libraries with GNAT, and also shows
3484 how to recompile the GNAT run-time library. You should be familiar with the
3485 Project Manager facility (see the @emph{GNAT_Project_Manager} chapter of the
3486 @emph{GPRbuild User's Guide}) before reading this chapter.
3488 @menu
3489 * Introduction to Libraries in GNAT:: 
3490 * General Ada Libraries:: 
3491 * Stand-alone Ada Libraries:: 
3492 * Rebuilding the GNAT Run-Time Library:: 
3494 @end menu
3496 @node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3497 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{80}@anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{81}
3498 @subsection Introduction to Libraries in GNAT
3501 A library is, conceptually, a collection of objects which does not have its
3502 own main thread of execution, but rather provides certain services to the
3503 applications that use it. A library can be either statically linked with the
3504 application, in which case its code is directly included in the application,
3505 or, on platforms that support it, be dynamically linked, in which case
3506 its code is shared by all applications making use of this library.
3508 GNAT supports both types of libraries.
3509 In the static case, the compiled code can be provided in different ways. The
3510 simplest approach is to provide directly the set of objects resulting from
3511 compilation of the library source files. Alternatively, you can group the
3512 objects into an archive using whatever commands are provided by the operating
3513 system. For the latter case, the objects are grouped into a shared library.
3515 In the GNAT environment, a library has three types of components:
3518 @itemize *
3520 @item 
3521 Source files,
3523 @item 
3524 @code{ALI} files (see @ref{42,,The Ada Library Information Files}), and
3526 @item 
3527 Object files, an archive or a shared library.
3528 @end itemize
3530 A GNAT library may expose all its source files, which is useful for
3531 documentation purposes. Alternatively, it may expose only the units needed by
3532 an external user to make use of the library. That is to say, the specs
3533 reflecting the library services along with all the units needed to compile
3534 those specs, which can include generic bodies or any body implementing an
3535 inlined routine. In the case of @emph{stand-alone libraries} those exposed
3536 units are called @emph{interface units} (@ref{82,,Stand-alone Ada Libraries}).
3538 All compilation units comprising an application, including those in a library,
3539 need to be elaborated in an order partially defined by Ada's semantics. GNAT
3540 computes the elaboration order from the @code{ALI} files and this is why they
3541 constitute a mandatory part of GNAT libraries.
3542 @emph{Stand-alone libraries} are the exception to this rule because a specific
3543 library elaboration routine is produced independently of the application(s)
3544 using the library.
3546 @node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3547 @anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{83}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{84}
3548 @subsection General Ada Libraries
3551 @menu
3552 * Building a library:: 
3553 * Installing a library:: 
3554 * Using a library:: 
3556 @end menu
3558 @node Building a library,Installing a library,,General Ada Libraries
3559 @anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{85}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{86}
3560 @subsubsection Building a library
3563 The easiest way to build a library is to use the Project Manager,
3564 which supports a special type of project called a @emph{Library Project}
3565 (see the @emph{Library Projects} section in the @emph{GNAT Project Manager}
3566 chapter of the @emph{GPRbuild User's Guide}).
3568 A project is considered a library project, when two project-level attributes
3569 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
3570 control different aspects of library configuration, additional optional
3571 project-level attributes can be specified:
3574 @itemize *
3576 @item 
3578 @table @asis
3580 @item @code{Library_Kind}
3582 This attribute controls whether the library is to be static or dynamic
3583 @end table
3585 @item 
3587 @table @asis
3589 @item @code{Library_Version}
3591 This attribute specifies the library version; this value is used
3592 during dynamic linking of shared libraries to determine if the currently
3593 installed versions of the binaries are compatible.
3594 @end table
3596 @item 
3597 @code{Library_Options}
3599 @item 
3601 @table @asis
3603 @item @code{Library_GCC}
3605 These attributes specify additional low-level options to be used during
3606 library generation, and redefine the actual application used to generate
3607 library.
3608 @end table
3609 @end itemize
3611 The GNAT Project Manager takes full care of the library maintenance task,
3612 including recompilation of the source files for which objects do not exist
3613 or are not up to date, assembly of the library archive, and installation of
3614 the library (i.e., copying associated source, object and @code{ALI} files
3615 to the specified location).
3617 Here is a simple library project file:
3619 @example
3620 project My_Lib is
3621   for Source_Dirs use ("src1", "src2");
3622   for Object_Dir use "obj";
3623   for Library_Name use "mylib";
3624   for Library_Dir use "lib";
3625   for Library_Kind use "dynamic";
3626 end My_lib;
3627 @end example
3629 and the compilation command to build and install the library:
3631 @example
3632 $ gnatmake -Pmy_lib
3633 @end example
3635 It is not entirely trivial to perform manually all the steps required to
3636 produce a library. We recommend that you use the GNAT Project Manager
3637 for this task. In special cases where this is not desired, the necessary
3638 steps are discussed below.
3640 There are various possibilities for compiling the units that make up the
3641 library: for example with a Makefile (@ref{1f,,Using the GNU make Utility}) or
3642 with a conventional script. For simple libraries, it is also possible to create
3643 a dummy main program which depends upon all the packages that comprise the
3644 interface of the library. This dummy main program can then be given to
3645 @code{gnatmake}, which will ensure that all necessary objects are built.
3647 After this task is accomplished, you should follow the standard procedure
3648 of the underlying operating system to produce the static or shared library.
3650 Here is an example of such a dummy program:
3652 @example
3653 with My_Lib.Service1;
3654 with My_Lib.Service2;
3655 with My_Lib.Service3;
3656 procedure My_Lib_Dummy is
3657 begin
3658    null;
3659 end;
3660 @end example
3662 Here are the generic commands that will build an archive or a shared library.
3664 @example
3665 # compiling the library
3666 $ gnatmake -c my_lib_dummy.adb
3668 # we don't need the dummy object itself
3669 $ rm my_lib_dummy.o my_lib_dummy.ali
3671 # create an archive with the remaining objects
3672 $ ar rc libmy_lib.a *.o
3673 # some systems may require "ranlib" to be run as well
3675 # or create a shared library
3676 $ gcc -shared -o libmy_lib.so *.o
3677 # some systems may require the code to have been compiled with -fPIC
3679 # remove the object files that are now in the library
3680 $ rm *.o
3682 # Make the ALI files read-only so that gnatmake will not try to
3683 # regenerate the objects that are in the library
3684 $ chmod -w *.ali
3685 @end example
3687 Please note that the library must have a name of the form @code{lib@emph{xxx}.a}
3688 or @code{lib@emph{xxx}.so} (or @code{lib@emph{xxx}.dll} on Windows) in order to
3689 be accessed by the directive @code{-l@emph{xxx}} at link time.
3691 @node Installing a library,Using a library,Building a library,General Ada Libraries
3692 @anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{87}@anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{88}
3693 @subsubsection Installing a library
3696 @geindex ADA_PROJECT_PATH
3698 @geindex GPR_PROJECT_PATH
3700 If you use project files, library installation is part of the library build
3701 process (see the @emph{Installing a Library with Project Files} section of the
3702 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}).
3704 When project files are not an option, it is also possible, but not recommended,
3705 to install the library so that the sources needed to use the library are on the
3706 Ada source path and the ALI files & libraries be on the Ada Object path (see
3707 @ref{89,,Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
3708 administrator can place general-purpose libraries in the default compiler
3709 paths, by specifying the libraries' location in the configuration files
3710 @code{ada_source_path} and @code{ada_object_path}. These configuration files
3711 must be located in the GNAT installation tree at the same place as the gcc spec
3712 file. The location of the gcc spec file can be determined as follows:
3714 @example
3715 $ gcc -v
3716 @end example
3718 The configuration files mentioned above have a simple format: each line
3719 must contain one unique directory name.
3720 Those names are added to the corresponding path
3721 in their order of appearance in the file. The names can be either absolute
3722 or relative; in the latter case, they are relative to where theses files
3723 are located.
3725 The files @code{ada_source_path} and @code{ada_object_path} might not be
3726 present in a
3727 GNAT installation, in which case, GNAT will look for its run-time library in
3728 the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3729 objects and @code{ALI} files). When the files exist, the compiler does not
3730 look in @code{adainclude} and @code{adalib}, and thus the
3731 @code{ada_source_path} file
3732 must contain the location for the GNAT run-time sources (which can simply
3733 be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3734 contain the location for the GNAT run-time objects (which can simply
3735 be @code{adalib}).
3737 You can also specify a new default path to the run-time library at compilation
3738 time with the switch @code{--RTS=rts-path}. You can thus choose / change
3739 the run-time library you want your program to be compiled with. This switch is
3740 recognized by @code{gcc}, @code{gnatmake}, @code{gnatbind},
3741 @code{gnatls}, @code{gnatfind} and @code{gnatxref}.
3743 It is possible to install a library before or after the standard GNAT
3744 library, by reordering the lines in the configuration files. In general, a
3745 library must be installed before the GNAT library if it redefines
3746 any part of it.
3748 @node Using a library,,Installing a library,General Ada Libraries
3749 @anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{8a}@anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{8b}
3750 @subsubsection Using a library
3753 Once again, the project facility greatly simplifies the use of
3754 libraries. In this context, using a library is just a matter of adding a
3755 @emph{with} clause in the user project. For instance, to make use of the
3756 library @code{My_Lib} shown in examples in earlier sections, you can
3757 write:
3759 @example
3760 with "my_lib";
3761 project My_Proj is
3762   ...
3763 end My_Proj;
3764 @end example
3766 Even if you have a third-party, non-Ada library, you can still use GNAT's
3767 Project Manager facility to provide a wrapper for it. For example, the
3768 following project, when @emph{with}ed by your main project, will link with the
3769 third-party library @code{liba.a}:
3771 @example
3772 project Liba is
3773    for Externally_Built use "true";
3774    for Source_Files use ();
3775    for Library_Dir use "lib";
3776    for Library_Name use "a";
3777    for Library_Kind use "static";
3778 end Liba;
3779 @end example
3781 This is an alternative to the use of @code{pragma Linker_Options}. It is
3782 especially interesting in the context of systems with several interdependent
3783 static libraries where finding a proper linker order is not easy and best be
3784 left to the tools having visibility over project dependence information.
3786 In order to use an Ada library manually, you need to make sure that this
3787 library is on both your source and object path
3788 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}
3789 and @ref{8c,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3790 in an archive or a shared library, you need to specify the desired
3791 library at link time.
3793 For example, you can use the library @code{mylib} installed in
3794 @code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3796 @example
3797 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3798   -largs -lmy_lib
3799 @end example
3801 This can be expressed more simply:
3803 @example
3804 $ gnatmake my_appl
3805 @end example
3807 when the following conditions are met:
3810 @itemize *
3812 @item 
3813 @code{/dir/my_lib_src} has been added by the user to the environment
3814 variable 
3815 @geindex ADA_INCLUDE_PATH
3816 @geindex environment variable; ADA_INCLUDE_PATH
3817 @code{ADA_INCLUDE_PATH}, or by the administrator to the file
3818 @code{ada_source_path}
3820 @item 
3821 @code{/dir/my_lib_obj} has been added by the user to the environment
3822 variable 
3823 @geindex ADA_OBJECTS_PATH
3824 @geindex environment variable; ADA_OBJECTS_PATH
3825 @code{ADA_OBJECTS_PATH}, or by the administrator to the file
3826 @code{ada_object_path}
3828 @item 
3829 a pragma @code{Linker_Options} has been added to one of the sources.
3830 For example:
3832 @example
3833 pragma Linker_Options ("-lmy_lib");
3834 @end example
3835 @end itemize
3837 Note that you may also load a library dynamically at
3838 run time given its filename, as illustrated in the GNAT @code{plugins} example
3839 in the directory @code{share/examples/gnat/plugins} within the GNAT
3840 install area.
3842 @node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3843 @anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{82}@anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{8d}
3844 @subsection Stand-alone Ada Libraries
3847 @geindex Stand-alone libraries
3849 @menu
3850 * Introduction to Stand-alone Libraries:: 
3851 * Building a Stand-alone Library:: 
3852 * Creating a Stand-alone Library to be used in a non-Ada context:: 
3853 * Restrictions in Stand-alone Libraries:: 
3855 @end menu
3857 @node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3858 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{8e}@anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{8f}
3859 @subsubsection Introduction to Stand-alone Libraries
3862 A Stand-alone Library (abbreviated 'SAL') is a library that contains the
3863 necessary code to
3864 elaborate the Ada units that are included in the library. In contrast with
3865 an ordinary library, which consists of all sources, objects and @code{ALI}
3866 files of the
3867 library, a SAL may specify a restricted subset of compilation units
3868 to serve as a library interface. In this case, the fully
3869 self-sufficient set of files will normally consist of an objects
3870 archive, the sources of interface units' specs, and the @code{ALI}
3871 files of interface units.
3872 If an interface spec contains a generic unit or an inlined subprogram,
3873 the body's
3874 source must also be provided; if the units that must be provided in the source
3875 form depend on other units, the source and @code{ALI} files of those must
3876 also be provided.
3878 The main purpose of a SAL is to minimize the recompilation overhead of client
3879 applications when a new version of the library is installed. Specifically,
3880 if the interface sources have not changed, client applications do not need to
3881 be recompiled. If, furthermore, a SAL is provided in the shared form and its
3882 version, controlled by @code{Library_Version} attribute, is not changed,
3883 then the clients do not need to be relinked.
3885 SALs also allow the library providers to minimize the amount of library source
3886 text exposed to the clients.  Such 'information hiding' might be useful or
3887 necessary for various reasons.
3889 Stand-alone libraries are also well suited to be used in an executable whose
3890 main routine is not written in Ada.
3892 @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
3893 @anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{90}@anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{91}
3894 @subsubsection Building a Stand-alone Library
3897 GNAT's Project facility provides a simple way of building and installing
3898 stand-alone libraries; see the @emph{Stand-alone Library Projects} section
3899 in the @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}.
3900 To be a Stand-alone Library Project, in addition to the two attributes
3901 that make a project a Library Project (@code{Library_Name} and
3902 @code{Library_Dir}; see the @emph{Library Projects} section in the
3903 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}),
3904 the attribute @code{Library_Interface} must be defined.  For example:
3906 @example
3907 for Library_Dir use "lib_dir";
3908 for Library_Name use "dummy";
3909 for Library_Interface use ("int1", "int1.child");
3910 @end example
3912 Attribute @code{Library_Interface} has a non-empty string list value,
3913 each string in the list designating a unit contained in an immediate source
3914 of the project file.
3916 When a Stand-alone Library is built, first the binder is invoked to build
3917 a package whose name depends on the library name
3918 (@code{b~dummy.ads/b} in the example above).
3919 This binder-generated package includes initialization and
3920 finalization procedures whose
3921 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
3922 in the example
3923 above). The object corresponding to this package is included in the library.
3925 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3926 calling of these procedures if a static SAL is built, or if a shared SAL
3927 is built
3928 with the project-level attribute @code{Library_Auto_Init} set to
3929 @code{"false"}.
3931 For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
3932 (those that are listed in attribute @code{Library_Interface}) are copied to
3933 the Library Directory. As a consequence, only the Interface Units may be
3934 imported from Ada units outside of the library. If other units are imported,
3935 the binding phase will fail.
3937 It is also possible to build an encapsulated library where not only
3938 the code to elaborate and finalize the library is embedded but also
3939 ensuring that the library is linked only against static
3940 libraries. So an encapsulated library only depends on system
3941 libraries, all other code, including the GNAT runtime, is embedded. To
3942 build an encapsulated library the attribute
3943 @code{Library_Standalone} must be set to @code{encapsulated}:
3945 @example
3946 for Library_Dir use "lib_dir";
3947 for Library_Name use "dummy";
3948 for Library_Kind use "dynamic";
3949 for Library_Interface use ("int1", "int1.child");
3950 for Library_Standalone use "encapsulated";
3951 @end example
3953 The default value for this attribute is @code{standard} in which case
3954 a stand-alone library is built.
3956 The attribute @code{Library_Src_Dir} may be specified for a
3957 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
3958 single string value. Its value must be the path (absolute or relative to the
3959 project directory) of an existing directory. This directory cannot be the
3960 object directory or one of the source directories, but it can be the same as
3961 the library directory. The sources of the Interface
3962 Units of the library that are needed by an Ada client of the library will be
3963 copied to the designated directory, called the Interface Copy directory.
3964 These sources include the specs of the Interface Units, but they may also
3965 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
3966 are used, or when there is a generic unit in the spec. Before the sources
3967 are copied to the Interface Copy directory, an attempt is made to delete all
3968 files in the Interface Copy directory.
3970 Building stand-alone libraries by hand is somewhat tedious, but for those
3971 occasions when it is necessary here are the steps that you need to perform:
3974 @itemize *
3976 @item 
3977 Compile all library sources.
3979 @item 
3980 Invoke the binder with the switch @code{-n} (No Ada main program),
3981 with all the @code{ALI} files of the interfaces, and
3982 with the switch @code{-L} to give specific names to the @code{init}
3983 and @code{final} procedures.  For example:
3985 @example
3986 $ gnatbind -n int1.ali int2.ali -Lsal1
3987 @end example
3989 @item 
3990 Compile the binder generated file:
3992 @example
3993 $ gcc -c b~int2.adb
3994 @end example
3996 @item 
3997 Link the dynamic library with all the necessary object files,
3998 indicating to the linker the names of the @code{init} (and possibly
3999 @code{final}) procedures for automatic initialization (and finalization).
4000 The built library should be placed in a directory different from
4001 the object directory.
4003 @item 
4004 Copy the @code{ALI} files of the interface to the library directory,
4005 add in this copy an indication that it is an interface to a SAL
4006 (i.e., add a word @code{SL} on the line in the @code{ALI} file that starts
4007 with letter 'P') and make the modified copy of the @code{ALI} file
4008 read-only.
4009 @end itemize
4011 Using SALs is not different from using other libraries
4012 (see @ref{8a,,Using a library}).
4014 @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
4015 @anchor{gnat_ugn/the_gnat_compilation_model creating-a-stand-alone-library-to-be-used-in-a-non-ada-context}@anchor{92}@anchor{gnat_ugn/the_gnat_compilation_model id44}@anchor{93}
4016 @subsubsection Creating a Stand-alone Library to be used in a non-Ada context
4019 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
4020 a non-Ada context.
4022 The only extra step required is to ensure that library interface subprograms
4023 are compatible with the main program, by means of @code{pragma Export}
4024 or @code{pragma Convention}.
4026 Here is an example of simple library interface for use with C main program:
4028 @example
4029 package My_Package is
4031    procedure Do_Something;
4032    pragma Export (C, Do_Something, "do_something");
4034    procedure Do_Something_Else;
4035    pragma Export (C, Do_Something_Else, "do_something_else");
4037 end My_Package;
4038 @end example
4040 On the foreign language side, you must provide a 'foreign' view of the
4041 library interface; remember that it should contain elaboration routines in
4042 addition to interface subprograms.
4044 The example below shows the content of @code{mylib_interface.h} (note
4045 that there is no rule for the naming of this file, any name can be used)
4047 @example
4048 /* the library elaboration procedure */
4049 extern void mylibinit (void);
4051 /* the library finalization procedure */
4052 extern void mylibfinal (void);
4054 /* the interface exported by the library */
4055 extern void do_something (void);
4056 extern void do_something_else (void);
4057 @end example
4059 Libraries built as explained above can be used from any program, provided
4060 that the elaboration procedures (named @code{mylibinit} in the previous
4061 example) are called before the library services are used. Any number of
4062 libraries can be used simultaneously, as long as the elaboration
4063 procedure of each library is called.
4065 Below is an example of a C program that uses the @code{mylib} library.
4067 @example
4068 #include "mylib_interface.h"
4071 main (void)
4073    /* First, elaborate the library before using it */
4074    mylibinit ();
4076    /* Main program, using the library exported entities */
4077    do_something ();
4078    do_something_else ();
4080    /* Library finalization at the end of the program */
4081    mylibfinal ();
4082    return 0;
4084 @end example
4086 Note that invoking any library finalization procedure generated by
4087 @code{gnatbind} shuts down the Ada run-time environment.
4088 Consequently, the
4089 finalization of all Ada libraries must be performed at the end of the program.
4090 No call to these libraries or to the Ada run-time library should be made
4091 after the finalization phase.
4093 Note also that special care must be taken with multi-tasks
4094 applications. The initialization and finalization routines are not
4095 protected against concurrent access. If such requirement is needed it
4096 must be ensured at the application level using a specific operating
4097 system services like a mutex or a critical-section.
4099 @node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
4100 @anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{94}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{95}
4101 @subsubsection Restrictions in Stand-alone Libraries
4104 The pragmas listed below should be used with caution inside libraries,
4105 as they can create incompatibilities with other Ada libraries:
4108 @itemize *
4110 @item 
4111 pragma @code{Locking_Policy}
4113 @item 
4114 pragma @code{Partition_Elaboration_Policy}
4116 @item 
4117 pragma @code{Queuing_Policy}
4119 @item 
4120 pragma @code{Task_Dispatching_Policy}
4122 @item 
4123 pragma @code{Unreserve_All_Interrupts}
4124 @end itemize
4126 When using a library that contains such pragmas, the user must make sure
4127 that all libraries use the same pragmas with the same values. Otherwise,
4128 @code{Program_Error} will
4129 be raised during the elaboration of the conflicting
4130 libraries. The usage of these pragmas and its consequences for the user
4131 should therefore be well documented.
4133 Similarly, the traceback in the exception occurrence mechanism should be
4134 enabled or disabled in a consistent manner across all libraries.
4135 Otherwise, Program_Error will be raised during the elaboration of the
4136 conflicting libraries.
4138 If the @code{Version} or @code{Body_Version}
4139 attributes are used inside a library, then you need to
4140 perform a @code{gnatbind} step that specifies all @code{ALI} files in all
4141 libraries, so that version identifiers can be properly computed.
4142 In practice these attributes are rarely used, so this is unlikely
4143 to be a consideration.
4145 @node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
4146 @anchor{gnat_ugn/the_gnat_compilation_model id46}@anchor{96}@anchor{gnat_ugn/the_gnat_compilation_model rebuilding-the-gnat-run-time-library}@anchor{97}
4147 @subsection Rebuilding the GNAT Run-Time Library
4150 @geindex GNAT Run-Time Library
4151 @geindex rebuilding
4153 @geindex Building the GNAT Run-Time Library
4155 @geindex Rebuilding the GNAT Run-Time Library
4157 @geindex Run-Time Library
4158 @geindex rebuilding
4160 It may be useful to recompile the GNAT library in various contexts, the
4161 most important one being the use of partition-wide configuration pragmas
4162 such as @code{Normalize_Scalars}. A special Makefile called
4163 @code{Makefile.adalib} is provided to that effect and can be found in
4164 the directory containing the GNAT library. The location of this
4165 directory depends on the way the GNAT environment has been installed and can
4166 be determined by means of the command:
4168 @example
4169 $ gnatls -v
4170 @end example
4172 The last entry in the object search path usually contains the
4173 gnat library. This Makefile contains its own documentation and in
4174 particular the set of instructions needed to rebuild a new library and
4175 to use it.
4177 @geindex Conditional compilation
4179 @node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
4180 @anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{98}@anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{16}
4181 @section Conditional Compilation
4184 This section presents some guidelines for modeling conditional compilation in Ada and describes the
4185 gnatprep preprocessor utility.
4187 @geindex Conditional compilation
4189 @menu
4190 * Modeling Conditional Compilation in Ada:: 
4191 * Preprocessing with gnatprep:: 
4192 * Integrated Preprocessing:: 
4194 @end menu
4196 @node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
4197 @anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{99}@anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{9a}
4198 @subsection Modeling Conditional Compilation in Ada
4201 It is often necessary to arrange for a single source program
4202 to serve multiple purposes, where it is compiled in different
4203 ways to achieve these different goals. Some examples of the
4204 need for this feature are
4207 @itemize *
4209 @item 
4210 Adapting a program to a different hardware environment
4212 @item 
4213 Adapting a program to a different target architecture
4215 @item 
4216 Turning debugging features on and off
4218 @item 
4219 Arranging for a program to compile with different compilers
4220 @end itemize
4222 In C, or C++, the typical approach would be to use the preprocessor
4223 that is defined as part of the language. The Ada language does not
4224 contain such a feature. This is not an oversight, but rather a very
4225 deliberate design decision, based on the experience that overuse of
4226 the preprocessing features in C and C++ can result in programs that
4227 are extremely difficult to maintain. For example, if we have ten
4228 switches that can be on or off, this means that there are a thousand
4229 separate programs, any one of which might not even be syntactically
4230 correct, and even if syntactically correct, the resulting program
4231 might not work correctly. Testing all combinations can quickly become
4232 impossible.
4234 Nevertheless, the need to tailor programs certainly exists, and in
4235 this section we will discuss how this can
4236 be achieved using Ada in general, and GNAT in particular.
4238 @menu
4239 * Use of Boolean Constants:: 
4240 * Debugging - A Special Case:: 
4241 * Conditionalizing Declarations:: 
4242 * Use of Alternative Implementations:: 
4243 * Preprocessing:: 
4245 @end menu
4247 @node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4248 @anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{9b}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{9c}
4249 @subsubsection Use of Boolean Constants
4252 In the case where the difference is simply which code
4253 sequence is executed, the cleanest solution is to use Boolean
4254 constants to control which code is executed.
4256 @example
4257 FP_Initialize_Required : constant Boolean := True;
4259 if FP_Initialize_Required then
4261 end if;
4262 @end example
4264 Not only will the code inside the @code{if} statement not be executed if
4265 the constant Boolean is @code{False}, but it will also be completely
4266 deleted from the program.
4267 However, the code is only deleted after the @code{if} statement
4268 has been checked for syntactic and semantic correctness.
4269 (In contrast, with preprocessors the code is deleted before the
4270 compiler ever gets to see it, so it is not checked until the switch
4271 is turned on.)
4273 @geindex Preprocessors (contrasted with conditional compilation)
4275 Typically the Boolean constants will be in a separate package,
4276 something like:
4278 @example
4279 package Config is
4280    FP_Initialize_Required : constant Boolean := True;
4281    Reset_Available        : constant Boolean := False;
4282    ...
4283 end Config;
4284 @end example
4286 The @code{Config} package exists in multiple forms for the various targets,
4287 with an appropriate script selecting the version of @code{Config} needed.
4288 Then any other unit requiring conditional compilation can do a @emph{with}
4289 of @code{Config} to make the constants visible.
4291 @node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4292 @anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{9d}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{9e}
4293 @subsubsection Debugging - A Special Case
4296 A common use of conditional code is to execute statements (for example
4297 dynamic checks, or output of intermediate results) under control of a
4298 debug switch, so that the debugging behavior can be turned on and off.
4299 This can be done using a Boolean constant to control whether the code
4300 is active:
4302 @example
4303 if Debugging then
4304    Put_Line ("got to the first stage!");
4305 end if;
4306 @end example
4310 @example
4311 if Debugging and then Temperature > 999.0 then
4312    raise Temperature_Crazy;
4313 end if;
4314 @end example
4316 @geindex pragma Assert
4318 Since this is a common case, there are special features to deal with
4319 this in a convenient manner. For the case of tests, Ada 2005 has added
4320 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
4321 on the @code{Assert} pragma that has always been available in GNAT, so this
4322 feature may be used with GNAT even if you are not using Ada 2005 features.
4323 The use of pragma @code{Assert} is described in the
4324 @cite{GNAT_Reference_Manual}, but as an
4325 example, the last test could be written:
4327 @example
4328 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4329 @end example
4331 or simply
4333 @example
4334 pragma Assert (Temperature <= 999.0);
4335 @end example
4337 In both cases, if assertions are active and the temperature is excessive,
4338 the exception @code{Assert_Failure} will be raised, with the given string in
4339 the first case or a string indicating the location of the pragma in the second
4340 case used as the exception message.
4342 @geindex pragma Assertion_Policy
4344 You can turn assertions on and off by using the @code{Assertion_Policy}
4345 pragma.
4347 @geindex -gnata switch
4349 This is an Ada 2005 pragma which is implemented in all modes by
4350 GNAT. Alternatively, you can use the @code{-gnata} switch
4351 to enable assertions from the command line, which applies to
4352 all versions of Ada.
4354 @geindex pragma Debug
4356 For the example above with the @code{Put_Line}, the GNAT-specific pragma
4357 @code{Debug} can be used:
4359 @example
4360 pragma Debug (Put_Line ("got to the first stage!"));
4361 @end example
4363 If debug pragmas are enabled, the argument, which must be of the form of
4364 a procedure call, is executed (in this case, @code{Put_Line} will be called).
4365 Only one call can be present, but of course a special debugging procedure
4366 containing any code you like can be included in the program and then
4367 called in a pragma @code{Debug} argument as needed.
4369 One advantage of pragma @code{Debug} over the @code{if Debugging then}
4370 construct is that pragma @code{Debug} can appear in declarative contexts,
4371 such as at the very beginning of a procedure, before local declarations have
4372 been elaborated.
4374 @geindex pragma Debug_Policy
4376 Debug pragmas are enabled using either the @code{-gnata} switch that also
4377 controls assertions, or with a separate Debug_Policy pragma.
4379 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4380 in Ada 95 and Ada 83 programs as well), and is analogous to
4381 pragma @code{Assertion_Policy} to control assertions.
4383 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
4384 and thus they can appear in @code{gnat.adc} if you are not using a
4385 project file, or in the file designated to contain configuration pragmas
4386 in a project file.
4387 They then apply to all subsequent compilations. In practice the use of
4388 the @code{-gnata} switch is often the most convenient method of controlling
4389 the status of these pragmas.
4391 Note that a pragma is not a statement, so in contexts where a statement
4392 sequence is required, you can't just write a pragma on its own. You have
4393 to add a @code{null} statement.
4395 @example
4396 if ... then
4397    ... -- some statements
4398 else
4399    pragma Assert (Num_Cases < 10);
4400    null;
4401 end if;
4402 @end example
4404 @node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4405 @anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{a0}
4406 @subsubsection Conditionalizing Declarations
4409 In some cases it may be necessary to conditionalize declarations to meet
4410 different requirements. For example we might want a bit string whose length
4411 is set to meet some hardware message requirement.
4413 This may be possible using declare blocks controlled
4414 by conditional constants:
4416 @example
4417 if Small_Machine then
4418    declare
4419       X : Bit_String (1 .. 10);
4420    begin
4421       ...
4422    end;
4423 else
4424    declare
4425       X : Large_Bit_String (1 .. 1000);
4426    begin
4427       ...
4428    end;
4429 end if;
4430 @end example
4432 Note that in this approach, both declarations are analyzed by the
4433 compiler so this can only be used where both declarations are legal,
4434 even though one of them will not be used.
4436 Another approach is to define integer constants, e.g., @code{Bits_Per_Word},
4437 or Boolean constants, e.g., @code{Little_Endian}, and then write declarations
4438 that are parameterized by these constants. For example
4440 @example
4441 for Rec use
4442   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4443 end record;
4444 @end example
4446 If @code{Bits_Per_Word} is set to 32, this generates either
4448 @example
4449 for Rec use
4450   Field1 at 0 range 0 .. 32;
4451 end record;
4452 @end example
4454 for the big endian case, or
4456 @example
4457 for Rec use record
4458     Field1 at 0 range 10 .. 32;
4459 end record;
4460 @end example
4462 for the little endian case. Since a powerful subset of Ada expression
4463 notation is usable for creating static constants, clever use of this
4464 feature can often solve quite difficult problems in conditionalizing
4465 compilation (note incidentally that in Ada 95, the little endian
4466 constant was introduced as @code{System.Default_Bit_Order}, so you do not
4467 need to define this one yourself).
4469 @node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4470 @anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{a2}
4471 @subsubsection Use of Alternative Implementations
4474 In some cases, none of the approaches described above are adequate. This
4475 can occur for example if the set of declarations required is radically
4476 different for two different configurations.
4478 In this situation, the official Ada way of dealing with conditionalizing
4479 such code is to write separate units for the different cases. As long as
4480 this does not result in excessive duplication of code, this can be done
4481 without creating maintenance problems. The approach is to share common
4482 code as far as possible, and then isolate the code and declarations
4483 that are different. Subunits are often a convenient method for breaking
4484 out a piece of a unit that is to be conditionalized, with separate files
4485 for different versions of the subunit for different targets, where the
4486 build script selects the right one to give to the compiler.
4488 @geindex Subunits (and conditional compilation)
4490 As an example, consider a situation where a new feature in Ada 2005
4491 allows something to be done in a really nice way. But your code must be able
4492 to compile with an Ada 95 compiler. Conceptually you want to say:
4494 @example
4495 if Ada_2005 then
4496    ... neat Ada 2005 code
4497 else
4498    ... not quite as neat Ada 95 code
4499 end if;
4500 @end example
4502 where @code{Ada_2005} is a Boolean constant.
4504 But this won't work when @code{Ada_2005} is set to @code{False},
4505 since the @code{then} clause will be illegal for an Ada 95 compiler.
4506 (Recall that although such unreachable code would eventually be deleted
4507 by the compiler, it still needs to be legal.  If it uses features
4508 introduced in Ada 2005, it will be illegal in Ada 95.)
4510 So instead we write
4512 @example
4513 procedure Insert is separate;
4514 @end example
4516 Then we have two files for the subunit @code{Insert}, with the two sets of
4517 code.
4518 If the package containing this is called @code{File_Queries}, then we might
4519 have two files
4522 @itemize *
4524 @item 
4525 @code{file_queries-insert-2005.adb}
4527 @item 
4528 @code{file_queries-insert-95.adb}
4529 @end itemize
4531 and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4533 This can also be done with project files' naming schemes. For example:
4535 @example
4536 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4537 @end example
4539 Note also that with project files it is desirable to use a different extension
4540 than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4541 conflict may arise through another commonly used feature: to declare as part
4542 of the project a set of directories containing all the sources obeying the
4543 default naming scheme.
4545 The use of alternative units is certainly feasible in all situations,
4546 and for example the Ada part of the GNAT run-time is conditionalized
4547 based on the target architecture using this approach. As a specific example,
4548 consider the implementation of the AST feature in VMS. There is one
4549 spec: @code{s-asthan.ads} which is the same for all architectures, and three
4550 bodies:
4553 @itemize *
4555 @item 
4557 @table @asis
4559 @item @code{s-asthan.adb}
4561 used for all non-VMS operating systems
4562 @end table
4564 @item 
4566 @table @asis
4568 @item @code{s-asthan-vms-alpha.adb}
4570 used for VMS on the Alpha
4571 @end table
4573 @item 
4575 @table @asis
4577 @item @code{s-asthan-vms-ia64.adb}
4579 used for VMS on the ia64
4580 @end table
4581 @end itemize
4583 The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4584 this operating system feature is not available, and the two remaining
4585 versions interface with the corresponding versions of VMS to provide
4586 VMS-compatible AST handling. The GNAT build script knows the architecture
4587 and operating system, and automatically selects the right version,
4588 renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4590 Another style for arranging alternative implementations is through Ada's
4591 access-to-subprogram facility.
4592 In case some functionality is to be conditionally included,
4593 you can declare an access-to-procedure variable @code{Ref} that is initialized
4594 to designate a 'do nothing' procedure, and then invoke @code{Ref.all}
4595 when appropriate.
4596 In some library package, set @code{Ref} to @code{Proc'Access} for some
4597 procedure @code{Proc} that performs the relevant processing.
4598 The initialization only occurs if the library package is included in the
4599 program.
4600 The same idea can also be implemented using tagged types and dispatching
4601 calls.
4603 @node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4604 @anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{a4}
4605 @subsubsection Preprocessing
4608 @geindex Preprocessing
4610 Although it is quite possible to conditionalize code without the use of
4611 C-style preprocessing, as described earlier in this section, it is
4612 nevertheless convenient in some cases to use the C approach. Moreover,
4613 older Ada compilers have often provided some preprocessing capability,
4614 so legacy code may depend on this approach, even though it is not
4615 standard.
4617 To accommodate such use, GNAT provides a preprocessor (modeled to a large
4618 extent on the various preprocessors that have been used
4619 with legacy code on other compilers, to enable easier transition).
4621 @geindex gnatprep
4623 The preprocessor may be used in two separate modes. It can be used quite
4624 separately from the compiler, to generate a separate output source file
4625 that is then fed to the compiler as a separate step. This is the
4626 @code{gnatprep} utility, whose use is fully described in
4627 @ref{17,,Preprocessing with gnatprep}.
4629 The preprocessing language allows such constructs as
4631 @example
4632 #if DEBUG or else (PRIORITY > 4) then
4633    sequence of declarations
4634 #else
4635    completely different sequence of declarations
4636 #end if;
4637 @end example
4639 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
4640 defined either on the command line or in a separate file.
4642 The other way of running the preprocessor is even closer to the C style and
4643 often more convenient. In this approach the preprocessing is integrated into
4644 the compilation process. The compiler is given the preprocessor input which
4645 includes @code{#if} lines etc, and then the compiler carries out the
4646 preprocessing internally and processes the resulting output.
4647 For more details on this approach, see @ref{18,,Integrated Preprocessing}.
4649 @node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4650 @anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{17}
4651 @subsection Preprocessing with @code{gnatprep}
4654 @geindex gnatprep
4656 @geindex Preprocessing (gnatprep)
4658 This section discusses how to use GNAT's @code{gnatprep} utility for simple
4659 preprocessing.
4660 Although designed for use with GNAT, @code{gnatprep} does not depend on any
4661 special GNAT features.
4662 For further discussion of conditional compilation in general, see
4663 @ref{16,,Conditional Compilation}.
4665 @menu
4666 * Preprocessing Symbols:: 
4667 * Using gnatprep:: 
4668 * Switches for gnatprep:: 
4669 * Form of Definitions File:: 
4670 * Form of Input Text for gnatprep:: 
4672 @end menu
4674 @node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4675 @anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{a6}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{a7}
4676 @subsubsection Preprocessing Symbols
4679 Preprocessing symbols are defined in @emph{definition files} and referenced in the
4680 sources to be preprocessed. A preprocessing symbol is an identifier, following
4681 normal Ada (case-insensitive) rules for its syntax, with the restriction that
4682 all characters need to be in the ASCII set (no accented letters).
4684 @node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4685 @anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{a8}@anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{a9}
4686 @subsubsection Using @code{gnatprep}
4689 To call @code{gnatprep} use:
4691 @example
4692 $ gnatprep [ switches ] infile outfile [ deffile ]
4693 @end example
4695 where
4698 @itemize *
4700 @item 
4702 @table @asis
4704 @item @emph{switches}
4706 is an optional sequence of switches as described in the next section.
4707 @end table
4709 @item 
4711 @table @asis
4713 @item @emph{infile}
4715 is the full name of the input file, which is an Ada source
4716 file containing preprocessor directives.
4717 @end table
4719 @item 
4721 @table @asis
4723 @item @emph{outfile}
4725 is the full name of the output file, which is an Ada source
4726 in standard Ada form. When used with GNAT, this file name will
4727 normally have an @code{ads} or @code{adb} suffix.
4728 @end table
4730 @item 
4732 @table @asis
4734 @item @code{deffile}
4736 is the full name of a text file containing definitions of
4737 preprocessing symbols to be referenced by the preprocessor. This argument is
4738 optional, and can be replaced by the use of the @code{-D} switch.
4739 @end table
4740 @end itemize
4742 @node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4743 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{aa}@anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{ab}
4744 @subsubsection Switches for @code{gnatprep}
4747 @geindex --version (gnatprep)
4750 @table @asis
4752 @item @code{--version}
4754 Display Copyright and version, then exit disregarding all other options.
4755 @end table
4757 @geindex --help (gnatprep)
4760 @table @asis
4762 @item @code{--help}
4764 If @code{--version} was not used, display usage and then exit disregarding
4765 all other options.
4766 @end table
4768 @geindex -b (gnatprep)
4771 @table @asis
4773 @item @code{-b}
4775 Causes both preprocessor lines and the lines deleted by
4776 preprocessing to be replaced by blank lines in the output source file,
4777 preserving line numbers in the output file.
4778 @end table
4780 @geindex -c (gnatprep)
4783 @table @asis
4785 @item @code{-c}
4787 Causes both preprocessor lines and the lines deleted
4788 by preprocessing to be retained in the output source as comments marked
4789 with the special string @code{"--! "}. This option will result in line numbers
4790 being preserved in the output file.
4791 @end table
4793 @geindex -C (gnatprep)
4796 @table @asis
4798 @item @code{-C}
4800 Causes comments to be scanned. Normally comments are ignored by gnatprep.
4801 If this option is specified, then comments are scanned and any $symbol
4802 substitutions performed as in program text. This is particularly useful
4803 when structured comments are used (e.g., for programs written in a
4804 pre-2014 version of the SPARK Ada subset). Note that this switch is not
4805 available when  doing integrated preprocessing (it would be useless in
4806 this context since comments are ignored by the compiler in any case).
4807 @end table
4809 @geindex -D (gnatprep)
4812 @table @asis
4814 @item @code{-D@emph{symbol}[=@emph{value}]}
4816 Defines a new preprocessing symbol with the specified value. If no value is given
4817 on the command line, then symbol is considered to be @code{True}. This switch
4818 can be used in place of a definition file.
4819 @end table
4821 @geindex -r (gnatprep)
4824 @table @asis
4826 @item @code{-r}
4828 Causes a @code{Source_Reference} pragma to be generated that
4829 references the original input file, so that error messages will use
4830 the file name of this original file. The use of this switch implies
4831 that preprocessor lines are not to be removed from the file, so its
4832 use will force @code{-b} mode if @code{-c}
4833 has not been specified explicitly.
4835 Note that if the file to be preprocessed contains multiple units, then
4836 it will be necessary to @code{gnatchop} the output file from
4837 @code{gnatprep}. If a @code{Source_Reference} pragma is present
4838 in the preprocessed file, it will be respected by
4839 @code{gnatchop -r}
4840 so that the final chopped files will correctly refer to the original
4841 input source file for @code{gnatprep}.
4842 @end table
4844 @geindex -s (gnatprep)
4847 @table @asis
4849 @item @code{-s}
4851 Causes a sorted list of symbol names and values to be
4852 listed on the standard output file.
4853 @end table
4855 @geindex -T (gnatprep)
4858 @table @asis
4860 @item @code{-T}
4862 Use LF as line terminators when writing files. By default the line terminator
4863 of the host (LF under unix, CR/LF under Windows) is used.
4864 @end table
4866 @geindex -u (gnatprep)
4869 @table @asis
4871 @item @code{-u}
4873 Causes undefined symbols to be treated as having the value FALSE in the context
4874 of a preprocessor test. In the absence of this option, an undefined symbol in
4875 a @code{#if} or @code{#elsif} test will be treated as an error.
4876 @end table
4878 @geindex -v (gnatprep)
4881 @table @asis
4883 @item @code{-v}
4885 Verbose mode: generates more output about work done.
4886 @end table
4888 Note: if neither @code{-b} nor @code{-c} is present,
4889 then preprocessor lines and
4890 deleted lines are completely removed from the output, unless -r is
4891 specified, in which case -b is assumed.
4893 @node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4894 @anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{ad}
4895 @subsubsection Form of Definitions File
4898 The definitions file contains lines of the form:
4900 @example
4901 symbol := value
4902 @end example
4904 where @code{symbol} is a preprocessing symbol, and @code{value} is one of the following:
4907 @itemize *
4909 @item 
4910 Empty, corresponding to a null substitution,
4912 @item 
4913 A string literal using normal Ada syntax, or
4915 @item 
4916 Any sequence of characters from the set @{letters, digits, period, underline@}.
4917 @end itemize
4919 Comment lines may also appear in the definitions file, starting with
4920 the usual @code{--},
4921 and comments may be added to the definitions lines.
4923 @node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4924 @anchor{gnat_ugn/the_gnat_compilation_model id59}@anchor{ae}@anchor{gnat_ugn/the_gnat_compilation_model form-of-input-text-for-gnatprep}@anchor{af}
4925 @subsubsection Form of Input Text for @code{gnatprep}
4928 The input text may contain preprocessor conditional inclusion lines,
4929 as well as general symbol substitution sequences.
4931 The preprocessor conditional inclusion commands have the form:
4933 @example
4934 #if <expression> [then]
4935    lines
4936 #elsif <expression> [then]
4937    lines
4938 #elsif <expression> [then]
4939    lines
4941 #else
4942    lines
4943 #end if;
4944 @end example
4946 In this example, <expression> is defined by the following grammar:
4948 @example
4949 <expression> ::=  <symbol>
4950 <expression> ::=  <symbol> = "<value>"
4951 <expression> ::=  <symbol> = <symbol>
4952 <expression> ::=  <symbol> = <integer>
4953 <expression> ::=  <symbol> > <integer>
4954 <expression> ::=  <symbol> >= <integer>
4955 <expression> ::=  <symbol> < <integer>
4956 <expression> ::=  <symbol> <= <integer>
4957 <expression> ::=  <symbol> 'Defined
4958 <expression> ::=  not <expression>
4959 <expression> ::=  <expression> and <expression>
4960 <expression> ::=  <expression> or <expression>
4961 <expression> ::=  <expression> and then <expression>
4962 <expression> ::=  <expression> or else <expression>
4963 <expression> ::=  ( <expression> )
4964 @end example
4966 Note the following restriction: it is not allowed to have "and" or "or"
4967 following "not" in the same expression without parentheses. For example, this
4968 is not allowed:
4970 @example
4971 not X or Y
4972 @end example
4974 This can be expressed instead as one of the following forms:
4976 @example
4977 (not X) or Y
4978 not (X or Y)
4979 @end example
4981 For the first test (<expression> ::= <symbol>) the symbol must have
4982 either the value true or false, that is to say the right-hand of the
4983 symbol definition must be one of the (case-insensitive) literals
4984 @code{True} or @code{False}. If the value is true, then the
4985 corresponding lines are included, and if the value is false, they are
4986 excluded.
4988 When comparing a symbol to an integer, the integer is any non negative
4989 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
4990 2#11#. The symbol value must also be a non negative integer. Integer values
4991 in the range 0 .. 2**31-1 are supported.
4993 The test (<expression> ::= <symbol>'Defined) is true only if
4994 the symbol has been defined in the definition file or by a @code{-D}
4995 switch on the command line. Otherwise, the test is false.
4997 The equality tests are case insensitive, as are all the preprocessor lines.
4999 If the symbol referenced is not defined in the symbol definitions file,
5000 then the effect depends on whether or not switch @code{-u}
5001 is specified. If so, then the symbol is treated as if it had the value
5002 false and the test fails. If this switch is not specified, then
5003 it is an error to reference an undefined symbol. It is also an error to
5004 reference a symbol that is defined with a value other than @code{True}
5005 or @code{False}.
5007 The use of the @code{not} operator inverts the sense of this logical test.
5008 The @code{not} operator cannot be combined with the @code{or} or @code{and}
5009 operators, without parentheses. For example, "if not X or Y then" is not
5010 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
5012 The @code{then} keyword is optional as shown
5014 The @code{#} must be the first non-blank character on a line, but
5015 otherwise the format is free form. Spaces or tabs may appear between
5016 the @code{#} and the keyword. The keywords and the symbols are case
5017 insensitive as in normal Ada code. Comments may be used on a
5018 preprocessor line, but other than that, no other tokens may appear on a
5019 preprocessor line. Any number of @code{elsif} clauses can be present,
5020 including none at all. The @code{else} is optional, as in Ada.
5022 The @code{#} marking the start of a preprocessor line must be the first
5023 non-blank character on the line, i.e., it must be preceded only by
5024 spaces or horizontal tabs.
5026 Symbol substitution outside of preprocessor lines is obtained by using
5027 the sequence:
5029 @example
5030 $symbol
5031 @end example
5033 anywhere within a source line, except in a comment or within a
5034 string literal. The identifier
5035 following the @code{$} must match one of the symbols defined in the symbol
5036 definition file, and the result is to substitute the value of the
5037 symbol in place of @code{$symbol} in the output file.
5039 Note that although the substitution of strings within a string literal
5040 is not possible, it is possible to have a symbol whose defined value is
5041 a string literal. So instead of setting XYZ to @code{hello} and writing:
5043 @example
5044 Header : String := "$XYZ";
5045 @end example
5047 you should set XYZ to @code{"hello"} and write:
5049 @example
5050 Header : String := $XYZ;
5051 @end example
5053 and then the substitution will occur as desired.
5055 @node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
5056 @anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{18}
5057 @subsection Integrated Preprocessing
5060 As noted above, a file to be preprocessed consists of Ada source code
5061 in which preprocessing lines have been inserted. However,
5062 instead of using @code{gnatprep} to explicitly preprocess a file as a separate
5063 step before compilation, you can carry out the preprocessing implicitly
5064 as part of compilation. Such @emph{integrated preprocessing}, which is the common
5065 style with C, is performed when either or both of the following switches
5066 are passed to the compiler:
5068 @quotation
5071 @itemize *
5073 @item 
5074 @code{-gnatep}, which specifies the @emph{preprocessor data file}.
5075 This file dictates how the source files will be preprocessed (e.g., which
5076 symbol definition files apply to which sources).
5078 @item 
5079 @code{-gnateD}, which defines values for preprocessing symbols.
5080 @end itemize
5081 @end quotation
5083 Integrated preprocessing applies only to Ada source files, it is
5084 not available for configuration pragma files.
5086 With integrated preprocessing, the output from the preprocessor is not,
5087 by default, written to any external file. Instead it is passed
5088 internally to the compiler. To preserve the result of
5089 preprocessing in a file, either run @code{gnatprep}
5090 in standalone mode or else supply the @code{-gnateG} switch
5091 (described below) to the compiler.
5093 When using project files:
5095 @quotation
5098 @itemize *
5100 @item 
5101 the builder switch @code{-x} should be used if any Ada source is
5102 compiled with @code{gnatep=}, so that the compiler finds the
5103 @emph{preprocessor data file}.
5105 @item 
5106 the preprocessing data file and the symbol definition files should be
5107 located in the source directories of the project.
5108 @end itemize
5109 @end quotation
5111 Note that the @code{gnatmake} switch @code{-m} will almost
5112 always trigger recompilation for sources that are preprocessed,
5113 because @code{gnatmake} cannot compute the checksum of the source after
5114 preprocessing.
5116 The actual preprocessing function is described in detail in
5117 @ref{17,,Preprocessing with gnatprep}. This section explains the switches
5118 that relate to integrated preprocessing.
5120 @geindex -gnatep (gcc)
5123 @table @asis
5125 @item @code{-gnatep=@emph{preprocessor_data_file}}
5127 This switch specifies the file name (without directory
5128 information) of the preprocessor data file. Either place this file
5129 in one of the source directories, or, when using project
5130 files, reference the project file's directory via the
5131 @code{project_name'Project_Dir} project attribute; e.g:
5133 @quotation
5135 @example
5136 project Prj is
5137    package Compiler is
5138       for Switches ("Ada") use
5139         ("-gnatep=" & Prj'Project_Dir & "prep.def");
5140    end Compiler;
5141 end Prj;
5142 @end example
5143 @end quotation
5145 A preprocessor data file is a text file that contains @emph{preprocessor
5146 control lines}.  A preprocessor control line directs the preprocessing of
5147 either a particular source file, or, analogous to @code{others} in Ada,
5148 all sources not specified elsewhere in  the preprocessor data file.
5149 A preprocessor control line
5150 can optionally identify a @emph{definition file} that assigns values to
5151 preprocessor symbols, as well as a list of switches that relate to
5152 preprocessing.
5153 Empty lines and comments (using Ada syntax) are also permitted, with no
5154 semantic effect.
5156 Here's an example of a preprocessor data file:
5158 @quotation
5160 @example
5161 "toto.adb"  "prep.def" -u
5162 --  Preprocess toto.adb, using definition file prep.def
5163 --  Undefined symbols are treated as False
5165 * -c -DVERSION=V101
5166 --  Preprocess all other sources without using a definition file
5167 --  Suppressed lined are commented
5168 --  Symbol VERSION has the value V101
5170 "tata.adb" "prep2.def" -s
5171 --  Preprocess tata.adb, using definition file prep2.def
5172 --  List all symbols with their values
5173 @end example
5174 @end quotation
5176 A preprocessor control line has the following syntax:
5178 @quotation
5180 @example
5181 <preprocessor_control_line> ::=
5182    <preprocessor_input> [ <definition_file_name> ] @{ <switch> @}
5184 <preprocessor_input> ::= <source_file_name> | '*'
5186 <definition_file_name> ::= <string_literal>
5188 <source_file_name> := <string_literal>
5190 <switch> := (See below for list)
5191 @end example
5192 @end quotation
5194 Thus  each preprocessor control line starts with either a literal string or
5195 the character '*':
5198 @itemize *
5200 @item 
5201 A literal string is the file name (without directory information) of the source
5202 file that will be input to the preprocessor.
5204 @item 
5205 The character '*' is a wild-card indicator; the additional parameters on the line
5206 indicate the preprocessing for all the sources
5207 that are not specified explicitly on other lines (the order of the lines is not
5208 significant).
5209 @end itemize
5211 It is an error to have two lines with the same file name or two
5212 lines starting with the character '*'.
5214 After the file name or '*', an optional literal string specifies the name of
5215 the definition file to be used for preprocessing
5216 (@ref{ac,,Form of Definitions File}). The definition files are found by the
5217 compiler in one of the source directories. In some cases, when compiling
5218 a source in a directory other than the current directory, if the definition
5219 file is in the current directory, it may be necessary to add the current
5220 directory as a source directory through the @code{-I} switch; otherwise
5221 the compiler would not find the definition file.
5223 Finally, switches similar to those of @code{gnatprep} may optionally appear:
5226 @table @asis
5228 @item @code{-b}
5230 Causes both preprocessor lines and the lines deleted by
5231 preprocessing to be replaced by blank lines, preserving the line number.
5232 This switch is always implied; however, if specified after @code{-c}
5233 it cancels the effect of @code{-c}.
5235 @item @code{-c}
5237 Causes both preprocessor lines and the lines deleted
5238 by preprocessing to be retained as comments marked
5239 with the special string '@cite{--!}'.
5241 @item @code{-D@emph{symbol}=@emph{new_value}}
5243 Define or redefine @code{symbol} to have @code{new_value} as its value.
5244 The permitted form for @code{symbol} is either an Ada identifier, or any Ada reserved word
5245 aside from @code{if},
5246 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5247 The permitted form for @code{new_value} is a literal string, an Ada identifier or any Ada reserved
5248 word. A symbol declared with this switch replaces a symbol with the
5249 same name defined in a definition file.
5251 @item @code{-s}
5253 Causes a sorted list of symbol names and values to be
5254 listed on the standard output file.
5256 @item @code{-u}
5258 Causes undefined symbols to be treated as having the value @code{FALSE}
5259 in the context
5260 of a preprocessor test. In the absence of this option, an undefined symbol in
5261 a @code{#if} or @code{#elsif} test will be treated as an error.
5262 @end table
5263 @end table
5265 @geindex -gnateD (gcc)
5268 @table @asis
5270 @item @code{-gnateD@emph{symbol}[=@emph{new_value}]}
5272 Define or redefine @code{symbol} to have @code{new_value} as its value. If no value
5273 is supplied, then the value of @code{symbol} is @code{True}.
5274 The form of @code{symbol} is an identifier, following normal Ada (case-insensitive)
5275 rules for its syntax, and @code{new_value} is either an arbitrary string between double
5276 quotes or any sequence (including an empty sequence) of characters from the
5277 set (letters, digits, period, underline).
5278 Ada reserved words may be used as symbols, with the exceptions of @code{if},
5279 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5281 Examples:
5283 @quotation
5285 @example
5286 -gnateDToto=Tata
5287 -gnateDFoo
5288 -gnateDFoo=\"Foo-Bar\"
5289 @end example
5290 @end quotation
5292 A symbol declared with this switch on the command line replaces a
5293 symbol with the same name either in a definition file or specified with a
5294 switch @code{-D} in the preprocessor data file.
5296 This switch is similar to switch @code{-D} of @code{gnatprep}.
5298 @item @code{-gnateG}
5300 When integrated preprocessing is performed on source file @code{filename.extension},
5301 create or overwrite @code{filename.extension.prep} to contain
5302 the result of the preprocessing.
5303 For example if the source file is @code{foo.adb} then
5304 the output file will be @code{foo.adb.prep}.
5305 @end table
5307 @node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5308 @anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{44}@anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{b1}
5309 @section Mixed Language Programming
5312 @geindex Mixed Language Programming
5314 This section describes how to develop a mixed-language program,
5315 with a focus on combining Ada with C or C++.
5317 @menu
5318 * Interfacing to C:: 
5319 * Calling Conventions:: 
5320 * Building Mixed Ada and C++ Programs:: 
5321 * Generating Ada Bindings for C and C++ headers:: 
5322 * Generating C Headers for Ada Specifications:: 
5324 @end menu
5326 @node Interfacing to C,Calling Conventions,,Mixed Language Programming
5327 @anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{b2}@anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{b3}
5328 @subsection Interfacing to C
5331 Interfacing Ada with a foreign language such as C involves using
5332 compiler directives to import and/or export entity definitions in each
5333 language -- using @code{extern} statements in C, for instance, and the
5334 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
5335 A full treatment of these topics is provided in Appendix B, section 1
5336 of the Ada Reference Manual.
5338 There are two ways to build a program using GNAT that contains some Ada
5339 sources and some foreign language sources, depending on whether or not
5340 the main subprogram is written in Ada.  Here is a source example with
5341 the main subprogram in Ada:
5343 @example
5344 /* file1.c */
5345 #include <stdio.h>
5347 void print_num (int num)
5349   printf ("num is %d.\\n", num);
5350   return;
5352 @end example
5354 @example
5355 /* file2.c */
5357 /* num_from_Ada is declared in my_main.adb */
5358 extern int num_from_Ada;
5360 int get_num (void)
5362   return num_from_Ada;
5364 @end example
5366 @example
5367 --  my_main.adb
5368 procedure My_Main is
5370    --  Declare then export an Integer entity called num_from_Ada
5371    My_Num : Integer := 10;
5372    pragma Export (C, My_Num, "num_from_Ada");
5374    --  Declare an Ada function spec for Get_Num, then use
5375    --  C function get_num for the implementation.
5376    function Get_Num return Integer;
5377    pragma Import (C, Get_Num, "get_num");
5379    --  Declare an Ada procedure spec for Print_Num, then use
5380    --  C function print_num for the implementation.
5381    procedure Print_Num (Num : Integer);
5382    pragma Import (C, Print_Num, "print_num");
5384 begin
5385    Print_Num (Get_Num);
5386 end My_Main;
5387 @end example
5389 To build this example:
5392 @itemize *
5394 @item 
5395 First compile the foreign language files to
5396 generate object files:
5398 @example
5399 $ gcc -c file1.c
5400 $ gcc -c file2.c
5401 @end example
5403 @item 
5404 Then, compile the Ada units to produce a set of object files and ALI
5405 files:
5407 @example
5408 $ gnatmake -c my_main.adb
5409 @end example
5411 @item 
5412 Run the Ada binder on the Ada main program:
5414 @example
5415 $ gnatbind my_main.ali
5416 @end example
5418 @item 
5419 Link the Ada main program, the Ada objects and the other language
5420 objects:
5422 @example
5423 $ gnatlink my_main.ali file1.o file2.o
5424 @end example
5425 @end itemize
5427 The last three steps can be grouped in a single command:
5429 @example
5430 $ gnatmake my_main.adb -largs file1.o file2.o
5431 @end example
5433 @geindex Binder output file
5435 If the main program is in a language other than Ada, then you may have
5436 more than one entry point into the Ada subsystem. You must use a special
5437 binder option to generate callable routines that initialize and
5438 finalize the Ada units (@ref{b4,,Binding with Non-Ada Main Programs}).
5439 Calls to the initialization and finalization routines must be inserted
5440 in the main program, or some other appropriate point in the code. The
5441 call to initialize the Ada units must occur before the first Ada
5442 subprogram is called, and the call to finalize the Ada units must occur
5443 after the last Ada subprogram returns. The binder will place the
5444 initialization and finalization subprograms into the
5445 @code{b~xxx.adb} file where they can be accessed by your C
5446 sources.  To illustrate, we have the following example:
5448 @example
5449 /* main.c */
5450 extern void adainit (void);
5451 extern void adafinal (void);
5452 extern int add (int, int);
5453 extern int sub (int, int);
5455 int main (int argc, char *argv[])
5457    int a = 21, b = 7;
5459    adainit();
5461    /* Should print "21 + 7 = 28" */
5462    printf ("%d + %d = %d\\n", a, b, add (a, b));
5464    /* Should print "21 - 7 = 14" */
5465    printf ("%d - %d = %d\\n", a, b, sub (a, b));
5467    adafinal();
5469 @end example
5471 @example
5472 --  unit1.ads
5473 package Unit1 is
5474    function Add (A, B : Integer) return Integer;
5475    pragma Export (C, Add, "add");
5476 end Unit1;
5477 @end example
5479 @example
5480 --  unit1.adb
5481 package body Unit1 is
5482    function Add (A, B : Integer) return Integer is
5483    begin
5484       return A + B;
5485    end Add;
5486 end Unit1;
5487 @end example
5489 @example
5490 --  unit2.ads
5491 package Unit2 is
5492    function Sub (A, B : Integer) return Integer;
5493    pragma Export (C, Sub, "sub");
5494 end Unit2;
5495 @end example
5497 @example
5498 --  unit2.adb
5499 package body Unit2 is
5500    function Sub (A, B : Integer) return Integer is
5501    begin
5502       return A - B;
5503    end Sub;
5504 end Unit2;
5505 @end example
5507 The build procedure for this application is similar to the last
5508 example's:
5511 @itemize *
5513 @item 
5514 First, compile the foreign language files to generate object files:
5516 @example
5517 $ gcc -c main.c
5518 @end example
5520 @item 
5521 Next, compile the Ada units to produce a set of object files and ALI
5522 files:
5524 @example
5525 $ gnatmake -c unit1.adb
5526 $ gnatmake -c unit2.adb
5527 @end example
5529 @item 
5530 Run the Ada binder on every generated ALI file.  Make sure to use the
5531 @code{-n} option to specify a foreign main program:
5533 @example
5534 $ gnatbind -n unit1.ali unit2.ali
5535 @end example
5537 @item 
5538 Link the Ada main program, the Ada objects and the foreign language
5539 objects. You need only list the last ALI file here:
5541 @example
5542 $ gnatlink unit2.ali main.o -o exec_file
5543 @end example
5545 This procedure yields a binary executable called @code{exec_file}.
5546 @end itemize
5548 Depending on the circumstances (for example when your non-Ada main object
5549 does not provide symbol @code{main}), you may also need to instruct the
5550 GNAT linker not to include the standard startup objects by passing the
5551 @code{-nostartfiles} switch to @code{gnatlink}.
5553 @node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5554 @anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{b5}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{b6}
5555 @subsection Calling Conventions
5558 @geindex Foreign Languages
5560 @geindex Calling Conventions
5562 GNAT follows standard calling sequence conventions and will thus interface
5563 to any other language that also follows these conventions. The following
5564 Convention identifiers are recognized by GNAT:
5566 @geindex Interfacing to Ada
5568 @geindex Other Ada compilers
5570 @geindex Convention Ada
5573 @table @asis
5575 @item @code{Ada}
5577 This indicates that the standard Ada calling sequence will be
5578 used and all Ada data items may be passed without any limitations in the
5579 case where GNAT is used to generate both the caller and callee. It is also
5580 possible to mix GNAT generated code and code generated by another Ada
5581 compiler. In this case, the data types should be restricted to simple
5582 cases, including primitive types. Whether complex data types can be passed
5583 depends on the situation. Probably it is safe to pass simple arrays, such
5584 as arrays of integers or floats. Records may or may not work, depending
5585 on whether both compilers lay them out identically. Complex structures
5586 involving variant records, access parameters, tasks, or protected types,
5587 are unlikely to be able to be passed.
5589 Note that in the case of GNAT running
5590 on a platform that supports HP Ada 83, a higher degree of compatibility
5591 can be guaranteed, and in particular records are laid out in an identical
5592 manner in the two compilers. Note also that if output from two different
5593 compilers is mixed, the program is responsible for dealing with elaboration
5594 issues. Probably the safest approach is to write the main program in the
5595 version of Ada other than GNAT, so that it takes care of its own elaboration
5596 requirements, and then call the GNAT-generated adainit procedure to ensure
5597 elaboration of the GNAT components. Consult the documentation of the other
5598 Ada compiler for further details on elaboration.
5600 However, it is not possible to mix the tasking run time of GNAT and
5601 HP Ada 83, All the tasking operations must either be entirely within
5602 GNAT compiled sections of the program, or entirely within HP Ada 83
5603 compiled sections of the program.
5604 @end table
5606 @geindex Interfacing to Assembly
5608 @geindex Convention Assembler
5611 @table @asis
5613 @item @code{Assembler}
5615 Specifies assembler as the convention. In practice this has the
5616 same effect as convention Ada (but is not equivalent in the sense of being
5617 considered the same convention).
5618 @end table
5620 @geindex Convention Asm
5622 @geindex Asm
5625 @table @asis
5627 @item @code{Asm}
5629 Equivalent to Assembler.
5631 @geindex Interfacing to COBOL
5633 @geindex Convention COBOL
5634 @end table
5636 @geindex COBOL
5639 @table @asis
5641 @item @code{COBOL}
5643 Data will be passed according to the conventions described
5644 in section B.4 of the Ada Reference Manual.
5645 @end table
5647 @geindex C
5649 @geindex Interfacing to C
5651 @geindex Convention C
5654 @table @asis
5656 @item @code{C}
5658 Data will be passed according to the conventions described
5659 in section B.3 of the Ada Reference Manual.
5661 A note on interfacing to a C 'varargs' function:
5663 @quotation
5665 @geindex C varargs function
5667 @geindex Interfacing to C varargs function
5669 @geindex varargs function interfaces
5671 In C, @code{varargs} allows a function to take a variable number of
5672 arguments. There is no direct equivalent in this to Ada. One
5673 approach that can be used is to create a C wrapper for each
5674 different profile and then interface to this C wrapper. For
5675 example, to print an @code{int} value using @code{printf},
5676 create a C function @code{printfi} that takes two arguments, a
5677 pointer to a string and an int, and calls @code{printf}.
5678 Then in the Ada program, use pragma @code{Import} to
5679 interface to @code{printfi}.
5681 It may work on some platforms to directly interface to
5682 a @code{varargs} function by providing a specific Ada profile
5683 for a particular call. However, this does not work on
5684 all platforms, since there is no guarantee that the
5685 calling sequence for a two argument normal C function
5686 is the same as for calling a @code{varargs} C function with
5687 the same two arguments.
5688 @end quotation
5689 @end table
5691 @geindex Convention Default
5693 @geindex Default
5696 @table @asis
5698 @item @code{Default}
5700 Equivalent to C.
5701 @end table
5703 @geindex Convention External
5705 @geindex External
5708 @table @asis
5710 @item @code{External}
5712 Equivalent to C.
5713 @end table
5715 @geindex C++
5717 @geindex Interfacing to C++
5719 @geindex Convention C++
5722 @table @asis
5724 @item @code{C_Plus_Plus} (or @code{CPP})
5726 This stands for C++. For most purposes this is identical to C.
5727 See the separate description of the specialized GNAT pragmas relating to
5728 C++ interfacing for further details.
5729 @end table
5731 @geindex Fortran
5733 @geindex Interfacing to Fortran
5735 @geindex Convention Fortran
5738 @table @asis
5740 @item @code{Fortran}
5742 Data will be passed according to the conventions described
5743 in section B.5 of the Ada Reference Manual.
5745 @item @code{Intrinsic}
5747 This applies to an intrinsic operation, as defined in the Ada
5748 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5749 this means that the body of the subprogram is provided by the compiler itself,
5750 usually by means of an efficient code sequence, and that the user does not
5751 supply an explicit body for it. In an application program, the pragma may
5752 be applied to the following sets of names:
5755 @itemize *
5757 @item 
5758 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5759 The corresponding subprogram declaration must have
5760 two formal parameters. The
5761 first one must be a signed integer type or a modular type with a binary
5762 modulus, and the second parameter must be of type Natural.
5763 The return type must be the same as the type of the first argument. The size
5764 of this type can only be 8, 16, 32, or 64.
5766 @item 
5767 Binary arithmetic operators: '+', '-', '*', '/'.
5768 The corresponding operator declaration must have parameters and result type
5769 that have the same root numeric type (for example, all three are long_float
5770 types). This simplifies the definition of operations that use type checking
5771 to perform dimensional checks:
5772 @end itemize
5774 @example
5775   type Distance is new Long_Float;
5776   type Time     is new Long_Float;
5777   type Velocity is new Long_Float;
5778   function "/" (D : Distance; T : Time)
5779     return Velocity;
5780   pragma Import (Intrinsic, "/");
5782 This common idiom is often programmed with a generic definition and an
5783 explicit body. The pragma makes it simpler to introduce such declarations.
5784 It incurs no overhead in compilation time or code size, because it is
5785 implemented as a single machine instruction.
5786 @end example
5789 @itemize *
5791 @item 
5792 General subprogram entities. This is used  to bind an Ada subprogram
5793 declaration to
5794 a compiler builtin by name with back-ends where such interfaces are
5795 available. A typical example is the set of @code{__builtin} functions
5796 exposed by the GCC back-end, as in the following example:
5798 @example
5799 function builtin_sqrt (F : Float) return Float;
5800 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5801 @end example
5803 Most of the GCC builtins are accessible this way, and as for other
5804 import conventions (e.g. C), it is the user's responsibility to ensure
5805 that the Ada subprogram profile matches the underlying builtin
5806 expectations.
5807 @end itemize
5808 @end table
5810 @geindex Stdcall
5812 @geindex Convention Stdcall
5815 @table @asis
5817 @item @code{Stdcall}
5819 This is relevant only to Windows implementations of GNAT,
5820 and specifies that the @code{Stdcall} calling sequence will be used,
5821 as defined by the NT API. Nevertheless, to ease building
5822 cross-platform bindings this convention will be handled as a @code{C} calling
5823 convention on non-Windows platforms.
5824 @end table
5826 @geindex DLL
5828 @geindex Convention DLL
5831 @table @asis
5833 @item @code{DLL}
5835 This is equivalent to @code{Stdcall}.
5836 @end table
5838 @geindex Win32
5840 @geindex Convention Win32
5843 @table @asis
5845 @item @code{Win32}
5847 This is equivalent to @code{Stdcall}.
5848 @end table
5850 @geindex Stubbed
5852 @geindex Convention Stubbed
5855 @table @asis
5857 @item @code{Stubbed}
5859 This is a special convention that indicates that the compiler
5860 should provide a stub body that raises @code{Program_Error}.
5861 @end table
5863 GNAT additionally provides a useful pragma @code{Convention_Identifier}
5864 that can be used to parameterize conventions and allow additional synonyms
5865 to be specified. For example if you have legacy code in which the convention
5866 identifier Fortran77 was used for Fortran, you can use the configuration
5867 pragma:
5869 @example
5870 pragma Convention_Identifier (Fortran77, Fortran);
5871 @end example
5873 And from now on the identifier Fortran77 may be used as a convention
5874 identifier (for example in an @code{Import} pragma) with the same
5875 meaning as Fortran.
5877 @node Building Mixed Ada and C++ Programs,Generating Ada Bindings for C and C++ headers,Calling Conventions,Mixed Language Programming
5878 @anchor{gnat_ugn/the_gnat_compilation_model id64}@anchor{b7}@anchor{gnat_ugn/the_gnat_compilation_model building-mixed-ada-and-c-programs}@anchor{b8}
5879 @subsection Building Mixed Ada and C++ Programs
5882 A programmer inexperienced with mixed-language development may find that
5883 building an application containing both Ada and C++ code can be a
5884 challenge.  This section gives a few hints that should make this task easier.
5886 @menu
5887 * Interfacing to C++:: 
5888 * Linking a Mixed C++ & Ada Program:: 
5889 * A Simple Example:: 
5890 * Interfacing with C++ constructors:: 
5891 * Interfacing with C++ at the Class Level:: 
5893 @end menu
5895 @node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5896 @anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{b9}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{ba}
5897 @subsubsection Interfacing to C++
5900 GNAT supports interfacing with the G++ compiler (or any C++ compiler
5901 generating code that is compatible with the G++ Application Binary
5902 Interface ---see @indicateurl{http://www.codesourcery.com/archives/cxx-abi}).
5904 Interfacing can be done at 3 levels: simple data, subprograms, and
5905 classes. In the first two cases, GNAT offers a specific @code{Convention C_Plus_Plus}
5906 (or @code{CPP}) that behaves exactly like @code{Convention C}.
5907 Usually, C++ mangles the names of subprograms. To generate proper mangled
5908 names automatically, see @ref{19,,Generating Ada Bindings for C and C++ headers}).
5909 This problem can also be addressed manually in two ways:
5912 @itemize *
5914 @item 
5915 by modifying the C++ code in order to force a C convention using
5916 the @code{extern "C"} syntax.
5918 @item 
5919 by figuring out the mangled name (using e.g. @code{nm}) and using it as the
5920 Link_Name argument of the pragma import.
5921 @end itemize
5923 Interfacing at the class level can be achieved by using the GNAT specific
5924 pragmas such as @code{CPP_Constructor}.  See the @cite{GNAT_Reference_Manual} for additional information.
5926 @node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5927 @anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-ada-program}@anchor{bb}@anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-and-ada-program}@anchor{bc}
5928 @subsubsection Linking a Mixed C++ & Ada Program
5931 Usually the linker of the C++ development system must be used to link
5932 mixed applications because most C++ systems will resolve elaboration
5933 issues (such as calling constructors on global class instances)
5934 transparently during the link phase. GNAT has been adapted to ease the
5935 use of a foreign linker for the last phase. Three cases can be
5936 considered:
5939 @itemize *
5941 @item 
5942 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5943 The C++ linker can simply be called by using the C++ specific driver
5944 called @code{g++}.
5946 Note that if the C++ code uses inline functions, you will need to
5947 compile your C++ code with the @code{-fkeep-inline-functions} switch in
5948 order to provide an existing function implementation that the Ada code can
5949 link with.
5951 @example
5952 $ g++ -c -fkeep-inline-functions file1.C
5953 $ g++ -c -fkeep-inline-functions file2.C
5954 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5955 @end example
5957 @item 
5958 Using GNAT and G++ from two different GCC installations: If both
5959 compilers are on the :envvar`PATH`, the previous method may be used. It is
5960 important to note that environment variables such as
5961 @geindex C_INCLUDE_PATH
5962 @geindex environment variable; C_INCLUDE_PATH
5963 @code{C_INCLUDE_PATH}, 
5964 @geindex GCC_EXEC_PREFIX
5965 @geindex environment variable; GCC_EXEC_PREFIX
5966 @code{GCC_EXEC_PREFIX},
5967 @geindex BINUTILS_ROOT
5968 @geindex environment variable; BINUTILS_ROOT
5969 @code{BINUTILS_ROOT}, and
5970 @geindex GCC_ROOT
5971 @geindex environment variable; GCC_ROOT
5972 @code{GCC_ROOT} will affect both compilers
5973 at the same time and may make one of the two compilers operate
5974 improperly if set during invocation of the wrong compiler.  It is also
5975 very important that the linker uses the proper @code{libgcc.a} GCC
5976 library -- that is, the one from the C++ compiler installation. The
5977 implicit link command as suggested in the @code{gnatmake} command
5978 from the former example can be replaced by an explicit link command with
5979 the full-verbosity option in order to verify which library is used:
5981 @example
5982 $ gnatbind ada_unit
5983 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5984 @end example
5986 If there is a problem due to interfering environment variables, it can
5987 be worked around by using an intermediate script. The following example
5988 shows the proper script to use when GNAT has not been installed at its
5989 default location and g++ has been installed at its default location:
5991 @example
5992 $ cat ./my_script
5993 #!/bin/sh
5994 unset BINUTILS_ROOT
5995 unset GCC_ROOT
5996 c++ $*
5997 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5998 @end example
6000 @item 
6001 Using a non-GNU C++ compiler: The commands previously described can be
6002 used to insure that the C++ linker is used. Nonetheless, you need to add
6003 a few more parameters to the link command line, depending on the exception
6004 mechanism used.
6006 If the @code{setjmp} / @code{longjmp} exception mechanism is used, only the paths
6007 to the @code{libgcc} libraries are required:
6009 @example
6010 $ cat ./my_script
6011 #!/bin/sh
6012 CC $* gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a
6013 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
6014 @end example
6016 where CC is the name of the non-GNU C++ compiler.
6018 If the "zero cost" exception mechanism is used, and the platform
6019 supports automatic registration of exception tables (e.g., Solaris),
6020 paths to more objects are required:
6022 @example
6023 $ cat ./my_script
6024 #!/bin/sh
6025 CC gcc -print-file-name=crtbegin.o $* \\
6026 gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a \\
6027 gcc -print-file-name=crtend.o
6028 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
6029 @end example
6031 If the "zero cost exception" mechanism is used, and the platform
6032 doesn't support automatic registration of exception tables (e.g., HP-UX
6033 or AIX), the simple approach described above will not work and
6034 a pre-linking phase using GNAT will be necessary.
6035 @end itemize
6037 Another alternative is to use the @code{gprbuild} multi-language builder
6038 which has a large knowledge base and knows how to link Ada and C++ code
6039 together automatically in most cases.
6041 @node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
6042 @anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{bd}@anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{be}
6043 @subsubsection A Simple Example
6046 The following example, provided as part of the GNAT examples, shows how
6047 to achieve procedural interfacing between Ada and C++ in both
6048 directions. The C++ class A has two methods. The first method is exported
6049 to Ada by the means of an extern C wrapper function. The second method
6050 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
6051 a limited record with a layout comparable to the C++ class. The Ada
6052 subprogram, in turn, calls the C++ method. So, starting from the C++
6053 main program, the process passes back and forth between the two
6054 languages.
6056 Here are the compilation commands:
6058 @example
6059 $ gnatmake -c simple_cpp_interface
6060 $ g++ -c cpp_main.C
6061 $ g++ -c ex7.C
6062 $ gnatbind -n simple_cpp_interface
6063 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
6064 @end example
6066 Here are the corresponding sources:
6068 @example
6069 //cpp_main.C
6071 #include "ex7.h"
6073 extern "C" @{
6074   void adainit (void);
6075   void adafinal (void);
6076   void method1 (A *t);
6079 void method1 (A *t)
6081   t->method1 ();
6084 int main ()
6086   A obj;
6087   adainit ();
6088   obj.method2 (3030);
6089   adafinal ();
6091 @end example
6093 @example
6094 //ex7.h
6096 class Origin @{
6097  public:
6098   int o_value;
6100 class A : public Origin @{
6101  public:
6102   void method1 (void);
6103   void method2 (int v);
6104   A();
6105   int   a_value;
6107 @end example
6109 @example
6110 //ex7.C
6112 #include "ex7.h"
6113 #include <stdio.h>
6115 extern "C" @{ void ada_method2 (A *t, int v);@}
6117 void A::method1 (void)
6119   a_value = 2020;
6120   printf ("in A::method1, a_value = %d \\n",a_value);
6123 void A::method2 (int v)
6125    ada_method2 (this, v);
6126    printf ("in A::method2, a_value = %d \\n",a_value);
6129 A::A(void)
6131    a_value = 1010;
6132   printf ("in A::A, a_value = %d \\n",a_value);
6134 @end example
6136 @example
6137 -- simple_cpp_interface.ads
6138 with System;
6139 package Simple_Cpp_Interface is
6140    type A is limited
6141       record
6142          Vptr    : System.Address;
6143          O_Value : Integer;
6144          A_Value : Integer;
6145       end record;
6146    pragma Convention (C, A);
6148    procedure Method1 (This : in out A);
6149    pragma Import (C, Method1);
6151    procedure Ada_Method2 (This : in out A; V : Integer);
6152    pragma Export (C, Ada_Method2);
6154 end Simple_Cpp_Interface;
6155 @end example
6157 @example
6158 -- simple_cpp_interface.adb
6159 package body Simple_Cpp_Interface is
6161    procedure Ada_Method2 (This : in out A; V : Integer) is
6162    begin
6163       Method1 (This);
6164       This.A_Value := V;
6165    end Ada_Method2;
6167 end Simple_Cpp_Interface;
6168 @end example
6170 @node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
6171 @anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{bf}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{c0}
6172 @subsubsection Interfacing with C++ constructors
6175 In order to interface with C++ constructors GNAT provides the
6176 @code{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
6177 for additional information).
6178 In this section we present some common uses of C++ constructors
6179 in mixed-languages programs in GNAT.
6181 Let us assume that we need to interface with the following
6182 C++ class:
6184 @example
6185 class Root @{
6186 public:
6187   int  a_value;
6188   int  b_value;
6189   virtual int Get_Value ();
6190   Root();              // Default constructor
6191   Root(int v);         // 1st non-default constructor
6192   Root(int v, int w);  // 2nd non-default constructor
6194 @end example
6196 For this purpose we can write the following package spec (further
6197 information on how to build this spec is available in
6198 @ref{c1,,Interfacing with C++ at the Class Level} and
6199 @ref{19,,Generating Ada Bindings for C and C++ headers}).
6201 @example
6202 with Interfaces.C; use Interfaces.C;
6203 package Pkg_Root is
6204   type Root is tagged limited record
6205      A_Value : int;
6206      B_Value : int;
6207   end record;
6208   pragma Import (CPP, Root);
6210   function Get_Value (Obj : Root) return int;
6211   pragma Import (CPP, Get_Value);
6213   function Constructor return Root;
6214   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
6216   function Constructor (v : Integer) return Root;
6217   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
6219   function Constructor (v, w : Integer) return Root;
6220   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
6221 end Pkg_Root;
6222 @end example
6224 On the Ada side the constructor is represented by a function (whose
6225 name is arbitrary) that returns the classwide type corresponding to
6226 the imported C++ class. Although the constructor is described as a
6227 function, it is typically a procedure with an extra implicit argument
6228 (the object being initialized) at the implementation level. GNAT
6229 issues the appropriate call, whatever it is, to get the object
6230 properly initialized.
6232 Constructors can only appear in the following contexts:
6235 @itemize *
6237 @item 
6238 On the right side of an initialization of an object of type @code{T}.
6240 @item 
6241 On the right side of an initialization of a record component of type @code{T}.
6243 @item 
6244 In an Ada 2005 limited aggregate.
6246 @item 
6247 In an Ada 2005 nested limited aggregate.
6249 @item 
6250 In an Ada 2005 limited aggregate that initializes an object built in
6251 place by an extended return statement.
6252 @end itemize
6254 In a declaration of an object whose type is a class imported from C++,
6255 either the default C++ constructor is implicitly called by GNAT, or
6256 else the required C++ constructor must be explicitly called in the
6257 expression that initializes the object. For example:
6259 @example
6260 Obj1 : Root;
6261 Obj2 : Root := Constructor;
6262 Obj3 : Root := Constructor (v => 10);
6263 Obj4 : Root := Constructor (30, 40);
6264 @end example
6266 The first two declarations are equivalent: in both cases the default C++
6267 constructor is invoked (in the former case the call to the constructor is
6268 implicit, and in the latter case the call is explicit in the object
6269 declaration). @code{Obj3} is initialized by the C++ non-default constructor
6270 that takes an integer argument, and @code{Obj4} is initialized by the
6271 non-default C++ constructor that takes two integers.
6273 Let us derive the imported C++ class in the Ada side. For example:
6275 @example
6276 type DT is new Root with record
6277    C_Value : Natural := 2009;
6278 end record;
6279 @end example
6281 In this case the components DT inherited from the C++ side must be
6282 initialized by a C++ constructor, and the additional Ada components
6283 of type DT are initialized by GNAT. The initialization of such an
6284 object is done either by default, or by means of a function returning
6285 an aggregate of type DT, or by means of an extension aggregate.
6287 @example
6288 Obj5 : DT;
6289 Obj6 : DT := Function_Returning_DT (50);
6290 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6291 @end example
6293 The declaration of @code{Obj5} invokes the default constructors: the
6294 C++ default constructor of the parent type takes care of the initialization
6295 of the components inherited from Root, and GNAT takes care of the default
6296 initialization of the additional Ada components of type DT (that is,
6297 @code{C_Value} is initialized to value 2009). The order of invocation of
6298 the constructors is consistent with the order of elaboration required by
6299 Ada and C++. That is, the constructor of the parent type is always called
6300 before the constructor of the derived type.
6302 Let us now consider a record that has components whose type is imported
6303 from C++. For example:
6305 @example
6306 type Rec1 is limited record
6307    Data1 : Root := Constructor (10);
6308    Value : Natural := 1000;
6309 end record;
6311 type Rec2 (D : Integer := 20) is limited record
6312    Rec   : Rec1;
6313    Data2 : Root := Constructor (D, 30);
6314 end record;
6315 @end example
6317 The initialization of an object of type @code{Rec2} will call the
6318 non-default C++ constructors specified for the imported components.
6319 For example:
6321 @example
6322 Obj8 : Rec2 (40);
6323 @end example
6325 Using Ada 2005 we can use limited aggregates to initialize an object
6326 invoking C++ constructors that differ from those specified in the type
6327 declarations. For example:
6329 @example
6330 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6331                         others => <>),
6332                 others => <>);
6333 @end example
6335 The above declaration uses an Ada 2005 limited aggregate to
6336 initialize @code{Obj9}, and the C++ constructor that has two integer
6337 arguments is invoked to initialize the @code{Data1} component instead
6338 of the constructor specified in the declaration of type @code{Rec1}. In
6339 Ada 2005 the box in the aggregate indicates that unspecified components
6340 are initialized using the expression (if any) available in the component
6341 declaration. That is, in this case discriminant @code{D} is initialized
6342 to value @code{20}, @code{Value} is initialized to value 1000, and the
6343 non-default C++ constructor that handles two integers takes care of
6344 initializing component @code{Data2} with values @code{20,30}.
6346 In Ada 2005 we can use the extended return statement to build the Ada
6347 equivalent to C++ non-default constructors. For example:
6349 @example
6350 function Constructor (V : Integer) return Rec2 is
6351 begin
6352    return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
6353                                  others => <>),
6354                          others => <>) do
6355       --  Further actions required for construction of
6356       --  objects of type Rec2
6357       ...
6358    end record;
6359 end Constructor;
6360 @end example
6362 In this example the extended return statement construct is used to
6363 build in place the returned object whose components are initialized
6364 by means of a limited aggregate. Any further action associated with
6365 the constructor can be placed inside the construct.
6367 @node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6368 @anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-at-the-class-level}@anchor{c1}@anchor{gnat_ugn/the_gnat_compilation_model id69}@anchor{c2}
6369 @subsubsection Interfacing with C++ at the Class Level
6372 In this section we demonstrate the GNAT features for interfacing with
6373 C++ by means of an example making use of Ada 2005 abstract interface
6374 types. This example consists of a classification of animals; classes
6375 have been used to model our main classification of animals, and
6376 interfaces provide support for the management of secondary
6377 classifications. We first demonstrate a case in which the types and
6378 constructors are defined on the C++ side and imported from the Ada
6379 side, and latter the reverse case.
6381 The root of our derivation will be the @code{Animal} class, with a
6382 single private attribute (the @code{Age} of the animal), a constructor,
6383 and two public primitives to set and get the value of this attribute.
6385 @example
6386 class Animal @{
6387  public:
6388    virtual void Set_Age (int New_Age);
6389    virtual int Age ();
6390    Animal() @{Age_Count = 0;@};
6391  private:
6392    int Age_Count;
6394 @end example
6396 Abstract interface types are defined in C++ by means of classes with pure
6397 virtual functions and no data members. In our example we will use two
6398 interfaces that provide support for the common management of @code{Carnivore}
6399 and @code{Domestic} animals:
6401 @example
6402 class Carnivore @{
6403 public:
6404    virtual int Number_Of_Teeth () = 0;
6407 class Domestic @{
6408 public:
6409    virtual void Set_Owner (char* Name) = 0;
6411 @end example
6413 Using these declarations, we can now say that a @code{Dog} is an animal that is
6414 both Carnivore and Domestic, that is:
6416 @example
6417 class Dog : Animal, Carnivore, Domestic @{
6418  public:
6419    virtual int  Number_Of_Teeth ();
6420    virtual void Set_Owner (char* Name);
6422    Dog(); // Constructor
6423  private:
6424    int  Tooth_Count;
6425    char *Owner;
6427 @end example
6429 In the following examples we will assume that the previous declarations are
6430 located in a file named @code{animals.h}. The following package demonstrates
6431 how to import these C++ declarations from the Ada side:
6433 @example
6434 with Interfaces.C.Strings; use Interfaces.C.Strings;
6435 package Animals is
6436   type Carnivore is limited interface;
6437   pragma Convention (C_Plus_Plus, Carnivore);
6438   function Number_Of_Teeth (X : Carnivore)
6439      return Natural is abstract;
6441   type Domestic is limited interface;
6442   pragma Convention (C_Plus_Plus, Domestic);
6443   procedure Set_Owner
6444     (X    : in out Domestic;
6445      Name : Chars_Ptr) is abstract;
6447   type Animal is tagged limited record
6448     Age : Natural;
6449   end record;
6450   pragma Import (C_Plus_Plus, Animal);
6452   procedure Set_Age (X : in out Animal; Age : Integer);
6453   pragma Import (C_Plus_Plus, Set_Age);
6455   function Age (X : Animal) return Integer;
6456   pragma Import (C_Plus_Plus, Age);
6458   function New_Animal return Animal;
6459   pragma CPP_Constructor (New_Animal);
6460   pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6462   type Dog is new Animal and Carnivore and Domestic with record
6463     Tooth_Count : Natural;
6464     Owner       : Chars_Ptr;
6465   end record;
6466   pragma Import (C_Plus_Plus, Dog);
6468   function Number_Of_Teeth (A : Dog) return Natural;
6469   pragma Import (C_Plus_Plus, Number_Of_Teeth);
6471   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6472   pragma Import (C_Plus_Plus, Set_Owner);
6474   function New_Dog return Dog;
6475   pragma CPP_Constructor (New_Dog);
6476   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6477 end Animals;
6478 @end example
6480 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6481 interfacing with these C++ classes is easy. The only requirement is that all
6482 the primitives and components must be declared exactly in the same order in
6483 the two languages.
6485 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6486 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
6487 the arguments to the called primitives will be the same as for C++. For the
6488 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
6489 to indicate that they have been defined on the C++ side; this is required
6490 because the dispatch table associated with these tagged types will be built
6491 in the C++ side and therefore will not contain the predefined Ada primitives
6492 which Ada would otherwise expect.
6494 As the reader can see there is no need to indicate the C++ mangled names
6495 associated with each subprogram because it is assumed that all the calls to
6496 these primitives will be dispatching calls. The only exception is the
6497 constructor, which must be registered with the compiler by means of
6498 @code{pragma CPP_Constructor} and needs to provide its associated C++
6499 mangled name because the Ada compiler generates direct calls to it.
6501 With the above packages we can now declare objects of type Dog on the Ada side
6502 and dispatch calls to the corresponding subprograms on the C++ side. We can
6503 also extend the tagged type Dog with further fields and primitives, and
6504 override some of its C++ primitives on the Ada side. For example, here we have
6505 a type derivation defined on the Ada side that inherits all the dispatching
6506 primitives of the ancestor from the C++ side.
6508 @example
6509 with Animals; use Animals;
6510 package Vaccinated_Animals is
6511   type Vaccinated_Dog is new Dog with null record;
6512   function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6513 end Vaccinated_Animals;
6514 @end example
6516 It is important to note that, because of the ABI compatibility, the programmer
6517 does not need to add any further information to indicate either the object
6518 layout or the dispatch table entry associated with each dispatching operation.
6520 Now let us define all the types and constructors on the Ada side and export
6521 them to C++, using the same hierarchy of our previous example:
6523 @example
6524 with Interfaces.C.Strings;
6525 use Interfaces.C.Strings;
6526 package Animals is
6527   type Carnivore is limited interface;
6528   pragma Convention (C_Plus_Plus, Carnivore);
6529   function Number_Of_Teeth (X : Carnivore)
6530      return Natural is abstract;
6532   type Domestic is limited interface;
6533   pragma Convention (C_Plus_Plus, Domestic);
6534   procedure Set_Owner
6535     (X    : in out Domestic;
6536      Name : Chars_Ptr) is abstract;
6538   type Animal is tagged record
6539     Age : Natural;
6540   end record;
6541   pragma Convention (C_Plus_Plus, Animal);
6543   procedure Set_Age (X : in out Animal; Age : Integer);
6544   pragma Export (C_Plus_Plus, Set_Age);
6546   function Age (X : Animal) return Integer;
6547   pragma Export (C_Plus_Plus, Age);
6549   function New_Animal return Animal'Class;
6550   pragma Export (C_Plus_Plus, New_Animal);
6552   type Dog is new Animal and Carnivore and Domestic with record
6553     Tooth_Count : Natural;
6554     Owner       : String (1 .. 30);
6555   end record;
6556   pragma Convention (C_Plus_Plus, Dog);
6558   function Number_Of_Teeth (A : Dog) return Natural;
6559   pragma Export (C_Plus_Plus, Number_Of_Teeth);
6561   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6562   pragma Export (C_Plus_Plus, Set_Owner);
6564   function New_Dog return Dog'Class;
6565   pragma Export (C_Plus_Plus, New_Dog);
6566 end Animals;
6567 @end example
6569 Compared with our previous example the only differences are the use of
6570 @code{pragma Convention} (instead of @code{pragma Import}), and the use of
6571 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
6572 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6573 nothing else to be done; as explained above, the only requirement is that all
6574 the primitives and components are declared in exactly the same order.
6576 For completeness, let us see a brief C++ main program that uses the
6577 declarations available in @code{animals.h} (presented in our first example) to
6578 import and use the declarations from the Ada side, properly initializing and
6579 finalizing the Ada run-time system along the way:
6581 @example
6582 #include "animals.h"
6583 #include <iostream>
6584 using namespace std;
6586 void Check_Carnivore (Carnivore *obj) @{...@}
6587 void Check_Domestic (Domestic *obj)   @{...@}
6588 void Check_Animal (Animal *obj)       @{...@}
6589 void Check_Dog (Dog *obj)             @{...@}
6591 extern "C" @{
6592   void adainit (void);
6593   void adafinal (void);
6594   Dog* new_dog ();
6597 void test ()
6599   Dog *obj = new_dog();  // Ada constructor
6600   Check_Carnivore (obj); // Check secondary DT
6601   Check_Domestic (obj);  // Check secondary DT
6602   Check_Animal (obj);    // Check primary DT
6603   Check_Dog (obj);       // Check primary DT
6606 int main ()
6608   adainit ();  test();  adafinal ();
6609   return 0;
6611 @end example
6613 @node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Building Mixed Ada and C++ Programs,Mixed Language Programming
6614 @anchor{gnat_ugn/the_gnat_compilation_model id70}@anchor{c3}@anchor{gnat_ugn/the_gnat_compilation_model generating-ada-bindings-for-c-and-c-headers}@anchor{19}
6615 @subsection Generating Ada Bindings for C and C++ headers
6618 @geindex Binding generation (for C and C++ headers)
6620 @geindex C headers (binding generation)
6622 @geindex C++ headers (binding generation)
6624 GNAT includes a binding generator for C and C++ headers which is
6625 intended to do 95% of the tedious work of generating Ada specs from C
6626 or C++ header files.
6628 Note that this capability is not intended to generate 100% correct Ada specs,
6629 and will is some cases require manual adjustments, although it can often
6630 be used out of the box in practice.
6632 Some of the known limitations include:
6635 @itemize *
6637 @item 
6638 only very simple character constant macros are translated into Ada
6639 constants. Function macros (macros with arguments) are partially translated
6640 as comments, to be completed manually if needed.
6642 @item 
6643 some extensions (e.g. vector types) are not supported
6645 @item 
6646 pointers to pointers or complex structures are mapped to System.Address
6648 @item 
6649 identifiers with identical name (except casing) will generate compilation
6650 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
6651 @end itemize
6653 The code generated is using the Ada 2005 syntax, which makes it
6654 easier to interface with other languages than previous versions of Ada.
6656 @menu
6657 * Running the Binding Generator:: 
6658 * Generating Bindings for C++ Headers:: 
6659 * Switches:: 
6661 @end menu
6663 @node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6664 @anchor{gnat_ugn/the_gnat_compilation_model id71}@anchor{c4}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{c5}
6665 @subsubsection Running the Binding Generator
6668 The binding generator is part of the @code{gcc} compiler and can be
6669 invoked via the @code{-fdump-ada-spec} switch, which will generate Ada
6670 spec files for the header files specified on the command line, and all
6671 header files needed by these files transitively. For example:
6673 @example
6674 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
6675 $ gcc -c -gnat05 *.ads
6676 @end example
6678 will generate, under GNU/Linux, the following files: @code{time_h.ads},
6679 @code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6680 correspond to the files @code{/usr/include/time.h},
6681 @code{/usr/include/bits/time.h}, etc..., and will then compile these Ada specs
6682 in Ada 2005 mode.
6684 The @code{-C} switch tells @code{gcc} to extract comments from headers,
6685 and will attempt to generate corresponding Ada comments.
6687 If you want to generate a single Ada file and not the transitive closure, you
6688 can use instead the @code{-fdump-ada-spec-slim} switch.
6690 You can optionally specify a parent unit, of which all generated units will
6691 be children, using @code{-fada-spec-parent=@emph{unit}}.
6693 Note that we recommend when possible to use the @emph{g++} driver to
6694 generate bindings, even for most C headers, since this will in general
6695 generate better Ada specs. For generating bindings for C++ headers, it is
6696 mandatory to use the @emph{g++} command, or @emph{gcc -x c++} which
6697 is equivalent in this case. If @emph{g++} cannot work on your C headers
6698 because of incompatibilities between C and C++, then you can fallback to
6699 @code{gcc} instead.
6701 For an example of better bindings generated from the C++ front-end,
6702 the name of the parameters (when available) are actually ignored by the C
6703 front-end. Consider the following C header:
6705 @example
6706 extern void foo (int variable);
6707 @end example
6709 with the C front-end, @code{variable} is ignored, and the above is handled as:
6711 @example
6712 extern void foo (int);
6713 @end example
6715 generating a generic:
6717 @example
6718 procedure foo (param1 : int);
6719 @end example
6721 with the C++ front-end, the name is available, and we generate:
6723 @example
6724 procedure foo (variable : int);
6725 @end example
6727 In some cases, the generated bindings will be more complete or more meaningful
6728 when defining some macros, which you can do via the @code{-D} switch. This
6729 is for example the case with @code{Xlib.h} under GNU/Linux:
6731 @example
6732 $ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6733 @end example
6735 The above will generate more complete bindings than a straight call without
6736 the @code{-DXLIB_ILLEGAL_ACCESS} switch.
6738 In other cases, it is not possible to parse a header file in a stand-alone
6739 manner, because other include files need to be included first. In this
6740 case, the solution is to create a small header file including the needed
6741 @code{#include} and possible @code{#define} directives. For example, to
6742 generate Ada bindings for @code{readline/readline.h}, you need to first
6743 include @code{stdio.h}, so you can create a file with the following two
6744 lines in e.g. @code{readline1.h}:
6746 @example
6747 #include <stdio.h>
6748 #include <readline/readline.h>
6749 @end example
6751 and then generate Ada bindings from this file:
6753 @example
6754 $ g++ -c -fdump-ada-spec readline1.h
6755 @end example
6757 @node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6758 @anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{c6}@anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{c7}
6759 @subsubsection Generating Bindings for C++ Headers
6762 Generating bindings for C++ headers is done using the same options, always
6763 with the @emph{g++} compiler. Note that generating Ada spec from C++ headers is a
6764 much more complex job and support for C++ headers is much more limited that
6765 support for C headers. As a result, you will need to modify the resulting
6766 bindings by hand more extensively when using C++ headers.
6768 In this mode, C++ classes will be mapped to Ada tagged types, constructors
6769 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
6770 multiple inheritance of abstract classes will be mapped to Ada interfaces
6771 (see the @emph{Interfacing to C++} section in the @cite{GNAT Reference Manual}
6772 for additional information on interfacing to C++).
6774 For example, given the following C++ header file:
6776 @example
6777 class Carnivore @{
6778 public:
6779    virtual int Number_Of_Teeth () = 0;
6782 class Domestic @{
6783 public:
6784    virtual void Set_Owner (char* Name) = 0;
6787 class Animal @{
6788 public:
6789   int Age_Count;
6790   virtual void Set_Age (int New_Age);
6793 class Dog : Animal, Carnivore, Domestic @{
6794  public:
6795   int  Tooth_Count;
6796   char *Owner;
6798   virtual int  Number_Of_Teeth ();
6799   virtual void Set_Owner (char* Name);
6801   Dog();
6803 @end example
6805 The corresponding Ada code is generated:
6807 @example
6808 package Class_Carnivore is
6809   type Carnivore is limited interface;
6810   pragma Import (CPP, Carnivore);
6812   function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6813 end;
6814 use Class_Carnivore;
6816 package Class_Domestic is
6817   type Domestic is limited interface;
6818   pragma Import (CPP, Domestic);
6820   procedure Set_Owner
6821     (this : access Domestic;
6822      Name : Interfaces.C.Strings.chars_ptr) is abstract;
6823 end;
6824 use Class_Domestic;
6826 package Class_Animal is
6827   type Animal is tagged limited record
6828     Age_Count : aliased int;
6829   end record;
6830   pragma Import (CPP, Animal);
6832   procedure Set_Age (this : access Animal; New_Age : int);
6833   pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6834 end;
6835 use Class_Animal;
6837 package Class_Dog is
6838   type Dog is new Animal and Carnivore and Domestic with record
6839     Tooth_Count : aliased int;
6840     Owner : Interfaces.C.Strings.chars_ptr;
6841   end record;
6842   pragma Import (CPP, Dog);
6844   function Number_Of_Teeth (this : access Dog) return int;
6845   pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6847   procedure Set_Owner
6848     (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6849   pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6851   function New_Dog return Dog;
6852   pragma CPP_Constructor (New_Dog);
6853   pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6854 end;
6855 use Class_Dog;
6856 @end example
6858 @node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6859 @anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{c8}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{c9}
6860 @subsubsection Switches
6863 @geindex -fdump-ada-spec (gcc)
6866 @table @asis
6868 @item @code{-fdump-ada-spec}
6870 Generate Ada spec files for the given header files transitively (including
6871 all header files that these headers depend upon).
6872 @end table
6874 @geindex -fdump-ada-spec-slim (gcc)
6877 @table @asis
6879 @item @code{-fdump-ada-spec-slim}
6881 Generate Ada spec files for the header files specified on the command line
6882 only.
6883 @end table
6885 @geindex -fada-spec-parent (gcc)
6888 @table @asis
6890 @item @code{-fada-spec-parent=@emph{unit}}
6892 Specifies that all files generated by @code{-fdump-ada-spec} are
6893 to be child units of the specified parent unit.
6894 @end table
6896 @geindex -C (gcc)
6899 @table @asis
6901 @item @code{-C}
6903 Extract comments from headers and generate Ada comments in the Ada spec files.
6904 @end table
6906 @node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6907 @anchor{gnat_ugn/the_gnat_compilation_model generating-c-headers-for-ada-specifications}@anchor{ca}@anchor{gnat_ugn/the_gnat_compilation_model id73}@anchor{cb}
6908 @subsection Generating C Headers for Ada Specifications
6911 @geindex Binding generation (for Ada specs)
6913 @geindex C headers (binding generation)
6915 GNAT includes a C header generator for Ada specifications which supports
6916 Ada types that have a direct mapping to C types. This includes in particular
6917 support for:
6920 @itemize *
6922 @item 
6923 Scalar types
6925 @item 
6926 Constrained arrays
6928 @item 
6929 Records (untagged)
6931 @item 
6932 Composition of the above types
6934 @item 
6935 Constant declarations
6937 @item 
6938 Object declarations
6940 @item 
6941 Subprogram declarations
6942 @end itemize
6944 @menu
6945 * Running the C Header Generator:: 
6947 @end menu
6949 @node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6950 @anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{cc}
6951 @subsubsection Running the C Header Generator
6954 The C header generator is part of the GNAT compiler and can be invoked via
6955 the @code{-gnatceg} combination of switches, which will generate a @code{.h}
6956 file corresponding to the given input file (Ada spec or body). Note that
6957 only spec files are processed in any case, so giving a spec or a body file
6958 as input is equivalent. For example:
6960 @example
6961 $ gcc -c -gnatceg pack1.ads
6962 @end example
6964 will generate a self-contained file called @code{pack1.h} including
6965 common definitions from the Ada Standard package, followed by the
6966 definitions included in @code{pack1.ads}, as well as all the other units
6967 withed by this file.
6969 For instance, given the following Ada files:
6971 @example
6972 package Pack2 is
6973    type Int is range 1 .. 10;
6974 end Pack2;
6975 @end example
6977 @example
6978 with Pack2;
6980 package Pack1 is
6981    type Rec is record
6982       Field1, Field2 : Pack2.Int;
6983    end record;
6985    Global : Rec := (1, 2);
6987    procedure Proc1 (R : Rec);
6988    procedure Proc2 (R : in out Rec);
6989 end Pack1;
6990 @end example
6992 The above @code{gcc} command will generate the following @code{pack1.h} file:
6994 @example
6995 /* Standard definitions skipped */
6996 #ifndef PACK2_ADS
6997 #define PACK2_ADS
6998 typedef short_short_integer pack2__TintB;
6999 typedef pack2__TintB pack2__int;
7000 #endif /* PACK2_ADS */
7002 #ifndef PACK1_ADS
7003 #define PACK1_ADS
7004 typedef struct _pack1__rec @{
7005   pack2__int field1;
7006   pack2__int field2;
7007 @} pack1__rec;
7008 extern pack1__rec pack1__global;
7009 extern void pack1__proc1(const pack1__rec r);
7010 extern void pack1__proc2(pack1__rec *r);
7011 #endif /* PACK1_ADS */
7012 @end example
7014 You can then @code{include} @code{pack1.h} from a C source file and use the types,
7015 call subprograms, reference objects, and constants.
7017 @node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
7018 @anchor{gnat_ugn/the_gnat_compilation_model id74}@anchor{cd}@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{45}
7019 @section GNAT and Other Compilation Models
7022 This section compares the GNAT model with the approaches taken in
7023 other environents, first the C/C++ model and then the mechanism that
7024 has been used in other Ada systems, in particular those traditionally
7025 used for Ada 83.
7027 @menu
7028 * Comparison between GNAT and C/C++ Compilation Models:: 
7029 * Comparison between GNAT and Conventional Ada Library Models:: 
7031 @end menu
7033 @node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
7034 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-c-c-compilation-models}@anchor{ce}@anchor{gnat_ugn/the_gnat_compilation_model id75}@anchor{cf}
7035 @subsection Comparison between GNAT and C/C++ Compilation Models
7038 The GNAT model of compilation is close to the C and C++ models. You can
7039 think of Ada specs as corresponding to header files in C. As in C, you
7040 don't need to compile specs; they are compiled when they are used. The
7041 Ada @emph{with} is similar in effect to the @code{#include} of a C
7042 header.
7044 One notable difference is that, in Ada, you may compile specs separately
7045 to check them for semantic and syntactic accuracy. This is not always
7046 possible with C headers because they are fragments of programs that have
7047 less specific syntactic or semantic rules.
7049 The other major difference is the requirement for running the binder,
7050 which performs two important functions. First, it checks for
7051 consistency. In C or C++, the only defense against assembling
7052 inconsistent programs lies outside the compiler, in a makefile, for
7053 example. The binder satisfies the Ada requirement that it be impossible
7054 to construct an inconsistent program when the compiler is used in normal
7055 mode.
7057 @geindex Elaboration order control
7059 The other important function of the binder is to deal with elaboration
7060 issues. There are also elaboration issues in C++ that are handled
7061 automatically. This automatic handling has the advantage of being
7062 simpler to use, but the C++ programmer has no control over elaboration.
7063 Where @code{gnatbind} might complain there was no valid order of
7064 elaboration, a C++ compiler would simply construct a program that
7065 malfunctioned at run time.
7067 @node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
7068 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-conventional-ada-library-models}@anchor{d0}@anchor{gnat_ugn/the_gnat_compilation_model id76}@anchor{d1}
7069 @subsection Comparison between GNAT and Conventional Ada Library Models
7072 This section is intended for Ada programmers who have
7073 used an Ada compiler implementing the traditional Ada library
7074 model, as described in the Ada Reference Manual.
7076 @geindex GNAT library
7078 In GNAT, there is no 'library' in the normal sense. Instead, the set of
7079 source files themselves acts as the library. Compiling Ada programs does
7080 not generate any centralized information, but rather an object file and
7081 a ALI file, which are of interest only to the binder and linker.
7082 In a traditional system, the compiler reads information not only from
7083 the source file being compiled, but also from the centralized library.
7084 This means that the effect of a compilation depends on what has been
7085 previously compiled. In particular:
7088 @itemize *
7090 @item 
7091 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7092 to the version of the unit most recently compiled into the library.
7094 @item 
7095 Inlining is effective only if the necessary body has already been
7096 compiled into the library.
7098 @item 
7099 Compiling a unit may obsolete other units in the library.
7100 @end itemize
7102 In GNAT, compiling one unit never affects the compilation of any other
7103 units because the compiler reads only source files. Only changes to source
7104 files can affect the results of a compilation. In particular:
7107 @itemize *
7109 @item 
7110 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7111 to the source version of the unit that is currently accessible to the
7112 compiler.
7114 @geindex Inlining
7116 @item 
7117 Inlining requires the appropriate source files for the package or
7118 subprogram bodies to be available to the compiler. Inlining is always
7119 effective, independent of the order in which units are compiled.
7121 @item 
7122 Compiling a unit never affects any other compilations. The editing of
7123 sources may cause previous compilations to be out of date if they
7124 depended on the source file being modified.
7125 @end itemize
7127 The most important result of these differences is that order of compilation
7128 is never significant in GNAT. There is no situation in which one is
7129 required to do one compilation before another. What shows up as order of
7130 compilation requirements in the traditional Ada library becomes, in
7131 GNAT, simple source dependencies; in other words, there is only a set
7132 of rules saying what source files must be present when a file is
7133 compiled.
7135 @node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
7136 @anchor{gnat_ugn/the_gnat_compilation_model using-gnat-files-with-external-tools}@anchor{1a}@anchor{gnat_ugn/the_gnat_compilation_model id77}@anchor{d2}
7137 @section Using GNAT Files with External Tools
7140 This section explains how files that are produced by GNAT may be
7141 used with tools designed for other languages.
7143 @menu
7144 * Using Other Utility Programs with GNAT:: 
7145 * The External Symbol Naming Scheme of GNAT:: 
7147 @end menu
7149 @node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
7150 @anchor{gnat_ugn/the_gnat_compilation_model using-other-utility-programs-with-gnat}@anchor{d3}@anchor{gnat_ugn/the_gnat_compilation_model id78}@anchor{d4}
7151 @subsection Using Other Utility Programs with GNAT
7154 The object files generated by GNAT are in standard system format and in
7155 particular the debugging information uses this format. This means
7156 programs generated by GNAT can be used with existing utilities that
7157 depend on these formats.
7159 In general, any utility program that works with C will also often work with
7160 Ada programs generated by GNAT. This includes software utilities such as
7161 gprof (a profiling program), gdb (the FSF debugger), and utilities such
7162 as Purify.
7164 @node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
7165 @anchor{gnat_ugn/the_gnat_compilation_model the-external-symbol-naming-scheme-of-gnat}@anchor{d5}@anchor{gnat_ugn/the_gnat_compilation_model id79}@anchor{d6}
7166 @subsection The External Symbol Naming Scheme of GNAT
7169 In order to interpret the output from GNAT, when using tools that are
7170 originally intended for use with other languages, it is useful to
7171 understand the conventions used to generate link names from the Ada
7172 entity names.
7174 All link names are in all lowercase letters. With the exception of library
7175 procedure names, the mechanism used is simply to use the full expanded
7176 Ada name with dots replaced by double underscores. For example, suppose
7177 we have the following package spec:
7179 @example
7180 package QRS is
7181    MN : Integer;
7182 end QRS;
7183 @end example
7185 @geindex pragma Export
7187 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
7188 the corresponding link name is @code{qrs__mn}.
7189 Of course if a @code{pragma Export} is used this may be overridden:
7191 @example
7192 package Exports is
7193    Var1 : Integer;
7194    pragma Export (Var1, C, External_Name => "var1_name");
7195    Var2 : Integer;
7196    pragma Export (Var2, C, Link_Name => "var2_link_name");
7197 end Exports;
7198 @end example
7200 In this case, the link name for @code{Var1} is whatever link name the
7201 C compiler would assign for the C function @code{var1_name}. This typically
7202 would be either @code{var1_name} or @code{_var1_name}, depending on operating
7203 system conventions, but other possibilities exist. The link name for
7204 @code{Var2} is @code{var2_link_name}, and this is not operating system
7205 dependent.
7207 One exception occurs for library level procedures. A potential ambiguity
7208 arises between the required name @code{_main} for the C main program,
7209 and the name we would otherwise assign to an Ada library level procedure
7210 called @code{Main} (which might well not be the main program).
7212 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
7213 names. So if we have a library level procedure such as:
7215 @example
7216 procedure Hello (S : String);
7217 @end example
7219 the external name of this procedure will be @code{_ada_hello}.
7221 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7223 @node Building Executable Programs with GNAT,GNAT Utility Programs,The GNAT Compilation Model,Top
7224 @anchor{gnat_ugn/building_executable_programs_with_gnat building-executable-programs-with-gnat}@anchor{a}@anchor{gnat_ugn/building_executable_programs_with_gnat doc}@anchor{d7}@anchor{gnat_ugn/building_executable_programs_with_gnat id1}@anchor{d8}
7225 @chapter Building Executable Programs with GNAT
7228 This chapter describes first the gnatmake tool
7229 (@ref{1b,,Building with gnatmake}),
7230 which automatically determines the set of sources
7231 needed by an Ada compilation unit and executes the necessary
7232 (re)compilations, binding and linking.
7233 It also explains how to use each tool individually: the
7234 compiler (gcc, see @ref{1c,,Compiling with gcc}),
7235 binder (gnatbind, see @ref{1d,,Binding with gnatbind}),
7236 and linker (gnatlink, see @ref{1e,,Linking with gnatlink})
7237 to build executable programs.
7238 Finally, this chapter provides examples of
7239 how to make use of the general GNU make mechanism
7240 in a GNAT context (see @ref{1f,,Using the GNU make Utility}).
7243 @menu
7244 * Building with gnatmake:: 
7245 * Compiling with gcc:: 
7246 * Compiler Switches:: 
7247 * Linker Switches:: 
7248 * Binding with gnatbind:: 
7249 * Linking with gnatlink:: 
7250 * Using the GNU make Utility:: 
7252 @end menu
7254 @node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7255 @anchor{gnat_ugn/building_executable_programs_with_gnat the-gnat-make-program-gnatmake}@anchor{1b}@anchor{gnat_ugn/building_executable_programs_with_gnat building-with-gnatmake}@anchor{d9}
7256 @section Building with @code{gnatmake}
7259 @geindex gnatmake
7261 A typical development cycle when working on an Ada program consists of
7262 the following steps:
7265 @enumerate 
7267 @item 
7268 Edit some sources to fix bugs;
7270 @item 
7271 Add enhancements;
7273 @item 
7274 Compile all sources affected;
7276 @item 
7277 Rebind and relink; and
7279 @item 
7280 Test.
7281 @end enumerate
7283 @geindex Dependency rules (compilation)
7285 The third step in particular can be tricky, because not only do the modified
7286 files have to be compiled, but any files depending on these files must also be
7287 recompiled. The dependency rules in Ada can be quite complex, especially
7288 in the presence of overloading, @code{use} clauses, generics and inlined
7289 subprograms.
7291 @code{gnatmake} automatically takes care of the third and fourth steps
7292 of this process. It determines which sources need to be compiled,
7293 compiles them, and binds and links the resulting object files.
7295 Unlike some other Ada make programs, the dependencies are always
7296 accurately recomputed from the new sources. The source based approach of
7297 the GNAT compilation model makes this possible. This means that if
7298 changes to the source program cause corresponding changes in
7299 dependencies, they will always be tracked exactly correctly by
7300 @code{gnatmake}.
7302 Note that for advanced forms of project structure, we recommend creating
7303 a project file as explained in the @emph{GNAT_Project_Manager} chapter in the
7304 @emph{GPRbuild User's Guide}, and using the
7305 @code{gprbuild} tool which supports building with project files and works similarly
7306 to @code{gnatmake}.
7308 @menu
7309 * Running gnatmake:: 
7310 * Switches for gnatmake:: 
7311 * Mode Switches for gnatmake:: 
7312 * Notes on the Command Line:: 
7313 * How gnatmake Works:: 
7314 * Examples of gnatmake Usage:: 
7316 @end menu
7318 @node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7319 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{da}@anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{db}
7320 @subsection Running @code{gnatmake}
7323 The usual form of the @code{gnatmake} command is
7325 @example
7326 $ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7327 @end example
7329 The only required argument is one @code{file_name}, which specifies
7330 a compilation unit that is a main program. Several @code{file_names} can be
7331 specified: this will result in several executables being built.
7332 If @code{switches} are present, they can be placed before the first
7333 @code{file_name}, between @code{file_names} or after the last @code{file_name}.
7334 If @code{mode_switches} are present, they must always be placed after
7335 the last @code{file_name} and all @code{switches}.
7337 If you are using standard file extensions (@code{.adb} and
7338 @code{.ads}), then the
7339 extension may be omitted from the @code{file_name} arguments. However, if
7340 you are using non-standard extensions, then it is required that the
7341 extension be given. A relative or absolute directory path can be
7342 specified in a @code{file_name}, in which case, the input source file will
7343 be searched for in the specified directory only. Otherwise, the input
7344 source file will first be searched in the directory where
7345 @code{gnatmake} was invoked and if it is not found, it will be search on
7346 the source path of the compiler as described in
7347 @ref{89,,Search Paths and the Run-Time Library (RTL)}.
7349 All @code{gnatmake} output (except when you specify @code{-M}) is sent to
7350 @code{stderr}. The output produced by the
7351 @code{-M} switch is sent to @code{stdout}.
7353 @node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7354 @anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{dc}@anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{dd}
7355 @subsection Switches for @code{gnatmake}
7358 You may specify any of the following switches to @code{gnatmake}:
7360 @geindex --version (gnatmake)
7363 @table @asis
7365 @item @code{--version}
7367 Display Copyright and version, then exit disregarding all other options.
7368 @end table
7370 @geindex --help (gnatmake)
7373 @table @asis
7375 @item @code{--help}
7377 If @code{--version} was not used, display usage, then exit disregarding
7378 all other options.
7379 @end table
7381 @geindex --GCC=compiler_name (gnatmake)
7384 @table @asis
7386 @item @code{--GCC=@emph{compiler_name}}
7388 Program used for compiling. The default is @code{gcc}. You need to use
7389 quotes around @code{compiler_name} if @code{compiler_name} contains
7390 spaces or other separator characters.
7391 As an example @code{--GCC="foo -x  -y"}
7392 will instruct @code{gnatmake} to use @code{foo -x -y} as your
7393 compiler. A limitation of this syntax is that the name and path name of
7394 the executable itself must not include any embedded spaces. Note that
7395 switch @code{-c} is always inserted after your command name. Thus in the
7396 above example the compiler command that will be used by @code{gnatmake}
7397 will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7398 used, only the last @code{compiler_name} is taken into account. However,
7399 all the additional switches are also taken into account. Thus,
7400 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7401 @code{--GCC="bar -x -y -z -t"}.
7402 @end table
7404 @geindex --GNATBIND=binder_name (gnatmake)
7407 @table @asis
7409 @item @code{--GNATBIND=@emph{binder_name}}
7411 Program used for binding. The default is @code{gnatbind}. You need to
7412 use quotes around @code{binder_name} if @code{binder_name} contains spaces
7413 or other separator characters.
7414 As an example @code{--GNATBIND="bar -x  -y"}
7415 will instruct @code{gnatmake} to use @code{bar -x -y} as your
7416 binder. Binder switches that are normally appended by @code{gnatmake}
7417 to @code{gnatbind} are now appended to the end of @code{bar -x -y}.
7418 A limitation of this syntax is that the name and path name of the executable
7419 itself must not include any embedded spaces.
7420 @end table
7422 @geindex --GNATLINK=linker_name (gnatmake)
7425 @table @asis
7427 @item @code{--GNATLINK=@emph{linker_name}}
7429 Program used for linking. The default is @code{gnatlink}. You need to
7430 use quotes around @code{linker_name} if @code{linker_name} contains spaces
7431 or other separator characters.
7432 As an example @code{--GNATLINK="lan -x  -y"}
7433 will instruct @code{gnatmake} to use @code{lan -x -y} as your
7434 linker. Linker switches that are normally appended by @code{gnatmake} to
7435 @code{gnatlink} are now appended to the end of @code{lan -x -y}.
7436 A limitation of this syntax is that the name and path name of the executable
7437 itself must not include any embedded spaces.
7439 @item @code{--create-map-file}
7441 When linking an executable, create a map file. The name of the map file
7442 has the same name as the executable with extension ".map".
7444 @item @code{--create-map-file=@emph{mapfile}}
7446 When linking an executable, create a map file with the specified name.
7447 @end table
7449 @geindex --create-missing-dirs (gnatmake)
7452 @table @asis
7454 @item @code{--create-missing-dirs}
7456 When using project files (@code{-P@emph{project}}), automatically create
7457 missing object directories, library directories and exec
7458 directories.
7460 @item @code{--single-compile-per-obj-dir}
7462 Disallow simultaneous compilations in the same object directory when
7463 project files are used.
7465 @item @code{--subdirs=@emph{subdir}}
7467 Actual object directory of each project file is the subdirectory subdir of the
7468 object directory specified or defaulted in the project file.
7470 @item @code{--unchecked-shared-lib-imports}
7472 By default, shared library projects are not allowed to import static library
7473 projects. When this switch is used on the command line, this restriction is
7474 relaxed.
7476 @item @code{--source-info=@emph{source info file}}
7478 Specify a source info file. This switch is active only when project files
7479 are used. If the source info file is specified as a relative path, then it is
7480 relative to the object directory of the main project. If the source info file
7481 does not exist, then after the Project Manager has successfully parsed and
7482 processed the project files and found the sources, it creates the source info
7483 file. If the source info file already exists and can be read successfully,
7484 then the Project Manager will get all the needed information about the sources
7485 from the source info file and will not look for them. This reduces the time
7486 to process the project files, especially when looking for sources that take a
7487 long time. If the source info file exists but cannot be parsed successfully,
7488 the Project Manager will attempt to recreate it. If the Project Manager fails
7489 to create the source info file, a message is issued, but gnatmake does not
7490 fail. @code{gnatmake} "trusts" the source info file. This means that
7491 if the source files have changed (addition, deletion, moving to a different
7492 source directory), then the source info file need to be deleted and recreated.
7493 @end table
7495 @geindex -a (gnatmake)
7498 @table @asis
7500 @item @code{-a}
7502 Consider all files in the make process, even the GNAT internal system
7503 files (for example, the predefined Ada library files), as well as any
7504 locked files. Locked files are files whose ALI file is write-protected.
7505 By default,
7506 @code{gnatmake} does not check these files,
7507 because the assumption is that the GNAT internal files are properly up
7508 to date, and also that any write protected ALI files have been properly
7509 installed. Note that if there is an installation problem, such that one
7510 of these files is not up to date, it will be properly caught by the
7511 binder.
7512 You may have to specify this switch if you are working on GNAT
7513 itself. The switch @code{-a} is also useful
7514 in conjunction with @code{-f}
7515 if you need to recompile an entire application,
7516 including run-time files, using special configuration pragmas,
7517 such as a @code{Normalize_Scalars} pragma.
7519 By default
7520 @code{gnatmake -a} compiles all GNAT
7521 internal files with
7522 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7523 @end table
7525 @geindex -b (gnatmake)
7528 @table @asis
7530 @item @code{-b}
7532 Bind only. Can be combined with @code{-c} to do
7533 compilation and binding, but no link.
7534 Can be combined with @code{-l}
7535 to do binding and linking. When not combined with
7536 @code{-c}
7537 all the units in the closure of the main program must have been previously
7538 compiled and must be up to date. The root unit specified by @code{file_name}
7539 may be given without extension, with the source extension or, if no GNAT
7540 Project File is specified, with the ALI file extension.
7541 @end table
7543 @geindex -c (gnatmake)
7546 @table @asis
7548 @item @code{-c}
7550 Compile only. Do not perform binding, except when @code{-b}
7551 is also specified. Do not perform linking, except if both
7552 @code{-b} and
7553 @code{-l} are also specified.
7554 If the root unit specified by @code{file_name} is not a main unit, this is the
7555 default. Otherwise @code{gnatmake} will attempt binding and linking
7556 unless all objects are up to date and the executable is more recent than
7557 the objects.
7558 @end table
7560 @geindex -C (gnatmake)
7563 @table @asis
7565 @item @code{-C}
7567 Use a temporary mapping file. A mapping file is a way to communicate
7568 to the compiler two mappings: from unit names to file names (without
7569 any directory information) and from file names to path names (with
7570 full directory information). A mapping file can make the compiler's
7571 file searches faster, especially if there are many source directories,
7572 or the sources are read over a slow network connection. If
7573 @code{-P} is used, a mapping file is always used, so
7574 @code{-C} is unnecessary; in this case the mapping file
7575 is initially populated based on the project file. If
7576 @code{-C} is used without
7577 @code{-P},
7578 the mapping file is initially empty. Each invocation of the compiler
7579 will add any newly accessed sources to the mapping file.
7580 @end table
7582 @geindex -C= (gnatmake)
7585 @table @asis
7587 @item @code{-C=@emph{file}}
7589 Use a specific mapping file. The file, specified as a path name (absolute or
7590 relative) by this switch, should already exist, otherwise the switch is
7591 ineffective. The specified mapping file will be communicated to the compiler.
7592 This switch is not compatible with a project file
7593 (-P`file`) or with multiple compiling processes
7594 (-jnnn, when nnn is greater than 1).
7595 @end table
7597 @geindex -d (gnatmake)
7600 @table @asis
7602 @item @code{-d}
7604 Display progress for each source, up to date or not, as a single line:
7606 @example
7607 completed x out of y (zz%)
7608 @end example
7610 If the file needs to be compiled this is displayed after the invocation of
7611 the compiler. These lines are displayed even in quiet output mode.
7612 @end table
7614 @geindex -D (gnatmake)
7617 @table @asis
7619 @item @code{-D @emph{dir}}
7621 Put all object files and ALI file in directory @code{dir}.
7622 If the @code{-D} switch is not used, all object files
7623 and ALI files go in the current working directory.
7625 This switch cannot be used when using a project file.
7626 @end table
7628 @geindex -eI (gnatmake)
7631 @table @asis
7633 @item @code{-eI@emph{nnn}}
7635 Indicates that the main source is a multi-unit source and the rank of the unit
7636 in the source file is nnn. nnn needs to be a positive number and a valid
7637 index in the source. This switch cannot be used when @code{gnatmake} is
7638 invoked for several mains.
7639 @end table
7641 @geindex -eL (gnatmake)
7643 @geindex symbolic links
7646 @table @asis
7648 @item @code{-eL}
7650 Follow all symbolic links when processing project files.
7651 This should be used if your project uses symbolic links for files or
7652 directories, but is not needed in other cases.
7654 @geindex naming scheme
7656 This also assumes that no directory matches the naming scheme for files (for
7657 instance that you do not have a directory called "sources.ads" when using the
7658 default GNAT naming scheme).
7660 When you do not have to use this switch (i.e., by default), gnatmake is able to
7661 save a lot of system calls (several per source file and object file), which
7662 can result in a significant speed up to load and manipulate a project file,
7663 especially when using source files from a remote system.
7664 @end table
7666 @geindex -eS (gnatmake)
7669 @table @asis
7671 @item @code{-eS}
7673 Output the commands for the compiler, the binder and the linker
7674 on standard output,
7675 instead of standard error.
7676 @end table
7678 @geindex -f (gnatmake)
7681 @table @asis
7683 @item @code{-f}
7685 Force recompilations. Recompile all sources, even though some object
7686 files may be up to date, but don't recompile predefined or GNAT internal
7687 files or locked files (files with a write-protected ALI file),
7688 unless the @code{-a} switch is also specified.
7689 @end table
7691 @geindex -F (gnatmake)
7694 @table @asis
7696 @item @code{-F}
7698 When using project files, if some errors or warnings are detected during
7699 parsing and verbose mode is not in effect (no use of switch
7700 -v), then error lines start with the full path name of the project
7701 file, rather than its simple file name.
7702 @end table
7704 @geindex -g (gnatmake)
7707 @table @asis
7709 @item @code{-g}
7711 Enable debugging. This switch is simply passed to the compiler and to the
7712 linker.
7713 @end table
7715 @geindex -i (gnatmake)
7718 @table @asis
7720 @item @code{-i}
7722 In normal mode, @code{gnatmake} compiles all object files and ALI files
7723 into the current directory. If the @code{-i} switch is used,
7724 then instead object files and ALI files that already exist are overwritten
7725 in place. This means that once a large project is organized into separate
7726 directories in the desired manner, then @code{gnatmake} will automatically
7727 maintain and update this organization. If no ALI files are found on the
7728 Ada object path (see @ref{89,,Search Paths and the Run-Time Library (RTL)}),
7729 the new object and ALI files are created in the
7730 directory containing the source being compiled. If another organization
7731 is desired, where objects and sources are kept in different directories,
7732 a useful technique is to create dummy ALI files in the desired directories.
7733 When detecting such a dummy file, @code{gnatmake} will be forced to
7734 recompile the corresponding source file, and it will be put the resulting
7735 object and ALI files in the directory where it found the dummy file.
7736 @end table
7738 @geindex -j (gnatmake)
7740 @geindex Parallel make
7743 @table @asis
7745 @item @code{-j@emph{n}}
7747 Use @code{n} processes to carry out the (re)compilations. On a multiprocessor
7748 machine compilations will occur in parallel. If @code{n} is 0, then the
7749 maximum number of parallel compilations is the number of core processors
7750 on the platform. In the event of compilation errors, messages from various
7751 compilations might get interspersed (but @code{gnatmake} will give you the
7752 full ordered list of failing compiles at the end). If this is problematic,
7753 rerun the make process with n set to 1 to get a clean list of messages.
7754 @end table
7756 @geindex -k (gnatmake)
7759 @table @asis
7761 @item @code{-k}
7763 Keep going. Continue as much as possible after a compilation error. To
7764 ease the programmer's task in case of compilation errors, the list of
7765 sources for which the compile fails is given when @code{gnatmake}
7766 terminates.
7768 If @code{gnatmake} is invoked with several @code{file_names} and with this
7769 switch, if there are compilation errors when building an executable,
7770 @code{gnatmake} will not attempt to build the following executables.
7771 @end table
7773 @geindex -l (gnatmake)
7776 @table @asis
7778 @item @code{-l}
7780 Link only. Can be combined with @code{-b} to binding
7781 and linking. Linking will not be performed if combined with
7782 @code{-c}
7783 but not with @code{-b}.
7784 When not combined with @code{-b}
7785 all the units in the closure of the main program must have been previously
7786 compiled and must be up to date, and the main program needs to have been bound.
7787 The root unit specified by @code{file_name}
7788 may be given without extension, with the source extension or, if no GNAT
7789 Project File is specified, with the ALI file extension.
7790 @end table
7792 @geindex -m (gnatmake)
7795 @table @asis
7797 @item @code{-m}
7799 Specify that the minimum necessary amount of recompilations
7800 be performed. In this mode @code{gnatmake} ignores time
7801 stamp differences when the only
7802 modifications to a source file consist in adding/removing comments,
7803 empty lines, spaces or tabs. This means that if you have changed the
7804 comments in a source file or have simply reformatted it, using this
7805 switch will tell @code{gnatmake} not to recompile files that depend on it
7806 (provided other sources on which these files depend have undergone no
7807 semantic modifications). Note that the debugging information may be
7808 out of date with respect to the sources if the @code{-m} switch causes
7809 a compilation to be switched, so the use of this switch represents a
7810 trade-off between compilation time and accurate debugging information.
7811 @end table
7813 @geindex Dependencies
7814 @geindex producing list
7816 @geindex -M (gnatmake)
7819 @table @asis
7821 @item @code{-M}
7823 Check if all objects are up to date. If they are, output the object
7824 dependences to @code{stdout} in a form that can be directly exploited in
7825 a @code{Makefile}. By default, each source file is prefixed with its
7826 (relative or absolute) directory name. This name is whatever you
7827 specified in the various @code{-aI}
7828 and @code{-I} switches. If you use
7829 @code{gnatmake -M}  @code{-q}
7830 (see below), only the source file names,
7831 without relative paths, are output. If you just specify the  @code{-M}
7832 switch, dependencies of the GNAT internal system files are omitted. This
7833 is typically what you want. If you also specify
7834 the @code{-a} switch,
7835 dependencies of the GNAT internal files are also listed. Note that
7836 dependencies of the objects in external Ada libraries (see
7837 switch  @code{-aL@emph{dir}} in the following list)
7838 are never reported.
7839 @end table
7841 @geindex -n (gnatmake)
7844 @table @asis
7846 @item @code{-n}
7848 Don't compile, bind, or link. Checks if all objects are up to date.
7849 If they are not, the full name of the first file that needs to be
7850 recompiled is printed.
7851 Repeated use of this option, followed by compiling the indicated source
7852 file, will eventually result in recompiling all required units.
7853 @end table
7855 @geindex -o (gnatmake)
7858 @table @asis
7860 @item @code{-o @emph{exec_name}}
7862 Output executable name. The name of the final executable program will be
7863 @code{exec_name}. If the @code{-o} switch is omitted the default
7864 name for the executable will be the name of the input file in appropriate form
7865 for an executable file on the host system.
7867 This switch cannot be used when invoking @code{gnatmake} with several
7868 @code{file_names}.
7869 @end table
7871 @geindex -p (gnatmake)
7874 @table @asis
7876 @item @code{-p}
7878 Same as @code{--create-missing-dirs}
7879 @end table
7881 @geindex -P (gnatmake)
7884 @table @asis
7886 @item @code{-P@emph{project}}
7888 Use project file @code{project}. Only one such switch can be used.
7889 @end table
7891 @c -- Comment:
7892 @c :ref:`gnatmake_and_Project_Files`.
7894 @geindex -q (gnatmake)
7897 @table @asis
7899 @item @code{-q}
7901 Quiet. When this flag is not set, the commands carried out by
7902 @code{gnatmake} are displayed.
7903 @end table
7905 @geindex -s (gnatmake)
7908 @table @asis
7910 @item @code{-s}
7912 Recompile if compiler switches have changed since last compilation.
7913 All compiler switches but -I and -o are taken into account in the
7914 following way:
7915 orders between different 'first letter' switches are ignored, but
7916 orders between same switches are taken into account. For example,
7917 @code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O}
7918 is equivalent to @code{-O -g}.
7920 This switch is recommended when Integrated Preprocessing is used.
7921 @end table
7923 @geindex -u (gnatmake)
7926 @table @asis
7928 @item @code{-u}
7930 Unique. Recompile at most the main files. It implies -c. Combined with
7931 -f, it is equivalent to calling the compiler directly. Note that using
7932 -u with a project file and no main has a special meaning.
7933 @end table
7935 @c --Comment
7936 @c (See :ref:`Project_Files_and_Main_Subprograms`.)
7938 @geindex -U (gnatmake)
7941 @table @asis
7943 @item @code{-U}
7945 When used without a project file or with one or several mains on the command
7946 line, is equivalent to -u. When used with a project file and no main
7947 on the command line, all sources of all project files are checked and compiled
7948 if not up to date, and libraries are rebuilt, if necessary.
7949 @end table
7951 @geindex -v (gnatmake)
7954 @table @asis
7956 @item @code{-v}
7958 Verbose. Display the reason for all recompilations @code{gnatmake}
7959 decides are necessary, with the highest verbosity level.
7960 @end table
7962 @geindex -vl (gnatmake)
7965 @table @asis
7967 @item @code{-vl}
7969 Verbosity level Low. Display fewer lines than in verbosity Medium.
7970 @end table
7972 @geindex -vm (gnatmake)
7975 @table @asis
7977 @item @code{-vm}
7979 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7980 @end table
7982 @geindex -vm (gnatmake)
7985 @table @asis
7987 @item @code{-vh}
7989 Verbosity level High. Equivalent to -v.
7991 @item @code{-vP@emph{x}}
7993 Indicate the verbosity of the parsing of GNAT project files.
7994 See @ref{de,,Switches Related to Project Files}.
7995 @end table
7997 @geindex -x (gnatmake)
8000 @table @asis
8002 @item @code{-x}
8004 Indicate that sources that are not part of any Project File may be compiled.
8005 Normally, when using Project Files, only sources that are part of a Project
8006 File may be compile. When this switch is used, a source outside of all Project
8007 Files may be compiled. The ALI file and the object file will be put in the
8008 object directory of the main Project. The compilation switches used will only
8009 be those specified on the command line. Even when
8010 @code{-x} is used, mains specified on the
8011 command line need to be sources of a project file.
8013 @item @code{-X@emph{name}=@emph{value}}
8015 Indicate that external variable @code{name} has the value @code{value}.
8016 The Project Manager will use this value for occurrences of
8017 @code{external(name)} when parsing the project file.
8018 @ref{de,,Switches Related to Project Files}.
8019 @end table
8021 @geindex -z (gnatmake)
8024 @table @asis
8026 @item @code{-z}
8028 No main subprogram. Bind and link the program even if the unit name
8029 given on the command line is a package name. The resulting executable
8030 will execute the elaboration routines of the package and its closure,
8031 then the finalization routines.
8032 @end table
8034 @subsubheading GCC switches
8037 Any uppercase or multi-character switch that is not a @code{gnatmake} switch
8038 is passed to @code{gcc} (e.g., @code{-O}, @code{-gnato,} etc.)
8040 @subsubheading Source and library search path switches
8043 @geindex -aI (gnatmake)
8046 @table @asis
8048 @item @code{-aI@emph{dir}}
8050 When looking for source files also look in directory @code{dir}.
8051 The order in which source files search is undertaken is
8052 described in @ref{89,,Search Paths and the Run-Time Library (RTL)}.
8053 @end table
8055 @geindex -aL (gnatmake)
8058 @table @asis
8060 @item @code{-aL@emph{dir}}
8062 Consider @code{dir} as being an externally provided Ada library.
8063 Instructs @code{gnatmake} to skip compilation units whose @code{.ALI}
8064 files have been located in directory @code{dir}. This allows you to have
8065 missing bodies for the units in @code{dir} and to ignore out of date bodies
8066 for the same units. You still need to specify
8067 the location of the specs for these units by using the switches
8068 @code{-aI@emph{dir}}  or @code{-I@emph{dir}}.
8069 Note: this switch is provided for compatibility with previous versions
8070 of @code{gnatmake}. The easier method of causing standard libraries
8071 to be excluded from consideration is to write-protect the corresponding
8072 ALI files.
8073 @end table
8075 @geindex -aO (gnatmake)
8078 @table @asis
8080 @item @code{-aO@emph{dir}}
8082 When searching for library and object files, look in directory
8083 @code{dir}. The order in which library files are searched is described in
8084 @ref{8c,,Search Paths for gnatbind}.
8085 @end table
8087 @geindex Search paths
8088 @geindex for gnatmake
8090 @geindex -A (gnatmake)
8093 @table @asis
8095 @item @code{-A@emph{dir}}
8097 Equivalent to @code{-aL@emph{dir}} @code{-aI@emph{dir}}.
8099 @geindex -I (gnatmake)
8101 @item @code{-I@emph{dir}}
8103 Equivalent to @code{-aO@emph{dir} -aI@emph{dir}}.
8104 @end table
8106 @geindex -I- (gnatmake)
8108 @geindex Source files
8109 @geindex suppressing search
8112 @table @asis
8114 @item @code{-I-}
8116 Do not look for source files in the directory containing the source
8117 file named in the command line.
8118 Do not look for ALI or object files in the directory
8119 where @code{gnatmake} was invoked.
8120 @end table
8122 @geindex -L (gnatmake)
8124 @geindex Linker libraries
8127 @table @asis
8129 @item @code{-L@emph{dir}}
8131 Add directory @code{dir} to the list of directories in which the linker
8132 will search for libraries. This is equivalent to
8133 @code{-largs} @code{-L@emph{dir}}.
8134 Furthermore, under Windows, the sources pointed to by the libraries path
8135 set in the registry are not searched for.
8136 @end table
8138 @geindex -nostdinc (gnatmake)
8141 @table @asis
8143 @item @code{-nostdinc}
8145 Do not look for source files in the system default directory.
8146 @end table
8148 @geindex -nostdlib (gnatmake)
8151 @table @asis
8153 @item @code{-nostdlib}
8155 Do not look for library files in the system default directory.
8156 @end table
8158 @geindex --RTS (gnatmake)
8161 @table @asis
8163 @item @code{--RTS=@emph{rts-path}}
8165 Specifies the default location of the runtime library. GNAT looks for the
8166 runtime
8167 in the following directories, and stops as soon as a valid runtime is found
8168 (@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
8169 @code{ada_object_path} present):
8172 @itemize *
8174 @item 
8175 @emph{<current directory>/$rts_path}
8177 @item 
8178 @emph{<default-search-dir>/$rts_path}
8180 @item 
8181 @emph{<default-search-dir>/rts-$rts_path}
8183 @item 
8184 The selected path is handled like a normal RTS path.
8185 @end itemize
8186 @end table
8188 @node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
8189 @anchor{gnat_ugn/building_executable_programs_with_gnat id4}@anchor{df}@anchor{gnat_ugn/building_executable_programs_with_gnat mode-switches-for-gnatmake}@anchor{e0}
8190 @subsection Mode Switches for @code{gnatmake}
8193 The mode switches (referred to as @code{mode_switches}) allow the
8194 inclusion of switches that are to be passed to the compiler itself, the
8195 binder or the linker. The effect of a mode switch is to cause all
8196 subsequent switches up to the end of the switch list, or up to the next
8197 mode switch, to be interpreted as switches to be passed on to the
8198 designated component of GNAT.
8200 @geindex -cargs (gnatmake)
8203 @table @asis
8205 @item @code{-cargs @emph{switches}}
8207 Compiler switches. Here @code{switches} is a list of switches
8208 that are valid switches for @code{gcc}. They will be passed on to
8209 all compile steps performed by @code{gnatmake}.
8210 @end table
8212 @geindex -bargs (gnatmake)
8215 @table @asis
8217 @item @code{-bargs @emph{switches}}
8219 Binder switches. Here @code{switches} is a list of switches
8220 that are valid switches for @code{gnatbind}. They will be passed on to
8221 all bind steps performed by @code{gnatmake}.
8222 @end table
8224 @geindex -largs (gnatmake)
8227 @table @asis
8229 @item @code{-largs @emph{switches}}
8231 Linker switches. Here @code{switches} is a list of switches
8232 that are valid switches for @code{gnatlink}. They will be passed on to
8233 all link steps performed by @code{gnatmake}.
8234 @end table
8236 @geindex -margs (gnatmake)
8239 @table @asis
8241 @item @code{-margs @emph{switches}}
8243 Make switches. The switches are directly interpreted by @code{gnatmake},
8244 regardless of any previous occurrence of @code{-cargs}, @code{-bargs}
8245 or @code{-largs}.
8246 @end table
8248 @node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8249 @anchor{gnat_ugn/building_executable_programs_with_gnat id5}@anchor{e1}@anchor{gnat_ugn/building_executable_programs_with_gnat notes-on-the-command-line}@anchor{e2}
8250 @subsection Notes on the Command Line
8253 This section contains some additional useful notes on the operation
8254 of the @code{gnatmake} command.
8256 @geindex Recompilation (by gnatmake)
8259 @itemize *
8261 @item 
8262 If @code{gnatmake} finds no ALI files, it recompiles the main program
8263 and all other units required by the main program.
8264 This means that @code{gnatmake}
8265 can be used for the initial compile, as well as during subsequent steps of
8266 the development cycle.
8268 @item 
8269 If you enter @code{gnatmake foo.adb}, where @code{foo}
8270 is a subunit or body of a generic unit, @code{gnatmake} recompiles
8271 @code{foo.adb} (because it finds no ALI) and stops, issuing a
8272 warning.
8274 @item 
8275 In @code{gnatmake} the switch @code{-I}
8276 is used to specify both source and
8277 library file paths. Use @code{-aI}
8278 instead if you just want to specify
8279 source paths only and @code{-aO}
8280 if you want to specify library paths
8281 only.
8283 @item 
8284 @code{gnatmake} will ignore any files whose ALI file is write-protected.
8285 This may conveniently be used to exclude standard libraries from
8286 consideration and in particular it means that the use of the
8287 @code{-f} switch will not recompile these files
8288 unless @code{-a} is also specified.
8290 @item 
8291 @code{gnatmake} has been designed to make the use of Ada libraries
8292 particularly convenient. Assume you have an Ada library organized
8293 as follows: @emph{obj-dir} contains the objects and ALI files for
8294 of your Ada compilation units,
8295 whereas @emph{include-dir} contains the
8296 specs of these units, but no bodies. Then to compile a unit
8297 stored in @code{main.adb}, which uses this Ada library you would just type:
8299 @example
8300 $ gnatmake -aI`include-dir`  -aL`obj-dir`  main
8301 @end example
8303 @item 
8304 Using @code{gnatmake} along with the @code{-m (minimal recompilation)}
8305 switch provides a mechanism for avoiding unnecessary recompilations. Using
8306 this switch,
8307 you can update the comments/format of your
8308 source files without having to recompile everything. Note, however, that
8309 adding or deleting lines in a source files may render its debugging
8310 info obsolete. If the file in question is a spec, the impact is rather
8311 limited, as that debugging info will only be useful during the
8312 elaboration phase of your program. For bodies the impact can be more
8313 significant. In all events, your debugger will warn you if a source file
8314 is more recent than the corresponding object, and alert you to the fact
8315 that the debugging information may be out of date.
8316 @end itemize
8318 @node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8319 @anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{e3}@anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{e4}
8320 @subsection How @code{gnatmake} Works
8323 Generally @code{gnatmake} automatically performs all necessary
8324 recompilations and you don't need to worry about how it works. However,
8325 it may be useful to have some basic understanding of the @code{gnatmake}
8326 approach and in particular to understand how it uses the results of
8327 previous compilations without incorrectly depending on them.
8329 First a definition: an object file is considered @emph{up to date} if the
8330 corresponding ALI file exists and if all the source files listed in the
8331 dependency section of this ALI file have time stamps matching those in
8332 the ALI file. This means that neither the source file itself nor any
8333 files that it depends on have been modified, and hence there is no need
8334 to recompile this file.
8336 @code{gnatmake} works by first checking if the specified main unit is up
8337 to date. If so, no compilations are required for the main unit. If not,
8338 @code{gnatmake} compiles the main program to build a new ALI file that
8339 reflects the latest sources. Then the ALI file of the main unit is
8340 examined to find all the source files on which the main program depends,
8341 and @code{gnatmake} recursively applies the above procedure on all these
8342 files.
8344 This process ensures that @code{gnatmake} only trusts the dependencies
8345 in an existing ALI file if they are known to be correct. Otherwise it
8346 always recompiles to determine a new, guaranteed accurate set of
8347 dependencies. As a result the program is compiled 'upside down' from what may
8348 be more familiar as the required order of compilation in some other Ada
8349 systems. In particular, clients are compiled before the units on which
8350 they depend. The ability of GNAT to compile in any order is critical in
8351 allowing an order of compilation to be chosen that guarantees that
8352 @code{gnatmake} will recompute a correct set of new dependencies if
8353 necessary.
8355 When invoking @code{gnatmake} with several @code{file_names}, if a unit is
8356 imported by several of the executables, it will be recompiled at most once.
8358 Note: when using non-standard naming conventions
8359 (@ref{35,,Using Other File Names}), changing through a configuration pragmas
8360 file the version of a source and invoking @code{gnatmake} to recompile may
8361 have no effect, if the previous version of the source is still accessible
8362 by @code{gnatmake}. It may be necessary to use the switch
8365 @node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8366 @anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatmake-usage}@anchor{e5}@anchor{gnat_ugn/building_executable_programs_with_gnat id7}@anchor{e6}
8367 @subsection Examples of @code{gnatmake} Usage
8371 @table @asis
8373 @item @emph{gnatmake hello.adb}
8375 Compile all files necessary to bind and link the main program
8376 @code{hello.adb} (containing unit @code{Hello}) and bind and link the
8377 resulting object files to generate an executable file @code{hello}.
8379 @item @emph{gnatmake main1 main2 main3}
8381 Compile all files necessary to bind and link the main programs
8382 @code{main1.adb} (containing unit @code{Main1}), @code{main2.adb}
8383 (containing unit @code{Main2}) and @code{main3.adb}
8384 (containing unit @code{Main3}) and bind and link the resulting object files
8385 to generate three executable files @code{main1},
8386 @code{main2}  and @code{main3}.
8388 @item @emph{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8390 Compile all files necessary to bind and link the main program unit
8391 @code{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8392 be done with optimization level 2 and the order of elaboration will be
8393 listed by the binder. @code{gnatmake} will operate in quiet mode, not
8394 displaying commands it is executing.
8395 @end table
8397 @node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8398 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{1c}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{e7}
8399 @section Compiling with @code{gcc}
8402 This section discusses how to compile Ada programs using the @code{gcc}
8403 command. It also describes the set of switches
8404 that can be used to control the behavior of the compiler.
8406 @menu
8407 * Compiling Programs:: 
8408 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
8409 * Order of Compilation Issues:: 
8410 * Examples:: 
8412 @end menu
8414 @node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8415 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{e8}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{e9}
8416 @subsection Compiling Programs
8419 The first step in creating an executable program is to compile the units
8420 of the program using the @code{gcc} command. You must compile the
8421 following files:
8424 @itemize *
8426 @item 
8427 the body file (@code{.adb}) for a library level subprogram or generic
8428 subprogram
8430 @item 
8431 the spec file (@code{.ads}) for a library level package or generic
8432 package that has no body
8434 @item 
8435 the body file (@code{.adb}) for a library level package
8436 or generic package that has a body
8437 @end itemize
8439 You need @emph{not} compile the following files
8442 @itemize *
8444 @item 
8445 the spec of a library unit which has a body
8447 @item 
8448 subunits
8449 @end itemize
8451 because they are compiled as part of compiling related units. GNAT
8452 package specs
8453 when the corresponding body is compiled, and subunits when the parent is
8454 compiled.
8456 @geindex cannot generate code
8458 If you attempt to compile any of these files, you will get one of the
8459 following error messages (where @code{fff} is the name of the file you
8460 compiled):
8462 @quotation
8464 @example
8465 cannot generate code for file `@w{`}fff`@w{`} (package spec)
8466 to check package spec, use -gnatc
8468 cannot generate code for file `@w{`}fff`@w{`} (missing subunits)
8469 to check parent unit, use -gnatc
8471 cannot generate code for file `@w{`}fff`@w{`} (subprogram spec)
8472 to check subprogram spec, use -gnatc
8474 cannot generate code for file `@w{`}fff`@w{`} (subunit)
8475 to check subunit, use -gnatc
8476 @end example
8477 @end quotation
8479 As indicated by the above error messages, if you want to submit
8480 one of these files to the compiler to check for correct semantics
8481 without generating code, then use the @code{-gnatc} switch.
8483 The basic command for compiling a file containing an Ada unit is:
8485 @example
8486 $ gcc -c [switches] <file name>
8487 @end example
8489 where @code{file name} is the name of the Ada file (usually
8490 having an extension @code{.ads} for a spec or @code{.adb} for a body).
8491 You specify the
8492 @code{-c} switch to tell @code{gcc} to compile, but not link, the file.
8493 The result of a successful compilation is an object file, which has the
8494 same name as the source file but an extension of @code{.o} and an Ada
8495 Library Information (ALI) file, which also has the same name as the
8496 source file, but with @code{.ali} as the extension. GNAT creates these
8497 two output files in the current directory, but you may specify a source
8498 file in any directory using an absolute or relative path specification
8499 containing the directory information.
8501 TESTING: the @code{--foobar@emph{NN}} switch
8503 @geindex gnat1
8505 @code{gcc} is actually a driver program that looks at the extensions of
8506 the file arguments and loads the appropriate compiler. For example, the
8507 GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8508 These programs are in directories known to the driver program (in some
8509 configurations via environment variables you set), but need not be in
8510 your path. The @code{gcc} driver also calls the assembler and any other
8511 utilities needed to complete the generation of the required object
8512 files.
8514 It is possible to supply several file names on the same @code{gcc}
8515 command. This causes @code{gcc} to call the appropriate compiler for
8516 each file. For example, the following command lists two separate
8517 files to be compiled:
8519 @example
8520 $ gcc -c x.adb y.adb
8521 @end example
8523 calls @code{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8524 @code{y.adb}.
8525 The compiler generates two object files @code{x.o} and @code{y.o}
8526 and the two ALI files @code{x.ali} and @code{y.ali}.
8528 Any switches apply to all the files listed, see @ref{ea,,Compiler Switches} for a
8529 list of available @code{gcc} switches.
8531 @node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8532 @anchor{gnat_ugn/building_executable_programs_with_gnat id10}@anchor{eb}@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-and-the-run-time-library-rtl}@anchor{89}
8533 @subsection Search Paths and the Run-Time Library (RTL)
8536 With the GNAT source-based library system, the compiler must be able to
8537 find source files for units that are needed by the unit being compiled.
8538 Search paths are used to guide this process.
8540 The compiler compiles one source file whose name must be given
8541 explicitly on the command line. In other words, no searching is done
8542 for this file. To find all other source files that are needed (the most
8543 common being the specs of units), the compiler examines the following
8544 directories, in the following order:
8547 @itemize *
8549 @item 
8550 The directory containing the source file of the main unit being compiled
8551 (the file name on the command line).
8553 @item 
8554 Each directory named by an @code{-I} switch given on the @code{gcc}
8555 command line, in the order given.
8557 @geindex ADA_PRJ_INCLUDE_FILE
8559 @item 
8560 Each of the directories listed in the text file whose name is given
8561 by the 
8562 @geindex ADA_PRJ_INCLUDE_FILE
8563 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8564 @code{ADA_PRJ_INCLUDE_FILE} environment variable.
8565 @geindex ADA_PRJ_INCLUDE_FILE
8566 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8567 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8568 driver when project files are used. It should not normally be set
8569 by other means.
8571 @geindex ADA_INCLUDE_PATH
8573 @item 
8574 Each of the directories listed in the value of the
8575 @geindex ADA_INCLUDE_PATH
8576 @geindex environment variable; ADA_INCLUDE_PATH
8577 @code{ADA_INCLUDE_PATH} environment variable.
8578 Construct this value
8579 exactly as the 
8580 @geindex PATH
8581 @geindex environment variable; PATH
8582 @code{PATH} environment variable: a list of directory
8583 names separated by colons (semicolons when working with the NT version).
8585 @item 
8586 The content of the @code{ada_source_path} file which is part of the GNAT
8587 installation tree and is used to store standard libraries such as the
8588 GNAT Run Time Library (RTL) source files.
8589 @ref{87,,Installing a library}
8590 @end itemize
8592 Specifying the switch @code{-I-}
8593 inhibits the use of the directory
8594 containing the source file named in the command line. You can still
8595 have this directory on your search path, but in this case it must be
8596 explicitly requested with a @code{-I} switch.
8598 Specifying the switch @code{-nostdinc}
8599 inhibits the search of the default location for the GNAT Run Time
8600 Library (RTL) source files.
8602 The compiler outputs its object files and ALI files in the current
8603 working directory.
8604 Caution: The object file can be redirected with the @code{-o} switch;
8605 however, @code{gcc} and @code{gnat1} have not been coordinated on this
8606 so the @code{ALI} file will not go to the right place. Therefore, you should
8607 avoid using the @code{-o} switch.
8609 @geindex System.IO
8611 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8612 children make up the GNAT RTL, together with the simple @code{System.IO}
8613 package used in the @code{"Hello World"} example. The sources for these units
8614 are needed by the compiler and are kept together in one directory. Not
8615 all of the bodies are needed, but all of the sources are kept together
8616 anyway. In a normal installation, you need not specify these directory
8617 names when compiling or binding. Either the environment variables or
8618 the built-in defaults cause these files to be found.
8620 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8621 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8622 consisting of child units of @code{GNAT}. This is a collection of generally
8623 useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8624 for further details.
8626 Besides simplifying access to the RTL, a major use of search paths is
8627 in compiling sources from multiple directories. This can make
8628 development environments much more flexible.
8630 @node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8631 @anchor{gnat_ugn/building_executable_programs_with_gnat id11}@anchor{ec}@anchor{gnat_ugn/building_executable_programs_with_gnat order-of-compilation-issues}@anchor{ed}
8632 @subsection Order of Compilation Issues
8635 If, in our earlier example, there was a spec for the @code{hello}
8636 procedure, it would be contained in the file @code{hello.ads}; yet this
8637 file would not have to be explicitly compiled. This is the result of the
8638 model we chose to implement library management. Some of the consequences
8639 of this model are as follows:
8642 @itemize *
8644 @item 
8645 There is no point in compiling specs (except for package
8646 specs with no bodies) because these are compiled as needed by clients. If
8647 you attempt a useless compilation, you will receive an error message.
8648 It is also useless to compile subunits because they are compiled as needed
8649 by the parent.
8651 @item 
8652 There are no order of compilation requirements: performing a
8653 compilation never obsoletes anything. The only way you can obsolete
8654 something and require recompilations is to modify one of the
8655 source files on which it depends.
8657 @item 
8658 There is no library as such, apart from the ALI files
8659 (@ref{42,,The Ada Library Information Files}, for information on the format
8660 of these files). For now we find it convenient to create separate ALI files,
8661 but eventually the information therein may be incorporated into the object
8662 file directly.
8664 @item 
8665 When you compile a unit, the source files for the specs of all units
8666 that it @emph{with}s, all its subunits, and the bodies of any generics it
8667 instantiates must be available (reachable by the search-paths mechanism
8668 described above), or you will receive a fatal error message.
8669 @end itemize
8671 @node Examples,,Order of Compilation Issues,Compiling with gcc
8672 @anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{ee}@anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{ef}
8673 @subsection Examples
8676 The following are some typical Ada compilation command line examples:
8678 @example
8679 $ gcc -c xyz.adb
8680 @end example
8682 Compile body in file @code{xyz.adb} with all default options.
8684 @example
8685 $ gcc -c -O2 -gnata xyz-def.adb
8686 @end example
8688 Compile the child unit package in file @code{xyz-def.adb} with extensive
8689 optimizations, and pragma @code{Assert}/@cite{Debug} statements
8690 enabled.
8692 @example
8693 $ gcc -c -gnatc abc-def.adb
8694 @end example
8696 Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8697 mode.
8699 @node Compiler Switches,Linker Switches,Compiling with gcc,Building Executable Programs with GNAT
8700 @anchor{gnat_ugn/building_executable_programs_with_gnat compiler-switches}@anchor{f0}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gcc}@anchor{ea}
8701 @section Compiler Switches
8704 The @code{gcc} command accepts switches that control the
8705 compilation process. These switches are fully described in this section:
8706 first an alphabetical listing of all switches with a brief description,
8707 and then functionally grouped sets of switches with more detailed
8708 information.
8710 More switches exist for GCC than those documented here, especially
8711 for specific targets. However, their use is not recommended as
8712 they may change code generation in ways that are incompatible with
8713 the Ada run-time library, or can cause inconsistencies between
8714 compilation units.
8716 @menu
8717 * Alphabetical List of All Switches:: 
8718 * Output and Error Message Control:: 
8719 * Warning Message Control:: 
8720 * Debugging and Assertion Control:: 
8721 * Validity Checking:: 
8722 * Style Checking:: 
8723 * Run-Time Checks:: 
8724 * Using gcc for Syntax Checking:: 
8725 * Using gcc for Semantic Checking:: 
8726 * Compiling Different Versions of Ada:: 
8727 * Character Set Control:: 
8728 * File Naming Control:: 
8729 * Subprogram Inlining Control:: 
8730 * Auxiliary Output Control:: 
8731 * Debugging Control:: 
8732 * Exception Handling Control:: 
8733 * Units to Sources Mapping Files:: 
8734 * Code Generation Control:: 
8736 @end menu
8738 @node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8739 @anchor{gnat_ugn/building_executable_programs_with_gnat id13}@anchor{f1}@anchor{gnat_ugn/building_executable_programs_with_gnat alphabetical-list-of-all-switches}@anchor{f2}
8740 @subsection Alphabetical List of All Switches
8743 @geindex -b (gcc)
8746 @table @asis
8748 @item @code{-b @emph{target}}
8750 Compile your program to run on @code{target}, which is the name of a
8751 system configuration. You must have a GNAT cross-compiler built if
8752 @code{target} is not the same as your host system.
8753 @end table
8755 @geindex -B (gcc)
8758 @table @asis
8760 @item @code{-B@emph{dir}}
8762 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8763 from @code{dir} instead of the default location. Only use this switch
8764 when multiple versions of the GNAT compiler are available.
8765 See the "Options for Directory Search" section in the
8766 @cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8767 You would normally use the @code{-b} or @code{-V} switch instead.
8768 @end table
8770 @geindex -c (gcc)
8773 @table @asis
8775 @item @code{-c}
8777 Compile. Always use this switch when compiling Ada programs.
8779 Note: for some other languages when using @code{gcc}, notably in
8780 the case of C and C++, it is possible to use
8781 use @code{gcc} without a @code{-c} switch to
8782 compile and link in one step. In the case of GNAT, you
8783 cannot use this approach, because the binder must be run
8784 and @code{gcc} cannot be used to run the GNAT binder.
8785 @end table
8787 @geindex -fcallgraph-info (gcc)
8790 @table @asis
8792 @item @code{-fcallgraph-info[=su,da]}
8794 Makes the compiler output callgraph information for the program, on a
8795 per-file basis. The information is generated in the VCG format.  It can
8796 be decorated with additional, per-node and/or per-edge information, if a
8797 list of comma-separated markers is additionally specified. When the
8798 @code{su} marker is specified, the callgraph is decorated with stack usage
8799 information; it is equivalent to @code{-fstack-usage}. When the @code{da}
8800 marker is specified, the callgraph is decorated with information about
8801 dynamically allocated objects.
8802 @end table
8804 @geindex -fdump-scos (gcc)
8807 @table @asis
8809 @item @code{-fdump-scos}
8811 Generates SCO (Source Coverage Obligation) information in the ALI file.
8812 This information is used by advanced coverage tools. See unit @code{SCOs}
8813 in the compiler sources for details in files @code{scos.ads} and
8814 @code{scos.adb}.
8815 @end table
8817 @geindex -flto (gcc)
8820 @table @asis
8822 @item @code{-flto[=@emph{n}]}
8824 Enables Link Time Optimization. This switch must be used in conjunction
8825 with the @code{-Ox} switches (but not with the @code{-gnatn} switch
8826 since it is a full replacement for the latter) and instructs the compiler
8827 to defer most optimizations until the link stage. The advantage of this
8828 approach is that the compiler can do a whole-program analysis and choose
8829 the best interprocedural optimization strategy based on a complete view
8830 of the program, instead of a fragmentary view with the usual approach.
8831 This can also speed up the compilation of big programs and reduce the
8832 size of the executable, compared with a traditional per-unit compilation
8833 with inlining across modules enabled by the @code{-gnatn} switch.
8834 The drawback of this approach is that it may require more memory and that
8835 the debugging information generated by -g with it might be hardly usable.
8836 The switch, as well as the accompanying @code{-Ox} switches, must be
8837 specified both for the compilation and the link phases.
8838 If the @code{n} parameter is specified, the optimization and final code
8839 generation at link time are executed using @code{n} parallel jobs by
8840 means of an installed @code{make} program.
8841 @end table
8843 @geindex -fno-inline (gcc)
8846 @table @asis
8848 @item @code{-fno-inline}
8850 Suppresses all inlining, unless requested with pragma @code{Inline_Always}. The
8851 effect is enforced regardless of other optimization or inlining switches.
8852 Note that inlining can also be suppressed on a finer-grained basis with
8853 pragma @code{No_Inline}.
8854 @end table
8856 @geindex -fno-inline-functions (gcc)
8859 @table @asis
8861 @item @code{-fno-inline-functions}
8863 Suppresses automatic inlining of subprograms, which is enabled
8864 if @code{-O3} is used.
8865 @end table
8867 @geindex -fno-inline-small-functions (gcc)
8870 @table @asis
8872 @item @code{-fno-inline-small-functions}
8874 Suppresses automatic inlining of small subprograms, which is enabled
8875 if @code{-O2} is used.
8876 @end table
8878 @geindex -fno-inline-functions-called-once (gcc)
8881 @table @asis
8883 @item @code{-fno-inline-functions-called-once}
8885 Suppresses inlining of subprograms local to the unit and called once
8886 from within it, which is enabled if @code{-O1} is used.
8887 @end table
8889 @geindex -fno-ivopts (gcc)
8892 @table @asis
8894 @item @code{-fno-ivopts}
8896 Suppresses high-level loop induction variable optimizations, which are
8897 enabled if @code{-O1} is used. These optimizations are generally
8898 profitable but, for some specific cases of loops with numerous uses
8899 of the iteration variable that follow a common pattern, they may end
8900 up destroying the regularity that could be exploited at a lower level
8901 and thus producing inferior code.
8902 @end table
8904 @geindex -fno-strict-aliasing (gcc)
8907 @table @asis
8909 @item @code{-fno-strict-aliasing}
8911 Causes the compiler to avoid assumptions regarding non-aliasing
8912 of objects of different types. See
8913 @ref{f3,,Optimization and Strict Aliasing} for details.
8914 @end table
8916 @geindex -fno-strict-overflow (gcc)
8919 @table @asis
8921 @item @code{-fno-strict-overflow}
8923 Causes the compiler to avoid assumptions regarding the rules of signed
8924 integer overflow. These rules specify that signed integer overflow will
8925 result in a Constraint_Error exception at run time and are enforced in
8926 default mode by the compiler, so this switch should not be necessary in
8927 normal operating mode. It might be useful in conjunction with @code{-gnato0}
8928 for very peculiar cases of low-level programming.
8929 @end table
8931 @geindex -fstack-check (gcc)
8934 @table @asis
8936 @item @code{-fstack-check}
8938 Activates stack checking.
8939 See @ref{f4,,Stack Overflow Checking} for details.
8940 @end table
8942 @geindex -fstack-usage (gcc)
8945 @table @asis
8947 @item @code{-fstack-usage}
8949 Makes the compiler output stack usage information for the program, on a
8950 per-subprogram basis. See @ref{f5,,Static Stack Usage Analysis} for details.
8951 @end table
8953 @geindex -g (gcc)
8956 @table @asis
8958 @item @code{-g}
8960 Generate debugging information. This information is stored in the object
8961 file and copied from there to the final executable file by the linker,
8962 where it can be read by the debugger. You must use the
8963 @code{-g} switch if you plan on using the debugger.
8964 @end table
8966 @geindex -gnat05 (gcc)
8969 @table @asis
8971 @item @code{-gnat05}
8973 Allow full Ada 2005 features.
8974 @end table
8976 @geindex -gnat12 (gcc)
8979 @table @asis
8981 @item @code{-gnat12}
8983 Allow full Ada 2012 features.
8984 @end table
8986 @geindex -gnat83 (gcc)
8988 @geindex -gnat2005 (gcc)
8991 @table @asis
8993 @item @code{-gnat2005}
8995 Allow full Ada 2005 features (same as @code{-gnat05})
8996 @end table
8998 @geindex -gnat2012 (gcc)
9001 @table @asis
9003 @item @code{-gnat2012}
9005 Allow full Ada 2012 features (same as @code{-gnat12})
9007 @item @code{-gnat83}
9009 Enforce Ada 83 restrictions.
9010 @end table
9012 @geindex -gnat95 (gcc)
9015 @table @asis
9017 @item @code{-gnat95}
9019 Enforce Ada 95 restrictions.
9021 Note: for compatibility with some Ada 95 compilers which support only
9022 the @code{overriding} keyword of Ada 2005, the @code{-gnatd.D} switch can
9023 be used along with @code{-gnat95} to achieve a similar effect with GNAT.
9025 @code{-gnatd.D} instructs GNAT to consider @code{overriding} as a keyword
9026 and handle its associated semantic checks, even in Ada 95 mode.
9027 @end table
9029 @geindex -gnata (gcc)
9032 @table @asis
9034 @item @code{-gnata}
9036 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
9037 activated. Note that these pragmas can also be controlled using the
9038 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
9039 It also activates pragmas @code{Check}, @code{Precondition}, and
9040 @code{Postcondition}. Note that these pragmas can also be controlled
9041 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
9042 also activates all assertions defined in the RM as aspects: preconditions,
9043 postconditions, type invariants and (sub)type predicates. In all Ada modes,
9044 corresponding pragmas for type invariants and (sub)type predicates are
9045 also activated. The default is that all these assertions are disabled,
9046 and have no effect, other than being checked for syntactic validity, and
9047 in the case of subtype predicates, constructions such as membership tests
9048 still test predicates even if assertions are turned off.
9049 @end table
9051 @geindex -gnatA (gcc)
9054 @table @asis
9056 @item @code{-gnatA}
9058 Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
9059 it will be ignored.
9060 @end table
9062 @geindex -gnatb (gcc)
9065 @table @asis
9067 @item @code{-gnatb}
9069 Generate brief messages to @code{stderr} even if verbose mode set.
9070 @end table
9072 @geindex -gnatB (gcc)
9075 @table @asis
9077 @item @code{-gnatB}
9079 Assume no invalid (bad) values except for 'Valid attribute use
9080 (@ref{f6,,Validity Checking}).
9081 @end table
9083 @geindex -gnatc (gcc)
9086 @table @asis
9088 @item @code{-gnatc}
9090 Check syntax and semantics only (no code generation attempted). When the
9091 compiler is invoked by @code{gnatmake}, if the switch @code{-gnatc} is
9092 only given to the compiler (after @code{-cargs} or in package Compiler of
9093 the project file, @code{gnatmake} will fail because it will not find the
9094 object file after compilation. If @code{gnatmake} is called with
9095 @code{-gnatc} as a builder switch (before @code{-cargs} or in package
9096 Builder of the project file) then @code{gnatmake} will not fail because
9097 it will not look for the object files after compilation, and it will not try
9098 to build and link.
9099 @end table
9101 @geindex -gnatC (gcc)
9104 @table @asis
9106 @item @code{-gnatC}
9108 Generate CodePeer intermediate format (no code generation attempted).
9109 This switch will generate an intermediate representation suitable for
9110 use by CodePeer (@code{.scil} files). This switch is not compatible with
9111 code generation (it will, among other things, disable some switches such
9112 as -gnatn, and enable others such as -gnata).
9113 @end table
9115 @geindex -gnatd (gcc)
9118 @table @asis
9120 @item @code{-gnatd}
9122 Specify debug options for the compiler. The string of characters after
9123 the @code{-gnatd} specify the specific debug options. The possible
9124 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
9125 compiler source file @code{debug.adb} for details of the implemented
9126 debug options. Certain debug options are relevant to applications
9127 programmers, and these are documented at appropriate points in this
9128 users guide.
9129 @end table
9131 @geindex -gnatD[nn] (gcc)
9134 @table @asis
9136 @item @code{-gnatD}
9138 Create expanded source files for source level debugging. This switch
9139 also suppresses generation of cross-reference information
9140 (see @code{-gnatx}). Note that this switch is not allowed if a previous
9141 -gnatR switch has been given, since these two switches are not compatible.
9142 @end table
9144 @geindex -gnateA (gcc)
9147 @table @asis
9149 @item @code{-gnateA}
9151 Check that the actual parameters of a subprogram call are not aliases of one
9152 another. To qualify as aliasing, the actuals must denote objects of a composite
9153 type, their memory locations must be identical or overlapping, and at least one
9154 of the corresponding formal parameters must be of mode OUT or IN OUT.
9156 @example
9157 type Rec_Typ is record
9158    Data : Integer := 0;
9159 end record;
9161 function Self (Val : Rec_Typ) return Rec_Typ is
9162 begin
9163    return Val;
9164 end Self;
9166 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
9167 begin
9168    null;
9169 end Detect_Aliasing;
9171 Obj : Rec_Typ;
9173 Detect_Aliasing (Obj, Obj);
9174 Detect_Aliasing (Obj, Self (Obj));
9175 @end example
9177 In the example above, the first call to @code{Detect_Aliasing} fails with a
9178 @code{Program_Error} at runtime because the actuals for @code{Val_1} and
9179 @code{Val_2} denote the same object. The second call executes without raising
9180 an exception because @code{Self(Obj)} produces an anonymous object which does
9181 not share the memory location of @code{Obj}.
9182 @end table
9184 @geindex -gnatec (gcc)
9187 @table @asis
9189 @item @code{-gnatec=@emph{path}}
9191 Specify a configuration pragma file
9192 (the equal sign is optional)
9193 (@ref{79,,The Configuration Pragmas Files}).
9194 @end table
9196 @geindex -gnateC (gcc)
9199 @table @asis
9201 @item @code{-gnateC}
9203 Generate CodePeer messages in a compiler-like format. This switch is only
9204 effective if @code{-gnatcC} is also specified and requires an installation
9205 of CodePeer.
9206 @end table
9208 @geindex -gnated (gcc)
9211 @table @asis
9213 @item @code{-gnated}
9215 Disable atomic synchronization
9216 @end table
9218 @geindex -gnateD (gcc)
9221 @table @asis
9223 @item @code{-gnateDsymbol[=@emph{value}]}
9225 Defines a symbol, associated with @code{value}, for preprocessing.
9226 (@ref{18,,Integrated Preprocessing}).
9227 @end table
9229 @geindex -gnateE (gcc)
9232 @table @asis
9234 @item @code{-gnateE}
9236 Generate extra information in exception messages. In particular, display
9237 extra column information and the value and range associated with index and
9238 range check failures, and extra column information for access checks.
9239 In cases where the compiler is able to determine at compile time that
9240 a check will fail, it gives a warning, and the extra information is not
9241 produced at run time.
9242 @end table
9244 @geindex -gnatef (gcc)
9247 @table @asis
9249 @item @code{-gnatef}
9251 Display full source path name in brief error messages.
9252 @end table
9254 @geindex -gnateF (gcc)
9257 @table @asis
9259 @item @code{-gnateF}
9261 Check for overflow on all floating-point operations, including those
9262 for unconstrained predefined types. See description of pragma
9263 @code{Check_Float_Overflow} in GNAT RM.
9264 @end table
9266 @geindex -gnateg (gcc)
9268 @code{-gnateg}
9269 @code{-gnatceg}
9271 @quotation
9273 The @code{-gnatc} switch must always be specified before this switch, e.g.
9274 @code{-gnatceg}. Generate a C header from the Ada input file. See
9275 @ref{ca,,Generating C Headers for Ada Specifications} for more
9276 information.
9277 @end quotation
9279 @geindex -gnateG (gcc)
9282 @table @asis
9284 @item @code{-gnateG}
9286 Save result of preprocessing in a text file.
9287 @end table
9289 @geindex -gnatei (gcc)
9292 @table @asis
9294 @item @code{-gnatei@emph{nnn}}
9296 Set maximum number of instantiations during compilation of a single unit to
9297 @code{nnn}. This may be useful in increasing the default maximum of 8000 for
9298 the rare case when a single unit legitimately exceeds this limit.
9299 @end table
9301 @geindex -gnateI (gcc)
9304 @table @asis
9306 @item @code{-gnateI@emph{nnn}}
9308 Indicates that the source is a multi-unit source and that the index of the
9309 unit to compile is @code{nnn}. @code{nnn} needs to be a positive number and need
9310 to be a valid index in the multi-unit source.
9311 @end table
9313 @geindex -gnatel (gcc)
9316 @table @asis
9318 @item @code{-gnatel}
9320 This switch can be used with the static elaboration model to issue info
9321 messages showing
9322 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
9323 are generated. This is useful in diagnosing elaboration circularities
9324 caused by these implicit pragmas when using the static elaboration
9325 model. See See the section in this guide on elaboration checking for
9326 further details. These messages are not generated by default, and are
9327 intended only for temporary use when debugging circularity problems.
9328 @end table
9330 @geindex -gnatel (gcc)
9333 @table @asis
9335 @item @code{-gnateL}
9337 This switch turns off the info messages about implicit elaboration pragmas.
9338 @end table
9340 @geindex -gnatem (gcc)
9343 @table @asis
9345 @item @code{-gnatem=@emph{path}}
9347 Specify a mapping file
9348 (the equal sign is optional)
9349 (@ref{f7,,Units to Sources Mapping Files}).
9350 @end table
9352 @geindex -gnatep (gcc)
9355 @table @asis
9357 @item @code{-gnatep=@emph{file}}
9359 Specify a preprocessing data file
9360 (the equal sign is optional)
9361 (@ref{18,,Integrated Preprocessing}).
9362 @end table
9364 @geindex -gnateP (gcc)
9367 @table @asis
9369 @item @code{-gnateP}
9371 Turn categorization dependency errors into warnings.
9372 Ada requires that units that WITH one another have compatible categories, for
9373 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9374 these errors become warnings (which can be ignored, or suppressed in the usual
9375 manner). This can be useful in some specialized circumstances such as the
9376 temporary use of special test software.
9377 @end table
9379 @geindex -gnateS (gcc)
9382 @table @asis
9384 @item @code{-gnateS}
9386 Synonym of @code{-fdump-scos}, kept for backwards compatibility.
9387 @end table
9389 @geindex -gnatet=file (gcc)
9392 @table @asis
9394 @item @code{-gnatet=@emph{path}}
9396 Generate target dependent information. The format of the output file is
9397 described in the section about switch @code{-gnateT}.
9398 @end table
9400 @geindex -gnateT (gcc)
9403 @table @asis
9405 @item @code{-gnateT=@emph{path}}
9407 Read target dependent information, such as endianness or sizes and alignments
9408 of base type. If this switch is passed, the default target dependent
9409 information of the compiler is replaced by the one read from the input file.
9410 This is used by tools other than the compiler, e.g. to do
9411 semantic analysis of programs that will run on some other target than
9412 the machine on which the tool is run.
9414 The following target dependent values should be defined,
9415 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
9416 positive integer value, and fields marked with a question mark are
9417 boolean fields, where a value of 0 is False, and a value of 1 is True:
9419 @example
9420 Bits_BE                    : Nat; -- Bits stored big-endian?
9421 Bits_Per_Unit              : Pos; -- Bits in a storage unit
9422 Bits_Per_Word              : Pos; -- Bits in a word
9423 Bytes_BE                   : Nat; -- Bytes stored big-endian?
9424 Char_Size                  : Pos; -- Standard.Character'Size
9425 Double_Float_Alignment     : Nat; -- Alignment of double float
9426 Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
9427 Double_Size                : Pos; -- Standard.Long_Float'Size
9428 Float_Size                 : Pos; -- Standard.Float'Size
9429 Float_Words_BE             : Nat; -- Float words stored big-endian?
9430 Int_Size                   : Pos; -- Standard.Integer'Size
9431 Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
9432 Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
9433 Long_Size                  : Pos; -- Standard.Long_Integer'Size
9434 Maximum_Alignment          : Pos; -- Maximum permitted alignment
9435 Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
9436 Pointer_Size               : Pos; -- System.Address'Size
9437 Short_Enums                : Nat; -- Short foreign convention enums?
9438 Short_Size                 : Pos; -- Standard.Short_Integer'Size
9439 Strict_Alignment           : Nat; -- Strict alignment?
9440 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9441 Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
9442 Words_BE                   : Nat; -- Words stored big-endian?
9443 @end example
9445 The format of the input file is as follows. First come the values of
9446 the variables defined above, with one line per value:
9448 @example
9449 name  value
9450 @end example
9452 where @code{name} is the name of the parameter, spelled out in full,
9453 and cased as in the above list, and @code{value} is an unsigned decimal
9454 integer. Two or more blanks separates the name from the value.
9456 All the variables must be present, in alphabetical order (i.e. the
9457 same order as the list above).
9459 Then there is a blank line to separate the two parts of the file. Then
9460 come the lines showing the floating-point types to be registered, with
9461 one line per registered mode:
9463 @example
9464 name  digs float_rep size alignment
9465 @end example
9467 where @code{name} is the string name of the type (which can have
9468 single spaces embedded in the name (e.g. long double), @code{digs} is
9469 the number of digits for the floating-point type, @code{float_rep} is
9470 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
9471 AAMP), @code{size} is the size in bits, @code{alignment} is the
9472 alignment in bits. The name is followed by at least two blanks, fields
9473 are separated by at least one blank, and a LF character immediately
9474 follows the alignment field.
9476 Here is an example of a target parameterization file:
9478 @example
9479 Bits_BE                       0
9480 Bits_Per_Unit                 8
9481 Bits_Per_Word                64
9482 Bytes_BE                      0
9483 Char_Size                     8
9484 Double_Float_Alignment        0
9485 Double_Scalar_Alignment       0
9486 Double_Size                  64
9487 Float_Size                   32
9488 Float_Words_BE                0
9489 Int_Size                     64
9490 Long_Double_Size            128
9491 Long_Long_Size               64
9492 Long_Size                    64
9493 Maximum_Alignment            16
9494 Max_Unaligned_Field          64
9495 Pointer_Size                 64
9496 Short_Size                   16
9497 Strict_Alignment              0
9498 System_Allocator_Alignment   16
9499 Wchar_T_Size                 32
9500 Words_BE                      0
9502 float         15  I  64  64
9503 double        15  I  64  64
9504 long double   18  I  80 128
9505 TF            33  I 128 128
9506 @end example
9507 @end table
9509 @geindex -gnateu (gcc)
9512 @table @asis
9514 @item @code{-gnateu}
9516 Ignore unrecognized validity, warning, and style switches that
9517 appear after this switch is given. This may be useful when
9518 compiling sources developed on a later version of the compiler
9519 with an earlier version. Of course the earlier version must
9520 support this switch.
9521 @end table
9523 @geindex -gnateV (gcc)
9526 @table @asis
9528 @item @code{-gnateV}
9530 Check that all actual parameters of a subprogram call are valid according to
9531 the rules of validity checking (@ref{f6,,Validity Checking}).
9532 @end table
9534 @geindex -gnateY (gcc)
9537 @table @asis
9539 @item @code{-gnateY}
9541 Ignore all STYLE_CHECKS pragmas. Full legality checks
9542 are still carried out, but the pragmas have no effect
9543 on what style checks are active. This allows all style
9544 checking options to be controlled from the command line.
9545 @end table
9547 @geindex -gnatE (gcc)
9550 @table @asis
9552 @item @code{-gnatE}
9554 Full dynamic elaboration checks.
9555 @end table
9557 @geindex -gnatf (gcc)
9560 @table @asis
9562 @item @code{-gnatf}
9564 Full errors. Multiple errors per line, all undefined references, do not
9565 attempt to suppress cascaded errors.
9566 @end table
9568 @geindex -gnatF (gcc)
9571 @table @asis
9573 @item @code{-gnatF}
9575 Externals names are folded to all uppercase.
9576 @end table
9578 @geindex -gnatg (gcc)
9581 @table @asis
9583 @item @code{-gnatg}
9585 Internal GNAT implementation mode. This should not be used for
9586 applications programs, it is intended only for use by the compiler
9587 and its run-time library. For documentation, see the GNAT sources.
9588 Note that @code{-gnatg} implies
9589 @code{-gnatw.ge} and
9590 @code{-gnatyg}
9591 so that all standard warnings and all standard style options are turned on.
9592 All warnings and style messages are treated as errors.
9593 @end table
9595 @geindex -gnatG[nn] (gcc)
9598 @table @asis
9600 @item @code{-gnatG=nn}
9602 List generated expanded code in source form.
9603 @end table
9605 @geindex -gnath (gcc)
9608 @table @asis
9610 @item @code{-gnath}
9612 Output usage information. The output is written to @code{stdout}.
9613 @end table
9615 @geindex -gnati (gcc)
9618 @table @asis
9620 @item @code{-gnati@emph{c}}
9622 Identifier character set (@code{c} = 1/2/3/4/8/9/p/f/n/w).
9623 For details of the possible selections for @code{c},
9624 see @ref{48,,Character Set Control}.
9625 @end table
9627 @geindex -gnatI (gcc)
9630 @table @asis
9632 @item @code{-gnatI}
9634 Ignore representation clauses. When this switch is used,
9635 representation clauses are treated as comments. This is useful
9636 when initially porting code where you want to ignore rep clause
9637 problems, and also for compiling foreign code (particularly
9638 for use with ASIS). The representation clauses that are ignored
9639 are: enumeration_representation_clause, record_representation_clause,
9640 and attribute_definition_clause for the following attributes:
9641 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9642 Object_Size, Scalar_Storage_Order, Size, Small, Stream_Size,
9643 and Value_Size. Pragma Default_Scalar_Storage_Order is also ignored.
9644 Note that this option should be used only for compiling -- the
9645 code is likely to malfunction at run time.
9647 Note that when @code{-gnatct} is used to generate trees for input
9648 into ASIS tools, these representation clauses are removed
9649 from the tree and ignored. This means that the tool will not see them.
9650 @end table
9652 @geindex -gnatjnn (gcc)
9655 @table @asis
9657 @item @code{-gnatj@emph{nn}}
9659 Reformat error messages to fit on @code{nn} character lines
9660 @end table
9662 @geindex -gnatk (gcc)
9665 @table @asis
9667 @item @code{-gnatk=@emph{n}}
9669 Limit file names to @code{n} (1-999) characters (@code{k} = krunch).
9670 @end table
9672 @geindex -gnatl (gcc)
9675 @table @asis
9677 @item @code{-gnatl}
9679 Output full source listing with embedded error messages.
9680 @end table
9682 @geindex -gnatL (gcc)
9685 @table @asis
9687 @item @code{-gnatL}
9689 Used in conjunction with -gnatG or -gnatD to intersperse original
9690 source lines (as comment lines with line numbers) in the expanded
9691 source output.
9692 @end table
9694 @geindex -gnatm (gcc)
9697 @table @asis
9699 @item @code{-gnatm=@emph{n}}
9701 Limit number of detected error or warning messages to @code{n}
9702 where @code{n} is in the range 1..999999. The default setting if
9703 no switch is given is 9999. If the number of warnings reaches this
9704 limit, then a message is output and further warnings are suppressed,
9705 but the compilation is continued. If the number of error messages
9706 reaches this limit, then a message is output and the compilation
9707 is abandoned. The equal sign here is optional. A value of zero
9708 means that no limit applies.
9709 @end table
9711 @geindex -gnatn (gcc)
9714 @table @asis
9716 @item @code{-gnatn[12]}
9718 Activate inlining across modules for subprograms for which pragma @code{Inline}
9719 is specified. This inlining is performed by the GCC back-end. An optional
9720 digit sets the inlining level: 1 for moderate inlining across modules
9721 or 2 for full inlining across modules. If no inlining level is specified,
9722 the compiler will pick it based on the optimization level.
9723 @end table
9725 @geindex -gnatN (gcc)
9728 @table @asis
9730 @item @code{-gnatN}
9732 Activate front end inlining for subprograms for which
9733 pragma @code{Inline} is specified. This inlining is performed
9734 by the front end and will be visible in the
9735 @code{-gnatG} output.
9737 When using a gcc-based back end (in practice this means using any version
9738 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
9739 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
9740 Historically front end inlining was more extensive than the gcc back end
9741 inlining, but that is no longer the case.
9742 @end table
9744 @geindex -gnato0 (gcc)
9747 @table @asis
9749 @item @code{-gnato0}
9751 Suppresses overflow checking. This causes the behavior of the compiler to
9752 match the default for older versions where overflow checking was suppressed
9753 by default. This is equivalent to having
9754 @code{pragma Suppress (Overflow_Check)} in a configuration pragma file.
9755 @end table
9757 @geindex -gnato?? (gcc)
9760 @table @asis
9762 @item @code{-gnato??}
9764 Set default mode for handling generation of code to avoid intermediate
9765 arithmetic overflow. Here @code{??} is two digits, a
9766 single digit, or nothing. Each digit is one of the digits @code{1}
9767 through @code{3}:
9770 @multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
9771 @item
9773 Digit
9775 @tab
9777 Interpretation
9779 @item
9781 @emph{1}
9783 @tab
9785 All intermediate overflows checked against base type (@code{STRICT})
9787 @item
9789 @emph{2}
9791 @tab
9793 Minimize intermediate overflows (@code{MINIMIZED})
9795 @item
9797 @emph{3}
9799 @tab
9801 Eliminate intermediate overflows (@code{ELIMINATED})
9803 @end multitable
9806 If only one digit appears, then it applies to all
9807 cases; if two digits are given, then the first applies outside
9808 assertions, pre/postconditions, and type invariants, and the second
9809 applies within assertions, pre/postconditions, and type invariants.
9811 If no digits follow the @code{-gnato}, then it is equivalent to
9812 @code{-gnato11},
9813 causing all intermediate overflows to be handled in strict
9814 mode.
9816 This switch also causes arithmetic overflow checking to be performed
9817 (as though @code{pragma Unsuppress (Overflow_Check)} had been specified).
9819 The default if no option @code{-gnato} is given is that overflow handling
9820 is in @code{STRICT} mode (computations done using the base type), and that
9821 overflow checking is enabled.
9823 Note that division by zero is a separate check that is not
9824 controlled by this switch (divide-by-zero checking is on by default).
9826 See also @ref{f8,,Specifying the Desired Mode}.
9827 @end table
9829 @geindex -gnatp (gcc)
9832 @table @asis
9834 @item @code{-gnatp}
9836 Suppress all checks. See @ref{f9,,Run-Time Checks} for details. This switch
9837 has no effect if cancelled by a subsequent @code{-gnat-p} switch.
9838 @end table
9840 @geindex -gnat-p (gcc)
9843 @table @asis
9845 @item @code{-gnat-p}
9847 Cancel effect of previous @code{-gnatp} switch.
9848 @end table
9850 @geindex -gnatP (gcc)
9853 @table @asis
9855 @item @code{-gnatP}
9857 Enable polling. This is required on some systems (notably Windows NT) to
9858 obtain asynchronous abort and asynchronous transfer of control capability.
9859 See @code{Pragma_Polling} in the @cite{GNAT_Reference_Manual} for full
9860 details.
9861 @end table
9863 @geindex -gnatq (gcc)
9866 @table @asis
9868 @item @code{-gnatq}
9870 Don't quit. Try semantics, even if parse errors.
9871 @end table
9873 @geindex -gnatQ (gcc)
9876 @table @asis
9878 @item @code{-gnatQ}
9880 Don't quit. Generate @code{ALI} and tree files even if illegalities.
9881 Note that code generation is still suppressed in the presence of any
9882 errors, so even with @code{-gnatQ} no object file is generated.
9883 @end table
9885 @geindex -gnatr (gcc)
9888 @table @asis
9890 @item @code{-gnatr}
9892 Treat pragma Restrictions as Restriction_Warnings.
9893 @end table
9895 @geindex -gnatR (gcc)
9898 @table @asis
9900 @item @code{-gnatR[0/1/2/3][e][m][s]}
9902 Output representation information for declared types, objects and
9903 subprograms. Note that this switch is not allowed if a previous
9904 @code{-gnatD} switch has been given, since these two switches
9905 are not compatible.
9906 @end table
9908 @geindex -gnats (gcc)
9911 @table @asis
9913 @item @code{-gnats}
9915 Syntax check only.
9916 @end table
9918 @geindex -gnatS (gcc)
9921 @table @asis
9923 @item @code{-gnatS}
9925 Print package Standard.
9926 @end table
9928 @geindex -gnatt (gcc)
9931 @table @asis
9933 @item @code{-gnatt}
9935 Generate tree output file.
9936 @end table
9938 @geindex -gnatT (gcc)
9941 @table @asis
9943 @item @code{-gnatT@emph{nnn}}
9945 All compiler tables start at @code{nnn} times usual starting size.
9946 @end table
9948 @geindex -gnatu (gcc)
9951 @table @asis
9953 @item @code{-gnatu}
9955 List units for this compilation.
9956 @end table
9958 @geindex -gnatU (gcc)
9961 @table @asis
9963 @item @code{-gnatU}
9965 Tag all error messages with the unique string 'error:'
9966 @end table
9968 @geindex -gnatv (gcc)
9971 @table @asis
9973 @item @code{-gnatv}
9975 Verbose mode. Full error output with source lines to @code{stdout}.
9976 @end table
9978 @geindex -gnatV (gcc)
9981 @table @asis
9983 @item @code{-gnatV}
9985 Control level of validity checking (@ref{f6,,Validity Checking}).
9986 @end table
9988 @geindex -gnatw (gcc)
9991 @table @asis
9993 @item @code{-gnatw@emph{xxx}}
9995 Warning mode where
9996 @code{xxx} is a string of option letters that denotes
9997 the exact warnings that
9998 are enabled or disabled (@ref{fa,,Warning Message Control}).
9999 @end table
10001 @geindex -gnatW (gcc)
10004 @table @asis
10006 @item @code{-gnatW@emph{e}}
10008 Wide character encoding method
10009 (@code{e}=n/h/u/s/e/8).
10010 @end table
10012 @geindex -gnatx (gcc)
10015 @table @asis
10017 @item @code{-gnatx}
10019 Suppress generation of cross-reference information.
10020 @end table
10022 @geindex -gnatX (gcc)
10025 @table @asis
10027 @item @code{-gnatX}
10029 Enable GNAT implementation extensions and latest Ada version.
10030 @end table
10032 @geindex -gnaty (gcc)
10035 @table @asis
10037 @item @code{-gnaty}
10039 Enable built-in style checks (@ref{fb,,Style Checking}).
10040 @end table
10042 @geindex -gnatz (gcc)
10045 @table @asis
10047 @item @code{-gnatz@emph{m}}
10049 Distribution stub generation and compilation
10050 (@code{m}=r/c for receiver/caller stubs).
10051 @end table
10053 @geindex -I (gcc)
10056 @table @asis
10058 @item @code{-I@emph{dir}}
10060 @geindex RTL
10062 Direct GNAT to search the @code{dir} directory for source files needed by
10063 the current compilation
10064 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
10065 @end table
10067 @geindex -I- (gcc)
10070 @table @asis
10072 @item @code{-I-}
10074 @geindex RTL
10076 Except for the source file named in the command line, do not look for source
10077 files in the directory containing the source file named in the command line
10078 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
10079 @end table
10081 @geindex -o (gcc)
10084 @table @asis
10086 @item @code{-o @emph{file}}
10088 This switch is used in @code{gcc} to redirect the generated object file
10089 and its associated ALI file. Beware of this switch with GNAT, because it may
10090 cause the object file and ALI file to have different names which in turn
10091 may confuse the binder and the linker.
10092 @end table
10094 @geindex -nostdinc (gcc)
10097 @table @asis
10099 @item @code{-nostdinc}
10101 Inhibit the search of the default location for the GNAT Run Time
10102 Library (RTL) source files.
10103 @end table
10105 @geindex -nostdlib (gcc)
10108 @table @asis
10110 @item @code{-nostdlib}
10112 Inhibit the search of the default location for the GNAT Run Time
10113 Library (RTL) ALI files.
10114 @end table
10116 @geindex -O (gcc)
10119 @table @asis
10121 @item @code{-O[@emph{n}]}
10123 @code{n} controls the optimization level:
10126 @multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
10127 @item
10129 @emph{n}
10131 @tab
10133 Effect
10135 @item
10137 @emph{0}
10139 @tab
10141 No optimization, the default setting if no @code{-O} appears
10143 @item
10145 @emph{1}
10147 @tab
10149 Normal optimization, the default if you specify @code{-O} without an
10150 operand. A good compromise between code quality and compilation
10151 time.
10153 @item
10155 @emph{2}
10157 @tab
10159 Extensive optimization, may improve execution time, possibly at
10160 the cost of substantially increased compilation time.
10162 @item
10164 @emph{3}
10166 @tab
10168 Same as @code{-O2}, and also includes inline expansion for small
10169 subprograms in the same unit.
10171 @item
10173 @emph{s}
10175 @tab
10177 Optimize space usage
10179 @end multitable
10182 See also @ref{fc,,Optimization Levels}.
10183 @end table
10185 @geindex -pass-exit-codes (gcc)
10188 @table @asis
10190 @item @code{-pass-exit-codes}
10192 Catch exit codes from the compiler and use the most meaningful as
10193 exit status.
10194 @end table
10196 @geindex --RTS (gcc)
10199 @table @asis
10201 @item @code{--RTS=@emph{rts-path}}
10203 Specifies the default location of the runtime library. Same meaning as the
10204 equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
10205 @end table
10207 @geindex -S (gcc)
10210 @table @asis
10212 @item @code{-S}
10214 Used in place of @code{-c} to
10215 cause the assembler source file to be
10216 generated, using @code{.s} as the extension,
10217 instead of the object file.
10218 This may be useful if you need to examine the generated assembly code.
10219 @end table
10221 @geindex -fverbose-asm (gcc)
10224 @table @asis
10226 @item @code{-fverbose-asm}
10228 Used in conjunction with @code{-S}
10229 to cause the generated assembly code file to be annotated with variable
10230 names, making it significantly easier to follow.
10231 @end table
10233 @geindex -v (gcc)
10236 @table @asis
10238 @item @code{-v}
10240 Show commands generated by the @code{gcc} driver. Normally used only for
10241 debugging purposes or if you need to be sure what version of the
10242 compiler you are executing.
10243 @end table
10245 @geindex -V (gcc)
10248 @table @asis
10250 @item @code{-V @emph{ver}}
10252 Execute @code{ver} version of the compiler. This is the @code{gcc}
10253 version, not the GNAT version.
10254 @end table
10256 @geindex -w (gcc)
10259 @table @asis
10261 @item @code{-w}
10263 Turn off warnings generated by the back end of the compiler. Use of
10264 this switch also causes the default for front end warnings to be set
10265 to suppress (as though @code{-gnatws} had appeared at the start of
10266 the options).
10267 @end table
10269 @geindex Combining GNAT switches
10271 You may combine a sequence of GNAT switches into a single switch. For
10272 example, the combined switch
10274 @quotation
10276 @example
10277 -gnatofi3
10278 @end example
10279 @end quotation
10281 is equivalent to specifying the following sequence of switches:
10283 @quotation
10285 @example
10286 -gnato -gnatf -gnati3
10287 @end example
10288 @end quotation
10290 The following restrictions apply to the combination of switches
10291 in this manner:
10294 @itemize *
10296 @item 
10297 The switch @code{-gnatc} if combined with other switches must come
10298 first in the string.
10300 @item 
10301 The switch @code{-gnats} if combined with other switches must come
10302 first in the string.
10304 @item 
10305 The switches
10306 @code{-gnatzc} and @code{-gnatzr} may not be combined with any other
10307 switches, and only one of them may appear in the command line.
10309 @item 
10310 The switch @code{-gnat-p} may not be combined with any other switch.
10312 @item 
10313 Once a 'y' appears in the string (that is a use of the @code{-gnaty}
10314 switch), then all further characters in the switch are interpreted
10315 as style modifiers (see description of @code{-gnaty}).
10317 @item 
10318 Once a 'd' appears in the string (that is a use of the @code{-gnatd}
10319 switch), then all further characters in the switch are interpreted
10320 as debug flags (see description of @code{-gnatd}).
10322 @item 
10323 Once a 'w' appears in the string (that is a use of the @code{-gnatw}
10324 switch), then all further characters in the switch are interpreted
10325 as warning mode modifiers (see description of @code{-gnatw}).
10327 @item 
10328 Once a 'V' appears in the string (that is a use of the @code{-gnatV}
10329 switch), then all further characters in the switch are interpreted
10330 as validity checking options (@ref{f6,,Validity Checking}).
10332 @item 
10333 Option 'em', 'ec', 'ep', 'l=' and 'R' must be the last options in
10334 a combined list of options.
10335 @end itemize
10337 @node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10338 @anchor{gnat_ugn/building_executable_programs_with_gnat id14}@anchor{fd}@anchor{gnat_ugn/building_executable_programs_with_gnat output-and-error-message-control}@anchor{fe}
10339 @subsection Output and Error Message Control
10342 @geindex stderr
10344 The standard default format for error messages is called 'brief format'.
10345 Brief format messages are written to @code{stderr} (the standard error
10346 file) and have the following form:
10348 @example
10349 e.adb:3:04: Incorrect spelling of keyword "function"
10350 e.adb:4:20: ";" should be "is"
10351 @end example
10353 The first integer after the file name is the line number in the file,
10354 and the second integer is the column number within the line.
10355 @code{GPS} can parse the error messages
10356 and point to the referenced character.
10357 The following switches provide control over the error message
10358 format:
10360 @geindex -gnatv (gcc)
10363 @table @asis
10365 @item @code{-gnatv}
10367 The @code{v} stands for verbose.
10368 The effect of this setting is to write long-format error
10369 messages to @code{stdout} (the standard output file.
10370 The same program compiled with the
10371 @code{-gnatv} switch would generate:
10373 @example
10374 3. funcion X (Q : Integer)
10375    |
10376 >>> Incorrect spelling of keyword "function"
10377 4. return Integer;
10378                  |
10379 >>> ";" should be "is"
10380 @end example
10382 The vertical bar indicates the location of the error, and the @code{>>>}
10383 prefix can be used to search for error messages. When this switch is
10384 used the only source lines output are those with errors.
10385 @end table
10387 @geindex -gnatl (gcc)
10390 @table @asis
10392 @item @code{-gnatl}
10394 The @code{l} stands for list.
10395 This switch causes a full listing of
10396 the file to be generated. In the case where a body is
10397 compiled, the corresponding spec is also listed, along
10398 with any subunits. Typical output from compiling a package
10399 body @code{p.adb} might look like:
10401 @example
10402 Compiling: p.adb
10404      1. package body p is
10405      2.    procedure a;
10406      3.    procedure a is separate;
10407      4. begin
10408      5.    null
10409                |
10410         >>> missing ";"
10412      6. end;
10414 Compiling: p.ads
10416      1. package p is
10417      2.    pragma Elaborate_Body
10418                                 |
10419         >>> missing ";"
10421      3. end p;
10423 Compiling: p-a.adb
10425      1. separate p
10426                 |
10427         >>> missing "("
10429      2. procedure a is
10430      3. begin
10431      4.    null
10432                |
10433         >>> missing ";"
10435      5. end;
10436 @end example
10438 When you specify the @code{-gnatv} or @code{-gnatl} switches and
10439 standard output is redirected, a brief summary is written to
10440 @code{stderr} (standard error) giving the number of error messages and
10441 warning messages generated.
10442 @end table
10444 @geindex -gnatl=fname (gcc)
10447 @table @asis
10449 @item @code{-gnatl=@emph{fname}}
10451 This has the same effect as @code{-gnatl} except that the output is
10452 written to a file instead of to standard output. If the given name
10453 @code{fname} does not start with a period, then it is the full name
10454 of the file to be written. If @code{fname} is an extension, it is
10455 appended to the name of the file being compiled. For example, if
10456 file @code{xyz.adb} is compiled with @code{-gnatl=.lst},
10457 then the output is written to file xyz.adb.lst.
10458 @end table
10460 @geindex -gnatU (gcc)
10463 @table @asis
10465 @item @code{-gnatU}
10467 This switch forces all error messages to be preceded by the unique
10468 string 'error:'. This means that error messages take a few more
10469 characters in space, but allows easy searching for and identification
10470 of error messages.
10471 @end table
10473 @geindex -gnatb (gcc)
10476 @table @asis
10478 @item @code{-gnatb}
10480 The @code{b} stands for brief.
10481 This switch causes GNAT to generate the
10482 brief format error messages to @code{stderr} (the standard error
10483 file) as well as the verbose
10484 format message or full listing (which as usual is written to
10485 @code{stdout} (the standard output file).
10486 @end table
10488 @geindex -gnatm (gcc)
10491 @table @asis
10493 @item @code{-gnatm=@emph{n}}
10495 The @code{m} stands for maximum.
10496 @code{n} is a decimal integer in the
10497 range of 1 to 999999 and limits the number of error or warning
10498 messages to be generated. For example, using
10499 @code{-gnatm2} might yield
10501 @example
10502 e.adb:3:04: Incorrect spelling of keyword "function"
10503 e.adb:5:35: missing ".."
10504 fatal error: maximum number of errors detected
10505 compilation abandoned
10506 @end example
10508 The default setting if
10509 no switch is given is 9999. If the number of warnings reaches this
10510 limit, then a message is output and further warnings are suppressed,
10511 but the compilation is continued. If the number of error messages
10512 reaches this limit, then a message is output and the compilation
10513 is abandoned. A value of zero means that no limit applies.
10515 Note that the equal sign is optional, so the switches
10516 @code{-gnatm2} and @code{-gnatm=2} are equivalent.
10517 @end table
10519 @geindex -gnatf (gcc)
10522 @table @asis
10524 @item @code{-gnatf}
10526 @geindex Error messages
10527 @geindex suppressing
10529 The @code{f} stands for full.
10530 Normally, the compiler suppresses error messages that are likely to be
10531 redundant. This switch causes all error
10532 messages to be generated. In particular, in the case of
10533 references to undefined variables. If a given variable is referenced
10534 several times, the normal format of messages is
10536 @example
10537 e.adb:7:07: "V" is undefined (more references follow)
10538 @end example
10540 where the parenthetical comment warns that there are additional
10541 references to the variable @code{V}. Compiling the same program with the
10542 @code{-gnatf} switch yields
10544 @example
10545 e.adb:7:07: "V" is undefined
10546 e.adb:8:07: "V" is undefined
10547 e.adb:8:12: "V" is undefined
10548 e.adb:8:16: "V" is undefined
10549 e.adb:9:07: "V" is undefined
10550 e.adb:9:12: "V" is undefined
10551 @end example
10553 The @code{-gnatf} switch also generates additional information for
10554 some error messages.  Some examples are:
10557 @itemize *
10559 @item 
10560 Details on possibly non-portable unchecked conversion
10562 @item 
10563 List possible interpretations for ambiguous calls
10565 @item 
10566 Additional details on incorrect parameters
10567 @end itemize
10568 @end table
10570 @geindex -gnatjnn (gcc)
10573 @table @asis
10575 @item @code{-gnatjnn}
10577 In normal operation mode (or if @code{-gnatj0} is used), then error messages
10578 with continuation lines are treated as though the continuation lines were
10579 separate messages (and so a warning with two continuation lines counts as
10580 three warnings, and is listed as three separate messages).
10582 If the @code{-gnatjnn} switch is used with a positive value for nn, then
10583 messages are output in a different manner. A message and all its continuation
10584 lines are treated as a unit, and count as only one warning or message in the
10585 statistics totals. Furthermore, the message is reformatted so that no line
10586 is longer than nn characters.
10587 @end table
10589 @geindex -gnatq (gcc)
10592 @table @asis
10594 @item @code{-gnatq}
10596 The @code{q} stands for quit (really 'don't quit').
10597 In normal operation mode, the compiler first parses the program and
10598 determines if there are any syntax errors. If there are, appropriate
10599 error messages are generated and compilation is immediately terminated.
10600 This switch tells
10601 GNAT to continue with semantic analysis even if syntax errors have been
10602 found. This may enable the detection of more errors in a single run. On
10603 the other hand, the semantic analyzer is more likely to encounter some
10604 internal fatal error when given a syntactically invalid tree.
10605 @end table
10607 @geindex -gnatQ (gcc)
10610 @table @asis
10612 @item @code{-gnatQ}
10614 In normal operation mode, the @code{ALI} file is not generated if any
10615 illegalities are detected in the program. The use of @code{-gnatQ} forces
10616 generation of the @code{ALI} file. This file is marked as being in
10617 error, so it cannot be used for binding purposes, but it does contain
10618 reasonably complete cross-reference information, and thus may be useful
10619 for use by tools (e.g., semantic browsing tools or integrated development
10620 environments) that are driven from the @code{ALI} file. This switch
10621 implies @code{-gnatq}, since the semantic phase must be run to get a
10622 meaningful ALI file.
10624 In addition, if @code{-gnatt} is also specified, then the tree file is
10625 generated even if there are illegalities. It may be useful in this case
10626 to also specify @code{-gnatq} to ensure that full semantic processing
10627 occurs. The resulting tree file can be processed by ASIS, for the purpose
10628 of providing partial information about illegal units, but if the error
10629 causes the tree to be badly malformed, then ASIS may crash during the
10630 analysis.
10632 When @code{-gnatQ} is used and the generated @code{ALI} file is marked as
10633 being in error, @code{gnatmake} will attempt to recompile the source when it
10634 finds such an @code{ALI} file, including with switch @code{-gnatc}.
10636 Note that @code{-gnatQ} has no effect if @code{-gnats} is specified,
10637 since ALI files are never generated if @code{-gnats} is set.
10638 @end table
10640 @node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10641 @anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{fa}@anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{ff}
10642 @subsection Warning Message Control
10645 @geindex Warning messages
10647 In addition to error messages, which correspond to illegalities as defined
10648 in the Ada Reference Manual, the compiler detects two kinds of warning
10649 situations.
10651 First, the compiler considers some constructs suspicious and generates a
10652 warning message to alert you to a possible error. Second, if the
10653 compiler detects a situation that is sure to raise an exception at
10654 run time, it generates a warning message. The following shows an example
10655 of warning messages:
10657 @example
10658 e.adb:4:24: warning: creation of object may raise Storage_Error
10659 e.adb:10:17: warning: static value out of range
10660 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10661 @end example
10663 GNAT considers a large number of situations as appropriate
10664 for the generation of warning messages. As always, warnings are not
10665 definite indications of errors. For example, if you do an out-of-range
10666 assignment with the deliberate intention of raising a
10667 @code{Constraint_Error} exception, then the warning that may be
10668 issued does not indicate an error. Some of the situations for which GNAT
10669 issues warnings (at least some of the time) are given in the following
10670 list. This list is not complete, and new warnings are often added to
10671 subsequent versions of GNAT. The list is intended to give a general idea
10672 of the kinds of warnings that are generated.
10675 @itemize *
10677 @item 
10678 Possible infinitely recursive calls
10680 @item 
10681 Out-of-range values being assigned
10683 @item 
10684 Possible order of elaboration problems
10686 @item 
10687 Size not a multiple of alignment for a record type
10689 @item 
10690 Assertions (pragma Assert) that are sure to fail
10692 @item 
10693 Unreachable code
10695 @item 
10696 Address clauses with possibly unaligned values, or where an attempt is
10697 made to overlay a smaller variable with a larger one.
10699 @item 
10700 Fixed-point type declarations with a null range
10702 @item 
10703 Direct_IO or Sequential_IO instantiated with a type that has access values
10705 @item 
10706 Variables that are never assigned a value
10708 @item 
10709 Variables that are referenced before being initialized
10711 @item 
10712 Task entries with no corresponding @code{accept} statement
10714 @item 
10715 Duplicate accepts for the same task entry in a @code{select}
10717 @item 
10718 Objects that take too much storage
10720 @item 
10721 Unchecked conversion between types of differing sizes
10723 @item 
10724 Missing @code{return} statement along some execution path in a function
10726 @item 
10727 Incorrect (unrecognized) pragmas
10729 @item 
10730 Incorrect external names
10732 @item 
10733 Allocation from empty storage pool
10735 @item 
10736 Potentially blocking operation in protected type
10738 @item 
10739 Suspicious parenthesization of expressions
10741 @item 
10742 Mismatching bounds in an aggregate
10744 @item 
10745 Attempt to return local value by reference
10747 @item 
10748 Premature instantiation of a generic body
10750 @item 
10751 Attempt to pack aliased components
10753 @item 
10754 Out of bounds array subscripts
10756 @item 
10757 Wrong length on string assignment
10759 @item 
10760 Violations of style rules if style checking is enabled
10762 @item 
10763 Unused @emph{with} clauses
10765 @item 
10766 @code{Bit_Order} usage that does not have any effect
10768 @item 
10769 @code{Standard.Duration} used to resolve universal fixed expression
10771 @item 
10772 Dereference of possibly null value
10774 @item 
10775 Declaration that is likely to cause storage error
10777 @item 
10778 Internal GNAT unit @emph{with}ed by application unit
10780 @item 
10781 Values known to be out of range at compile time
10783 @item 
10784 Unreferenced or unmodified variables. Note that a special
10785 exemption applies to variables which contain any of the substrings
10786 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
10787 are considered likely to be intentionally used in a situation where
10788 otherwise a warning would be given, so warnings of this kind are
10789 always suppressed for such variables.
10791 @item 
10792 Address overlays that could clobber memory
10794 @item 
10795 Unexpected initialization when address clause present
10797 @item 
10798 Bad alignment for address clause
10800 @item 
10801 Useless type conversions
10803 @item 
10804 Redundant assignment statements and other redundant constructs
10806 @item 
10807 Useless exception handlers
10809 @item 
10810 Accidental hiding of name by child unit
10812 @item 
10813 Access before elaboration detected at compile time
10815 @item 
10816 A range in a @code{for} loop that is known to be null or might be null
10817 @end itemize
10819 The following section lists compiler switches that are available
10820 to control the handling of warning messages. It is also possible
10821 to exercise much finer control over what warnings are issued and
10822 suppressed using the GNAT pragma Warnings (see the description
10823 of the pragma in the @cite{GNAT_Reference_manual}).
10825 @geindex -gnatwa (gcc)
10828 @table @asis
10830 @item @code{-gnatwa}
10832 @emph{Activate most optional warnings.}
10834 This switch activates most optional warning messages.  See the remaining list
10835 in this section for details on optional warning messages that can be
10836 individually controlled.  The warnings that are not turned on by this
10837 switch are:
10840 @itemize *
10842 @item 
10843 @code{-gnatwd} (implicit dereferencing)
10845 @item 
10846 @code{-gnatw.d} (tag warnings with -gnatw switch)
10848 @item 
10849 @code{-gnatwh} (hiding)
10851 @item 
10852 @code{-gnatw.h} (holes in record layouts)
10854 @item 
10855 @code{-gnatw.j} (late primitives of tagged types)
10857 @item 
10858 @code{-gnatw.k} (redefinition of names in standard)
10860 @item 
10861 @code{-gnatwl} (elaboration warnings)
10863 @item 
10864 @code{-gnatw.l} (inherited aspects)
10866 @item 
10867 @code{-gnatw.n} (atomic synchronization)
10869 @item 
10870 @code{-gnatwo} (address clause overlay)
10872 @item 
10873 @code{-gnatw.o} (values set by out parameters ignored)
10875 @item 
10876 @code{-gnatw.q} (questionable layout of record types)
10878 @item 
10879 @code{-gnatw.s} (overridden size clause)
10881 @item 
10882 @code{-gnatwt} (tracking of deleted conditional code)
10884 @item 
10885 @code{-gnatw.u} (unordered enumeration)
10887 @item 
10888 @code{-gnatw.w} (use of Warnings Off)
10890 @item 
10891 @code{-gnatw.y} (reasons for package needing body)
10892 @end itemize
10894 All other optional warnings are turned on.
10895 @end table
10897 @geindex -gnatwA (gcc)
10900 @table @asis
10902 @item @code{-gnatwA}
10904 @emph{Suppress all optional errors.}
10906 This switch suppresses all optional warning messages, see remaining list
10907 in this section for details on optional warning messages that can be
10908 individually controlled. Note that unlike switch @code{-gnatws}, the
10909 use of switch @code{-gnatwA} does not suppress warnings that are
10910 normally given unconditionally and cannot be individually controlled
10911 (for example, the warning about a missing exit path in a function).
10912 Also, again unlike switch @code{-gnatws}, warnings suppressed by
10913 the use of switch @code{-gnatwA} can be individually turned back
10914 on. For example the use of switch @code{-gnatwA} followed by
10915 switch @code{-gnatwd} will suppress all optional warnings except
10916 the warnings for implicit dereferencing.
10917 @end table
10919 @geindex -gnatw.a (gcc)
10922 @table @asis
10924 @item @code{-gnatw.a}
10926 @emph{Activate warnings on failing assertions.}
10928 @geindex Assert failures
10930 This switch activates warnings for assertions where the compiler can tell at
10931 compile time that the assertion will fail. Note that this warning is given
10932 even if assertions are disabled. The default is that such warnings are
10933 generated.
10934 @end table
10936 @geindex -gnatw.A (gcc)
10939 @table @asis
10941 @item @code{-gnatw.A}
10943 @emph{Suppress warnings on failing assertions.}
10945 @geindex Assert failures
10947 This switch suppresses warnings for assertions where the compiler can tell at
10948 compile time that the assertion will fail.
10949 @end table
10951 @geindex -gnatwb (gcc)
10954 @table @asis
10956 @item @code{-gnatwb}
10958 @emph{Activate warnings on bad fixed values.}
10960 @geindex Bad fixed values
10962 @geindex Fixed-point Small value
10964 @geindex Small value
10966 This switch activates warnings for static fixed-point expressions whose
10967 value is not an exact multiple of Small. Such values are implementation
10968 dependent, since an implementation is free to choose either of the multiples
10969 that surround the value. GNAT always chooses the closer one, but this is not
10970 required behavior, and it is better to specify a value that is an exact
10971 multiple, ensuring predictable execution. The default is that such warnings
10972 are not generated.
10973 @end table
10975 @geindex -gnatwB (gcc)
10978 @table @asis
10980 @item @code{-gnatwB}
10982 @emph{Suppress warnings on bad fixed values.}
10984 This switch suppresses warnings for static fixed-point expressions whose
10985 value is not an exact multiple of Small.
10986 @end table
10988 @geindex -gnatw.b (gcc)
10991 @table @asis
10993 @item @code{-gnatw.b}
10995 @emph{Activate warnings on biased representation.}
10997 @geindex Biased representation
10999 This switch activates warnings when a size clause, value size clause, component
11000 clause, or component size clause forces the use of biased representation for an
11001 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
11002 to represent 10/11). The default is that such warnings are generated.
11003 @end table
11005 @geindex -gnatwB (gcc)
11008 @table @asis
11010 @item @code{-gnatw.B}
11012 @emph{Suppress warnings on biased representation.}
11014 This switch suppresses warnings for representation clauses that force the use
11015 of biased representation.
11016 @end table
11018 @geindex -gnatwc (gcc)
11021 @table @asis
11023 @item @code{-gnatwc}
11025 @emph{Activate warnings on conditionals.}
11027 @geindex Conditionals
11028 @geindex constant
11030 This switch activates warnings for conditional expressions used in
11031 tests that are known to be True or False at compile time. The default
11032 is that such warnings are not generated.
11033 Note that this warning does
11034 not get issued for the use of boolean variables or constants whose
11035 values are known at compile time, since this is a standard technique
11036 for conditional compilation in Ada, and this would generate too many
11037 false positive warnings.
11039 This warning option also activates a special test for comparisons using
11040 the operators '>=' and' <='.
11041 If the compiler can tell that only the equality condition is possible,
11042 then it will warn that the '>' or '<' part of the test
11043 is useless and that the operator could be replaced by '='.
11044 An example would be comparing a @code{Natural} variable <= 0.
11046 This warning option also generates warnings if
11047 one or both tests is optimized away in a membership test for integer
11048 values if the result can be determined at compile time. Range tests on
11049 enumeration types are not included, since it is common for such tests
11050 to include an end point.
11052 This warning can also be turned on using @code{-gnatwa}.
11053 @end table
11055 @geindex -gnatwC (gcc)
11058 @table @asis
11060 @item @code{-gnatwC}
11062 @emph{Suppress warnings on conditionals.}
11064 This switch suppresses warnings for conditional expressions used in
11065 tests that are known to be True or False at compile time.
11066 @end table
11068 @geindex -gnatw.c (gcc)
11071 @table @asis
11073 @item @code{-gnatw.c}
11075 @emph{Activate warnings on missing component clauses.}
11077 @geindex Component clause
11078 @geindex missing
11080 This switch activates warnings for record components where a record
11081 representation clause is present and has component clauses for the
11082 majority, but not all, of the components. A warning is given for each
11083 component for which no component clause is present.
11084 @end table
11086 @geindex -gnatwC (gcc)
11089 @table @asis
11091 @item @code{-gnatw.C}
11093 @emph{Suppress warnings on missing component clauses.}
11095 This switch suppresses warnings for record components that are
11096 missing a component clause in the situation described above.
11097 @end table
11099 @geindex -gnatwd (gcc)
11102 @table @asis
11104 @item @code{-gnatwd}
11106 @emph{Activate warnings on implicit dereferencing.}
11108 If this switch is set, then the use of a prefix of an access type
11109 in an indexed component, slice, or selected component without an
11110 explicit @code{.all} will generate a warning. With this warning
11111 enabled, access checks occur only at points where an explicit
11112 @code{.all} appears in the source code (assuming no warnings are
11113 generated as a result of this switch). The default is that such
11114 warnings are not generated.
11115 @end table
11117 @geindex -gnatwD (gcc)
11120 @table @asis
11122 @item @code{-gnatwD}
11124 @emph{Suppress warnings on implicit dereferencing.}
11126 @geindex Implicit dereferencing
11128 @geindex Dereferencing
11129 @geindex implicit
11131 This switch suppresses warnings for implicit dereferences in
11132 indexed components, slices, and selected components.
11133 @end table
11135 @geindex -gnatw.d (gcc)
11138 @table @asis
11140 @item @code{-gnatw.d}
11142 @emph{Activate tagging of warning and info messages.}
11144 If this switch is set, then warning messages are tagged, with one of the
11145 following strings:
11147 @quotation
11150 @itemize -
11152 @item 
11153 @emph{[-gnatw?]}
11154 Used to tag warnings controlled by the switch @code{-gnatwx} where x
11155 is a letter a-z.
11157 @item 
11158 @emph{[-gnatw.?]}
11159 Used to tag warnings controlled by the switch @code{-gnatw.x} where x
11160 is a letter a-z.
11162 @item 
11163 @emph{[-gnatel]}
11164 Used to tag elaboration information (info) messages generated when the
11165 static model of elaboration is used and the @code{-gnatel} switch is set.
11167 @item 
11168 @emph{[restriction warning]}
11169 Used to tag warning messages for restriction violations, activated by use
11170 of the pragma @code{Restriction_Warnings}.
11172 @item 
11173 @emph{[warning-as-error]}
11174 Used to tag warning messages that have been converted to error messages by
11175 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11176 the string "error: " rather than "warning: ".
11178 @item 
11179 @emph{[enabled by default]}
11180 Used to tag all other warnings that are always given by default, unless
11181 warnings are completely suppressed using pragma @emph{Warnings(Off)} or
11182 the switch @code{-gnatws}.
11183 @end itemize
11184 @end quotation
11185 @end table
11187 @geindex -gnatw.d (gcc)
11190 @table @asis
11192 @item @code{-gnatw.D}
11194 @emph{Deactivate tagging of warning and info messages messages.}
11196 If this switch is set, then warning messages return to the default
11197 mode in which warnings and info messages are not tagged as described above for
11198 @code{-gnatw.d}.
11199 @end table
11201 @geindex -gnatwe (gcc)
11203 @geindex Warnings
11204 @geindex treat as error
11207 @table @asis
11209 @item @code{-gnatwe}
11211 @emph{Treat warnings and style checks as errors.}
11213 This switch causes warning messages and style check messages to be
11214 treated as errors.
11215 The warning string still appears, but the warning messages are counted
11216 as errors, and prevent the generation of an object file. Note that this
11217 is the only -gnatw switch that affects the handling of style check messages.
11218 Note also that this switch has no effect on info (information) messages, which
11219 are not treated as errors if this switch is present.
11220 @end table
11222 @geindex -gnatw.e (gcc)
11225 @table @asis
11227 @item @code{-gnatw.e}
11229 @emph{Activate every optional warning.}
11231 @geindex Warnings
11232 @geindex activate every optional warning
11234 This switch activates all optional warnings, including those which
11235 are not activated by @code{-gnatwa}. The use of this switch is not
11236 recommended for normal use. If you turn this switch on, it is almost
11237 certain that you will get large numbers of useless warnings. The
11238 warnings that are excluded from @code{-gnatwa} are typically highly
11239 specialized warnings that are suitable for use only in code that has
11240 been specifically designed according to specialized coding rules.
11241 @end table
11243 @geindex -gnatwE (gcc)
11245 @geindex Warnings
11246 @geindex treat as error
11249 @table @asis
11251 @item @code{-gnatwE}
11253 @emph{Treat all run-time exception warnings as errors.}
11255 This switch causes warning messages regarding errors that will be raised
11256 during run-time execution to be treated as errors.
11257 @end table
11259 @geindex -gnatwf (gcc)
11262 @table @asis
11264 @item @code{-gnatwf}
11266 @emph{Activate warnings on unreferenced formals.}
11268 @geindex Formals
11269 @geindex unreferenced
11271 This switch causes a warning to be generated if a formal parameter
11272 is not referenced in the body of the subprogram. This warning can
11273 also be turned on using @code{-gnatwu}. The
11274 default is that these warnings are not generated.
11275 @end table
11277 @geindex -gnatwF (gcc)
11280 @table @asis
11282 @item @code{-gnatwF}
11284 @emph{Suppress warnings on unreferenced formals.}
11286 This switch suppresses warnings for unreferenced formal
11287 parameters. Note that the
11288 combination @code{-gnatwu} followed by @code{-gnatwF} has the
11289 effect of warning on unreferenced entities other than subprogram
11290 formals.
11291 @end table
11293 @geindex -gnatwg (gcc)
11296 @table @asis
11298 @item @code{-gnatwg}
11300 @emph{Activate warnings on unrecognized pragmas.}
11302 @geindex Pragmas
11303 @geindex unrecognized
11305 This switch causes a warning to be generated if an unrecognized
11306 pragma is encountered. Apart from issuing this warning, the
11307 pragma is ignored and has no effect. The default
11308 is that such warnings are issued (satisfying the Ada Reference
11309 Manual requirement that such warnings appear).
11310 @end table
11312 @geindex -gnatwG (gcc)
11315 @table @asis
11317 @item @code{-gnatwG}
11319 @emph{Suppress warnings on unrecognized pragmas.}
11321 This switch suppresses warnings for unrecognized pragmas.
11322 @end table
11324 @geindex -gnatw.g (gcc)
11327 @table @asis
11329 @item @code{-gnatw.g}
11331 @emph{Warnings used for GNAT sources.}
11333 This switch sets the warning categories that are used by the standard
11334 GNAT style. Currently this is equivalent to
11335 @code{-gnatwAao.q.s.CI.V.X.Z}
11336 but more warnings may be added in the future without advanced notice.
11337 @end table
11339 @geindex -gnatwh (gcc)
11342 @table @asis
11344 @item @code{-gnatwh}
11346 @emph{Activate warnings on hiding.}
11348 @geindex Hiding of Declarations
11350 This switch activates warnings on hiding declarations that are considered
11351 potentially confusing. Not all cases of hiding cause warnings; for example an
11352 overriding declaration hides an implicit declaration, which is just normal
11353 code. The default is that warnings on hiding are not generated.
11354 @end table
11356 @geindex -gnatwH (gcc)
11359 @table @asis
11361 @item @code{-gnatwH}
11363 @emph{Suppress warnings on hiding.}
11365 This switch suppresses warnings on hiding declarations.
11366 @end table
11368 @geindex -gnatw.h (gcc)
11371 @table @asis
11373 @item @code{-gnatw.h}
11375 @emph{Activate warnings on holes/gaps in records.}
11377 @geindex Record Representation (gaps)
11379 This switch activates warnings on component clauses in record
11380 representation clauses that leave holes (gaps) in the record layout.
11381 If this warning option is active, then record representation clauses
11382 should specify a contiguous layout, adding unused fill fields if needed.
11383 @end table
11385 @geindex -gnatw.H (gcc)
11388 @table @asis
11390 @item @code{-gnatw.H}
11392 @emph{Suppress warnings on holes/gaps in records.}
11394 This switch suppresses warnings on component clauses in record
11395 representation clauses that leave holes (haps) in the record layout.
11396 @end table
11398 @geindex -gnatwi (gcc)
11401 @table @asis
11403 @item @code{-gnatwi}
11405 @emph{Activate warnings on implementation units.}
11407 This switch activates warnings for a @emph{with} of an internal GNAT
11408 implementation unit, defined as any unit from the @code{Ada},
11409 @code{Interfaces}, @code{GNAT},
11410 or @code{System}
11411 hierarchies that is not
11412 documented in either the Ada Reference Manual or the GNAT
11413 Programmer's Reference Manual. Such units are intended only
11414 for internal implementation purposes and should not be @emph{with}ed
11415 by user programs. The default is that such warnings are generated
11416 @end table
11418 @geindex -gnatwI (gcc)
11421 @table @asis
11423 @item @code{-gnatwI}
11425 @emph{Disable warnings on implementation units.}
11427 This switch disables warnings for a @emph{with} of an internal GNAT
11428 implementation unit.
11429 @end table
11431 @geindex -gnatw.i (gcc)
11434 @table @asis
11436 @item @code{-gnatw.i}
11438 @emph{Activate warnings on overlapping actuals.}
11440 This switch enables a warning on statically detectable overlapping actuals in
11441 a subprogram call, when one of the actuals is an in-out parameter, and the
11442 types of the actuals are not by-copy types. This warning is off by default.
11443 @end table
11445 @geindex -gnatw.I (gcc)
11448 @table @asis
11450 @item @code{-gnatw.I}
11452 @emph{Disable warnings on overlapping actuals.}
11454 This switch disables warnings on overlapping actuals in a call..
11455 @end table
11457 @geindex -gnatwj (gcc)
11460 @table @asis
11462 @item @code{-gnatwj}
11464 @emph{Activate warnings on obsolescent features (Annex J).}
11466 @geindex Features
11467 @geindex obsolescent
11469 @geindex Obsolescent features
11471 If this warning option is activated, then warnings are generated for
11472 calls to subprograms marked with @code{pragma Obsolescent} and
11473 for use of features in Annex J of the Ada Reference Manual. In the
11474 case of Annex J, not all features are flagged. In particular use
11475 of the renamed packages (like @code{Text_IO}) and use of package
11476 @code{ASCII} are not flagged, since these are very common and
11477 would generate many annoying positive warnings. The default is that
11478 such warnings are not generated.
11480 In addition to the above cases, warnings are also generated for
11481 GNAT features that have been provided in past versions but which
11482 have been superseded (typically by features in the new Ada standard).
11483 For example, @code{pragma Ravenscar} will be flagged since its
11484 function is replaced by @code{pragma Profile(Ravenscar)}, and
11485 @code{pragma Interface_Name} will be flagged since its function
11486 is replaced by @code{pragma Import}.
11488 Note that this warning option functions differently from the
11489 restriction @code{No_Obsolescent_Features} in two respects.
11490 First, the restriction applies only to annex J features.
11491 Second, the restriction does flag uses of package @code{ASCII}.
11492 @end table
11494 @geindex -gnatwJ (gcc)
11497 @table @asis
11499 @item @code{-gnatwJ}
11501 @emph{Suppress warnings on obsolescent features (Annex J).}
11503 This switch disables warnings on use of obsolescent features.
11504 @end table
11506 @geindex -gnatw.j (gcc)
11509 @table @asis
11511 @item @code{-gnatw.j}
11513 @emph{Activate warnings on late declarations of tagged type primitives.}
11515 This switch activates warnings on visible primitives added to a
11516 tagged type after deriving a private extension from it.
11517 @end table
11519 @geindex -gnatw.J (gcc)
11522 @table @asis
11524 @item @code{-gnatw.J}
11526 @emph{Suppress warnings on late declarations of tagged type primitives.}
11528 This switch suppresses warnings on visible primitives added to a
11529 tagged type after deriving a private extension from it.
11530 @end table
11532 @geindex -gnatwk (gcc)
11535 @table @asis
11537 @item @code{-gnatwk}
11539 @emph{Activate warnings on variables that could be constants.}
11541 This switch activates warnings for variables that are initialized but
11542 never modified, and then could be declared constants. The default is that
11543 such warnings are not given.
11544 @end table
11546 @geindex -gnatwK (gcc)
11549 @table @asis
11551 @item @code{-gnatwK}
11553 @emph{Suppress warnings on variables that could be constants.}
11555 This switch disables warnings on variables that could be declared constants.
11556 @end table
11558 @geindex -gnatw.k (gcc)
11561 @table @asis
11563 @item @code{-gnatw.k}
11565 @emph{Activate warnings on redefinition of names in standard.}
11567 This switch activates warnings for declarations that declare a name that
11568 is defined in package Standard. Such declarations can be confusing,
11569 especially since the names in package Standard continue to be directly
11570 visible, meaning that use visibiliy on such redeclared names does not
11571 work as expected. Names of discriminants and components in records are
11572 not included in this check.
11573 @end table
11575 @geindex -gnatwK (gcc)
11578 @table @asis
11580 @item @code{-gnatw.K}
11582 @emph{Suppress warnings on redefinition of names in standard.}
11584 This switch activates warnings for declarations that declare a name that
11585 is defined in package Standard.
11586 @end table
11588 @geindex -gnatwl (gcc)
11591 @table @asis
11593 @item @code{-gnatwl}
11595 @emph{Activate warnings for elaboration pragmas.}
11597 @geindex Elaboration
11598 @geindex warnings
11600 This switch activates warnings for possible elaboration problems,
11601 including suspicious use
11602 of @code{Elaborate} pragmas, when using the static elaboration model, and
11603 possible situations that may raise @code{Program_Error} when using the
11604 dynamic elaboration model.
11605 See the section in this guide on elaboration checking for further details.
11606 The default is that such warnings
11607 are not generated.
11608 @end table
11610 @geindex -gnatwL (gcc)
11613 @table @asis
11615 @item @code{-gnatwL}
11617 @emph{Suppress warnings for elaboration pragmas.}
11619 This switch suppresses warnings for possible elaboration problems.
11620 @end table
11622 @geindex -gnatw.l (gcc)
11625 @table @asis
11627 @item @code{-gnatw.l}
11629 @emph{List inherited aspects.}
11631 This switch causes the compiler to list inherited invariants,
11632 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
11633 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
11634 @end table
11636 @geindex -gnatw.L (gcc)
11639 @table @asis
11641 @item @code{-gnatw.L}
11643 @emph{Suppress listing of inherited aspects.}
11645 This switch suppresses listing of inherited aspects.
11646 @end table
11648 @geindex -gnatwm (gcc)
11651 @table @asis
11653 @item @code{-gnatwm}
11655 @emph{Activate warnings on modified but unreferenced variables.}
11657 This switch activates warnings for variables that are assigned (using
11658 an initialization value or with one or more assignment statements) but
11659 whose value is never read. The warning is suppressed for volatile
11660 variables and also for variables that are renamings of other variables
11661 or for which an address clause is given.
11662 The default is that these warnings are not given.
11663 @end table
11665 @geindex -gnatwM (gcc)
11668 @table @asis
11670 @item @code{-gnatwM}
11672 @emph{Disable warnings on modified but unreferenced variables.}
11674 This switch disables warnings for variables that are assigned or
11675 initialized, but never read.
11676 @end table
11678 @geindex -gnatw.m (gcc)
11681 @table @asis
11683 @item @code{-gnatw.m}
11685 @emph{Activate warnings on suspicious modulus values.}
11687 This switch activates warnings for modulus values that seem suspicious.
11688 The cases caught are where the size is the same as the modulus (e.g.
11689 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11690 with no size clause. The guess in both cases is that 2**x was intended
11691 rather than x. In addition expressions of the form 2*x for small x
11692 generate a warning (the almost certainly accurate guess being that
11693 2**x was intended). The default is that these warnings are given.
11694 @end table
11696 @geindex -gnatw.M (gcc)
11699 @table @asis
11701 @item @code{-gnatw.M}
11703 @emph{Disable warnings on suspicious modulus values.}
11705 This switch disables warnings for suspicious modulus values.
11706 @end table
11708 @geindex -gnatwn (gcc)
11711 @table @asis
11713 @item @code{-gnatwn}
11715 @emph{Set normal warnings mode.}
11717 This switch sets normal warning mode, in which enabled warnings are
11718 issued and treated as warnings rather than errors. This is the default
11719 mode. the switch @code{-gnatwn} can be used to cancel the effect of
11720 an explicit @code{-gnatws} or
11721 @code{-gnatwe}. It also cancels the effect of the
11722 implicit @code{-gnatwe} that is activated by the
11723 use of @code{-gnatg}.
11724 @end table
11726 @geindex -gnatw.n (gcc)
11728 @geindex Atomic Synchronization
11729 @geindex warnings
11732 @table @asis
11734 @item @code{-gnatw.n}
11736 @emph{Activate warnings on atomic synchronization.}
11738 This switch actives warnings when an access to an atomic variable
11739 requires the generation of atomic synchronization code. These
11740 warnings are off by default.
11741 @end table
11743 @geindex -gnatw.N (gcc)
11746 @table @asis
11748 @item @code{-gnatw.N}
11750 @emph{Suppress warnings on atomic synchronization.}
11752 @geindex Atomic Synchronization
11753 @geindex warnings
11755 This switch suppresses warnings when an access to an atomic variable
11756 requires the generation of atomic synchronization code.
11757 @end table
11759 @geindex -gnatwo (gcc)
11761 @geindex Address Clauses
11762 @geindex warnings
11765 @table @asis
11767 @item @code{-gnatwo}
11769 @emph{Activate warnings on address clause overlays.}
11771 This switch activates warnings for possibly unintended initialization
11772 effects of defining address clauses that cause one variable to overlap
11773 another. The default is that such warnings are generated.
11774 @end table
11776 @geindex -gnatwO (gcc)
11779 @table @asis
11781 @item @code{-gnatwO}
11783 @emph{Suppress warnings on address clause overlays.}
11785 This switch suppresses warnings on possibly unintended initialization
11786 effects of defining address clauses that cause one variable to overlap
11787 another.
11788 @end table
11790 @geindex -gnatw.o (gcc)
11793 @table @asis
11795 @item @code{-gnatw.o}
11797 @emph{Activate warnings on modified but unreferenced out parameters.}
11799 This switch activates warnings for variables that are modified by using
11800 them as actuals for a call to a procedure with an out mode formal, where
11801 the resulting assigned value is never read. It is applicable in the case
11802 where there is more than one out mode formal. If there is only one out
11803 mode formal, the warning is issued by default (controlled by -gnatwu).
11804 The warning is suppressed for volatile
11805 variables and also for variables that are renamings of other variables
11806 or for which an address clause is given.
11807 The default is that these warnings are not given.
11808 @end table
11810 @geindex -gnatw.O (gcc)
11813 @table @asis
11815 @item @code{-gnatw.O}
11817 @emph{Disable warnings on modified but unreferenced out parameters.}
11819 This switch suppresses warnings for variables that are modified by using
11820 them as actuals for a call to a procedure with an out mode formal, where
11821 the resulting assigned value is never read.
11822 @end table
11824 @geindex -gnatwp (gcc)
11826 @geindex Inlining
11827 @geindex warnings
11830 @table @asis
11832 @item @code{-gnatwp}
11834 @emph{Activate warnings on ineffective pragma Inlines.}
11836 This switch activates warnings for failure of front end inlining
11837 (activated by @code{-gnatN}) to inline a particular call. There are
11838 many reasons for not being able to inline a call, including most
11839 commonly that the call is too complex to inline. The default is
11840 that such warnings are not given.
11841 Warnings on ineffective inlining by the gcc back-end can be activated
11842 separately, using the gcc switch -Winline.
11843 @end table
11845 @geindex -gnatwP (gcc)
11848 @table @asis
11850 @item @code{-gnatwP}
11852 @emph{Suppress warnings on ineffective pragma Inlines.}
11854 This switch suppresses warnings on ineffective pragma Inlines. If the
11855 inlining mechanism cannot inline a call, it will simply ignore the
11856 request silently.
11857 @end table
11859 @geindex -gnatw.p (gcc)
11861 @geindex Parameter order
11862 @geindex warnings
11865 @table @asis
11867 @item @code{-gnatw.p}
11869 @emph{Activate warnings on parameter ordering.}
11871 This switch activates warnings for cases of suspicious parameter
11872 ordering when the list of arguments are all simple identifiers that
11873 match the names of the formals, but are in a different order. The
11874 warning is suppressed if any use of named parameter notation is used,
11875 so this is the appropriate way to suppress a false positive (and
11876 serves to emphasize that the "misordering" is deliberate). The
11877 default is that such warnings are not given.
11878 @end table
11880 @geindex -gnatw.P (gcc)
11883 @table @asis
11885 @item @code{-gnatw.P}
11887 @emph{Suppress warnings on parameter ordering.}
11889 This switch suppresses warnings on cases of suspicious parameter
11890 ordering.
11891 @end table
11893 @geindex -gnatwq (gcc)
11895 @geindex Parentheses
11896 @geindex warnings
11899 @table @asis
11901 @item @code{-gnatwq}
11903 @emph{Activate warnings on questionable missing parentheses.}
11905 This switch activates warnings for cases where parentheses are not used and
11906 the result is potential ambiguity from a readers point of view. For example
11907 (not a > b) when a and b are modular means ((not a) > b) and very likely the
11908 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11909 quite likely ((-x) mod 5) was intended. In such situations it seems best to
11910 follow the rule of always parenthesizing to make the association clear, and
11911 this warning switch warns if such parentheses are not present. The default
11912 is that these warnings are given.
11913 @end table
11915 @geindex -gnatwQ (gcc)
11918 @table @asis
11920 @item @code{-gnatwQ}
11922 @emph{Suppress warnings on questionable missing parentheses.}
11924 This switch suppresses warnings for cases where the association is not
11925 clear and the use of parentheses is preferred.
11926 @end table
11928 @geindex -gnatw.q (gcc)
11930 @geindex Layout
11931 @geindex warnings
11934 @table @asis
11936 @item @code{-gnatw.q}
11938 @emph{Activate warnings on questionable layout of record types.}
11940 This switch activates warnings for cases where the default layout of
11941 a record type, that is to say the layout of its components in textual
11942 order of the source code, would very likely cause inefficiencies in
11943 the code generated by the compiler, both in terms of space and speed
11944 during execution. One warning is issued for each problematic component
11945 without representation clause in the nonvariant part and then in each
11946 variant recursively, if any.
11948 The purpose of these warnings is neither to prescribe an optimal layout
11949 nor to force the use of representation clauses, but rather to get rid of
11950 the most blatant inefficiencies in the layout. Therefore, the default
11951 layout is matched against the following synthetic ordered layout and
11952 the deviations are flagged on a component-by-component basis:
11955 @itemize *
11957 @item 
11958 first all components or groups of components whose length is fixed
11959 and a multiple of the storage unit,
11961 @item 
11962 then the remaining components whose length is fixed and not a multiple
11963 of the storage unit,
11965 @item 
11966 then the remaining components whose length doesn't depend on discriminants
11967 (that is to say, with variable but uniform length for all objects),
11969 @item 
11970 then all components whose length depends on discriminants,
11972 @item 
11973 finally the variant part (if any),
11974 @end itemize
11976 for the nonvariant part and for each variant recursively, if any.
11978 The exact wording of the warning depends on whether the compiler is allowed
11979 to reorder the components in the record type or precluded from doing it by
11980 means of pragma @code{No_Component_Reordering}.
11982 The default is that these warnings are not given.
11983 @end table
11985 @geindex -gnatw.Q (gcc)
11988 @table @asis
11990 @item @code{-gnatw.Q}
11992 @emph{Suppress warnings on questionable layout of record types.}
11994 This switch suppresses warnings for cases where the default layout of
11995 a record type would very likely cause inefficiencies.
11996 @end table
11998 @geindex -gnatwr (gcc)
12001 @table @asis
12003 @item @code{-gnatwr}
12005 @emph{Activate warnings on redundant constructs.}
12007 This switch activates warnings for redundant constructs. The following
12008 is the current list of constructs regarded as redundant:
12011 @itemize *
12013 @item 
12014 Assignment of an item to itself.
12016 @item 
12017 Type conversion that converts an expression to its own type.
12019 @item 
12020 Use of the attribute @code{Base} where @code{typ'Base} is the same
12021 as @code{typ}.
12023 @item 
12024 Use of pragma @code{Pack} when all components are placed by a record
12025 representation clause.
12027 @item 
12028 Exception handler containing only a reraise statement (raise with no
12029 operand) which has no effect.
12031 @item 
12032 Use of the operator abs on an operand that is known at compile time
12033 to be non-negative
12035 @item 
12036 Comparison of an object or (unary or binary) operation of boolean type to
12037 an explicit True value.
12038 @end itemize
12040 The default is that warnings for redundant constructs are not given.
12041 @end table
12043 @geindex -gnatwR (gcc)
12046 @table @asis
12048 @item @code{-gnatwR}
12050 @emph{Suppress warnings on redundant constructs.}
12052 This switch suppresses warnings for redundant constructs.
12053 @end table
12055 @geindex -gnatw.r (gcc)
12058 @table @asis
12060 @item @code{-gnatw.r}
12062 @emph{Activate warnings for object renaming function.}
12064 This switch activates warnings for an object renaming that renames a
12065 function call, which is equivalent to a constant declaration (as
12066 opposed to renaming the function itself).  The default is that these
12067 warnings are given.
12068 @end table
12070 @geindex -gnatwT (gcc)
12073 @table @asis
12075 @item @code{-gnatw.R}
12077 @emph{Suppress warnings for object renaming function.}
12079 This switch suppresses warnings for object renaming function.
12080 @end table
12082 @geindex -gnatws (gcc)
12085 @table @asis
12087 @item @code{-gnatws}
12089 @emph{Suppress all warnings.}
12091 This switch completely suppresses the
12092 output of all warning messages from the GNAT front end, including
12093 both warnings that can be controlled by switches described in this
12094 section, and those that are normally given unconditionally. The
12095 effect of this suppress action can only be cancelled by a subsequent
12096 use of the switch @code{-gnatwn}.
12098 Note that switch @code{-gnatws} does not suppress
12099 warnings from the @code{gcc} back end.
12100 To suppress these back end warnings as well, use the switch @code{-w}
12101 in addition to @code{-gnatws}. Also this switch has no effect on the
12102 handling of style check messages.
12103 @end table
12105 @geindex -gnatw.s (gcc)
12107 @geindex Record Representation (component sizes)
12110 @table @asis
12112 @item @code{-gnatw.s}
12114 @emph{Activate warnings on overridden size clauses.}
12116 This switch activates warnings on component clauses in record
12117 representation clauses where the length given overrides that
12118 specified by an explicit size clause for the component type. A
12119 warning is similarly given in the array case if a specified
12120 component size overrides an explicit size clause for the array
12121 component type.
12122 @end table
12124 @geindex -gnatw.S (gcc)
12127 @table @asis
12129 @item @code{-gnatw.S}
12131 @emph{Suppress warnings on overridden size clauses.}
12133 This switch suppresses warnings on component clauses in record
12134 representation clauses that override size clauses, and similar
12135 warnings when an array component size overrides a size clause.
12136 @end table
12138 @geindex -gnatwt (gcc)
12140 @geindex Deactivated code
12141 @geindex warnings
12143 @geindex Deleted code
12144 @geindex warnings
12147 @table @asis
12149 @item @code{-gnatwt}
12151 @emph{Activate warnings for tracking of deleted conditional code.}
12153 This switch activates warnings for tracking of code in conditionals (IF and
12154 CASE statements) that is detected to be dead code which cannot be executed, and
12155 which is removed by the front end. This warning is off by default. This may be
12156 useful for detecting deactivated code in certified applications.
12157 @end table
12159 @geindex -gnatwT (gcc)
12162 @table @asis
12164 @item @code{-gnatwT}
12166 @emph{Suppress warnings for tracking of deleted conditional code.}
12168 This switch suppresses warnings for tracking of deleted conditional code.
12169 @end table
12171 @geindex -gnatw.t (gcc)
12174 @table @asis
12176 @item @code{-gnatw.t}
12178 @emph{Activate warnings on suspicious contracts.}
12180 This switch activates warnings on suspicious contracts. This includes
12181 warnings on suspicious postconditions (whether a pragma @code{Postcondition} or a
12182 @code{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
12183 @code{Contract_Cases}). A function postcondition or contract case is suspicious
12184 when no postcondition or contract case for this function mentions the result
12185 of the function.  A procedure postcondition or contract case is suspicious
12186 when it only refers to the pre-state of the procedure, because in that case
12187 it should rather be expressed as a precondition. This switch also controls
12188 warnings on suspicious cases of expressions typically found in contracts like
12189 quantified expressions and uses of Update attribute. The default is that such
12190 warnings are generated.
12191 @end table
12193 @geindex -gnatw.T (gcc)
12196 @table @asis
12198 @item @code{-gnatw.T}
12200 @emph{Suppress warnings on suspicious contracts.}
12202 This switch suppresses warnings on suspicious contracts.
12203 @end table
12205 @geindex -gnatwu (gcc)
12208 @table @asis
12210 @item @code{-gnatwu}
12212 @emph{Activate warnings on unused entities.}
12214 This switch activates warnings to be generated for entities that
12215 are declared but not referenced, and for units that are @emph{with}ed
12216 and not
12217 referenced. In the case of packages, a warning is also generated if
12218 no entities in the package are referenced. This means that if a with'ed
12219 package is referenced but the only references are in @code{use}
12220 clauses or @code{renames}
12221 declarations, a warning is still generated. A warning is also generated
12222 for a generic package that is @emph{with}ed but never instantiated.
12223 In the case where a package or subprogram body is compiled, and there
12224 is a @emph{with} on the corresponding spec
12225 that is only referenced in the body,
12226 a warning is also generated, noting that the
12227 @emph{with} can be moved to the body. The default is that
12228 such warnings are not generated.
12229 This switch also activates warnings on unreferenced formals
12230 (it includes the effect of @code{-gnatwf}).
12231 @end table
12233 @geindex -gnatwU (gcc)
12236 @table @asis
12238 @item @code{-gnatwU}
12240 @emph{Suppress warnings on unused entities.}
12242 This switch suppresses warnings for unused entities and packages.
12243 It also turns off warnings on unreferenced formals (and thus includes
12244 the effect of @code{-gnatwF}).
12245 @end table
12247 @geindex -gnatw.u (gcc)
12250 @table @asis
12252 @item @code{-gnatw.u}
12254 @emph{Activate warnings on unordered enumeration types.}
12256 This switch causes enumeration types to be considered as conceptually
12257 unordered, unless an explicit pragma @code{Ordered} is given for the type.
12258 The effect is to generate warnings in clients that use explicit comparisons
12259 or subranges, since these constructs both treat objects of the type as
12260 ordered. (A @emph{client} is defined as a unit that is other than the unit in
12261 which the type is declared, or its body or subunits.) Please refer to
12262 the description of pragma @code{Ordered} in the
12263 @cite{GNAT Reference Manual} for further details.
12264 The default is that such warnings are not generated.
12265 @end table
12267 @geindex -gnatw.U (gcc)
12270 @table @asis
12272 @item @code{-gnatw.U}
12274 @emph{Deactivate warnings on unordered enumeration types.}
12276 This switch causes all enumeration types to be considered as ordered, so
12277 that no warnings are given for comparisons or subranges for any type.
12278 @end table
12280 @geindex -gnatwv (gcc)
12282 @geindex Unassigned variable warnings
12285 @table @asis
12287 @item @code{-gnatwv}
12289 @emph{Activate warnings on unassigned variables.}
12291 This switch activates warnings for access to variables which
12292 may not be properly initialized. The default is that
12293 such warnings are generated.
12294 @end table
12296 @geindex -gnatwV (gcc)
12299 @table @asis
12301 @item @code{-gnatwV}
12303 @emph{Suppress warnings on unassigned variables.}
12305 This switch suppresses warnings for access to variables which
12306 may not be properly initialized.
12307 For variables of a composite type, the warning can also be suppressed in
12308 Ada 2005 by using a default initialization with a box. For example, if
12309 Table is an array of records whose components are only partially uninitialized,
12310 then the following code:
12312 @example
12313 Tab : Table := (others => <>);
12314 @end example
12316 will suppress warnings on subsequent statements that access components
12317 of variable Tab.
12318 @end table
12320 @geindex -gnatw.v (gcc)
12322 @geindex bit order warnings
12325 @table @asis
12327 @item @code{-gnatw.v}
12329 @emph{Activate info messages for non-default bit order.}
12331 This switch activates messages (labeled "info", they are not warnings,
12332 just informational messages) about the effects of non-default bit-order
12333 on records to which a component clause is applied. The effect of specifying
12334 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12335 these messages, which are given by default, are useful in understanding the
12336 exact consequences of using this feature.
12337 @end table
12339 @geindex -gnatw.V (gcc)
12342 @table @asis
12344 @item @code{-gnatw.V}
12346 @emph{Suppress info messages for non-default bit order.}
12348 This switch suppresses information messages for the effects of specifying
12349 non-default bit order on record components with component clauses.
12350 @end table
12352 @geindex -gnatww (gcc)
12354 @geindex String indexing warnings
12357 @table @asis
12359 @item @code{-gnatww}
12361 @emph{Activate warnings on wrong low bound assumption.}
12363 This switch activates warnings for indexing an unconstrained string parameter
12364 with a literal or S'Length. This is a case where the code is assuming that the
12365 low bound is one, which is in general not true (for example when a slice is
12366 passed). The default is that such warnings are generated.
12367 @end table
12369 @geindex -gnatwW (gcc)
12372 @table @asis
12374 @item @code{-gnatwW}
12376 @emph{Suppress warnings on wrong low bound assumption.}
12378 This switch suppresses warnings for indexing an unconstrained string parameter
12379 with a literal or S'Length. Note that this warning can also be suppressed
12380 in a particular case by adding an assertion that the lower bound is 1,
12381 as shown in the following example:
12383 @example
12384 procedure K (S : String) is
12385    pragma Assert (S'First = 1);
12386    ...
12387 @end example
12388 @end table
12390 @geindex -gnatw.w (gcc)
12392 @geindex Warnings Off control
12395 @table @asis
12397 @item @code{-gnatw.w}
12399 @emph{Activate warnings on Warnings Off pragmas.}
12401 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
12402 where either the pragma is entirely useless (because it suppresses no
12403 warnings), or it could be replaced by @code{pragma Unreferenced} or
12404 @code{pragma Unmodified}.
12405 Also activates warnings for the case of
12406 Warnings (Off, String), where either there is no matching
12407 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12408 The default is that these warnings are not given.
12409 @end table
12411 @geindex -gnatw.W (gcc)
12414 @table @asis
12416 @item @code{-gnatw.W}
12418 @emph{Suppress warnings on unnecessary Warnings Off pragmas.}
12420 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
12421 @end table
12423 @geindex -gnatwx (gcc)
12425 @geindex Export/Import pragma warnings
12428 @table @asis
12430 @item @code{-gnatwx}
12432 @emph{Activate warnings on Export/Import pragmas.}
12434 This switch activates warnings on Export/Import pragmas when
12435 the compiler detects a possible conflict between the Ada and
12436 foreign language calling sequences. For example, the use of
12437 default parameters in a convention C procedure is dubious
12438 because the C compiler cannot supply the proper default, so
12439 a warning is issued. The default is that such warnings are
12440 generated.
12441 @end table
12443 @geindex -gnatwX (gcc)
12446 @table @asis
12448 @item @code{-gnatwX}
12450 @emph{Suppress warnings on Export/Import pragmas.}
12452 This switch suppresses warnings on Export/Import pragmas.
12453 The sense of this is that you are telling the compiler that
12454 you know what you are doing in writing the pragma, and it
12455 should not complain at you.
12456 @end table
12458 @geindex -gnatwm (gcc)
12461 @table @asis
12463 @item @code{-gnatw.x}
12465 @emph{Activate warnings for No_Exception_Propagation mode.}
12467 This switch activates warnings for exception usage when pragma Restrictions
12468 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
12469 explicit exception raises which are not covered by a local handler, and for
12470 exception handlers which do not cover a local raise. The default is that
12471 these warnings are given for units that contain exception handlers.
12473 @item @code{-gnatw.X}
12475 @emph{Disable warnings for No_Exception_Propagation mode.}
12477 This switch disables warnings for exception usage when pragma Restrictions
12478 (No_Exception_Propagation) is in effect.
12479 @end table
12481 @geindex -gnatwy (gcc)
12483 @geindex Ada compatibility issues warnings
12486 @table @asis
12488 @item @code{-gnatwy}
12490 @emph{Activate warnings for Ada compatibility issues.}
12492 For the most part, newer versions of Ada are upwards compatible
12493 with older versions. For example, Ada 2005 programs will almost
12494 always work when compiled as Ada 2012.
12495 However there are some exceptions (for example the fact that
12496 @code{some} is now a reserved word in Ada 2012). This
12497 switch activates several warnings to help in identifying
12498 and correcting such incompatibilities. The default is that
12499 these warnings are generated. Note that at one point Ada 2005
12500 was called Ada 0Y, hence the choice of character.
12501 @end table
12503 @geindex -gnatwY (gcc)
12505 @geindex Ada compatibility issues warnings
12508 @table @asis
12510 @item @code{-gnatwY}
12512 @emph{Disable warnings for Ada compatibility issues.}
12514 This switch suppresses the warnings intended to help in identifying
12515 incompatibilities between Ada language versions.
12516 @end table
12518 @geindex -gnatw.y (gcc)
12520 @geindex Package spec needing body
12523 @table @asis
12525 @item @code{-gnatw.y}
12527 @emph{Activate information messages for why package spec needs body.}
12529 There are a number of cases in which a package spec needs a body.
12530 For example, the use of pragma Elaborate_Body, or the declaration
12531 of a procedure specification requiring a completion. This switch
12532 causes information messages to be output showing why a package
12533 specification requires a body. This can be useful in the case of
12534 a large package specification which is unexpectedly requiring a
12535 body. The default is that such information messages are not output.
12536 @end table
12538 @geindex -gnatw.Y (gcc)
12540 @geindex No information messages for why package spec needs body
12543 @table @asis
12545 @item @code{-gnatw.Y}
12547 @emph{Disable information messages for why package spec needs body.}
12549 This switch suppresses the output of information messages showing why
12550 a package specification needs a body.
12551 @end table
12553 @geindex -gnatwz (gcc)
12555 @geindex Unchecked_Conversion warnings
12558 @table @asis
12560 @item @code{-gnatwz}
12562 @emph{Activate warnings on unchecked conversions.}
12564 This switch activates warnings for unchecked conversions
12565 where the types are known at compile time to have different
12566 sizes. The default is that such warnings are generated. Warnings are also
12567 generated for subprogram pointers with different conventions.
12568 @end table
12570 @geindex -gnatwZ (gcc)
12573 @table @asis
12575 @item @code{-gnatwZ}
12577 @emph{Suppress warnings on unchecked conversions.}
12579 This switch suppresses warnings for unchecked conversions
12580 where the types are known at compile time to have different
12581 sizes or conventions.
12582 @end table
12584 @geindex -gnatw.z (gcc)
12586 @geindex Size/Alignment warnings
12589 @table @asis
12591 @item @code{-gnatw.z}
12593 @emph{Activate warnings for size not a multiple of alignment.}
12595 This switch activates warnings for cases of record types with
12596 specified @code{Size} and @code{Alignment} attributes where the
12597 size is not a multiple of the alignment, resulting in an object
12598 size that is greater than the specified size. The default
12599 is that such warnings are generated.
12600 @end table
12602 @geindex -gnatw.Z (gcc)
12604 @geindex Size/Alignment warnings
12607 @table @asis
12609 @item @code{-gnatw.Z}
12611 @emph{Suppress warnings for size not a multiple of alignment.}
12613 This switch suppresses warnings for cases of record types with
12614 specified @code{Size} and @code{Alignment} attributes where the
12615 size is not a multiple of the alignment, resulting in an object
12616 size that is greater than the specified size.
12617 The warning can also be
12618 suppressed by giving an explicit @code{Object_Size} value.
12619 @end table
12621 @geindex -Wunused (gcc)
12624 @table @asis
12626 @item @code{-Wunused}
12628 The warnings controlled by the @code{-gnatw} switch are generated by
12629 the front end of the compiler. The GCC back end can provide
12630 additional warnings and they are controlled by the @code{-W} switch.
12631 For example, @code{-Wunused} activates back end
12632 warnings for entities that are declared but not referenced.
12633 @end table
12635 @geindex -Wuninitialized (gcc)
12638 @table @asis
12640 @item @code{-Wuninitialized}
12642 Similarly, @code{-Wuninitialized} activates
12643 the back end warning for uninitialized variables. This switch must be
12644 used in conjunction with an optimization level greater than zero.
12645 @end table
12647 @geindex -Wstack-usage (gcc)
12650 @table @asis
12652 @item @code{-Wstack-usage=@emph{len}}
12654 Warn if the stack usage of a subprogram might be larger than @code{len} bytes.
12655 See @ref{f5,,Static Stack Usage Analysis} for details.
12656 @end table
12658 @geindex -Wall (gcc)
12661 @table @asis
12663 @item @code{-Wall}
12665 This switch enables most warnings from the GCC back end.
12666 The code generator detects a number of warning situations that are missed
12667 by the GNAT front end, and this switch can be used to activate them.
12668 The use of this switch also sets the default front end warning mode to
12669 @code{-gnatwa}, that is, most front end warnings activated as well.
12670 @end table
12672 @geindex -w (gcc)
12675 @table @asis
12677 @item @code{-w}
12679 Conversely, this switch suppresses warnings from the GCC back end.
12680 The use of this switch also sets the default front end warning mode to
12681 @code{-gnatws}, that is, front end warnings suppressed as well.
12682 @end table
12684 @geindex -Werror (gcc)
12687 @table @asis
12689 @item @code{-Werror}
12691 This switch causes warnings from the GCC back end to be treated as
12692 errors.  The warning string still appears, but the warning messages are
12693 counted as errors, and prevent the generation of an object file.
12694 @end table
12696 A string of warning parameters can be used in the same parameter. For example:
12698 @example
12699 -gnatwaGe
12700 @end example
12702 will turn on all optional warnings except for unrecognized pragma warnings,
12703 and also specify that warnings should be treated as errors.
12705 When no switch @code{-gnatw} is used, this is equivalent to:
12707 @quotation
12710 @itemize *
12712 @item 
12713 @code{-gnatw.a}
12715 @item 
12716 @code{-gnatwB}
12718 @item 
12719 @code{-gnatw.b}
12721 @item 
12722 @code{-gnatwC}
12724 @item 
12725 @code{-gnatw.C}
12727 @item 
12728 @code{-gnatwD}
12730 @item 
12731 @code{-gnatwF}
12733 @item 
12734 @code{-gnatwg}
12736 @item 
12737 @code{-gnatwH}
12739 @item 
12740 @code{-gnatwi}
12742 @item 
12743 @code{-gnatw.I}
12745 @item 
12746 @code{-gnatwJ}
12748 @item 
12749 @code{-gnatwK}
12751 @item 
12752 @code{-gnatwL}
12754 @item 
12755 @code{-gnatw.L}
12757 @item 
12758 @code{-gnatwM}
12760 @item 
12761 @code{-gnatw.m}
12763 @item 
12764 @code{-gnatwn}
12766 @item 
12767 @code{-gnatwo}
12769 @item 
12770 @code{-gnatw.O}
12772 @item 
12773 @code{-gnatwP}
12775 @item 
12776 @code{-gnatw.P}
12778 @item 
12779 @code{-gnatwq}
12781 @item 
12782 @code{-gnatw.Q}
12784 @item 
12785 @code{-gnatwR}
12787 @item 
12788 @code{-gnatw.R}
12790 @item 
12791 @code{-gnatw.S}
12793 @item 
12794 @code{-gnatwT}
12796 @item 
12797 @code{-gnatw.T}
12799 @item 
12800 @code{-gnatwU}
12802 @item 
12803 @code{-gnatwv}
12805 @item 
12806 @code{-gnatww}
12808 @item 
12809 @code{-gnatw.W}
12811 @item 
12812 @code{-gnatwx}
12814 @item 
12815 @code{-gnatw.X}
12817 @item 
12818 @code{-gnatwy}
12820 @item 
12821 @code{-gnatwz}
12822 @end itemize
12823 @end quotation
12825 @node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12826 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-and-assertion-control}@anchor{100}@anchor{gnat_ugn/building_executable_programs_with_gnat id16}@anchor{101}
12827 @subsection Debugging and Assertion Control
12830 @geindex -gnata (gcc)
12833 @table @asis
12835 @item @code{-gnata}
12837 @geindex Assert
12839 @geindex Debug
12841 @geindex Assertions
12843 @geindex Precondition
12845 @geindex Postcondition
12847 @geindex Type invariants
12849 @geindex Subtype predicates
12851 The @code{-gnata} option is equivalent to the following @code{Assertion_Policy} pragma:
12853 @example
12854 pragma Assertion_Policy (Check);
12855 @end example
12857 Which is a shorthand for:
12859 @example
12860 pragma Assertion_Policy
12861   (Assert               => Check,
12862    Static_Predicate     => Check,
12863    Dynamic_Predicate    => Check,
12864    Pre                  => Check,
12865    Pre'Class            => Check,
12866    Post                 => Check,
12867    Post'Class           => Check,
12868    Type_Invariant       => Check,
12869    Type_Invariant'Class => Check);
12870 @end example
12872 The pragmas @code{Assert} and @code{Debug} normally have no effect and
12873 are ignored. This switch, where @code{a} stands for 'assert', causes
12874 pragmas @code{Assert} and @code{Debug} to be activated. This switch also
12875 causes preconditions, postconditions, subtype predicates, and
12876 type invariants to be activated.
12878 The pragmas have the form:
12880 @example
12881 pragma Assert (<Boolean-expression> [, <static-string-expression>])
12882 pragma Debug (<procedure call>)
12883 pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
12884 pragma Predicate (<type-local-name>, <Boolean-expression>)
12885 pragma Precondition (<Boolean-expression>, <string-expression>)
12886 pragma Postcondition (<Boolean-expression>, <string-expression>)
12887 @end example
12889 The aspects have the form:
12891 @example
12892 with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
12893   => <Boolean-expression>;
12894 @end example
12896 The @code{Assert} pragma causes @code{Boolean-expression} to be tested.
12897 If the result is @code{True}, the pragma has no effect (other than
12898 possible side effects from evaluating the expression). If the result is
12899 @code{False}, the exception @code{Assert_Failure} declared in the package
12900 @code{System.Assertions} is raised (passing @code{static-string-expression}, if
12901 present, as the message associated with the exception). If no string
12902 expression is given, the default is a string containing the file name and
12903 line number of the pragma.
12905 The @code{Debug} pragma causes @code{procedure} to be called. Note that
12906 @code{pragma Debug} may appear within a declaration sequence, allowing
12907 debugging procedures to be called between declarations.
12909 For the aspect specification, the @code{Boolean-expression} is evaluated.
12910 If the result is @code{True}, the aspect has no effect. If the result
12911 is @code{False}, the exception @code{Assert_Failure} is raised.
12912 @end table
12914 @node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
12915 @anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{102}
12916 @subsection Validity Checking
12919 @geindex Validity Checking
12921 The Ada Reference Manual defines the concept of invalid values (see
12922 RM 13.9.1). The primary source of invalid values is uninitialized
12923 variables. A scalar variable that is left uninitialized may contain
12924 an invalid value; the concept of invalid does not apply to access or
12925 composite types.
12927 It is an error to read an invalid value, but the RM does not require
12928 run-time checks to detect such errors, except for some minimal
12929 checking to prevent erroneous execution (i.e. unpredictable
12930 behavior). This corresponds to the @code{-gnatVd} switch below,
12931 which is the default. For example, by default, if the expression of a
12932 case statement is invalid, it will raise Constraint_Error rather than
12933 causing a wild jump, and if an array index on the left-hand side of an
12934 assignment is invalid, it will raise Constraint_Error rather than
12935 overwriting an arbitrary memory location.
12937 The @code{-gnatVa} may be used to enable additional validity checks,
12938 which are not required by the RM. These checks are often very
12939 expensive (which is why the RM does not require them). These checks
12940 are useful in tracking down uninitialized variables, but they are
12941 not usually recommended for production builds, and in particular
12942 we do not recommend using these extra validity checking options in
12943 combination with optimization, since this can confuse the optimizer.
12944 If performance is a consideration, leading to the need to optimize,
12945 then the validity checking options should not be used.
12947 The other @code{-gnatV@emph{x}} switches below allow finer-grained
12948 control; you can enable whichever validity checks you desire. However,
12949 for most debugging purposes, @code{-gnatVa} is sufficient, and the
12950 default @code{-gnatVd} (i.e. standard Ada behavior) is usually
12951 sufficient for non-debugging use.
12953 The @code{-gnatB} switch tells the compiler to assume that all
12954 values are valid (that is, within their declared subtype range)
12955 except in the context of a use of the Valid attribute. This means
12956 the compiler can generate more efficient code, since the range
12957 of values is better known at compile time. However, an uninitialized
12958 variable can cause wild jumps and memory corruption in this mode.
12960 The @code{-gnatV@emph{x}} switch allows control over the validity
12961 checking mode as described below.
12962 The @code{x} argument is a string of letters that
12963 indicate validity checks that are performed or not performed in addition
12964 to the default checks required by Ada as described above.
12966 @geindex -gnatVa (gcc)
12969 @table @asis
12971 @item @code{-gnatVa}
12973 @emph{All validity checks.}
12975 All validity checks are turned on.
12976 That is, @code{-gnatVa} is
12977 equivalent to @code{gnatVcdfimorst}.
12978 @end table
12980 @geindex -gnatVc (gcc)
12983 @table @asis
12985 @item @code{-gnatVc}
12987 @emph{Validity checks for copies.}
12989 The right hand side of assignments, and the initializing values of
12990 object declarations are validity checked.
12991 @end table
12993 @geindex -gnatVd (gcc)
12996 @table @asis
12998 @item @code{-gnatVd}
13000 @emph{Default (RM) validity checks.}
13002 Some validity checks are done by default following normal Ada semantics
13003 (RM 13.9.1 (9-11)).
13004 A check is done in case statements that the expression is within the range
13005 of the subtype. If it is not, Constraint_Error is raised.
13006 For assignments to array components, a check is done that the expression used
13007 as index is within the range. If it is not, Constraint_Error is raised.
13008 Both these validity checks may be turned off using switch @code{-gnatVD}.
13009 They are turned on by default. If @code{-gnatVD} is specified, a subsequent
13010 switch @code{-gnatVd} will leave the checks turned on.
13011 Switch @code{-gnatVD} should be used only if you are sure that all such
13012 expressions have valid values. If you use this switch and invalid values
13013 are present, then the program is erroneous, and wild jumps or memory
13014 overwriting may occur.
13015 @end table
13017 @geindex -gnatVe (gcc)
13020 @table @asis
13022 @item @code{-gnatVe}
13024 @emph{Validity checks for elementary components.}
13026 In the absence of this switch, assignments to record or array components are
13027 not validity checked, even if validity checks for assignments generally
13028 (@code{-gnatVc}) are turned on. In Ada, assignment of composite values do not
13029 require valid data, but assignment of individual components does. So for
13030 example, there is a difference between copying the elements of an array with a
13031 slice assignment, compared to assigning element by element in a loop. This
13032 switch allows you to turn off validity checking for components, even when they
13033 are assigned component by component.
13034 @end table
13036 @geindex -gnatVf (gcc)
13039 @table @asis
13041 @item @code{-gnatVf}
13043 @emph{Validity checks for floating-point values.}
13045 In the absence of this switch, validity checking occurs only for discrete
13046 values. If @code{-gnatVf} is specified, then validity checking also applies
13047 for floating-point values, and NaNs and infinities are considered invalid,
13048 as well as out of range values for constrained types. Note that this means
13049 that standard IEEE infinity mode is not allowed. The exact contexts
13050 in which floating-point values are checked depends on the setting of other
13051 options. For example, @code{-gnatVif} or @code{-gnatVfi}
13052 (the order does not matter) specifies that floating-point parameters of mode
13053 @code{in} should be validity checked.
13054 @end table
13056 @geindex -gnatVi (gcc)
13059 @table @asis
13061 @item @code{-gnatVi}
13063 @emph{Validity checks for `@w{`}in`@w{`} mode parameters.}
13065 Arguments for parameters of mode @code{in} are validity checked in function
13066 and procedure calls at the point of call.
13067 @end table
13069 @geindex -gnatVm (gcc)
13072 @table @asis
13074 @item @code{-gnatVm}
13076 @emph{Validity checks for `@w{`}in out`@w{`} mode parameters.}
13078 Arguments for parameters of mode @code{in out} are validity checked in
13079 procedure calls at the point of call. The @code{'m'} here stands for
13080 modify, since this concerns parameters that can be modified by the call.
13081 Note that there is no specific option to test @code{out} parameters,
13082 but any reference within the subprogram will be tested in the usual
13083 manner, and if an invalid value is copied back, any reference to it
13084 will be subject to validity checking.
13085 @end table
13087 @geindex -gnatVn (gcc)
13090 @table @asis
13092 @item @code{-gnatVn}
13094 @emph{No validity checks.}
13096 This switch turns off all validity checking, including the default checking
13097 for case statements and left hand side subscripts. Note that the use of
13098 the switch @code{-gnatp} suppresses all run-time checks, including
13099 validity checks, and thus implies @code{-gnatVn}. When this switch
13100 is used, it cancels any other @code{-gnatV} previously issued.
13101 @end table
13103 @geindex -gnatVo (gcc)
13106 @table @asis
13108 @item @code{-gnatVo}
13110 @emph{Validity checks for operator and attribute operands.}
13112 Arguments for predefined operators and attributes are validity checked.
13113 This includes all operators in package @code{Standard},
13114 the shift operators defined as intrinsic in package @code{Interfaces}
13115 and operands for attributes such as @code{Pos}. Checks are also made
13116 on individual component values for composite comparisons, and on the
13117 expressions in type conversions and qualified expressions. Checks are
13118 also made on explicit ranges using @code{..} (e.g., slices, loops etc).
13119 @end table
13121 @geindex -gnatVp (gcc)
13124 @table @asis
13126 @item @code{-gnatVp}
13128 @emph{Validity checks for parameters.}
13130 This controls the treatment of parameters within a subprogram (as opposed
13131 to @code{-gnatVi} and @code{-gnatVm} which control validity testing
13132 of parameters on a call. If either of these call options is used, then
13133 normally an assumption is made within a subprogram that the input arguments
13134 have been validity checking at the point of call, and do not need checking
13135 again within a subprogram). If @code{-gnatVp} is set, then this assumption
13136 is not made, and parameters are not assumed to be valid, so their validity
13137 will be checked (or rechecked) within the subprogram.
13138 @end table
13140 @geindex -gnatVr (gcc)
13143 @table @asis
13145 @item @code{-gnatVr}
13147 @emph{Validity checks for function returns.}
13149 The expression in @code{return} statements in functions is validity
13150 checked.
13151 @end table
13153 @geindex -gnatVs (gcc)
13156 @table @asis
13158 @item @code{-gnatVs}
13160 @emph{Validity checks for subscripts.}
13162 All subscripts expressions are checked for validity, whether they appear
13163 on the right side or left side (in default mode only left side subscripts
13164 are validity checked).
13165 @end table
13167 @geindex -gnatVt (gcc)
13170 @table @asis
13172 @item @code{-gnatVt}
13174 @emph{Validity checks for tests.}
13176 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
13177 statements are checked, as well as guard expressions in entry calls.
13178 @end table
13180 The @code{-gnatV} switch may be followed by a string of letters
13181 to turn on a series of validity checking options.
13182 For example, @code{-gnatVcr}
13183 specifies that in addition to the default validity checking, copies and
13184 function return expressions are to be validity checked.
13185 In order to make it easier to specify the desired combination of effects,
13186 the upper case letters @code{CDFIMORST} may
13187 be used to turn off the corresponding lower case option.
13188 Thus @code{-gnatVaM} turns on all validity checking options except for
13189 checking of @code{in out} parameters.
13191 The specification of additional validity checking generates extra code (and
13192 in the case of @code{-gnatVa} the code expansion can be substantial).
13193 However, these additional checks can be very useful in detecting
13194 uninitialized variables, incorrect use of unchecked conversion, and other
13195 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
13196 is useful in conjunction with the extra validity checking, since this
13197 ensures that wherever possible uninitialized variables have invalid values.
13199 See also the pragma @code{Validity_Checks} which allows modification of
13200 the validity checking mode at the program source level, and also allows for
13201 temporary disabling of validity checks.
13203 @node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
13204 @anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{103}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{fb}
13205 @subsection Style Checking
13208 @geindex Style checking
13210 @geindex -gnaty (gcc)
13212 The @code{-gnatyx} switch causes the compiler to
13213 enforce specified style rules. A limited set of style rules has been used
13214 in writing the GNAT sources themselves. This switch allows user programs
13215 to activate all or some of these checks. If the source program fails a
13216 specified style check, an appropriate message is given, preceded by
13217 the character sequence '(style)'. This message does not prevent
13218 successful compilation (unless the @code{-gnatwe} switch is used).
13220 Note that this is by no means intended to be a general facility for
13221 checking arbitrary coding standards. It is simply an embedding of the
13222 style rules we have chosen for the GNAT sources. If you are starting
13223 a project which does not have established style standards, you may
13224 find it useful to adopt the entire set of GNAT coding standards, or
13225 some subset of them.
13228 The string @code{x} is a sequence of letters or digits
13229 indicating the particular style
13230 checks to be performed. The following checks are defined:
13232 @geindex -gnaty[0-9] (gcc)
13235 @table @asis
13237 @item @code{-gnaty0}
13239 @emph{Specify indentation level.}
13241 If a digit from 1-9 appears
13242 in the string after @code{-gnaty}
13243 then proper indentation is checked, with the digit indicating the
13244 indentation level required. A value of zero turns off this style check.
13245 The general style of required indentation is as specified by
13246 the examples in the Ada Reference Manual. Full line comments must be
13247 aligned with the @code{--} starting on a column that is a multiple of
13248 the alignment level, or they may be aligned the same way as the following
13249 non-blank line (this is useful when full line comments appear in the middle
13250 of a statement, or they may be aligned with the source line on the previous
13251 non-blank line.
13252 @end table
13254 @geindex -gnatya (gcc)
13257 @table @asis
13259 @item @code{-gnatya}
13261 @emph{Check attribute casing.}
13263 Attribute names, including the case of keywords such as @code{digits}
13264 used as attributes names, must be written in mixed case, that is, the
13265 initial letter and any letter following an underscore must be uppercase.
13266 All other letters must be lowercase.
13267 @end table
13269 @geindex -gnatyA (gcc)
13272 @table @asis
13274 @item @code{-gnatyA}
13276 @emph{Use of array index numbers in array attributes.}
13278 When using the array attributes First, Last, Range,
13279 or Length, the index number must be omitted for one-dimensional arrays
13280 and is required for multi-dimensional arrays.
13281 @end table
13283 @geindex -gnatyb (gcc)
13286 @table @asis
13288 @item @code{-gnatyb}
13290 @emph{Blanks not allowed at statement end.}
13292 Trailing blanks are not allowed at the end of statements. The purpose of this
13293 rule, together with h (no horizontal tabs), is to enforce a canonical format
13294 for the use of blanks to separate source tokens.
13295 @end table
13297 @geindex -gnatyB (gcc)
13300 @table @asis
13302 @item @code{-gnatyB}
13304 @emph{Check Boolean operators.}
13306 The use of AND/OR operators is not permitted except in the cases of modular
13307 operands, array operands, and simple stand-alone boolean variables or
13308 boolean constants. In all other cases @code{and then}/@cite{or else} are
13309 required.
13310 @end table
13312 @geindex -gnatyc (gcc)
13315 @table @asis
13317 @item @code{-gnatyc}
13319 @emph{Check comments, double space.}
13321 Comments must meet the following set of rules:
13324 @itemize *
13326 @item 
13327 The @code{--} that starts the column must either start in column one,
13328 or else at least one blank must precede this sequence.
13330 @item 
13331 Comments that follow other tokens on a line must have at least one blank
13332 following the @code{--} at the start of the comment.
13334 @item 
13335 Full line comments must have at least two blanks following the
13336 @code{--} that starts the comment, with the following exceptions.
13338 @item 
13339 A line consisting only of the @code{--} characters, possibly preceded
13340 by blanks is permitted.
13342 @item 
13343 A comment starting with @code{--x} where @code{x} is a special character
13344 is permitted.
13345 This allows proper processing of the output from specialized tools
13346 such as @code{gnatprep} (where @code{--!} is used) and in earlier versions of the SPARK
13347 annotation
13348 language (where @code{--#} is used). For the purposes of this rule, a
13349 special character is defined as being in one of the ASCII ranges
13350 @code{16#21#...16#2F#} or @code{16#3A#...16#3F#}.
13351 Note that this usage is not permitted
13352 in GNAT implementation units (i.e., when @code{-gnatg} is used).
13354 @item 
13355 A line consisting entirely of minus signs, possibly preceded by blanks, is
13356 permitted. This allows the construction of box comments where lines of minus
13357 signs are used to form the top and bottom of the box.
13359 @item 
13360 A comment that starts and ends with @code{--} is permitted as long as at
13361 least one blank follows the initial @code{--}. Together with the preceding
13362 rule, this allows the construction of box comments, as shown in the following
13363 example:
13365 @example
13366 ---------------------------
13367 -- This is a box comment --
13368 -- with two text lines.  --
13369 ---------------------------
13370 @end example
13371 @end itemize
13372 @end table
13374 @geindex -gnatyC (gcc)
13377 @table @asis
13379 @item @code{-gnatyC}
13381 @emph{Check comments, single space.}
13383 This is identical to @code{c} except that only one space
13384 is required following the @code{--} of a comment instead of two.
13385 @end table
13387 @geindex -gnatyd (gcc)
13390 @table @asis
13392 @item @code{-gnatyd}
13394 @emph{Check no DOS line terminators present.}
13396 All lines must be terminated by a single ASCII.LF
13397 character (in particular the DOS line terminator sequence CR/LF is not
13398 allowed).
13399 @end table
13401 @geindex -gnatye (gcc)
13404 @table @asis
13406 @item @code{-gnatye}
13408 @emph{Check end/exit labels.}
13410 Optional labels on @code{end} statements ending subprograms and on
13411 @code{exit} statements exiting named loops, are required to be present.
13412 @end table
13414 @geindex -gnatyf (gcc)
13417 @table @asis
13419 @item @code{-gnatyf}
13421 @emph{No form feeds or vertical tabs.}
13423 Neither form feeds nor vertical tab characters are permitted
13424 in the source text.
13425 @end table
13427 @geindex -gnatyg (gcc)
13430 @table @asis
13432 @item @code{-gnatyg}
13434 @emph{GNAT style mode.}
13436 The set of style check switches is set to match that used by the GNAT sources.
13437 This may be useful when developing code that is eventually intended to be
13438 incorporated into GNAT. Currently this is equivalent to @code{-gnatwydISux})
13439 but additional style switches may be added to this set in the future without
13440 advance notice.
13441 @end table
13443 @geindex -gnatyh (gcc)
13446 @table @asis
13448 @item @code{-gnatyh}
13450 @emph{No horizontal tabs.}
13452 Horizontal tab characters are not permitted in the source text.
13453 Together with the b (no blanks at end of line) check, this
13454 enforces a canonical form for the use of blanks to separate
13455 source tokens.
13456 @end table
13458 @geindex -gnatyi (gcc)
13461 @table @asis
13463 @item @code{-gnatyi}
13465 @emph{Check if-then layout.}
13467 The keyword @code{then} must appear either on the same
13468 line as corresponding @code{if}, or on a line on its own, lined
13469 up under the @code{if}.
13470 @end table
13472 @geindex -gnatyI (gcc)
13475 @table @asis
13477 @item @code{-gnatyI}
13479 @emph{check mode IN keywords.}
13481 Mode @code{in} (the default mode) is not
13482 allowed to be given explicitly. @code{in out} is fine,
13483 but not @code{in} on its own.
13484 @end table
13486 @geindex -gnatyk (gcc)
13489 @table @asis
13491 @item @code{-gnatyk}
13493 @emph{Check keyword casing.}
13495 All keywords must be in lower case (with the exception of keywords
13496 such as @code{digits} used as attribute names to which this check
13497 does not apply).
13498 @end table
13500 @geindex -gnatyl (gcc)
13503 @table @asis
13505 @item @code{-gnatyl}
13507 @emph{Check layout.}
13509 Layout of statement and declaration constructs must follow the
13510 recommendations in the Ada Reference Manual, as indicated by the
13511 form of the syntax rules. For example an @code{else} keyword must
13512 be lined up with the corresponding @code{if} keyword.
13514 There are two respects in which the style rule enforced by this check
13515 option are more liberal than those in the Ada Reference Manual. First
13516 in the case of record declarations, it is permissible to put the
13517 @code{record} keyword on the same line as the @code{type} keyword, and
13518 then the @code{end} in @code{end record} must line up under @code{type}.
13519 This is also permitted when the type declaration is split on two lines.
13520 For example, any of the following three layouts is acceptable:
13522 @example
13523 type q is record
13524    a : integer;
13525    b : integer;
13526 end record;
13528 type q is
13529    record
13530       a : integer;
13531       b : integer;
13532    end record;
13534 type q is
13535    record
13536       a : integer;
13537       b : integer;
13538 end record;
13539 @end example
13541 Second, in the case of a block statement, a permitted alternative
13542 is to put the block label on the same line as the @code{declare} or
13543 @code{begin} keyword, and then line the @code{end} keyword up under
13544 the block label. For example both the following are permitted:
13546 @example
13547 Block : declare
13548    A : Integer := 3;
13549 begin
13550    Proc (A, A);
13551 end Block;
13553 Block :
13554    declare
13555       A : Integer := 3;
13556    begin
13557       Proc (A, A);
13558    end Block;
13559 @end example
13561 The same alternative format is allowed for loops. For example, both of
13562 the following are permitted:
13564 @example
13565 Clear : while J < 10 loop
13566    A (J) := 0;
13567 end loop Clear;
13569 Clear :
13570    while J < 10 loop
13571       A (J) := 0;
13572    end loop Clear;
13573 @end example
13574 @end table
13576 @geindex -gnatyLnnn (gcc)
13579 @table @asis
13581 @item @code{-gnatyL}
13583 @emph{Set maximum nesting level.}
13585 The maximum level of nesting of constructs (including subprograms, loops,
13586 blocks, packages, and conditionals) may not exceed the given value
13587 @emph{nnn}. A value of zero disconnects this style check.
13588 @end table
13590 @geindex -gnatym (gcc)
13593 @table @asis
13595 @item @code{-gnatym}
13597 @emph{Check maximum line length.}
13599 The length of source lines must not exceed 79 characters, including
13600 any trailing blanks. The value of 79 allows convenient display on an
13601 80 character wide device or window, allowing for possible special
13602 treatment of 80 character lines. Note that this count is of
13603 characters in the source text. This means that a tab character counts
13604 as one character in this count and a wide character sequence counts as
13605 a single character (however many bytes are needed in the encoding).
13606 @end table
13608 @geindex -gnatyMnnn (gcc)
13611 @table @asis
13613 @item @code{-gnatyM}
13615 @emph{Set maximum line length.}
13617 The length of lines must not exceed the
13618 given value @emph{nnn}. The maximum value that can be specified is 32767.
13619 If neither style option for setting the line length is used, then the
13620 default is 255. This also controls the maximum length of lexical elements,
13621 where the only restriction is that they must fit on a single line.
13622 @end table
13624 @geindex -gnatyn (gcc)
13627 @table @asis
13629 @item @code{-gnatyn}
13631 @emph{Check casing of entities in Standard.}
13633 Any identifier from Standard must be cased
13634 to match the presentation in the Ada Reference Manual (for example,
13635 @code{Integer} and @code{ASCII.NUL}).
13636 @end table
13638 @geindex -gnatyN (gcc)
13641 @table @asis
13643 @item @code{-gnatyN}
13645 @emph{Turn off all style checks.}
13647 All style check options are turned off.
13648 @end table
13650 @geindex -gnatyo (gcc)
13653 @table @asis
13655 @item @code{-gnatyo}
13657 @emph{Check order of subprogram bodies.}
13659 All subprogram bodies in a given scope
13660 (e.g., a package body) must be in alphabetical order. The ordering
13661 rule uses normal Ada rules for comparing strings, ignoring casing
13662 of letters, except that if there is a trailing numeric suffix, then
13663 the value of this suffix is used in the ordering (e.g., Junk2 comes
13664 before Junk10).
13665 @end table
13667 @geindex -gnatyO (gcc)
13670 @table @asis
13672 @item @code{-gnatyO}
13674 @emph{Check that overriding subprograms are explicitly marked as such.}
13676 This applies to all subprograms of a derived type that override a primitive
13677 operation of the type, for both tagged and untagged types. In particular,
13678 the declaration of a primitive operation of a type extension that overrides
13679 an inherited operation must carry an overriding indicator. Another case is
13680 the declaration of a function that overrides a predefined operator (such
13681 as an equality operator).
13682 @end table
13684 @geindex -gnatyp (gcc)
13687 @table @asis
13689 @item @code{-gnatyp}
13691 @emph{Check pragma casing.}
13693 Pragma names must be written in mixed case, that is, the
13694 initial letter and any letter following an underscore must be uppercase.
13695 All other letters must be lowercase. An exception is that SPARK_Mode is
13696 allowed as an alternative for Spark_Mode.
13697 @end table
13699 @geindex -gnatyr (gcc)
13702 @table @asis
13704 @item @code{-gnatyr}
13706 @emph{Check references.}
13708 All identifier references must be cased in the same way as the
13709 corresponding declaration. No specific casing style is imposed on
13710 identifiers. The only requirement is for consistency of references
13711 with declarations.
13712 @end table
13714 @geindex -gnatys (gcc)
13717 @table @asis
13719 @item @code{-gnatys}
13721 @emph{Check separate specs.}
13723 Separate declarations ('specs') are required for subprograms (a
13724 body is not allowed to serve as its own declaration). The only
13725 exception is that parameterless library level procedures are
13726 not required to have a separate declaration. This exception covers
13727 the most frequent form of main program procedures.
13728 @end table
13730 @geindex -gnatyS (gcc)
13733 @table @asis
13735 @item @code{-gnatyS}
13737 @emph{Check no statements after then/else.}
13739 No statements are allowed
13740 on the same line as a @code{then} or @code{else} keyword following the
13741 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
13742 affected, and a special exception allows a pragma to appear after @code{else}.
13743 @end table
13745 @geindex -gnatyt (gcc)
13748 @table @asis
13750 @item @code{-gnatyt}
13752 @emph{Check token spacing.}
13754 The following token spacing rules are enforced:
13757 @itemize *
13759 @item 
13760 The keywords @code{abs} and @code{not} must be followed by a space.
13762 @item 
13763 The token @code{=>} must be surrounded by spaces.
13765 @item 
13766 The token @code{<>} must be preceded by a space or a left parenthesis.
13768 @item 
13769 Binary operators other than @code{**} must be surrounded by spaces.
13770 There is no restriction on the layout of the @code{**} binary operator.
13772 @item 
13773 Colon must be surrounded by spaces.
13775 @item 
13776 Colon-equal (assignment, initialization) must be surrounded by spaces.
13778 @item 
13779 Comma must be the first non-blank character on the line, or be
13780 immediately preceded by a non-blank character, and must be followed
13781 by a space.
13783 @item 
13784 If the token preceding a left parenthesis ends with a letter or digit, then
13785 a space must separate the two tokens.
13787 @item 
13788 If the token following a right parenthesis starts with a letter or digit, then
13789 a space must separate the two tokens.
13791 @item 
13792 A right parenthesis must either be the first non-blank character on
13793 a line, or it must be preceded by a non-blank character.
13795 @item 
13796 A semicolon must not be preceded by a space, and must not be followed by
13797 a non-blank character.
13799 @item 
13800 A unary plus or minus may not be followed by a space.
13802 @item 
13803 A vertical bar must be surrounded by spaces.
13804 @end itemize
13806 Exactly one blank (and no other white space) must appear between
13807 a @code{not} token and a following @code{in} token.
13808 @end table
13810 @geindex -gnatyu (gcc)
13813 @table @asis
13815 @item @code{-gnatyu}
13817 @emph{Check unnecessary blank lines.}
13819 Unnecessary blank lines are not allowed. A blank line is considered
13820 unnecessary if it appears at the end of the file, or if more than
13821 one blank line occurs in sequence.
13822 @end table
13824 @geindex -gnatyx (gcc)
13827 @table @asis
13829 @item @code{-gnatyx}
13831 @emph{Check extra parentheses.}
13833 Unnecessary extra level of parentheses (C-style) are not allowed
13834 around conditions in @code{if} statements, @code{while} statements and
13835 @code{exit} statements.
13836 @end table
13838 @geindex -gnatyy (gcc)
13841 @table @asis
13843 @item @code{-gnatyy}
13845 @emph{Set all standard style check options.}
13847 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
13848 options enabled with the exception of @code{-gnatyB}, @code{-gnatyd},
13849 @code{-gnatyI}, @code{-gnatyLnnn}, @code{-gnatyo}, @code{-gnatyO},
13850 @code{-gnatyS}, @code{-gnatyu}, and @code{-gnatyx}.
13851 @end table
13853 @geindex -gnaty- (gcc)
13856 @table @asis
13858 @item @code{-gnaty-}
13860 @emph{Remove style check options.}
13862 This causes any subsequent options in the string to act as canceling the
13863 corresponding style check option. To cancel maximum nesting level control,
13864 use the @code{L} parameter without any integer value after that, because any
13865 digit following @emph{-} in the parameter string of the @code{-gnaty}
13866 option will be treated as canceling the indentation check. The same is true
13867 for the @code{M} parameter. @code{y} and @code{N} parameters are not
13868 allowed after @emph{-}.
13869 @end table
13871 @geindex -gnaty+ (gcc)
13874 @table @asis
13876 @item @code{-gnaty+}
13878 @emph{Enable style check options.}
13880 This causes any subsequent options in the string to enable the corresponding
13881 style check option. That is, it cancels the effect of a previous -,
13882 if any.
13883 @end table
13885 @c end of switch description (leave this comment to ease automatic parsing for
13887 @c GPS
13889 In the above rules, appearing in column one is always permitted, that is,
13890 counts as meeting either a requirement for a required preceding space,
13891 or as meeting a requirement for no preceding space.
13893 Appearing at the end of a line is also always permitted, that is, counts
13894 as meeting either a requirement for a following space, or as meeting
13895 a requirement for no following space.
13897 If any of these style rules is violated, a message is generated giving
13898 details on the violation. The initial characters of such messages are
13899 always '@cite{(style)}'. Note that these messages are treated as warning
13900 messages, so they normally do not prevent the generation of an object
13901 file. The @code{-gnatwe} switch can be used to treat warning messages,
13902 including style messages, as fatal errors.
13904 The switch @code{-gnaty} on its own (that is not
13905 followed by any letters or digits) is equivalent
13906 to the use of @code{-gnatyy} as described above, that is all
13907 built-in standard style check options are enabled.
13909 The switch @code{-gnatyN} clears any previously set style checks.
13911 @node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
13912 @anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{f9}@anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{104}
13913 @subsection Run-Time Checks
13916 @geindex Division by zero
13918 @geindex Access before elaboration
13920 @geindex Checks
13921 @geindex division by zero
13923 @geindex Checks
13924 @geindex access before elaboration
13926 @geindex Checks
13927 @geindex stack overflow checking
13929 By default, the following checks are suppressed: stack overflow
13930 checks, and checks for access before elaboration on subprogram
13931 calls. All other checks, including overflow checks, range checks and
13932 array bounds checks, are turned on by default. The following @code{gcc}
13933 switches refine this default behavior.
13935 @geindex -gnatp (gcc)
13938 @table @asis
13940 @item @code{-gnatp}
13942 @geindex Suppressing checks
13944 @geindex Checks
13945 @geindex suppressing
13947 This switch causes the unit to be compiled
13948 as though @code{pragma Suppress (All_checks)}
13949 had been present in the source. Validity checks are also eliminated (in
13950 other words @code{-gnatp} also implies @code{-gnatVn}.
13951 Use this switch to improve the performance
13952 of the code at the expense of safety in the presence of invalid data or
13953 program bugs.
13955 Note that when checks are suppressed, the compiler is allowed, but not
13956 required, to omit the checking code. If the run-time cost of the
13957 checking code is zero or near-zero, the compiler will generate it even
13958 if checks are suppressed. In particular, if the compiler can prove
13959 that a certain check will necessarily fail, it will generate code to
13960 do an unconditional 'raise', even if checks are suppressed. The
13961 compiler warns in this case. Another case in which checks may not be
13962 eliminated is when they are embedded in certain run time routines such
13963 as math library routines.
13965 Of course, run-time checks are omitted whenever the compiler can prove
13966 that they will not fail, whether or not checks are suppressed.
13968 Note that if you suppress a check that would have failed, program
13969 execution is erroneous, which means the behavior is totally
13970 unpredictable. The program might crash, or print wrong answers, or
13971 do anything else. It might even do exactly what you wanted it to do
13972 (and then it might start failing mysteriously next week or next
13973 year). The compiler will generate code based on the assumption that
13974 the condition being checked is true, which can result in erroneous
13975 execution if that assumption is wrong.
13977 The checks subject to suppression include all the checks defined by the Ada
13978 standard, the additional implementation defined checks @code{Alignment_Check},
13979 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, @code{Container_Checks}, @code{Tampering_Check},
13980 and @code{Validity_Check}, as well as any checks introduced using @code{pragma Check_Name}.
13981 Note that @code{Atomic_Synchronization} is not automatically suppressed by use of this option.
13983 If the code depends on certain checks being active, you can use
13984 pragma @code{Unsuppress} either as a configuration pragma or as
13985 a local pragma to make sure that a specified check is performed
13986 even if @code{gnatp} is specified.
13988 The @code{-gnatp} switch has no effect if a subsequent
13989 @code{-gnat-p} switch appears.
13990 @end table
13992 @geindex -gnat-p (gcc)
13994 @geindex Suppressing checks
13996 @geindex Checks
13997 @geindex suppressing
13999 @geindex Suppress
14002 @table @asis
14004 @item @code{-gnat-p}
14006 This switch cancels the effect of a previous @code{gnatp} switch.
14007 @end table
14009 @geindex -gnato?? (gcc)
14011 @geindex Overflow checks
14013 @geindex Overflow mode
14015 @geindex Check
14016 @geindex overflow
14019 @table @asis
14021 @item @code{-gnato??}
14023 This switch controls the mode used for computing intermediate
14024 arithmetic integer operations, and also enables overflow checking.
14025 For a full description of overflow mode and checking control, see
14026 the 'Overflow Check Handling in GNAT' appendix in this
14027 User's Guide.
14029 Overflow checks are always enabled by this switch. The argument
14030 controls the mode, using the codes
14033 @table @asis
14035 @item @emph{1 = STRICT}
14037 In STRICT mode, intermediate operations are always done using the
14038 base type, and overflow checking ensures that the result is within
14039 the base type range.
14041 @item @emph{2 = MINIMIZED}
14043 In MINIMIZED mode, overflows in intermediate operations are avoided
14044 where possible by using a larger integer type for the computation
14045 (typically @code{Long_Long_Integer}). Overflow checking ensures that
14046 the result fits in this larger integer type.
14048 @item @emph{3 = ELIMINATED}
14050 In ELIMINATED mode, overflows in intermediate operations are avoided
14051 by using multi-precision arithmetic. In this case, overflow checking
14052 has no effect on intermediate operations (since overflow is impossible).
14053 @end table
14055 If two digits are present after @code{-gnato} then the first digit
14056 sets the mode for expressions outside assertions, and the second digit
14057 sets the mode for expressions within assertions. Here assertions is used
14058 in the technical sense (which includes for example precondition and
14059 postcondition expressions).
14061 If one digit is present, the corresponding mode is applicable to both
14062 expressions within and outside assertion expressions.
14064 If no digits are present, the default is to enable overflow checks
14065 and set STRICT mode for both kinds of expressions. This is compatible
14066 with the use of @code{-gnato} in previous versions of GNAT.
14068 @geindex Machine_Overflows
14070 Note that the @code{-gnato??} switch does not affect the code generated
14071 for any floating-point operations; it applies only to integer semantics.
14072 For floating-point, GNAT has the @code{Machine_Overflows}
14073 attribute set to @code{False} and the normal mode of operation is to
14074 generate IEEE NaN and infinite values on overflow or invalid operations
14075 (such as dividing 0.0 by 0.0).
14077 The reason that we distinguish overflow checking from other kinds of
14078 range constraint checking is that a failure of an overflow check, unlike
14079 for example the failure of a range check, can result in an incorrect
14080 value, but cannot cause random memory destruction (like an out of range
14081 subscript), or a wild jump (from an out of range case value). Overflow
14082 checking is also quite expensive in time and space, since in general it
14083 requires the use of double length arithmetic.
14085 Note again that the default is @code{-gnato11} (equivalent to @code{-gnato1}),
14086 so overflow checking is performed in STRICT mode by default.
14087 @end table
14089 @geindex -gnatE (gcc)
14091 @geindex Elaboration checks
14093 @geindex Check
14094 @geindex elaboration
14097 @table @asis
14099 @item @code{-gnatE}
14101 Enables dynamic checks for access-before-elaboration
14102 on subprogram calls and generic instantiations.
14103 Note that @code{-gnatE} is not necessary for safety, because in the
14104 default mode, GNAT ensures statically that the checks would not fail.
14105 For full details of the effect and use of this switch,
14106 @ref{1c,,Compiling with gcc}.
14107 @end table
14109 @geindex -fstack-check (gcc)
14111 @geindex Stack Overflow Checking
14113 @geindex Checks
14114 @geindex stack overflow checking
14117 @table @asis
14119 @item @code{-fstack-check}
14121 Activates stack overflow checking. For full details of the effect and use of
14122 this switch see @ref{f4,,Stack Overflow Checking}.
14123 @end table
14125 @geindex Unsuppress
14127 The setting of these switches only controls the default setting of the
14128 checks. You may modify them using either @code{Suppress} (to remove
14129 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
14130 the program source.
14132 @node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
14133 @anchor{gnat_ugn/building_executable_programs_with_gnat id20}@anchor{105}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-syntax-checking}@anchor{106}
14134 @subsection Using @code{gcc} for Syntax Checking
14137 @geindex -gnats (gcc)
14140 @table @asis
14142 @item @code{-gnats}
14144 The @code{s} stands for 'syntax'.
14146 Run GNAT in syntax checking only mode. For
14147 example, the command
14149 @example
14150 $ gcc -c -gnats x.adb
14151 @end example
14153 compiles file @code{x.adb} in syntax-check-only mode. You can check a
14154 series of files in a single command
14155 , and can use wild cards to specify such a group of files.
14156 Note that you must specify the @code{-c} (compile
14157 only) flag in addition to the @code{-gnats} flag.
14159 You may use other switches in conjunction with @code{-gnats}. In
14160 particular, @code{-gnatl} and @code{-gnatv} are useful to control the
14161 format of any generated error messages.
14163 When the source file is empty or contains only empty lines and/or comments,
14164 the output is a warning:
14166 @example
14167 $ gcc -c -gnats -x ada toto.txt
14168 toto.txt:1:01: warning: empty file, contains no compilation units
14170 @end example
14172 Otherwise, the output is simply the error messages, if any. No object file or
14173 ALI file is generated by a syntax-only compilation. Also, no units other
14174 than the one specified are accessed. For example, if a unit @code{X}
14175 @emph{with}s a unit @code{Y}, compiling unit @code{X} in syntax
14176 check only mode does not access the source file containing unit
14177 @code{Y}.
14179 @geindex Multiple units
14180 @geindex syntax checking
14182 Normally, GNAT allows only a single unit in a source file. However, this
14183 restriction does not apply in syntax-check-only mode, and it is possible
14184 to check a file containing multiple compilation units concatenated
14185 together. This is primarily used by the @code{gnatchop} utility
14186 (@ref{36,,Renaming Files with gnatchop}).
14187 @end table
14189 @node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
14190 @anchor{gnat_ugn/building_executable_programs_with_gnat id21}@anchor{107}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-semantic-checking}@anchor{108}
14191 @subsection Using @code{gcc} for Semantic Checking
14194 @geindex -gnatc (gcc)
14197 @table @asis
14199 @item @code{-gnatc}
14201 The @code{c} stands for 'check'.
14202 Causes the compiler to operate in semantic check mode,
14203 with full checking for all illegalities specified in the
14204 Ada Reference Manual, but without generation of any object code
14205 (no object file is generated).
14207 Because dependent files must be accessed, you must follow the GNAT
14208 semantic restrictions on file structuring to operate in this mode:
14211 @itemize *
14213 @item 
14214 The needed source files must be accessible
14215 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
14217 @item 
14218 Each file must contain only one compilation unit.
14220 @item 
14221 The file name and unit name must match (@ref{52,,File Naming Rules}).
14222 @end itemize
14224 The output consists of error messages as appropriate. No object file is
14225 generated. An @code{ALI} file is generated for use in the context of
14226 cross-reference tools, but this file is marked as not being suitable
14227 for binding (since no object file is generated).
14228 The checking corresponds exactly to the notion of
14229 legality in the Ada Reference Manual.
14231 Any unit can be compiled in semantics-checking-only mode, including
14232 units that would not normally be compiled (subunits,
14233 and specifications where a separate body is present).
14234 @end table
14236 @node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14237 @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{109}
14238 @subsection Compiling Different Versions of Ada
14241 The switches described in this section allow you to explicitly specify
14242 the version of the Ada language that your programs are written in.
14243 The default mode is Ada 2012,
14244 but you can also specify Ada 95, Ada 2005 mode, or
14245 indicate Ada 83 compatibility mode.
14247 @geindex Compatibility with Ada 83
14249 @geindex -gnat83 (gcc)
14251 @geindex ACVC
14252 @geindex Ada 83 tests
14254 @geindex Ada 83 mode
14257 @table @asis
14259 @item @code{-gnat83} (Ada 83 Compatibility Mode)
14261 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14262 specifies that the program is to be compiled in Ada 83 mode. With
14263 @code{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14264 semantics where this can be done easily.
14265 It is not possible to guarantee this switch does a perfect
14266 job; some subtle tests, such as are
14267 found in earlier ACVC tests (and that have been removed from the ACATS suite
14268 for Ada 95), might not compile correctly.
14269 Nevertheless, this switch may be useful in some circumstances, for example
14270 where, due to contractual reasons, existing code needs to be maintained
14271 using only Ada 83 features.
14273 With few exceptions (most notably the need to use @code{<>} on
14274 unconstrained 
14275 @geindex Generic formal parameters
14276 generic formal parameters,
14277 the use of the new Ada 95 / Ada 2005
14278 reserved words, and the use of packages
14279 with optional bodies), it is not necessary to specify the
14280 @code{-gnat83} switch when compiling Ada 83 programs, because, with rare
14281 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14282 a correct Ada 83 program is usually also a correct program
14283 in these later versions of the language standard. For further information
14284 please refer to the @emph{Compatibility and Porting Guide} chapter in the
14285 @cite{GNAT Reference Manual}.
14286 @end table
14288 @geindex -gnat95 (gcc)
14290 @geindex Ada 95 mode
14293 @table @asis
14295 @item @code{-gnat95} (Ada 95 mode)
14297 This switch directs the compiler to implement the Ada 95 version of the
14298 language.
14299 Since Ada 95 is almost completely upwards
14300 compatible with Ada 83, Ada 83 programs may generally be compiled using
14301 this switch (see the description of the @code{-gnat83} switch for further
14302 information about Ada 83 mode).
14303 If an Ada 2005 program is compiled in Ada 95 mode,
14304 uses of the new Ada 2005 features will cause error
14305 messages or warnings.
14307 This switch also can be used to cancel the effect of a previous
14308 @code{-gnat83}, @code{-gnat05/2005}, or @code{-gnat12/2012}
14309 switch earlier in the command line.
14310 @end table
14312 @geindex -gnat05 (gcc)
14314 @geindex -gnat2005 (gcc)
14316 @geindex Ada 2005 mode
14319 @table @asis
14321 @item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14323 This switch directs the compiler to implement the Ada 2005 version of the
14324 language, as documented in the official Ada standards document.
14325 Since Ada 2005 is almost completely upwards
14326 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14327 may generally be compiled using this switch (see the description of the
14328 @code{-gnat83} and @code{-gnat95} switches for further
14329 information).
14330 @end table
14332 @geindex -gnat12 (gcc)
14334 @geindex -gnat2012 (gcc)
14336 @geindex Ada 2012 mode
14339 @table @asis
14341 @item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14343 This switch directs the compiler to implement the Ada 2012 version of the
14344 language (also the default).
14345 Since Ada 2012 is almost completely upwards
14346 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14347 Ada 83 and Ada 95 programs
14348 may generally be compiled using this switch (see the description of the
14349 @code{-gnat83}, @code{-gnat95}, and @code{-gnat05/2005} switches
14350 for further information).
14351 @end table
14353 @geindex -gnatX (gcc)
14355 @geindex Ada language extensions
14357 @geindex GNAT extensions
14360 @table @asis
14362 @item @code{-gnatX} (Enable GNAT Extensions)
14364 This switch directs the compiler to implement the latest version of the
14365 language (currently Ada 2012) and also to enable certain GNAT implementation
14366 extensions that are not part of any Ada standard. For a full list of these
14367 extensions, see the GNAT reference manual.
14368 @end table
14370 @node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14371 @anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{48}
14372 @subsection Character Set Control
14375 @geindex -gnati (gcc)
14378 @table @asis
14380 @item @code{-gnati@emph{c}}
14382 Normally GNAT recognizes the Latin-1 character set in source program
14383 identifiers, as described in the Ada Reference Manual.
14384 This switch causes
14385 GNAT to recognize alternate character sets in identifiers. @code{c} is a
14386 single character  indicating the character set, as follows:
14389 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14390 @item
14392 @emph{1}
14394 @tab
14396 ISO 8859-1 (Latin-1) identifiers
14398 @item
14400 @emph{2}
14402 @tab
14404 ISO 8859-2 (Latin-2) letters allowed in identifiers
14406 @item
14408 @emph{3}
14410 @tab
14412 ISO 8859-3 (Latin-3) letters allowed in identifiers
14414 @item
14416 @emph{4}
14418 @tab
14420 ISO 8859-4 (Latin-4) letters allowed in identifiers
14422 @item
14424 @emph{5}
14426 @tab
14428 ISO 8859-5 (Cyrillic) letters allowed in identifiers
14430 @item
14432 @emph{9}
14434 @tab
14436 ISO 8859-15 (Latin-9) letters allowed in identifiers
14438 @item
14440 @emph{p}
14442 @tab
14444 IBM PC letters (code page 437) allowed in identifiers
14446 @item
14448 @emph{8}
14450 @tab
14452 IBM PC letters (code page 850) allowed in identifiers
14454 @item
14456 @emph{f}
14458 @tab
14460 Full upper-half codes allowed in identifiers
14462 @item
14464 @emph{n}
14466 @tab
14468 No upper-half codes allowed in identifiers
14470 @item
14472 @emph{w}
14474 @tab
14476 Wide-character codes (that is, codes greater than 255)
14477 allowed in identifiers
14479 @end multitable
14482 See @ref{3e,,Foreign Language Representation} for full details on the
14483 implementation of these character sets.
14484 @end table
14486 @geindex -gnatW (gcc)
14489 @table @asis
14491 @item @code{-gnatW@emph{e}}
14493 Specify the method of encoding for wide characters.
14494 @code{e} is one of the following:
14497 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14498 @item
14500 @emph{h}
14502 @tab
14504 Hex encoding (brackets coding also recognized)
14506 @item
14508 @emph{u}
14510 @tab
14512 Upper half encoding (brackets encoding also recognized)
14514 @item
14516 @emph{s}
14518 @tab
14520 Shift/JIS encoding (brackets encoding also recognized)
14522 @item
14524 @emph{e}
14526 @tab
14528 EUC encoding (brackets encoding also recognized)
14530 @item
14532 @emph{8}
14534 @tab
14536 UTF-8 encoding (brackets encoding also recognized)
14538 @item
14540 @emph{b}
14542 @tab
14544 Brackets encoding only (default value)
14546 @end multitable
14549 For full details on these encoding
14550 methods see @ref{4e,,Wide_Character Encodings}.
14551 Note that brackets coding is always accepted, even if one of the other
14552 options is specified, so for example @code{-gnatW8} specifies that both
14553 brackets and UTF-8 encodings will be recognized. The units that are
14554 with'ed directly or indirectly will be scanned using the specified
14555 representation scheme, and so if one of the non-brackets scheme is
14556 used, it must be used consistently throughout the program. However,
14557 since brackets encoding is always recognized, it may be conveniently
14558 used in standard libraries, allowing these libraries to be used with
14559 any of the available coding schemes.
14561 Note that brackets encoding only applies to program text. Within comments,
14562 brackets are considered to be normal graphic characters, and bracket sequences
14563 are never recognized as wide characters.
14565 If no @code{-gnatW?} parameter is present, then the default
14566 representation is normally Brackets encoding only. However, if the
14567 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14568 byte order mark or BOM for UTF-8), then these three characters are
14569 skipped and the default representation for the file is set to UTF-8.
14571 Note that the wide character representation that is specified (explicitly
14572 or by default) for the main program also acts as the default encoding used
14573 for Wide_Text_IO files if not specifically overridden by a WCEM form
14574 parameter.
14575 @end table
14577 When no @code{-gnatW?} is specified, then characters (other than wide
14578 characters represented using brackets notation) are treated as 8-bit
14579 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14580 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14581 characters in the range 16#00#..16#1F# are not accepted in program text
14582 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14583 in program text, but allowed and ignored in comments. Note in particular
14584 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14585 as an end of line in this default mode. If your source program contains
14586 instances of the NEL character used as a line terminator,
14587 you must use UTF-8 encoding for the whole
14588 source program. In default mode, all lines must be ended by a standard
14589 end of line sequence (CR, CR/LF, or LF).
14591 Note that the convention of simply accepting all upper half characters in
14592 comments means that programs that use standard ASCII for program text, but
14593 UTF-8 encoding for comments are accepted in default mode, providing that the
14594 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14595 This is a common mode for many programs with foreign language comments.
14597 @node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14598 @anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{10b}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{10c}
14599 @subsection File Naming Control
14602 @geindex -gnatk (gcc)
14605 @table @asis
14607 @item @code{-gnatk@emph{n}}
14609 Activates file name 'krunching'. @code{n}, a decimal integer in the range
14610 1-999, indicates the maximum allowable length of a file name (not
14611 including the @code{.ads} or @code{.adb} extension). The default is not
14612 to enable file name krunching.
14614 For the source file naming rules, @ref{52,,File Naming Rules}.
14615 @end table
14617 @node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14618 @anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{10d}@anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{10e}
14619 @subsection Subprogram Inlining Control
14622 @geindex -gnatn (gcc)
14625 @table @asis
14627 @item @code{-gnatn[12]}
14629 The @code{n} here is intended to suggest the first syllable of the word 'inline'.
14630 GNAT recognizes and processes @code{Inline} pragmas. However, for inlining to
14631 actually occur, optimization must be enabled and, by default, inlining of
14632 subprograms across modules is not performed. If you want to additionally
14633 enable inlining of subprograms specified by pragma @code{Inline} across modules,
14634 you must also specify this switch.
14636 In the absence of this switch, GNAT does not attempt inlining across modules
14637 and does not access the bodies of subprograms for which @code{pragma Inline} is
14638 specified if they are not in the current unit.
14640 You can optionally specify the inlining level: 1 for moderate inlining across
14641 modules, which is a good compromise between compilation times and performances
14642 at run time, or 2 for full inlining across modules, which may bring about
14643 longer compilation times. If no inlining level is specified, the compiler will
14644 pick it based on the optimization level: 1 for @code{-O1}, @code{-O2} or
14645 @code{-Os} and 2 for @code{-O3}.
14647 If you specify this switch the compiler will access these bodies,
14648 creating an extra source dependency for the resulting object file, and
14649 where possible, the call will be inlined.
14650 For further details on when inlining is possible
14651 see @ref{10f,,Inlining of Subprograms}.
14652 @end table
14654 @geindex -gnatN (gcc)
14657 @table @asis
14659 @item @code{-gnatN}
14661 This switch activates front-end inlining which also
14662 generates additional dependencies.
14664 When using a gcc-based back end (in practice this means using any version
14665 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
14666 @code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
14667 Historically front end inlining was more extensive than the gcc back end
14668 inlining, but that is no longer the case.
14669 @end table
14671 @node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14672 @anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{110}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{111}
14673 @subsection Auxiliary Output Control
14676 @geindex -gnatt (gcc)
14678 @geindex Writing internal trees
14680 @geindex Internal trees
14681 @geindex writing to file
14684 @table @asis
14686 @item @code{-gnatt}
14688 Causes GNAT to write the internal tree for a unit to a file (with the
14689 extension @code{.adt}.
14690 This not normally required, but is used by separate analysis tools.
14691 Typically
14692 these tools do the necessary compilations automatically, so you should
14693 not have to specify this switch in normal operation.
14694 Note that the combination of switches @code{-gnatct}
14695 generates a tree in the form required by ASIS applications.
14696 @end table
14698 @geindex -gnatu (gcc)
14701 @table @asis
14703 @item @code{-gnatu}
14705 Print a list of units required by this compilation on @code{stdout}.
14706 The listing includes all units on which the unit being compiled depends
14707 either directly or indirectly.
14708 @end table
14710 @geindex -pass-exit-codes (gcc)
14713 @table @asis
14715 @item @code{-pass-exit-codes}
14717 If this switch is not used, the exit code returned by @code{gcc} when
14718 compiling multiple files indicates whether all source files have
14719 been successfully used to generate object files or not.
14721 When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
14722 exit status and allows an integrated development environment to better
14723 react to a compilation failure. Those exit status are:
14726 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14727 @item
14729 @emph{5}
14731 @tab
14733 There was an error in at least one source file.
14735 @item
14737 @emph{3}
14739 @tab
14741 At least one source file did not generate an object file.
14743 @item
14745 @emph{2}
14747 @tab
14749 The compiler died unexpectedly (internal error for example).
14751 @item
14753 @emph{0}
14755 @tab
14757 An object file has been generated for every source file.
14759 @end multitable
14761 @end table
14763 @node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
14764 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{112}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{113}
14765 @subsection Debugging Control
14768 @quotation
14770 @geindex Debugging options
14771 @end quotation
14773 @geindex -gnatd (gcc)
14776 @table @asis
14778 @item @code{-gnatd@emph{x}}
14780 Activate internal debugging switches. @code{x} is a letter or digit, or
14781 string of letters or digits, which specifies the type of debugging
14782 outputs desired. Normally these are used only for internal development
14783 or system debugging purposes. You can find full documentation for these
14784 switches in the body of the @code{Debug} unit in the compiler source
14785 file @code{debug.adb}.
14786 @end table
14788 @geindex -gnatG (gcc)
14791 @table @asis
14793 @item @code{-gnatG[=@emph{nn}]}
14795 This switch causes the compiler to generate auxiliary output containing
14796 a pseudo-source listing of the generated expanded code. Like most Ada
14797 compilers, GNAT works by first transforming the high level Ada code into
14798 lower level constructs. For example, tasking operations are transformed
14799 into calls to the tasking run-time routines. A unique capability of GNAT
14800 is to list this expanded code in a form very close to normal Ada source.
14801 This is very useful in understanding the implications of various Ada
14802 usage on the efficiency of the generated code. There are many cases in
14803 Ada (e.g., the use of controlled types), where simple Ada statements can
14804 generate a lot of run-time code. By using @code{-gnatG} you can identify
14805 these cases, and consider whether it may be desirable to modify the coding
14806 approach to improve efficiency.
14808 The optional parameter @code{nn} if present after -gnatG specifies an
14809 alternative maximum line length that overrides the normal default of 72.
14810 This value is in the range 40-999999, values less than 40 being silently
14811 reset to 40. The equal sign is optional.
14813 The format of the output is very similar to standard Ada source, and is
14814 easily understood by an Ada programmer. The following special syntactic
14815 additions correspond to low level features used in the generated code that
14816 do not have any exact analogies in pure Ada source form. The following
14817 is a partial list of these special constructions. See the spec
14818 of package @code{Sprint} in file @code{sprint.ads} for a full list.
14820 @geindex -gnatL (gcc)
14822 If the switch @code{-gnatL} is used in conjunction with
14823 @code{-gnatG}, then the original source lines are interspersed
14824 in the expanded source (as comment lines with the original line number).
14827 @table @asis
14829 @item @code{new @emph{xxx} [storage_pool = @emph{yyy}]}
14831 Shows the storage pool being used for an allocator.
14833 @item @code{at end @emph{procedure-name};}
14835 Shows the finalization (cleanup) procedure for a scope.
14837 @item @code{(if @emph{expr} then @emph{expr} else @emph{expr})}
14839 Conditional expression equivalent to the @code{x?y:z} construction in C.
14841 @item @code{@emph{target}^(@emph{source})}
14843 A conversion with floating-point truncation instead of rounding.
14845 @item @code{@emph{target}?(@emph{source})}
14847 A conversion that bypasses normal Ada semantic checking. In particular
14848 enumeration types and fixed-point types are treated simply as integers.
14850 @item @code{@emph{target}?^(@emph{source})}
14852 Combines the above two cases.
14853 @end table
14855 @code{@emph{x} #/ @emph{y}}
14857 @code{@emph{x} #mod @emph{y}}
14859 @code{@emph{x} # @emph{y}}
14862 @table @asis
14864 @item @code{@emph{x} #rem @emph{y}}
14866 A division or multiplication of fixed-point values which are treated as
14867 integers without any kind of scaling.
14869 @item @code{free @emph{expr} [storage_pool = @emph{xxx}]}
14871 Shows the storage pool associated with a @code{free} statement.
14873 @item @code{[subtype or type declaration]}
14875 Used to list an equivalent declaration for an internally generated
14876 type that is referenced elsewhere in the listing.
14878 @item @code{freeze @emph{type-name} [@emph{actions}]}
14880 Shows the point at which @code{type-name} is frozen, with possible
14881 associated actions to be performed at the freeze point.
14883 @item @code{reference @emph{itype}}
14885 Reference (and hence definition) to internal type @code{itype}.
14887 @item @code{@emph{function-name}! (@emph{arg}, @emph{arg}, @emph{arg})}
14889 Intrinsic function call.
14891 @item @code{@emph{label-name} : label}
14893 Declaration of label @code{labelname}.
14895 @item @code{#$ @emph{subprogram-name}}
14897 An implicit call to a run-time support routine
14898 (to meet the requirement of H.3.1(9) in a
14899 convenient manner).
14901 @item @code{@emph{expr} && @emph{expr} && @emph{expr} ... && @emph{expr}}
14903 A multiple concatenation (same effect as @code{expr} & @code{expr} &
14904 @code{expr}, but handled more efficiently).
14906 @item @code{[constraint_error]}
14908 Raise the @code{Constraint_Error} exception.
14910 @item @code{@emph{expression}'reference}
14912 A pointer to the result of evaluating @{expression@}.
14914 @item @code{@emph{target-type}!(@emph{source-expression})}
14916 An unchecked conversion of @code{source-expression} to @code{target-type}.
14918 @item @code{[@emph{numerator}/@emph{denominator}]}
14920 Used to represent internal real literals (that) have no exact
14921 representation in base 2-16 (for example, the result of compile time
14922 evaluation of the expression 1.0/27.0).
14923 @end table
14924 @end table
14926 @geindex -gnatD (gcc)
14929 @table @asis
14931 @item @code{-gnatD[=nn]}
14933 When used in conjunction with @code{-gnatG}, this switch causes
14934 the expanded source, as described above for
14935 @code{-gnatG} to be written to files with names
14936 @code{xxx.dg}, where @code{xxx} is the normal file name,
14937 instead of to the standard output file. For
14938 example, if the source file name is @code{hello.adb}, then a file
14939 @code{hello.adb.dg} will be written.  The debugging
14940 information generated by the @code{gcc} @code{-g} switch
14941 will refer to the generated @code{xxx.dg} file. This allows
14942 you to do source level debugging using the generated code which is
14943 sometimes useful for complex code, for example to find out exactly
14944 which part of a complex construction raised an exception. This switch
14945 also suppresses generation of cross-reference information (see
14946 @code{-gnatx}) since otherwise the cross-reference information
14947 would refer to the @code{.dg} file, which would cause
14948 confusion since this is not the original source file.
14950 Note that @code{-gnatD} actually implies @code{-gnatG}
14951 automatically, so it is not necessary to give both options.
14952 In other words @code{-gnatD} is equivalent to @code{-gnatDG}).
14954 @geindex -gnatL (gcc)
14956 If the switch @code{-gnatL} is used in conjunction with
14957 @code{-gnatDG}, then the original source lines are interspersed
14958 in the expanded source (as comment lines with the original line number).
14960 The optional parameter @code{nn} if present after -gnatD specifies an
14961 alternative maximum line length that overrides the normal default of 72.
14962 This value is in the range 40-999999, values less than 40 being silently
14963 reset to 40. The equal sign is optional.
14964 @end table
14966 @geindex -gnatr (gcc)
14968 @geindex pragma Restrictions
14971 @table @asis
14973 @item @code{-gnatr}
14975 This switch causes pragma Restrictions to be treated as Restriction_Warnings
14976 so that violation of restrictions causes warnings rather than illegalities.
14977 This is useful during the development process when new restrictions are added
14978 or investigated. The switch also causes pragma Profile to be treated as
14979 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
14980 restriction warnings rather than restrictions.
14981 @end table
14983 @geindex -gnatR (gcc)
14986 @table @asis
14988 @item @code{-gnatR[0|1|2|3][e][m][s]}
14990 This switch controls output from the compiler of a listing showing
14991 representation information for declared types, objects and subprograms.
14992 For @code{-gnatR0}, no information is output (equivalent to omitting
14993 the @code{-gnatR} switch). For @code{-gnatR1} (which is the default,
14994 so @code{-gnatR} with no parameter has the same effect), size and
14995 alignment information is listed for declared array and record types.
14996 For @code{-gnatR2}, size and alignment information is listed for all
14997 declared types and objects. The @code{Linker_Section} is also listed for any
14998 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
14999 latter case occurs for objects of a type for which a @code{Linker_Section}
15000 is set).
15002 For @code{-gnatR3}, symbolic expressions for values that are computed
15003 at run time for records are included. These symbolic expressions have
15004 a mostly obvious format with #n being used to represent the value of the
15005 n'th discriminant. See source files @code{repinfo.ads/adb} in the
15006 GNAT sources for full details on the format of @code{-gnatR3} output.
15008 If the switch is followed by an @code{e} (e.g. @code{-gnatR2e}), then
15009 extended representation information for record sub-components of records
15010 are included.
15012 If the switch is followed by an @code{m} (e.g. @code{-gnatRm}), then
15013 subprogram conventions and parameter passing mechanisms for all the
15014 subprograms are included.
15016 If the switch is followed by an @code{s} (e.g., @code{-gnatR3s}), then
15017 the output is to a file with the name @code{file.rep} where file is
15018 the name of the corresponding source file.
15020 Note that it is possible for record components to have zero size. In
15021 this case, the component clause uses an obvious extension of permitted
15022 Ada syntax, for example @code{at 0 range 0 .. -1}.
15023 @end table
15025 @geindex -gnatS (gcc)
15028 @table @asis
15030 @item @code{-gnatS}
15032 The use of the switch @code{-gnatS} for an
15033 Ada compilation will cause the compiler to output a
15034 representation of package Standard in a form very
15035 close to standard Ada. It is not quite possible to
15036 do this entirely in standard Ada (since new
15037 numeric base types cannot be created in standard
15038 Ada), but the output is easily
15039 readable to any Ada programmer, and is useful to
15040 determine the characteristics of target dependent
15041 types in package Standard.
15042 @end table
15044 @geindex -gnatx (gcc)
15047 @table @asis
15049 @item @code{-gnatx}
15051 Normally the compiler generates full cross-referencing information in
15052 the @code{ALI} file. This information is used by a number of tools,
15053 including @code{gnatfind} and @code{gnatxref}. The @code{-gnatx} switch
15054 suppresses this information. This saves some space and may slightly
15055 speed up compilation, but means that these tools cannot be used.
15056 @end table
15058 @node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
15059 @anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{114}@anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{115}
15060 @subsection Exception Handling Control
15063 GNAT uses two methods for handling exceptions at run-time. The
15064 @code{setjmp/longjmp} method saves the context when entering
15065 a frame with an exception handler. Then when an exception is
15066 raised, the context can be restored immediately, without the
15067 need for tracing stack frames. This method provides very fast
15068 exception propagation, but introduces significant overhead for
15069 the use of exception handlers, even if no exception is raised.
15071 The other approach is called 'zero cost' exception handling.
15072 With this method, the compiler builds static tables to describe
15073 the exception ranges. No dynamic code is required when entering
15074 a frame containing an exception handler. When an exception is
15075 raised, the tables are used to control a back trace of the
15076 subprogram invocation stack to locate the required exception
15077 handler. This method has considerably poorer performance for
15078 the propagation of exceptions, but there is no overhead for
15079 exception handlers if no exception is raised. Note that in this
15080 mode and in the context of mixed Ada and C/C++ programming,
15081 to propagate an exception through a C/C++ code, the C/C++ code
15082 must be compiled with the @code{-funwind-tables} GCC's
15083 option.
15085 The following switches may be used to control which of the
15086 two exception handling methods is used.
15088 @geindex --RTS=sjlj (gnatmake)
15091 @table @asis
15093 @item @code{--RTS=sjlj}
15095 This switch causes the setjmp/longjmp run-time (when available) to be used
15096 for exception handling. If the default
15097 mechanism for the target is zero cost exceptions, then
15098 this switch can be used to modify this default, and must be
15099 used for all units in the partition.
15100 This option is rarely used. One case in which it may be
15101 advantageous is if you have an application where exception
15102 raising is common and the overall performance of the
15103 application is improved by favoring exception propagation.
15104 @end table
15106 @geindex --RTS=zcx (gnatmake)
15108 @geindex Zero Cost Exceptions
15111 @table @asis
15113 @item @code{--RTS=zcx}
15115 This switch causes the zero cost approach to be used
15116 for exception handling. If this is the default mechanism for the
15117 target (see below), then this switch is unneeded. If the default
15118 mechanism for the target is setjmp/longjmp exceptions, then
15119 this switch can be used to modify this default, and must be
15120 used for all units in the partition.
15121 This option can only be used if the zero cost approach
15122 is available for the target in use, otherwise it will generate an error.
15123 @end table
15125 The same option @code{--RTS} must be used both for @code{gcc}
15126 and @code{gnatbind}. Passing this option to @code{gnatmake}
15127 (@ref{dc,,Switches for gnatmake}) will ensure the required consistency
15128 through the compilation and binding steps.
15130 @node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
15131 @anchor{gnat_ugn/building_executable_programs_with_gnat id29}@anchor{116}@anchor{gnat_ugn/building_executable_programs_with_gnat units-to-sources-mapping-files}@anchor{f7}
15132 @subsection Units to Sources Mapping Files
15135 @geindex -gnatem (gcc)
15138 @table @asis
15140 @item @code{-gnatem=@emph{path}}
15142 A mapping file is a way to communicate to the compiler two mappings:
15143 from unit names to file names (without any directory information) and from
15144 file names to path names (with full directory information). These mappings
15145 are used by the compiler to short-circuit the path search.
15147 The use of mapping files is not required for correct operation of the
15148 compiler, but mapping files can improve efficiency, particularly when
15149 sources are read over a slow network connection. In normal operation,
15150 you need not be concerned with the format or use of mapping files,
15151 and the @code{-gnatem} switch is not a switch that you would use
15152 explicitly. It is intended primarily for use by automatic tools such as
15153 @code{gnatmake} running under the project file facility. The
15154 description here of the format of mapping files is provided
15155 for completeness and for possible use by other tools.
15157 A mapping file is a sequence of sets of three lines. In each set, the
15158 first line is the unit name, in lower case, with @code{%s} appended
15159 for specs and @code{%b} appended for bodies; the second line is the
15160 file name; and the third line is the path name.
15162 Example:
15164 @example
15165 main%b
15166 main.2.ada
15167 /gnat/project1/sources/main.2.ada
15168 @end example
15170 When the switch @code{-gnatem} is specified, the compiler will
15171 create in memory the two mappings from the specified file. If there is
15172 any problem (nonexistent file, truncated file or duplicate entries),
15173 no mapping will be created.
15175 Several @code{-gnatem} switches may be specified; however, only the
15176 last one on the command line will be taken into account.
15178 When using a project file, @code{gnatmake} creates a temporary
15179 mapping file and communicates it to the compiler using this switch.
15180 @end table
15182 @node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
15183 @anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{117}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{118}
15184 @subsection Code Generation Control
15187 The GCC technology provides a wide range of target dependent
15188 @code{-m} switches for controlling
15189 details of code generation with respect to different versions of
15190 architectures. This includes variations in instruction sets (e.g.,
15191 different members of the power pc family), and different requirements
15192 for optimal arrangement of instructions (e.g., different members of
15193 the x86 family). The list of available @code{-m} switches may be
15194 found in the GCC documentation.
15196 Use of these @code{-m} switches may in some cases result in improved
15197 code performance.
15199 The GNAT technology is tested and qualified without any
15200 @code{-m} switches,
15201 so generally the most reliable approach is to avoid the use of these
15202 switches. However, we generally expect most of these switches to work
15203 successfully with GNAT, and many customers have reported successful
15204 use of these options.
15206 Our general advice is to avoid the use of @code{-m} switches unless
15207 special needs lead to requirements in this area. In particular,
15208 there is no point in using @code{-m} switches to improve performance
15209 unless you actually see a performance improvement.
15211 @node Linker Switches,Binding with gnatbind,Compiler Switches,Building Executable Programs with GNAT
15212 @anchor{gnat_ugn/building_executable_programs_with_gnat linker-switches}@anchor{119}@anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{11a}
15213 @section Linker Switches
15216 Linker switches can be specified after @code{-largs} builder switch.
15218 @geindex -fuse-ld=name
15221 @table @asis
15223 @item @code{-fuse-ld=@emph{name}}
15225 Linker to be used. The default is @code{bfd} for @code{ld.bfd},
15226 the alternative being @code{gold} for @code{ld.gold}. The later is
15227 a more recent and faster linker, but only available on GNU/Linux
15228 platforms.
15229 @end table
15231 @node Binding with gnatbind,Linking with gnatlink,Linker Switches,Building Executable Programs with GNAT
15232 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{1d}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{11b}
15233 @section Binding with @code{gnatbind}
15236 @geindex gnatbind
15238 This chapter describes the GNAT binder, @code{gnatbind}, which is used
15239 to bind compiled GNAT objects.
15241 The @code{gnatbind} program performs four separate functions:
15244 @itemize *
15246 @item 
15247 Checks that a program is consistent, in accordance with the rules in
15248 Chapter 10 of the Ada Reference Manual. In particular, error
15249 messages are generated if a program uses inconsistent versions of a
15250 given unit.
15252 @item 
15253 Checks that an acceptable order of elaboration exists for the program
15254 and issues an error message if it cannot find an order of elaboration
15255 that satisfies the rules in Chapter 10 of the Ada Language Manual.
15257 @item 
15258 Generates a main program incorporating the given elaboration order.
15259 This program is a small Ada package (body and spec) that
15260 must be subsequently compiled
15261 using the GNAT compiler. The necessary compilation step is usually
15262 performed automatically by @code{gnatlink}. The two most important
15263 functions of this program
15264 are to call the elaboration routines of units in an appropriate order
15265 and to call the main program.
15267 @item 
15268 Determines the set of object files required by the given main program.
15269 This information is output in the forms of comments in the generated program,
15270 to be read by the @code{gnatlink} utility used to link the Ada application.
15271 @end itemize
15273 @menu
15274 * Running gnatbind:: 
15275 * Switches for gnatbind:: 
15276 * Command-Line Access:: 
15277 * Search Paths for gnatbind:: 
15278 * Examples of gnatbind Usage:: 
15280 @end menu
15282 @node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15283 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{11c}@anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{11d}
15284 @subsection Running @code{gnatbind}
15287 The form of the @code{gnatbind} command is
15289 @example
15290 $ gnatbind [ switches ] mainprog[.ali] [ switches ]
15291 @end example
15293 where @code{mainprog.adb} is the Ada file containing the main program
15294 unit body. @code{gnatbind} constructs an Ada
15295 package in two files whose names are
15296 @code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15297 For example, if given the
15298 parameter @code{hello.ali}, for a main program contained in file
15299 @code{hello.adb}, the binder output files would be @code{b~hello.ads}
15300 and @code{b~hello.adb}.
15302 When doing consistency checking, the binder takes into consideration
15303 any source files it can locate. For example, if the binder determines
15304 that the given main program requires the package @code{Pack}, whose
15305 @code{.ALI}
15306 file is @code{pack.ali} and whose corresponding source spec file is
15307 @code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15308 (using the same search path conventions as previously described for the
15309 @code{gcc} command). If it can locate this source file, it checks that
15310 the time stamps
15311 or source checksums of the source and its references to in @code{ALI} files
15312 match. In other words, any @code{ALI} files that mentions this spec must have
15313 resulted from compiling this version of the source file (or in the case
15314 where the source checksums match, a version close enough that the
15315 difference does not matter).
15317 @geindex Source files
15318 @geindex use by binder
15320 The effect of this consistency checking, which includes source files, is
15321 that the binder ensures that the program is consistent with the latest
15322 version of the source files that can be located at bind time. Editing a
15323 source file without compiling files that depend on the source file cause
15324 error messages to be generated by the binder.
15326 For example, suppose you have a main program @code{hello.adb} and a
15327 package @code{P}, from file @code{p.ads} and you perform the following
15328 steps:
15331 @itemize *
15333 @item 
15334 Enter @code{gcc -c hello.adb} to compile the main program.
15336 @item 
15337 Enter @code{gcc -c p.ads} to compile package @code{P}.
15339 @item 
15340 Edit file @code{p.ads}.
15342 @item 
15343 Enter @code{gnatbind hello}.
15344 @end itemize
15346 At this point, the file @code{p.ali} contains an out-of-date time stamp
15347 because the file @code{p.ads} has been edited. The attempt at binding
15348 fails, and the binder generates the following error messages:
15350 @example
15351 error: "hello.adb" must be recompiled ("p.ads" has been modified)
15352 error: "p.ads" has been modified and must be recompiled
15353 @end example
15355 Now both files must be recompiled as indicated, and then the bind can
15356 succeed, generating a main program. You need not normally be concerned
15357 with the contents of this file, but for reference purposes a sample
15358 binder output file is given in @ref{e,,Example of Binder Output File}.
15360 In most normal usage, the default mode of @code{gnatbind} which is to
15361 generate the main package in Ada, as described in the previous section.
15362 In particular, this means that any Ada programmer can read and understand
15363 the generated main program. It can also be debugged just like any other
15364 Ada code provided the @code{-g} switch is used for
15365 @code{gnatbind} and @code{gnatlink}.
15367 @node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15368 @anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{11e}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{11f}
15369 @subsection Switches for @code{gnatbind}
15372 The following switches are available with @code{gnatbind}; details will
15373 be presented in subsequent sections.
15375 @geindex --version (gnatbind)
15378 @table @asis
15380 @item @code{--version}
15382 Display Copyright and version, then exit disregarding all other options.
15383 @end table
15385 @geindex --help (gnatbind)
15388 @table @asis
15390 @item @code{--help}
15392 If @code{--version} was not used, display usage, then exit disregarding
15393 all other options.
15394 @end table
15396 @geindex -a (gnatbind)
15399 @table @asis
15401 @item @code{-a}
15403 Indicates that, if supported by the platform, the adainit procedure should
15404 be treated as an initialisation routine by the linker (a constructor). This
15405 is intended to be used by the Project Manager to automatically initialize
15406 shared Stand-Alone Libraries.
15407 @end table
15409 @geindex -aO (gnatbind)
15412 @table @asis
15414 @item @code{-aO}
15416 Specify directory to be searched for ALI files.
15417 @end table
15419 @geindex -aI (gnatbind)
15422 @table @asis
15424 @item @code{-aI}
15426 Specify directory to be searched for source file.
15427 @end table
15429 @geindex -A (gnatbind)
15432 @table @asis
15434 @item @code{-A[=@emph{filename}]}
15436 Output ALI list (to standard output or to the named file).
15437 @end table
15439 @geindex -b (gnatbind)
15442 @table @asis
15444 @item @code{-b}
15446 Generate brief messages to @code{stderr} even if verbose mode set.
15447 @end table
15449 @geindex -c (gnatbind)
15452 @table @asis
15454 @item @code{-c}
15456 Check only, no generation of binder output file.
15457 @end table
15459 @geindex -dnn[k|m] (gnatbind)
15462 @table @asis
15464 @item @code{-d@emph{nn}[k|m]}
15466 This switch can be used to change the default task stack size value
15467 to a specified size @code{nn}, which is expressed in bytes by default, or
15468 in kilobytes when suffixed with @code{k} or in megabytes when suffixed
15469 with @code{m}.
15470 In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15471 in effect, to completing all task specs with
15473 @example
15474 pragma Storage_Size (nn);
15475 @end example
15477 When they do not already have such a pragma.
15478 @end table
15480 @geindex -D (gnatbind)
15483 @table @asis
15485 @item @code{-D@emph{nn}[k|m]}
15487 This switch can be used to change the default secondary stack size value
15488 to a specified size @code{nn}, which is expressed in bytes by default, or
15489 in kilobytes when suffixed with @code{k} or in megabytes when suffixed
15490 with @code{m}.
15492 The secondary stack is used to deal with functions that return a variable
15493 sized result, for example a function returning an unconstrained
15494 String. There are two ways in which this secondary stack is allocated.
15496 For most targets, the secondary stack grows on demand and is allocated
15497 as a chain of blocks in the heap. The -D option is not very
15498 relevant. It only give some control over the size of the allocated
15499 blocks (whose size is the minimum of the default secondary stack size value,
15500 and the actual size needed for the current allocation request).
15502 For certain targets, notably VxWorks 653 and bare board targets,
15503 the secondary stack is allocated by carving off a chunk of the primary task
15504 stack. By default this is a fixed percentage of the primary task stack as
15505 defined by System.Parameter.Sec_Stack_Percentage. This can be overridden per
15506 task using the Secondary_Stack_Size pragma/aspect. The -D option is used to
15507 define the size of the environment task's secondary stack.
15508 @end table
15510 @geindex -e (gnatbind)
15513 @table @asis
15515 @item @code{-e}
15517 Output complete list of elaboration-order dependencies.
15518 @end table
15520 @geindex -Ea (gnatbind)
15523 @table @asis
15525 @item @code{-Ea}
15527 Store tracebacks in exception occurrences when the target supports it.
15528 The "a" is for "address"; tracebacks will contain hexadecimal addresses,
15529 unless symbolic tracebacks are enabled.
15531 See also the packages @code{GNAT.Traceback} and
15532 @code{GNAT.Traceback.Symbolic} for more information.
15533 Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
15534 @code{gcc} option.
15535 @end table
15537 @geindex -Es (gnatbind)
15540 @table @asis
15542 @item @code{-Es}
15544 Store tracebacks in exception occurrences when the target supports it.
15545 The "s" is for "symbolic"; symbolic tracebacks are enabled.
15546 @end table
15548 @geindex -E (gnatbind)
15551 @table @asis
15553 @item @code{-E}
15555 Currently the same as @code{-Ea}.
15556 @end table
15558 @geindex -f (gnatbind)
15561 @table @asis
15563 @item @code{-f@emph{elab-order}}
15565 Force elaboration order.
15566 @end table
15568 @geindex -F (gnatbind)
15571 @table @asis
15573 @item @code{-F}
15575 Force the checks of elaboration flags. @code{gnatbind} does not normally
15576 generate checks of elaboration flags for the main executable, except when
15577 a Stand-Alone Library is used. However, there are cases when this cannot be
15578 detected by gnatbind. An example is importing an interface of a Stand-Alone
15579 Library through a pragma Import and only specifying through a linker switch
15580 this Stand-Alone Library. This switch is used to guarantee that elaboration
15581 flag checks are generated.
15582 @end table
15584 @geindex -h (gnatbind)
15587 @table @asis
15589 @item @code{-h}
15591 Output usage (help) information.
15593 @geindex -H32 (gnatbind)
15595 @item @code{-H32}
15597 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
15598 For further details see @ref{120,,Dynamic Allocation Control}.
15600 @geindex -H64 (gnatbind)
15602 @geindex __gnat_malloc
15604 @item @code{-H64}
15606 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
15607 For further details see @ref{120,,Dynamic Allocation Control}.
15609 @geindex -I (gnatbind)
15611 @item @code{-I}
15613 Specify directory to be searched for source and ALI files.
15615 @geindex -I- (gnatbind)
15617 @item @code{-I-}
15619 Do not look for sources in the current directory where @code{gnatbind} was
15620 invoked, and do not look for ALI files in the directory containing the
15621 ALI file named in the @code{gnatbind} command line.
15623 @geindex -l (gnatbind)
15625 @item @code{-l}
15627 Output chosen elaboration order.
15629 @geindex -L (gnatbind)
15631 @item @code{-L@emph{xxx}}
15633 Bind the units for library building. In this case the @code{adainit} and
15634 @code{adafinal} procedures (@ref{b4,,Binding with Non-Ada Main Programs})
15635 are renamed to @code{@emph{xxx}init} and
15636 @code{@emph{xxx}final}.
15637 Implies -n.
15638 (@ref{15,,GNAT and Libraries}, for more details.)
15640 @geindex -M (gnatbind)
15642 @item @code{-M@emph{xyz}}
15644 Rename generated main program from main to xyz. This option is
15645 supported on cross environments only.
15647 @geindex -m (gnatbind)
15649 @item @code{-m@emph{n}}
15651 Limit number of detected errors or warnings to @code{n}, where @code{n} is
15652 in the range 1..999999. The default value if no switch is
15653 given is 9999. If the number of warnings reaches this limit, then a
15654 message is output and further warnings are suppressed, the bind
15655 continues in this case. If the number of errors reaches this
15656 limit, then a message is output and the bind is abandoned.
15657 A value of zero means that no limit is enforced. The equal
15658 sign is optional.
15660 @geindex -n (gnatbind)
15662 @item @code{-n}
15664 No main program.
15666 @geindex -nostdinc (gnatbind)
15668 @item @code{-nostdinc}
15670 Do not look for sources in the system default directory.
15672 @geindex -nostdlib (gnatbind)
15674 @item @code{-nostdlib}
15676 Do not look for library files in the system default directory.
15678 @geindex --RTS (gnatbind)
15680 @item @code{--RTS=@emph{rts-path}}
15682 Specifies the default location of the runtime library. Same meaning as the
15683 equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
15685 @geindex -o (gnatbind)
15687 @item @code{-o @emph{file}}
15689 Name the output file @code{file} (default is @code{b~`xxx}.adb`).
15690 Note that if this option is used, then linking must be done manually,
15691 gnatlink cannot be used.
15693 @geindex -O (gnatbind)
15695 @item @code{-O[=@emph{filename}]}
15697 Output object list (to standard output or to the named file).
15699 @geindex -p (gnatbind)
15701 @item @code{-p}
15703 Pessimistic (worst-case) elaboration order.
15705 @geindex -P (gnatbind)
15707 @item @code{-P}
15709 Generate binder file suitable for CodePeer.
15711 @geindex -R (gnatbind)
15713 @item @code{-R}
15715 Output closure source list, which includes all non-run-time units that are
15716 included in the bind.
15718 @geindex -Ra (gnatbind)
15720 @item @code{-Ra}
15722 Like @code{-R} but the list includes run-time units.
15724 @geindex -s (gnatbind)
15726 @item @code{-s}
15728 Require all source files to be present.
15730 @geindex -S (gnatbind)
15732 @item @code{-S@emph{xxx}}
15734 Specifies the value to be used when detecting uninitialized scalar
15735 objects with pragma Initialize_Scalars.
15736 The @code{xxx} string specified with the switch is one of:
15739 @itemize *
15741 @item 
15742 @code{in} for an invalid value.
15744 If zero is invalid for the discrete type in question,
15745 then the scalar value is set to all zero bits.
15746 For signed discrete types, the largest possible negative value of
15747 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15748 For unsigned discrete types, the underlying scalar value is set to all
15749 one bits. For floating-point types, a NaN value is set
15750 (see body of package System.Scalar_Values for exact values).
15752 @item 
15753 @code{lo} for low value.
15755 If zero is invalid for the discrete type in question,
15756 then the scalar value is set to all zero bits.
15757 For signed discrete types, the largest possible negative value of
15758 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15759 For unsigned discrete types, the underlying scalar value is set to all
15760 zero bits. For floating-point, a small value is set
15761 (see body of package System.Scalar_Values for exact values).
15763 @item 
15764 @code{hi} for high value.
15766 If zero is invalid for the discrete type in question,
15767 then the scalar value is set to all one bits.
15768 For signed discrete types, the largest possible positive value of
15769 the underlying scalar is set (i.e. a zero bit followed by all one bits).
15770 For unsigned discrete types, the underlying scalar value is set to all
15771 one bits. For floating-point, a large value is set
15772 (see body of package System.Scalar_Values for exact values).
15774 @item 
15775 @code{xx} for hex value (two hex digits).
15777 The underlying scalar is set to a value consisting of repeated bytes, whose
15778 value corresponds to the given value. For example if @code{BF} is given,
15779 then a 32-bit scalar value will be set to the bit patterm @code{16#BFBFBFBF#}.
15780 @end itemize
15782 @geindex GNAT_INIT_SCALARS
15784 In addition, you can specify @code{-Sev} to indicate that the value is
15785 to be set at run time. In this case, the program will look for an environment
15786 variable of the form @code{GNAT_INIT_SCALARS=@emph{yy}}, where @code{yy} is one
15787 of @code{in/lo/hi/@emph{xx}} with the same meanings as above.
15788 If no environment variable is found, or if it does not have a valid value,
15789 then the default is @code{in} (invalid values).
15790 @end table
15792 @geindex -static (gnatbind)
15795 @table @asis
15797 @item @code{-static}
15799 Link against a static GNAT run time.
15801 @geindex -shared (gnatbind)
15803 @item @code{-shared}
15805 Link against a shared GNAT run time when available.
15807 @geindex -t (gnatbind)
15809 @item @code{-t}
15811 Tolerate time stamp and other consistency errors.
15813 @geindex -T (gnatbind)
15815 @item @code{-T@emph{n}}
15817 Set the time slice value to @code{n} milliseconds. If the system supports
15818 the specification of a specific time slice value, then the indicated value
15819 is used. If the system does not support specific time slice values, but
15820 does support some general notion of round-robin scheduling, then any
15821 nonzero value will activate round-robin scheduling.
15823 A value of zero is treated specially. It turns off time
15824 slicing, and in addition, indicates to the tasking run time that the
15825 semantics should match as closely as possible the Annex D
15826 requirements of the Ada RM, and in particular sets the default
15827 scheduling policy to @code{FIFO_Within_Priorities}.
15829 @geindex -u (gnatbind)
15831 @item @code{-u@emph{n}}
15833 Enable dynamic stack usage, with @code{n} results stored and displayed
15834 at program termination. A result is generated when a task
15835 terminates. Results that can't be stored are displayed on the fly, at
15836 task termination. This option is currently not supported on Itanium
15837 platforms. (See @ref{121,,Dynamic Stack Usage Analysis} for details.)
15839 @geindex -v (gnatbind)
15841 @item @code{-v}
15843 Verbose mode. Write error messages, header, summary output to
15844 @code{stdout}.
15846 @geindex -V (gnatbind)
15848 @item @code{-V@emph{key}=@emph{value}}
15850 Store the given association of @code{key} to @code{value} in the bind environment.
15851 Values stored this way can be retrieved at run time using
15852 @code{GNAT.Bind_Environment}.
15854 @geindex -w (gnatbind)
15856 @item @code{-w@emph{x}}
15858 Warning mode; @code{x} = s/e for suppress/treat as error.
15860 @geindex -Wx (gnatbind)
15862 @item @code{-Wx@emph{e}}
15864 Override default wide character encoding for standard Text_IO files.
15866 @geindex -x (gnatbind)
15868 @item @code{-x}
15870 Exclude source files (check object consistency only).
15872 @geindex -Xnnn (gnatbind)
15874 @item @code{-X@emph{nnn}}
15876 Set default exit status value, normally 0 for POSIX compliance.
15878 @geindex -y (gnatbind)
15880 @item @code{-y}
15882 Enable leap seconds support in @code{Ada.Calendar} and its children.
15884 @geindex -z (gnatbind)
15886 @item @code{-z}
15888 No main subprogram.
15889 @end table
15891 You may obtain this listing of switches by running @code{gnatbind} with
15892 no arguments.
15894 @menu
15895 * Consistency-Checking Modes:: 
15896 * Binder Error Message Control:: 
15897 * Elaboration Control:: 
15898 * Output Control:: 
15899 * Dynamic Allocation Control:: 
15900 * Binding with Non-Ada Main Programs:: 
15901 * Binding Programs with No Main Subprogram:: 
15903 @end menu
15905 @node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
15906 @anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{122}@anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{123}
15907 @subsubsection Consistency-Checking Modes
15910 As described earlier, by default @code{gnatbind} checks
15911 that object files are consistent with one another and are consistent
15912 with any source files it can locate. The following switches control binder
15913 access to sources.
15915 @quotation
15917 @geindex -s (gnatbind)
15918 @end quotation
15921 @table @asis
15923 @item @code{-s}
15925 Require source files to be present. In this mode, the binder must be
15926 able to locate all source files that are referenced, in order to check
15927 their consistency. In normal mode, if a source file cannot be located it
15928 is simply ignored. If you specify this switch, a missing source
15929 file is an error.
15931 @geindex -Wx (gnatbind)
15933 @item @code{-Wx@emph{e}}
15935 Override default wide character encoding for standard Text_IO files.
15936 Normally the default wide character encoding method used for standard
15937 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
15938 the main source input (see description of switch
15939 @code{-gnatWx} for the compiler). The
15940 use of this switch for the binder (which has the same set of
15941 possible arguments) overrides this default as specified.
15943 @geindex -x (gnatbind)
15945 @item @code{-x}
15947 Exclude source files. In this mode, the binder only checks that ALI
15948 files are consistent with one another. Source files are not accessed.
15949 The binder runs faster in this mode, and there is still a guarantee that
15950 the resulting program is self-consistent.
15951 If a source file has been edited since it was last compiled, and you
15952 specify this switch, the binder will not detect that the object
15953 file is out of date with respect to the source file. Note that this is the
15954 mode that is automatically used by @code{gnatmake} because in this
15955 case the checking against sources has already been performed by
15956 @code{gnatmake} in the course of compilation (i.e., before binding).
15957 @end table
15959 @node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
15960 @anchor{gnat_ugn/building_executable_programs_with_gnat id36}@anchor{124}@anchor{gnat_ugn/building_executable_programs_with_gnat binder-error-message-control}@anchor{125}
15961 @subsubsection Binder Error Message Control
15964 The following switches provide control over the generation of error
15965 messages from the binder:
15967 @quotation
15969 @geindex -v (gnatbind)
15970 @end quotation
15973 @table @asis
15975 @item @code{-v}
15977 Verbose mode. In the normal mode, brief error messages are generated to
15978 @code{stderr}. If this switch is present, a header is written
15979 to @code{stdout} and any error messages are directed to @code{stdout}.
15980 All that is written to @code{stderr} is a brief summary message.
15982 @geindex -b (gnatbind)
15984 @item @code{-b}
15986 Generate brief error messages to @code{stderr} even if verbose mode is
15987 specified. This is relevant only when used with the
15988 @code{-v} switch.
15990 @geindex -m (gnatbind)
15992 @item @code{-m@emph{n}}
15994 Limits the number of error messages to @code{n}, a decimal integer in the
15995 range 1-999. The binder terminates immediately if this limit is reached.
15997 @geindex -M (gnatbind)
15999 @item @code{-M@emph{xxx}}
16001 Renames the generated main program from @code{main} to @code{xxx}.
16002 This is useful in the case of some cross-building environments, where
16003 the actual main program is separate from the one generated
16004 by @code{gnatbind}.
16006 @geindex -ws (gnatbind)
16008 @geindex Warnings
16010 @item @code{-ws}
16012 Suppress all warning messages.
16014 @geindex -we (gnatbind)
16016 @item @code{-we}
16018 Treat any warning messages as fatal errors.
16020 @geindex -t (gnatbind)
16022 @geindex Time stamp checks
16023 @geindex in binder
16025 @geindex Binder consistency checks
16027 @geindex Consistency checks
16028 @geindex in binder
16030 @item @code{-t}
16032 The binder performs a number of consistency checks including:
16035 @itemize *
16037 @item 
16038 Check that time stamps of a given source unit are consistent
16040 @item 
16041 Check that checksums of a given source unit are consistent
16043 @item 
16044 Check that consistent versions of @code{GNAT} were used for compilation
16046 @item 
16047 Check consistency of configuration pragmas as required
16048 @end itemize
16050 Normally failure of such checks, in accordance with the consistency
16051 requirements of the Ada Reference Manual, causes error messages to be
16052 generated which abort the binder and prevent the output of a binder
16053 file and subsequent link to obtain an executable.
16055 The @code{-t} switch converts these error messages
16056 into warnings, so that
16057 binding and linking can continue to completion even in the presence of such
16058 errors. The result may be a failed link (due to missing symbols), or a
16059 non-functional executable which has undefined semantics.
16061 @cartouche
16062 @quotation Note 
16063 This means that @code{-t} should be used only in unusual situations,
16064 with extreme care.
16065 @end quotation
16066 @end cartouche
16067 @end table
16069 @node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
16070 @anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{126}@anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{127}
16071 @subsubsection Elaboration Control
16074 The following switches provide additional control over the elaboration
16075 order. For full details see @ref{f,,Elaboration Order Handling in GNAT}.
16077 @geindex -f (gnatbind)
16080 @table @asis
16082 @item @code{-f@emph{elab-order}}
16084 Force elaboration order.
16086 @code{elab-order} should be the name of a "forced elaboration order file", that
16087 is, a text file containing library item names, one per line. A name of the
16088 form "some.unit%s" or "some.unit (spec)" denotes the spec of Some.Unit. A
16089 name of the form "some.unit%b" or "some.unit (body)" denotes the body of
16090 Some.Unit. Each pair of lines is taken to mean that there is an elaboration
16091 dependence of the second line on the first. For example, if the file
16092 contains:
16094 @example
16095 this (spec)
16096 this (body)
16097 that (spec)
16098 that (body)
16099 @end example
16101 then the spec of This will be elaborated before the body of This, and the
16102 body of This will be elaborated before the spec of That, and the spec of That
16103 will be elaborated before the body of That. The first and last of these three
16104 dependences are already required by Ada rules, so this file is really just
16105 forcing the body of This to be elaborated before the spec of That.
16107 The given order must be consistent with Ada rules, or else @code{gnatbind} will
16108 give elaboration cycle errors. For example, if you say x (body) should be
16109 elaborated before x (spec), there will be a cycle, because Ada rules require
16110 x (spec) to be elaborated before x (body); you can't have the spec and body
16111 both elaborated before each other.
16113 If you later add "with That;" to the body of This, there will be a cycle, in
16114 which case you should erase either "this (body)" or "that (spec)" from the
16115 above forced elaboration order file.
16117 Blank lines and Ada-style comments are ignored. Unit names that do not exist
16118 in the program are ignored. Units in the GNAT predefined library are also
16119 ignored.
16121 @geindex -p (gnatbind)
16123 @item @code{-p}
16125 Normally the binder attempts to choose an elaboration order that is
16126 likely to minimize the likelihood of an elaboration order error resulting
16127 in raising a @code{Program_Error} exception. This switch reverses the
16128 action of the binder, and requests that it deliberately choose an order
16129 that is likely to maximize the likelihood of an elaboration error.
16130 This is useful in ensuring portability and avoiding dependence on
16131 accidental fortuitous elaboration ordering.
16133 Normally it only makes sense to use the @code{-p}
16134 switch if dynamic
16135 elaboration checking is used (@code{-gnatE} switch used for compilation).
16136 This is because in the default static elaboration mode, all necessary
16137 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
16138 These implicit pragmas are still respected by the binder in
16139 @code{-p} mode, so a
16140 safe elaboration order is assured.
16142 Note that @code{-p} is not intended for
16143 production use; it is more for debugging/experimental use.
16144 @end table
16146 @node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
16147 @anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{128}@anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{129}
16148 @subsubsection Output Control
16151 The following switches allow additional control over the output
16152 generated by the binder.
16154 @quotation
16156 @geindex -c (gnatbind)
16157 @end quotation
16160 @table @asis
16162 @item @code{-c}
16164 Check only. Do not generate the binder output file. In this mode the
16165 binder performs all error checks but does not generate an output file.
16167 @geindex -e (gnatbind)
16169 @item @code{-e}
16171 Output complete list of elaboration-order dependencies, showing the
16172 reason for each dependency. This output can be rather extensive but may
16173 be useful in diagnosing problems with elaboration order. The output is
16174 written to @code{stdout}.
16176 @geindex -h (gnatbind)
16178 @item @code{-h}
16180 Output usage information. The output is written to @code{stdout}.
16182 @geindex -K (gnatbind)
16184 @item @code{-K}
16186 Output linker options to @code{stdout}. Includes library search paths,
16187 contents of pragmas Ident and Linker_Options, and libraries added
16188 by @code{gnatbind}.
16190 @geindex -l (gnatbind)
16192 @item @code{-l}
16194 Output chosen elaboration order. The output is written to @code{stdout}.
16196 @geindex -O (gnatbind)
16198 @item @code{-O}
16200 Output full names of all the object files that must be linked to provide
16201 the Ada component of the program. The output is written to @code{stdout}.
16202 This list includes the files explicitly supplied and referenced by the user
16203 as well as implicitly referenced run-time unit files. The latter are
16204 omitted if the corresponding units reside in shared libraries. The
16205 directory names for the run-time units depend on the system configuration.
16207 @geindex -o (gnatbind)
16209 @item @code{-o @emph{file}}
16211 Set name of output file to @code{file} instead of the normal
16212 @code{b~`mainprog}.adb` default. Note that @code{file} denote the Ada
16213 binder generated body filename.
16214 Note that if this option is used, then linking must be done manually.
16215 It is not possible to use gnatlink in this case, since it cannot locate
16216 the binder file.
16218 @geindex -r (gnatbind)
16220 @item @code{-r}
16222 Generate list of @code{pragma Restrictions} that could be applied to
16223 the current unit. This is useful for code audit purposes, and also may
16224 be used to improve code generation in some cases.
16225 @end table
16227 @node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
16228 @anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{120}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{12a}
16229 @subsubsection Dynamic Allocation Control
16232 The heap control switches -- @code{-H32} and @code{-H64} --
16233 determine whether dynamic allocation uses 32-bit or 64-bit memory.
16234 They only affect compiler-generated allocations via @code{__gnat_malloc};
16235 explicit calls to @code{malloc} and related functions from the C
16236 run-time library are unaffected.
16239 @table @asis
16241 @item @code{-H32}
16243 Allocate memory on 32-bit heap
16245 @item @code{-H64}
16247 Allocate memory on 64-bit heap.  This is the default
16248 unless explicitly overridden by a @code{'Size} clause on the access type.
16249 @end table
16251 These switches are only effective on VMS platforms.
16253 @node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
16254 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-non-ada-main-programs}@anchor{b4}@anchor{gnat_ugn/building_executable_programs_with_gnat id40}@anchor{12b}
16255 @subsubsection Binding with Non-Ada Main Programs
16258 The description so far has assumed that the main
16259 program is in Ada, and that the task of the binder is to generate a
16260 corresponding function @code{main} that invokes this Ada main
16261 program. GNAT also supports the building of executable programs where
16262 the main program is not in Ada, but some of the called routines are
16263 written in Ada and compiled using GNAT (@ref{44,,Mixed Language Programming}).
16264 The following switch is used in this situation:
16266 @quotation
16268 @geindex -n (gnatbind)
16269 @end quotation
16272 @table @asis
16274 @item @code{-n}
16276 No main program. The main program is not in Ada.
16277 @end table
16279 In this case, most of the functions of the binder are still required,
16280 but instead of generating a main program, the binder generates a file
16281 containing the following callable routines:
16283 @quotation
16285 @geindex adainit
16288 @table @asis
16290 @item @code{adainit}
16292 You must call this routine to initialize the Ada part of the program by
16293 calling the necessary elaboration routines. A call to @code{adainit} is
16294 required before the first call to an Ada subprogram.
16296 Note that it is assumed that the basic execution environment must be setup
16297 to be appropriate for Ada execution at the point where the first Ada
16298 subprogram is called. In particular, if the Ada code will do any
16299 floating-point operations, then the FPU must be setup in an appropriate
16300 manner. For the case of the x86, for example, full precision mode is
16301 required. The procedure GNAT.Float_Control.Reset may be used to ensure
16302 that the FPU is in the right state.
16303 @end table
16305 @geindex adafinal
16308 @table @asis
16310 @item @code{adafinal}
16312 You must call this routine to perform any library-level finalization
16313 required by the Ada subprograms. A call to @code{adafinal} is required
16314 after the last call to an Ada subprogram, and before the program
16315 terminates.
16316 @end table
16317 @end quotation
16319 @geindex -n (gnatbind)
16321 @geindex Binder
16322 @geindex multiple input files
16324 If the @code{-n} switch
16325 is given, more than one ALI file may appear on
16326 the command line for @code{gnatbind}. The normal @code{closure}
16327 calculation is performed for each of the specified units. Calculating
16328 the closure means finding out the set of units involved by tracing
16329 @emph{with} references. The reason it is necessary to be able to
16330 specify more than one ALI file is that a given program may invoke two or
16331 more quite separate groups of Ada units.
16333 The binder takes the name of its output file from the last specified ALI
16334 file, unless overridden by the use of the @code{-o file}.
16336 @geindex -o (gnatbind)
16338 The output is an Ada unit in source form that can be compiled with GNAT.
16339 This compilation occurs automatically as part of the @code{gnatlink}
16340 processing.
16342 Currently the GNAT run time requires a FPU using 80 bits mode
16343 precision. Under targets where this is not the default it is required to
16344 call GNAT.Float_Control.Reset before using floating point numbers (this
16345 include float computation, float input and output) in the Ada code. A
16346 side effect is that this could be the wrong mode for the foreign code
16347 where floating point computation could be broken after this call.
16349 @node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16350 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-programs-with-no-main-subprogram}@anchor{12c}@anchor{gnat_ugn/building_executable_programs_with_gnat id41}@anchor{12d}
16351 @subsubsection Binding Programs with No Main Subprogram
16354 It is possible to have an Ada program which does not have a main
16355 subprogram. This program will call the elaboration routines of all the
16356 packages, then the finalization routines.
16358 The following switch is used to bind programs organized in this manner:
16360 @quotation
16362 @geindex -z (gnatbind)
16363 @end quotation
16366 @table @asis
16368 @item @code{-z}
16370 Normally the binder checks that the unit name given on the command line
16371 corresponds to a suitable main subprogram. When this switch is used,
16372 a list of ALI files can be given, and the execution of the program
16373 consists of elaboration of these units in an appropriate order. Note
16374 that the default wide character encoding method for standard Text_IO
16375 files is always set to Brackets if this switch is set (you can use
16376 the binder switch
16377 @code{-Wx} to override this default).
16378 @end table
16380 @node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16381 @anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{12e}@anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{12f}
16382 @subsection Command-Line Access
16385 The package @code{Ada.Command_Line} provides access to the command-line
16386 arguments and program name. In order for this interface to operate
16387 correctly, the two variables
16389 @example
16390 int gnat_argc;
16391 char **gnat_argv;
16392 @end example
16394 @geindex gnat_argv
16396 @geindex gnat_argc
16398 are declared in one of the GNAT library routines. These variables must
16399 be set from the actual @code{argc} and @code{argv} values passed to the
16400 main program. With no @emph{n} present, @code{gnatbind}
16401 generates the C main program to automatically set these variables.
16402 If the @emph{n} switch is used, there is no automatic way to
16403 set these variables. If they are not set, the procedures in
16404 @code{Ada.Command_Line} will not be available, and any attempt to use
16405 them will raise @code{Constraint_Error}. If command line access is
16406 required, your main program must set @code{gnat_argc} and
16407 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
16410 @node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16411 @anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-for-gnatbind}@anchor{8c}@anchor{gnat_ugn/building_executable_programs_with_gnat id43}@anchor{130}
16412 @subsection Search Paths for @code{gnatbind}
16415 The binder takes the name of an ALI file as its argument and needs to
16416 locate source files as well as other ALI files to verify object consistency.
16418 For source files, it follows exactly the same search rules as @code{gcc}
16419 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16420 directories searched are:
16423 @itemize *
16425 @item 
16426 The directory containing the ALI file named in the command line, unless
16427 the switch @code{-I-} is specified.
16429 @item 
16430 All directories specified by @code{-I}
16431 switches on the @code{gnatbind}
16432 command line, in the order given.
16434 @geindex ADA_PRJ_OBJECTS_FILE
16436 @item 
16437 Each of the directories listed in the text file whose name is given
16438 by the 
16439 @geindex ADA_PRJ_OBJECTS_FILE
16440 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16441 @code{ADA_PRJ_OBJECTS_FILE} environment variable.
16443 @geindex ADA_PRJ_OBJECTS_FILE
16444 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16445 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16446 driver when project files are used. It should not normally be set
16447 by other means.
16449 @geindex ADA_OBJECTS_PATH
16451 @item 
16452 Each of the directories listed in the value of the
16453 @geindex ADA_OBJECTS_PATH
16454 @geindex environment variable; ADA_OBJECTS_PATH
16455 @code{ADA_OBJECTS_PATH} environment variable.
16456 Construct this value
16457 exactly as the 
16458 @geindex PATH
16459 @geindex environment variable; PATH
16460 @code{PATH} environment variable: a list of directory
16461 names separated by colons (semicolons when working with the NT version
16462 of GNAT).
16464 @item 
16465 The content of the @code{ada_object_path} file which is part of the GNAT
16466 installation tree and is used to store standard libraries such as the
16467 GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is
16468 specified. See @ref{87,,Installing a library}
16469 @end itemize
16471 @geindex -I (gnatbind)
16473 @geindex -aI (gnatbind)
16475 @geindex -aO (gnatbind)
16477 In the binder the switch @code{-I}
16478 is used to specify both source and
16479 library file paths. Use @code{-aI}
16480 instead if you want to specify
16481 source paths only, and @code{-aO}
16482 if you want to specify library paths
16483 only. This means that for the binder
16484 @code{-I@emph{dir}} is equivalent to
16485 @code{-aI@emph{dir}}
16486 @code{-aO`@emph{dir}}.
16487 The binder generates the bind file (a C language source file) in the
16488 current working directory.
16490 @geindex Ada
16492 @geindex System
16494 @geindex Interfaces
16496 @geindex GNAT
16498 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
16499 children make up the GNAT Run-Time Library, together with the package
16500 GNAT and its children, which contain a set of useful additional
16501 library functions provided by GNAT. The sources for these units are
16502 needed by the compiler and are kept together in one directory. The ALI
16503 files and object files generated by compiling the RTL are needed by the
16504 binder and the linker and are kept together in one directory, typically
16505 different from the directory containing the sources. In a normal
16506 installation, you need not specify these directory names when compiling
16507 or binding. Either the environment variables or the built-in defaults
16508 cause these files to be found.
16510 Besides simplifying access to the RTL, a major use of search paths is
16511 in compiling sources from multiple directories. This can make
16512 development environments much more flexible.
16514 @node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16515 @anchor{gnat_ugn/building_executable_programs_with_gnat id44}@anchor{131}@anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatbind-usage}@anchor{132}
16516 @subsection Examples of @code{gnatbind} Usage
16519 Here are some examples of @code{gnatbind} invovations:
16521 @quotation
16523 @example
16524 gnatbind hello
16525 @end example
16527 The main program @code{Hello} (source program in @code{hello.adb}) is
16528 bound using the standard switch settings. The generated main program is
16529 @code{b~hello.adb}. This is the normal, default use of the binder.
16531 @example
16532 gnatbind hello -o mainprog.adb
16533 @end example
16535 The main program @code{Hello} (source program in @code{hello.adb}) is
16536 bound using the standard switch settings. The generated main program is
16537 @code{mainprog.adb} with the associated spec in
16538 @code{mainprog.ads}. Note that you must specify the body here not the
16539 spec. Note that if this option is used, then linking must be done manually,
16540 since gnatlink will not be able to find the generated file.
16541 @end quotation
16543 @node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16544 @anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{133}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{1e}
16545 @section Linking with @code{gnatlink}
16548 @geindex gnatlink
16550 This chapter discusses @code{gnatlink}, a tool that links
16551 an Ada program and builds an executable file. This utility
16552 invokes the system linker (via the @code{gcc} command)
16553 with a correct list of object files and library references.
16554 @code{gnatlink} automatically determines the list of files and
16555 references for the Ada part of a program. It uses the binder file
16556 generated by the @code{gnatbind} to determine this list.
16558 @menu
16559 * Running gnatlink:: 
16560 * Switches for gnatlink:: 
16562 @end menu
16564 @node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16565 @anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{134}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{135}
16566 @subsection Running @code{gnatlink}
16569 The form of the @code{gnatlink} command is
16571 @example
16572 $ gnatlink [ switches ] mainprog [.ali]
16573            [ non-Ada objects ] [ linker options ]
16574 @end example
16576 The arguments of @code{gnatlink} (switches, main @code{ALI} file,
16577 non-Ada objects
16578 or linker options) may be in any order, provided that no non-Ada object may
16579 be mistaken for a main @code{ALI} file.
16580 Any file name @code{F} without the @code{.ali}
16581 extension will be taken as the main @code{ALI} file if a file exists
16582 whose name is the concatenation of @code{F} and @code{.ali}.
16584 @code{mainprog.ali} references the ALI file of the main program.
16585 The @code{.ali} extension of this file can be omitted. From this
16586 reference, @code{gnatlink} locates the corresponding binder file
16587 @code{b~mainprog.adb} and, using the information in this file along
16588 with the list of non-Ada objects and linker options, constructs a
16589 linker command file to create the executable.
16591 The arguments other than the @code{gnatlink} switches and the main
16592 @code{ALI} file are passed to the linker uninterpreted.
16593 They typically include the names of
16594 object files for units written in other languages than Ada and any library
16595 references required to resolve references in any of these foreign language
16596 units, or in @code{Import} pragmas in any Ada units.
16598 @code{linker options} is an optional list of linker specific
16599 switches.
16600 The default linker called by gnatlink is @code{gcc} which in
16601 turn calls the appropriate system linker.
16603 One useful option for the linker is @code{-s}: it reduces the size of the
16604 executable by removing all symbol table and relocation information from the
16605 executable.
16607 Standard options for the linker such as @code{-lmy_lib} or
16608 @code{-Ldir} can be added as is.
16609 For options that are not recognized by
16610 @code{gcc} as linker options, use the @code{gcc} switches
16611 @code{-Xlinker} or @code{-Wl,}.
16613 Refer to the GCC documentation for
16614 details.
16616 Here is an example showing how to generate a linker map:
16618 @example
16619 $ gnatlink my_prog -Wl,-Map,MAPFILE
16620 @end example
16622 Using @code{linker options} it is possible to set the program stack and
16623 heap size.
16624 See @ref{136,,Setting Stack Size from gnatlink} and
16625 @ref{137,,Setting Heap Size from gnatlink}.
16627 @code{gnatlink} determines the list of objects required by the Ada
16628 program and prepends them to the list of objects passed to the linker.
16629 @code{gnatlink} also gathers any arguments set by the use of
16630 @code{pragma Linker_Options} and adds them to the list of arguments
16631 presented to the linker.
16633 @node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
16634 @anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{138}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{139}
16635 @subsection Switches for @code{gnatlink}
16638 The following switches are available with the @code{gnatlink} utility:
16640 @geindex --version (gnatlink)
16643 @table @asis
16645 @item @code{--version}
16647 Display Copyright and version, then exit disregarding all other options.
16648 @end table
16650 @geindex --help (gnatlink)
16653 @table @asis
16655 @item @code{--help}
16657 If @code{--version} was not used, display usage, then exit disregarding
16658 all other options.
16659 @end table
16661 @geindex Command line length
16663 @geindex -f (gnatlink)
16666 @table @asis
16668 @item @code{-f}
16670 On some targets, the command line length is limited, and @code{gnatlink}
16671 will generate a separate file for the linker if the list of object files
16672 is too long.
16673 The @code{-f} switch forces this file
16674 to be generated even if
16675 the limit is not exceeded. This is useful in some cases to deal with
16676 special situations where the command line length is exceeded.
16677 @end table
16679 @geindex Debugging information
16680 @geindex including
16682 @geindex -g (gnatlink)
16685 @table @asis
16687 @item @code{-g}
16689 The option to include debugging information causes the Ada bind file (in
16690 other words, @code{b~mainprog.adb}) to be compiled with @code{-g}.
16691 In addition, the binder does not delete the @code{b~mainprog.adb},
16692 @code{b~mainprog.o} and @code{b~mainprog.ali} files.
16693 Without @code{-g}, the binder removes these files by default.
16694 @end table
16696 @geindex -n (gnatlink)
16699 @table @asis
16701 @item @code{-n}
16703 Do not compile the file generated by the binder. This may be used when
16704 a link is rerun with different options, but there is no need to recompile
16705 the binder file.
16706 @end table
16708 @geindex -v (gnatlink)
16711 @table @asis
16713 @item @code{-v}
16715 Verbose mode. Causes additional information to be output, including a full
16716 list of the included object files.
16717 This switch option is most useful when you want
16718 to see what set of object files are being used in the link step.
16719 @end table
16721 @geindex -v -v (gnatlink)
16724 @table @asis
16726 @item @code{-v -v}
16728 Very verbose mode. Requests that the compiler operate in verbose mode when
16729 it compiles the binder file, and that the system linker run in verbose mode.
16730 @end table
16732 @geindex -o (gnatlink)
16735 @table @asis
16737 @item @code{-o @emph{exec-name}}
16739 @code{exec-name} specifies an alternate name for the generated
16740 executable program. If this switch is omitted, the executable has the same
16741 name as the main unit. For example, @code{gnatlink try.ali} creates
16742 an executable called @code{try}.
16743 @end table
16745 @geindex -b (gnatlink)
16748 @table @asis
16750 @item @code{-b @emph{target}}
16752 Compile your program to run on @code{target}, which is the name of a
16753 system configuration. You must have a GNAT cross-compiler built if
16754 @code{target} is not the same as your host system.
16755 @end table
16757 @geindex -B (gnatlink)
16760 @table @asis
16762 @item @code{-B@emph{dir}}
16764 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
16765 from @code{dir} instead of the default location. Only use this switch
16766 when multiple versions of the GNAT compiler are available.
16767 See the @code{Directory Options} section in @cite{The_GNU_Compiler_Collection}
16768 for further details. You would normally use the @code{-b} or
16769 @code{-V} switch instead.
16770 @end table
16772 @geindex -M (gnatlink)
16775 @table @asis
16777 @item @code{-M}
16779 When linking an executable, create a map file. The name of the map file
16780 has the same name as the executable with extension ".map".
16781 @end table
16783 @geindex -M= (gnatlink)
16786 @table @asis
16788 @item @code{-M=@emph{mapfile}}
16790 When linking an executable, create a map file. The name of the map file is
16791 @code{mapfile}.
16792 @end table
16794 @geindex --GCC=compiler_name (gnatlink)
16797 @table @asis
16799 @item @code{--GCC=@emph{compiler_name}}
16801 Program used for compiling the binder file. The default is
16802 @code{gcc}. You need to use quotes around @code{compiler_name} if
16803 @code{compiler_name} contains spaces or other separator characters.
16804 As an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to
16805 use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
16806 inserted after your command name. Thus in the above example the compiler
16807 command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
16808 A limitation of this syntax is that the name and path name of the executable
16809 itself must not include any embedded spaces. If the compiler executable is
16810 different from the default one (gcc or <prefix>-gcc), then the back-end
16811 switches in the ALI file are not used to compile the binder generated source.
16812 For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
16813 switches will be used for @code{--GCC="gcc -gnatv"}. If several
16814 @code{--GCC=compiler_name} are used, only the last @code{compiler_name}
16815 is taken into account. However, all the additional switches are also taken
16816 into account. Thus,
16817 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
16818 @code{--GCC="bar -x -y -z -t"}.
16819 @end table
16821 @geindex --LINK= (gnatlink)
16824 @table @asis
16826 @item @code{--LINK=@emph{name}}
16828 @code{name} is the name of the linker to be invoked. This is especially
16829 useful in mixed language programs since languages such as C++ require
16830 their own linker to be used. When this switch is omitted, the default
16831 name for the linker is @code{gcc}. When this switch is used, the
16832 specified linker is called instead of @code{gcc} with exactly the same
16833 parameters that would have been passed to @code{gcc} so if the desired
16834 linker requires different parameters it is necessary to use a wrapper
16835 script that massages the parameters before invoking the real linker. It
16836 may be useful to control the exact invocation by using the verbose
16837 switch.
16838 @end table
16840 @node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
16841 @anchor{gnat_ugn/building_executable_programs_with_gnat using-the-gnu-make-utility}@anchor{1f}@anchor{gnat_ugn/building_executable_programs_with_gnat id48}@anchor{13a}
16842 @section Using the GNU @code{make} Utility
16845 @geindex make (GNU)
16846 @geindex GNU make
16848 This chapter offers some examples of makefiles that solve specific
16849 problems. It does not explain how to write a makefile, nor does it try to replace the
16850 @code{gnatmake} utility (@ref{1b,,Building with gnatmake}).
16852 All the examples in this section are specific to the GNU version of
16853 make. Although @code{make} is a standard utility, and the basic language
16854 is the same, these examples use some advanced features found only in
16855 @code{GNU make}.
16857 @menu
16858 * Using gnatmake in a Makefile:: 
16859 * Automatically Creating a List of Directories:: 
16860 * Generating the Command Line Switches:: 
16861 * Overcoming Command Line Length Limits:: 
16863 @end menu
16865 @node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
16866 @anchor{gnat_ugn/building_executable_programs_with_gnat using-gnatmake-in-a-makefile}@anchor{13b}@anchor{gnat_ugn/building_executable_programs_with_gnat id49}@anchor{13c}
16867 @subsection Using gnatmake in a Makefile
16870 @c index makefile (GNU make)
16872 Complex project organizations can be handled in a very powerful way by
16873 using GNU make combined with gnatmake. For instance, here is a Makefile
16874 which allows you to build each subsystem of a big project into a separate
16875 shared library. Such a makefile allows you to significantly reduce the link
16876 time of very big applications while maintaining full coherence at
16877 each step of the build process.
16879 The list of dependencies are handled automatically by
16880 @code{gnatmake}. The Makefile is simply used to call gnatmake in each of
16881 the appropriate directories.
16883 Note that you should also read the example on how to automatically
16884 create the list of directories
16885 (@ref{13d,,Automatically Creating a List of Directories})
16886 which might help you in case your project has a lot of subdirectories.
16888 @example
16889 ## This Makefile is intended to be used with the following directory
16890 ## configuration:
16891 ##  - The sources are split into a series of csc (computer software components)
16892 ##    Each of these csc is put in its own directory.
16893 ##    Their name are referenced by the directory names.
16894 ##    They will be compiled into shared library (although this would also work
16895 ##    with static libraries
16896 ##  - The main program (and possibly other packages that do not belong to any
16897 ##    csc is put in the top level directory (where the Makefile is).
16898 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16899 ##                    \\_ second_csc (sources) __ lib (will contain the library)
16900 ##                    \\_ ...
16901 ## Although this Makefile is build for shared library, it is easy to modify
16902 ## to build partial link objects instead (modify the lines with -shared and
16903 ## gnatlink below)
16905 ## With this makefile, you can change any file in the system or add any new
16906 ## file, and everything will be recompiled correctly (only the relevant shared
16907 ## objects will be recompiled, and the main program will be re-linked).
16909 # The list of computer software component for your project. This might be
16910 # generated automatically.
16911 CSC_LIST=aa bb cc
16913 # Name of the main program (no extension)
16914 MAIN=main
16916 # If we need to build objects with -fPIC, uncomment the following line
16917 #NEED_FPIC=-fPIC
16919 # The following variable should give the directory containing libgnat.so
16920 # You can get this directory through 'gnatls -v'. This is usually the last
16921 # directory in the Object_Path.
16922 GLIB=...
16924 # The directories for the libraries
16925 # (This macro expands the list of CSC to the list of shared libraries, you
16926 # could simply use the expanded form:
16927 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16928 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16930 $@{MAIN@}: objects $@{LIB_DIR@}
16931     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16932     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16934 objects::
16935     # recompile the sources
16936     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16938 # Note: In a future version of GNAT, the following commands will be simplified
16939 # by a new tool, gnatmlib
16940 $@{LIB_DIR@}:
16941     mkdir -p $@{dir $@@ @}
16942     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16943     cd $@{dir $@@ @} && cp -f ../*.ali .
16945 # The dependencies for the modules
16946 # Note that we have to force the expansion of *.o, since in some cases
16947 # make won't be able to do it itself.
16948 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16949 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16950 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16952 # Make sure all of the shared libraries are in the path before starting the
16953 # program
16954 run::
16955     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16957 clean::
16958     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16959     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16960     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16961     $@{RM@} *.o *.ali $@{MAIN@}
16962 @end example
16964 @node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
16965 @anchor{gnat_ugn/building_executable_programs_with_gnat id50}@anchor{13e}@anchor{gnat_ugn/building_executable_programs_with_gnat automatically-creating-a-list-of-directories}@anchor{13d}
16966 @subsection Automatically Creating a List of Directories
16969 In most makefiles, you will have to specify a list of directories, and
16970 store it in a variable. For small projects, it is often easier to
16971 specify each of them by hand, since you then have full control over what
16972 is the proper order for these directories, which ones should be
16973 included.
16975 However, in larger projects, which might involve hundreds of
16976 subdirectories, it might be more convenient to generate this list
16977 automatically.
16979 The example below presents two methods. The first one, although less
16980 general, gives you more control over the list. It involves wildcard
16981 characters, that are automatically expanded by @code{make}. Its
16982 shortcoming is that you need to explicitly specify some of the
16983 organization of your project, such as for instance the directory tree
16984 depth, whether some directories are found in a separate tree, etc.
16986 The second method is the most general one. It requires an external
16987 program, called @code{find}, which is standard on all Unix systems. All
16988 the directories found under a given root directory will be added to the
16989 list.
16991 @example
16992 # The examples below are based on the following directory hierarchy:
16993 # All the directories can contain any number of files
16994 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16995 #                       ->  ab
16996 #                       ->  ac
16997 #                ->  b  ->  ba  ->  baa
16998 #                       ->  bb
16999 #                       ->  bc
17000 # This Makefile creates a variable called DIRS, that can be reused any time
17001 # you need this list (see the other examples in this section)
17003 # The root of your project's directory hierarchy
17004 ROOT_DIRECTORY=.
17006 ####
17007 # First method: specify explicitly the list of directories
17008 # This allows you to specify any subset of all the directories you need.
17009 ####
17011 DIRS := a/aa/ a/ab/ b/ba/
17013 ####
17014 # Second method: use wildcards
17015 # Note that the argument(s) to wildcard below should end with a '/'.
17016 # Since wildcards also return file names, we have to filter them out
17017 # to avoid duplicate directory names.
17018 # We thus use make's `@w{`}dir`@w{`} and `@w{`}sort`@w{`} functions.
17019 # It sets DIRs to the following value (note that the directories aaa and baa
17020 # are not given, unless you change the arguments to wildcard).
17021 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17022 ####
17024 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17025                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17027 ####
17028 # Third method: use an external program
17029 # This command is much faster if run on local disks, avoiding NFS slowdowns.
17030 # This is the most complete command: it sets DIRs to the following value:
17031 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17032 ####
17034 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17035 @end example
17037 @node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
17038 @anchor{gnat_ugn/building_executable_programs_with_gnat id51}@anchor{13f}@anchor{gnat_ugn/building_executable_programs_with_gnat generating-the-command-line-switches}@anchor{140}
17039 @subsection Generating the Command Line Switches
17042 Once you have created the list of directories as explained in the
17043 previous section (@ref{13d,,Automatically Creating a List of Directories}),
17044 you can easily generate the command line arguments to pass to gnatmake.
17046 For the sake of completeness, this example assumes that the source path
17047 is not the same as the object path, and that you have two separate lists
17048 of directories.
17050 @example
17051 # see "Automatically creating a list of directories" to create
17052 # these variables
17053 SOURCE_DIRS=
17054 OBJECT_DIRS=
17056 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17057 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17059 all:
17060         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17061 @end example
17063 @node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
17064 @anchor{gnat_ugn/building_executable_programs_with_gnat overcoming-command-line-length-limits}@anchor{141}@anchor{gnat_ugn/building_executable_programs_with_gnat id52}@anchor{142}
17065 @subsection Overcoming Command Line Length Limits
17068 One problem that might be encountered on big projects is that many
17069 operating systems limit the length of the command line. It is thus hard to give
17070 gnatmake the list of source and object directories.
17072 This example shows how you can set up environment variables, which will
17073 make @code{gnatmake} behave exactly as if the directories had been
17074 specified on the command line, but have a much higher length limit (or
17075 even none on most systems).
17077 It assumes that you have created a list of directories in your Makefile,
17078 using one of the methods presented in
17079 @ref{13d,,Automatically Creating a List of Directories}.
17080 For the sake of completeness, we assume that the object
17081 path (where the ALI files are found) is different from the sources patch.
17083 Note a small trick in the Makefile below: for efficiency reasons, we
17084 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17085 expanded immediately by @code{make}. This way we overcome the standard
17086 make behavior which is to expand the variables only when they are
17087 actually used.
17089 On Windows, if you are using the standard Windows command shell, you must
17090 replace colons with semicolons in the assignments to these variables.
17092 @example
17093 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17094 # This is the same thing as putting the -I arguments on the command line.
17095 # (the equivalent of using -aI on the command line would be to define
17096 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17097 # You can of course have different values for these variables.
17099 # Note also that we need to keep the previous values of these variables, since
17100 # they might have been set before running 'make' to specify where the GNAT
17101 # library is installed.
17103 # see "Automatically creating a list of directories" to create these
17104 # variables
17105 SOURCE_DIRS=
17106 OBJECT_DIRS=
17108 empty:=
17109 space:=$@{empty@} $@{empty@}
17110 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17111 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17112 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17113 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17114 export ADA_INCLUDE_PATH
17115 export ADA_OBJECTS_PATH
17117 all:
17118         gnatmake main_unit
17119 @end example
17121 @node GNAT Utility Programs,GNAT and Program Execution,Building Executable Programs with GNAT,Top
17122 @anchor{gnat_ugn/gnat_utility_programs doc}@anchor{143}@anchor{gnat_ugn/gnat_utility_programs gnat-utility-programs}@anchor{b}@anchor{gnat_ugn/gnat_utility_programs id1}@anchor{144}
17123 @chapter GNAT Utility Programs
17126 This chapter describes a number of utility programs:
17130 @itemize *
17132 @item 
17133 @ref{20,,The File Cleanup Utility gnatclean}
17135 @item 
17136 @ref{21,,The GNAT Library Browser gnatls}
17138 @item 
17139 @ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
17141 @item 
17142 @ref{23,,The Ada to HTML Converter gnathtml}
17143 @end itemize
17145 Other GNAT utilities are described elsewhere in this manual:
17148 @itemize *
17150 @item 
17151 @ref{59,,Handling Arbitrary File Naming Conventions with gnatname}
17153 @item 
17154 @ref{63,,File Name Krunching with gnatkr}
17156 @item 
17157 @ref{36,,Renaming Files with gnatchop}
17159 @item 
17160 @ref{17,,Preprocessing with gnatprep}
17161 @end itemize
17163 @menu
17164 * The File Cleanup Utility gnatclean:: 
17165 * The GNAT Library Browser gnatls:: 
17166 * The Cross-Referencing Tools gnatxref and gnatfind:: 
17167 * The Ada to HTML Converter gnathtml:: 
17169 @end menu
17171 @node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
17172 @anchor{gnat_ugn/gnat_utility_programs id2}@anchor{145}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{20}
17173 @section The File Cleanup Utility @code{gnatclean}
17176 @geindex File cleanup tool
17178 @geindex gnatclean
17180 @code{gnatclean} is a tool that allows the deletion of files produced by the
17181 compiler, binder and linker, including ALI files, object files, tree files,
17182 expanded source files, library files, interface copy source files, binder
17183 generated files and executable files.
17185 @menu
17186 * Running gnatclean:: 
17187 * Switches for gnatclean:: 
17189 @end menu
17191 @node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
17192 @anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{146}@anchor{gnat_ugn/gnat_utility_programs id3}@anchor{147}
17193 @subsection Running @code{gnatclean}
17196 The @code{gnatclean} command has the form:
17198 @quotation
17200 @example
17201 $ gnatclean switches names
17202 @end example
17203 @end quotation
17205 where @code{names} is a list of source file names. Suffixes @code{.ads} and
17206 @code{adb} may be omitted. If a project file is specified using switch
17207 @code{-P}, then @code{names} may be completely omitted.
17209 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17210 if switch @code{-c} is not specified, by the binder and
17211 the linker. In informative-only mode, specified by switch
17212 @code{-n}, the list of files that would have been deleted in
17213 normal mode is listed, but no file is actually deleted.
17215 @node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
17216 @anchor{gnat_ugn/gnat_utility_programs id4}@anchor{148}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{149}
17217 @subsection Switches for @code{gnatclean}
17220 @code{gnatclean} recognizes the following switches:
17222 @geindex --version (gnatclean)
17225 @table @asis
17227 @item @code{--version}
17229 Display Copyright and version, then exit disregarding all other options.
17230 @end table
17232 @geindex --help (gnatclean)
17235 @table @asis
17237 @item @code{--help}
17239 If @code{--version} was not used, display usage, then exit disregarding
17240 all other options.
17242 @item @code{--subdirs=@emph{subdir}}
17244 Actual object directory of each project file is the subdirectory subdir of the
17245 object directory specified or defaulted in the project file.
17247 @item @code{--unchecked-shared-lib-imports}
17249 By default, shared library projects are not allowed to import static library
17250 projects. When this switch is used on the command line, this restriction is
17251 relaxed.
17252 @end table
17254 @geindex -c (gnatclean)
17257 @table @asis
17259 @item @code{-c}
17261 Only attempt to delete the files produced by the compiler, not those produced
17262 by the binder or the linker. The files that are not to be deleted are library
17263 files, interface copy files, binder generated files and executable files.
17264 @end table
17266 @geindex -D (gnatclean)
17269 @table @asis
17271 @item @code{-D @emph{dir}}
17273 Indicate that ALI and object files should normally be found in directory @code{dir}.
17274 @end table
17276 @geindex -F (gnatclean)
17279 @table @asis
17281 @item @code{-F}
17283 When using project files, if some errors or warnings are detected during
17284 parsing and verbose mode is not in effect (no use of switch
17285 -v), then error lines start with the full path name of the project
17286 file, rather than its simple file name.
17287 @end table
17289 @geindex -h (gnatclean)
17292 @table @asis
17294 @item @code{-h}
17296 Output a message explaining the usage of @code{gnatclean}.
17297 @end table
17299 @geindex -n (gnatclean)
17302 @table @asis
17304 @item @code{-n}
17306 Informative-only mode. Do not delete any files. Output the list of the files
17307 that would have been deleted if this switch was not specified.
17308 @end table
17310 @geindex -P (gnatclean)
17313 @table @asis
17315 @item @code{-P@emph{project}}
17317 Use project file @code{project}. Only one such switch can be used.
17318 When cleaning a project file, the files produced by the compilation of the
17319 immediate sources or inherited sources of the project files are to be
17320 deleted. This is not depending on the presence or not of executable names
17321 on the command line.
17322 @end table
17324 @geindex -q (gnatclean)
17327 @table @asis
17329 @item @code{-q}
17331 Quiet output. If there are no errors, do not output anything, except in
17332 verbose mode (switch -v) or in informative-only mode
17333 (switch -n).
17334 @end table
17336 @geindex -r (gnatclean)
17339 @table @asis
17341 @item @code{-r}
17343 When a project file is specified (using switch -P),
17344 clean all imported and extended project files, recursively. If this switch
17345 is not specified, only the files related to the main project file are to be
17346 deleted. This switch has no effect if no project file is specified.
17347 @end table
17349 @geindex -v (gnatclean)
17352 @table @asis
17354 @item @code{-v}
17356 Verbose mode.
17357 @end table
17359 @geindex -vP (gnatclean)
17362 @table @asis
17364 @item @code{-vP@emph{x}}
17366 Indicates the verbosity of the parsing of GNAT project files.
17367 @ref{de,,Switches Related to Project Files}.
17368 @end table
17370 @geindex -X (gnatclean)
17373 @table @asis
17375 @item @code{-X@emph{name}=@emph{value}}
17377 Indicates that external variable @code{name} has the value @code{value}.
17378 The Project Manager will use this value for occurrences of
17379 @code{external(name)} when parsing the project file.
17380 See @ref{de,,Switches Related to Project Files}.
17381 @end table
17383 @geindex -aO (gnatclean)
17386 @table @asis
17388 @item @code{-aO@emph{dir}}
17390 When searching for ALI and object files, look in directory @code{dir}.
17391 @end table
17393 @geindex -I (gnatclean)
17396 @table @asis
17398 @item @code{-I@emph{dir}}
17400 Equivalent to @code{-aO@emph{dir}}.
17401 @end table
17403 @geindex -I- (gnatclean)
17405 @geindex Source files
17406 @geindex suppressing search
17409 @table @asis
17411 @item @code{-I-}
17413 Do not look for ALI or object files in the directory
17414 where @code{gnatclean} was invoked.
17415 @end table
17417 @node The GNAT Library Browser gnatls,The Cross-Referencing Tools gnatxref and gnatfind,The File Cleanup Utility gnatclean,GNAT Utility Programs
17418 @anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{21}@anchor{gnat_ugn/gnat_utility_programs id5}@anchor{14a}
17419 @section The GNAT Library Browser @code{gnatls}
17422 @geindex Library browser
17424 @geindex gnatls
17426 @code{gnatls} is a tool that outputs information about compiled
17427 units. It gives the relationship between objects, unit names and source
17428 files. It can also be used to check the source dependencies of a unit
17429 as well as various characteristics.
17431 @menu
17432 * Running gnatls:: 
17433 * Switches for gnatls:: 
17434 * Example of gnatls Usage:: 
17436 @end menu
17438 @node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
17439 @anchor{gnat_ugn/gnat_utility_programs id6}@anchor{14b}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{14c}
17440 @subsection Running @code{gnatls}
17443 The @code{gnatls} command has the form
17445 @quotation
17447 @example
17448 $ gnatls switches object_or_ali_file
17449 @end example
17450 @end quotation
17452 The main argument is the list of object or @code{ali} files
17453 (see @ref{42,,The Ada Library Information Files})
17454 for which information is requested.
17456 In normal mode, without additional option, @code{gnatls} produces a
17457 four-column listing. Each line represents information for a specific
17458 object. The first column gives the full path of the object, the second
17459 column gives the name of the principal unit in this object, the third
17460 column gives the status of the source and the fourth column gives the
17461 full path of the source representing this unit.
17462 Here is a simple example of use:
17464 @quotation
17466 @example
17467 $ gnatls *.o
17468 ./demo1.o            demo1            DIF demo1.adb
17469 ./demo2.o            demo2             OK demo2.adb
17470 ./hello.o            h1                OK hello.adb
17471 ./instr-child.o      instr.child      MOK instr-child.adb
17472 ./instr.o            instr             OK instr.adb
17473 ./tef.o              tef              DIF tef.adb
17474 ./text_io_example.o  text_io_example   OK text_io_example.adb
17475 ./tgef.o             tgef             DIF tgef.adb
17476 @end example
17477 @end quotation
17479 The first line can be interpreted as follows: the main unit which is
17480 contained in
17481 object file @code{demo1.o} is demo1, whose main source is in
17482 @code{demo1.adb}. Furthermore, the version of the source used for the
17483 compilation of demo1 has been modified (DIF). Each source file has a status
17484 qualifier which can be:
17487 @table @asis
17489 @item @emph{OK (unchanged)}
17491 The version of the source file used for the compilation of the
17492 specified unit corresponds exactly to the actual source file.
17494 @item @emph{MOK (slightly modified)}
17496 The version of the source file used for the compilation of the
17497 specified unit differs from the actual source file but not enough to
17498 require recompilation. If you use gnatmake with the option
17499 @code{-m} (minimal recompilation), a file marked
17500 MOK will not be recompiled.
17502 @item @emph{DIF (modified)}
17504 No version of the source found on the path corresponds to the source
17505 used to build this object.
17507 @item @emph{??? (file not found)}
17509 No source file was found for this unit.
17511 @item @emph{HID (hidden,  unchanged version not first on PATH)}
17513 The version of the source that corresponds exactly to the source used
17514 for compilation has been found on the path but it is hidden by another
17515 version of the same source that has been modified.
17516 @end table
17518 @node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
17519 @anchor{gnat_ugn/gnat_utility_programs id7}@anchor{14d}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{14e}
17520 @subsection Switches for @code{gnatls}
17523 @code{gnatls} recognizes the following switches:
17525 @geindex --version (gnatls)
17528 @table @asis
17530 @item @code{--version}
17532 Display Copyright and version, then exit disregarding all other options.
17533 @end table
17535 @geindex --help (gnatls)
17538 @table @asis
17540 @item @code{--help}
17542 If @code{--version} was not used, display usage, then exit disregarding
17543 all other options.
17544 @end table
17546 @geindex -a (gnatls)
17549 @table @asis
17551 @item @code{-a}
17553 Consider all units, including those of the predefined Ada library.
17554 Especially useful with @code{-d}.
17555 @end table
17557 @geindex -d (gnatls)
17560 @table @asis
17562 @item @code{-d}
17564 List sources from which specified units depend on.
17565 @end table
17567 @geindex -h (gnatls)
17570 @table @asis
17572 @item @code{-h}
17574 Output the list of options.
17575 @end table
17577 @geindex -o (gnatls)
17580 @table @asis
17582 @item @code{-o}
17584 Only output information about object files.
17585 @end table
17587 @geindex -s (gnatls)
17590 @table @asis
17592 @item @code{-s}
17594 Only output information about source files.
17595 @end table
17597 @geindex -u (gnatls)
17600 @table @asis
17602 @item @code{-u}
17604 Only output information about compilation units.
17605 @end table
17607 @geindex -files (gnatls)
17610 @table @asis
17612 @item @code{-files=@emph{file}}
17614 Take as arguments the files listed in text file @code{file}.
17615 Text file @code{file} may contain empty lines that are ignored.
17616 Each nonempty line should contain the name of an existing file.
17617 Several such switches may be specified simultaneously.
17618 @end table
17620 @geindex -aO (gnatls)
17622 @geindex -aI (gnatls)
17624 @geindex -I (gnatls)
17626 @geindex -I- (gnatls)
17629 @table @asis
17631 @item @code{-aO@emph{dir}}, @code{-aI@emph{dir}}, @code{-I@emph{dir}}, @code{-I-}, @code{-nostdinc}
17633 Source path manipulation. Same meaning as the equivalent @code{gnatmake}
17634 flags (@ref{dc,,Switches for gnatmake}).
17635 @end table
17637 @geindex -aP (gnatls)
17640 @table @asis
17642 @item @code{-aP@emph{dir}}
17644 Add @code{dir} at the beginning of the project search dir.
17645 @end table
17647 @geindex --RTS (gnatls)
17650 @table @asis
17652 @item @code{--RTS=@emph{rts-path}}
17654 Specifies the default location of the runtime library. Same meaning as the
17655 equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17656 @end table
17658 @geindex -v (gnatls)
17661 @table @asis
17663 @item @code{-v}
17665 Verbose mode. Output the complete source, object and project paths. Do not use
17666 the default column layout but instead use long format giving as much as
17667 information possible on each requested units, including special
17668 characteristics such as:
17671 @itemize *
17673 @item 
17674 @emph{Preelaborable}: The unit is preelaborable in the Ada sense.
17676 @item 
17677 @emph{No_Elab_Code}:  No elaboration code has been produced by the compiler for this unit.
17679 @item 
17680 @emph{Pure}: The unit is pure in the Ada sense.
17682 @item 
17683 @emph{Elaborate_Body}: The unit contains a pragma Elaborate_Body.
17685 @item 
17686 @emph{Remote_Types}: The unit contains a pragma Remote_Types.
17688 @item 
17689 @emph{Shared_Passive}: The unit contains a pragma Shared_Passive.
17691 @item 
17692 @emph{Predefined}: This unit is part of the predefined environment and cannot be modified
17693 by the user.
17695 @item 
17696 @emph{Remote_Call_Interface}: The unit contains a pragma Remote_Call_Interface.
17697 @end itemize
17698 @end table
17700 @node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
17701 @anchor{gnat_ugn/gnat_utility_programs id8}@anchor{14f}@anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{150}
17702 @subsection Example of @code{gnatls} Usage
17705 Example of using the verbose switch. Note how the source and
17706 object paths are affected by the -I switch.
17708 @quotation
17710 @example
17711 $ gnatls -v -I.. demo1.o
17713 GNATLS 5.03w (20041123-34)
17714 Copyright 1997-2004 Free Software Foundation, Inc.
17716 Source Search Path:
17717    <Current_Directory>
17718    ../
17719    /home/comar/local/adainclude/
17721 Object Search Path:
17722    <Current_Directory>
17723    ../
17724    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17726 Project Search Path:
17727    <Current_Directory>
17728    /home/comar/local/lib/gnat/
17730 ./demo1.o
17731    Unit =>
17732      Name   => demo1
17733      Kind   => subprogram body
17734      Flags  => No_Elab_Code
17735      Source => demo1.adb    modified
17736 @end example
17737 @end quotation
17739 The following is an example of use of the dependency list.
17740 Note the use of the -s switch
17741 which gives a straight list of source files. This can be useful for
17742 building specialized scripts.
17744 @quotation
17746 @example
17747 $ gnatls -d demo2.o
17748 ./demo2.o   demo2        OK demo2.adb
17749                          OK gen_list.ads
17750                          OK gen_list.adb
17751                          OK instr.ads
17752                          OK instr-child.ads
17754 $ gnatls -d -s -a demo1.o
17755 demo1.adb
17756 /home/comar/local/adainclude/ada.ads
17757 /home/comar/local/adainclude/a-finali.ads
17758 /home/comar/local/adainclude/a-filico.ads
17759 /home/comar/local/adainclude/a-stream.ads
17760 /home/comar/local/adainclude/a-tags.ads
17761 gen_list.ads
17762 gen_list.adb
17763 /home/comar/local/adainclude/gnat.ads
17764 /home/comar/local/adainclude/g-io.ads
17765 instr.ads
17766 /home/comar/local/adainclude/system.ads
17767 /home/comar/local/adainclude/s-exctab.ads
17768 /home/comar/local/adainclude/s-finimp.ads
17769 /home/comar/local/adainclude/s-finroo.ads
17770 /home/comar/local/adainclude/s-secsta.ads
17771 /home/comar/local/adainclude/s-stalib.ads
17772 /home/comar/local/adainclude/s-stoele.ads
17773 /home/comar/local/adainclude/s-stratt.ads
17774 /home/comar/local/adainclude/s-tasoli.ads
17775 /home/comar/local/adainclude/s-unstyp.ads
17776 /home/comar/local/adainclude/unchconv.ads
17777 @end example
17778 @end quotation
17780 @node The Cross-Referencing Tools gnatxref and gnatfind,The Ada to HTML Converter gnathtml,The GNAT Library Browser gnatls,GNAT Utility Programs
17781 @anchor{gnat_ugn/gnat_utility_programs the-cross-referencing-tools-gnatxref-and-gnatfind}@anchor{22}@anchor{gnat_ugn/gnat_utility_programs id9}@anchor{151}
17782 @section The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
17785 @geindex gnatxref
17787 @geindex gnatfind
17789 The compiler generates cross-referencing information (unless
17790 you set the @code{-gnatx} switch), which are saved in the @code{.ali} files.
17791 This information indicates where in the source each entity is declared and
17792 referenced. Note that entities in package Standard are not included, but
17793 entities in all other predefined units are included in the output.
17795 Before using any of these two tools, you need to compile successfully your
17796 application, so that GNAT gets a chance to generate the cross-referencing
17797 information.
17799 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
17800 information to provide the user with the capability to easily locate the
17801 declaration and references to an entity. These tools are quite similar,
17802 the difference being that @code{gnatfind} is intended for locating
17803 definitions and/or references to a specified entity or entities, whereas
17804 @code{gnatxref} is oriented to generating a full report of all
17805 cross-references.
17807 To use these tools, you must not compile your application using the
17808 @code{-gnatx} switch on the @code{gnatmake} command line
17809 (see @ref{1b,,Building with gnatmake}). Otherwise, cross-referencing
17810 information will not be generated.
17812 @menu
17813 * gnatxref Switches:: 
17814 * gnatfind Switches:: 
17815 * Configuration Files for gnatxref and gnatfind:: 
17816 * Regular Expressions in gnatfind and gnatxref:: 
17817 * Examples of gnatxref Usage:: 
17818 * Examples of gnatfind Usage:: 
17820 @end menu
17822 @node gnatxref Switches,gnatfind Switches,,The Cross-Referencing Tools gnatxref and gnatfind
17823 @anchor{gnat_ugn/gnat_utility_programs id10}@anchor{152}@anchor{gnat_ugn/gnat_utility_programs gnatxref-switches}@anchor{153}
17824 @subsection @code{gnatxref} Switches
17827 The command invocation for @code{gnatxref} is:
17829 @quotation
17831 @example
17832 $ gnatxref [ switches ] sourcefile1 [ sourcefile2 ... ]
17833 @end example
17834 @end quotation
17836 where
17839 @table @asis
17841 @item @code{sourcefile1} [, @code{sourcefile2} ...]
17843 identify the source files for which a report is to be generated. The
17844 @code{with}ed units will be processed too. You must provide at least one file.
17846 These file names are considered to be regular expressions, so for instance
17847 specifying @code{source*.adb} is the same as giving every file in the current
17848 directory whose name starts with @code{source} and whose extension is
17849 @code{adb}.
17851 You shouldn't specify any directory name, just base names. @code{gnatxref}
17852 and @code{gnatfind} will be able to locate these files by themselves using
17853 the source path. If you specify directories, no result is produced.
17854 @end table
17856 The following switches are available for @code{gnatxref}:
17858 @geindex --version (gnatxref)
17861 @table @asis
17863 @item @code{--version}
17865 Display Copyright and version, then exit disregarding all other options.
17866 @end table
17868 @geindex --help (gnatxref)
17871 @table @asis
17873 @item @code{--help}
17875 If @code{--version} was not used, display usage, then exit disregarding
17876 all other options.
17877 @end table
17879 @geindex -a (gnatxref)
17882 @table @asis
17884 @item @code{-a}
17886 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
17887 the read-only files found in the library search path. Otherwise, these files
17888 will be ignored. This option can be used to protect Gnat sources or your own
17889 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
17890 much faster, and their output much smaller. Read-only here refers to access
17891 or permissions status in the file system for the current user.
17892 @end table
17894 @geindex -aIDIR (gnatxref)
17897 @table @asis
17899 @item @code{-aI@emph{DIR}}
17901 When looking for source files also look in directory DIR. The order in which
17902 source file search is undertaken is the same as for @code{gnatmake}.
17903 @end table
17905 @geindex -aODIR (gnatxref)
17908 @table @asis
17910 @item @code{aO@emph{DIR}}
17912 When -searching for library and object files, look in directory
17913 DIR. The order in which library files are searched is the same as for
17914 @code{gnatmake}.
17915 @end table
17917 @geindex -nostdinc (gnatxref)
17920 @table @asis
17922 @item @code{-nostdinc}
17924 Do not look for sources in the system default directory.
17925 @end table
17927 @geindex -nostdlib (gnatxref)
17930 @table @asis
17932 @item @code{-nostdlib}
17934 Do not look for library files in the system default directory.
17935 @end table
17937 @geindex --ext (gnatxref)
17940 @table @asis
17942 @item @code{--ext=@emph{extension}}
17944 Specify an alternate ali file extension. The default is @code{ali} and other
17945 extensions (e.g. @code{gli} for C/C++ sources) may be specified via this switch.
17946 Note that if this switch overrides the default, which means that only the
17947 new extension will be considered.
17948 @end table
17950 @geindex --RTS (gnatxref)
17953 @table @asis
17955 @item @code{--RTS=@emph{rts-path}}
17957 Specifies the default location of the runtime library. Same meaning as the
17958 equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17959 @end table
17961 @geindex -d (gnatxref)
17964 @table @asis
17966 @item @code{-d}
17968 If this switch is set @code{gnatxref} will output the parent type
17969 reference for each matching derived types.
17970 @end table
17972 @geindex -f (gnatxref)
17975 @table @asis
17977 @item @code{-f}
17979 If this switch is set, the output file names will be preceded by their
17980 directory (if the file was found in the search path). If this switch is
17981 not set, the directory will not be printed.
17982 @end table
17984 @geindex -g (gnatxref)
17987 @table @asis
17989 @item @code{-g}
17991 If this switch is set, information is output only for library-level
17992 entities, ignoring local entities. The use of this switch may accelerate
17993 @code{gnatfind} and @code{gnatxref}.
17994 @end table
17996 @geindex -IDIR (gnatxref)
17999 @table @asis
18001 @item @code{-I@emph{DIR}}
18003 Equivalent to @code{-aODIR -aIDIR}.
18004 @end table
18006 @geindex -pFILE (gnatxref)
18009 @table @asis
18011 @item @code{-p@emph{FILE}}
18013 Specify a configuration file to use to list the source and object directories.
18015 If a file is specified, then the content of the source directory and object
18016 directory lines are added as if they had been specified respectively
18017 by @code{-aI} and @code{-aO}.
18019 See @ref{154,,Configuration Files for gnatxref and gnatfind} for the syntax
18020 of this configuration file.
18022 @item @code{-u}
18024 Output only unused symbols. This may be really useful if you give your
18025 main compilation unit on the command line, as @code{gnatxref} will then
18026 display every unused entity and 'with'ed package.
18028 @item @code{-v}
18030 Instead of producing the default output, @code{gnatxref} will generate a
18031 @code{tags} file that can be used by vi. For examples how to use this
18032 feature, see @ref{155,,Examples of gnatxref Usage}. The tags file is output
18033 to the standard output, thus you will have to redirect it to a file.
18034 @end table
18036 All these switches may be in any order on the command line, and may even
18037 appear after the file names. They need not be separated by spaces, thus
18038 you can say @code{gnatxref -ag} instead of @code{gnatxref -a -g}.
18040 @node gnatfind Switches,Configuration Files for gnatxref and gnatfind,gnatxref Switches,The Cross-Referencing Tools gnatxref and gnatfind
18041 @anchor{gnat_ugn/gnat_utility_programs id11}@anchor{156}@anchor{gnat_ugn/gnat_utility_programs gnatfind-switches}@anchor{157}
18042 @subsection @code{gnatfind} Switches
18045 The command invocation for @code{gnatfind} is:
18047 @quotation
18049 @example
18050 $ gnatfind [ switches ]  pattern[:sourcefile[:line[:column]]]
18051       [file1 file2 ...]
18052 @end example
18053 @end quotation
18055 with the following iterpretation of the command arguments:
18058 @table @asis
18060 @item @emph{pattern}
18062 An entity will be output only if it matches the regular expression found
18063 in @emph{pattern}, see @ref{158,,Regular Expressions in gnatfind and gnatxref}.
18065 Omitting the pattern is equivalent to specifying @code{*}, which
18066 will match any entity. Note that if you do not provide a pattern, you
18067 have to provide both a sourcefile and a line.
18069 Entity names are given in Latin-1, with uppercase/lowercase equivalence
18070 for matching purposes. At the current time there is no support for
18071 8-bit codes other than Latin-1, or for wide characters in identifiers.
18073 @item @emph{sourcefile}
18075 @code{gnatfind} will look for references, bodies or declarations
18076 of symbols referenced in @code{sourcefile}, at line @code{line}
18077 and column @code{column}. See @ref{159,,Examples of gnatfind Usage}
18078 for syntax examples.
18080 @item @emph{line}
18082 A decimal integer identifying the line number containing
18083 the reference to the entity (or entities) to be located.
18085 @item @emph{column}
18087 A decimal integer identifying the exact location on the
18088 line of the first character of the identifier for the
18089 entity reference. Columns are numbered from 1.
18091 @item @emph{file1 file2 ...}
18093 The search will be restricted to these source files. If none are given, then
18094 the search will be conducted for every library file in the search path.
18095 These files must appear only after the pattern or sourcefile.
18097 These file names are considered to be regular expressions, so for instance
18098 specifying @code{source*.adb} is the same as giving every file in the current
18099 directory whose name starts with @code{source} and whose extension is
18100 @code{adb}.
18102 The location of the spec of the entity will always be displayed, even if it
18103 isn't in one of @code{file1}, @code{file2}, ... The
18104 occurrences of the entity in the separate units of the ones given on the
18105 command line will also be displayed.
18107 Note that if you specify at least one file in this part, @code{gnatfind} may
18108 sometimes not be able to find the body of the subprograms.
18109 @end table
18111 At least one of 'sourcefile' or 'pattern' has to be present on
18112 the command line.
18114 The following switches are available:
18116 @geindex --version (gnatfind)
18119 @table @asis
18121 @item @code{--version}
18123 Display Copyright and version, then exit disregarding all other options.
18124 @end table
18126 @geindex --help (gnatfind)
18129 @table @asis
18131 @item @code{--help}
18133 If @code{--version} was not used, display usage, then exit disregarding
18134 all other options.
18135 @end table
18137 @geindex -a (gnatfind)
18140 @table @asis
18142 @item @code{-a}
18144 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
18145 the read-only files found in the library search path. Otherwise, these files
18146 will be ignored. This option can be used to protect Gnat sources or your own
18147 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
18148 much faster, and their output much smaller. Read-only here refers to access
18149 or permission status in the file system for the current user.
18150 @end table
18152 @geindex -aIDIR (gnatfind)
18155 @table @asis
18157 @item @code{-aI@emph{DIR}}
18159 When looking for source files also look in directory DIR. The order in which
18160 source file search is undertaken is the same as for @code{gnatmake}.
18161 @end table
18163 @geindex -aODIR (gnatfind)
18166 @table @asis
18168 @item @code{-aO@emph{DIR}}
18170 When searching for library and object files, look in directory
18171 DIR. The order in which library files are searched is the same as for
18172 @code{gnatmake}.
18173 @end table
18175 @geindex -nostdinc (gnatfind)
18178 @table @asis
18180 @item @code{-nostdinc}
18182 Do not look for sources in the system default directory.
18183 @end table
18185 @geindex -nostdlib (gnatfind)
18188 @table @asis
18190 @item @code{-nostdlib}
18192 Do not look for library files in the system default directory.
18193 @end table
18195 @geindex --ext (gnatfind)
18198 @table @asis
18200 @item @code{--ext=@emph{extension}}
18202 Specify an alternate ali file extension. The default is @code{ali} and other
18203 extensions (e.g. @code{gli} for C/C++ sources when using @code{-fdump-xref})
18204 may be specified via this switch. Note that if this switch overrides the
18205 default, which means that only the new extension will be considered.
18206 @end table
18208 @geindex --RTS (gnatfind)
18211 @table @asis
18213 @item @code{--RTS=@emph{rts-path}}
18215 Specifies the default location of the runtime library. Same meaning as the
18216 equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
18217 @end table
18219 @geindex -d (gnatfind)
18222 @table @asis
18224 @item @code{-d}
18226 If this switch is set, then @code{gnatfind} will output the parent type
18227 reference for each matching derived types.
18228 @end table
18230 @geindex -e (gnatfind)
18233 @table @asis
18235 @item @code{-e}
18237 By default, @code{gnatfind} accept the simple regular expression set for
18238 @code{pattern}. If this switch is set, then the pattern will be
18239 considered as full Unix-style regular expression.
18240 @end table
18242 @geindex -f (gnatfind)
18245 @table @asis
18247 @item @code{-f}
18249 If this switch is set, the output file names will be preceded by their
18250 directory (if the file was found in the search path). If this switch is
18251 not set, the directory will not be printed.
18252 @end table
18254 @geindex -g (gnatfind)
18257 @table @asis
18259 @item @code{-g}
18261 If this switch is set, information is output only for library-level
18262 entities, ignoring local entities. The use of this switch may accelerate
18263 @code{gnatfind} and @code{gnatxref}.
18264 @end table
18266 @geindex -IDIR (gnatfind)
18269 @table @asis
18271 @item @code{-I@emph{DIR}}
18273 Equivalent to @code{-aODIR -aIDIR}.
18274 @end table
18276 @geindex -pFILE (gnatfind)
18279 @table @asis
18281 @item @code{-p@emph{FILE}}
18283 Specify a configuration file to use to list the source and object directories.
18285 If a file is specified, then the content of the source directory and object
18286 directory lines are added as if they had been specified respectively
18287 by @code{-aI} and @code{-aO}.
18289 See @ref{154,,Configuration Files for gnatxref and gnatfind} for the syntax
18290 of this configuration file.
18291 @end table
18293 @geindex -r (gnatfind)
18296 @table @asis
18298 @item @code{-r}
18300 By default, @code{gnatfind} will output only the information about the
18301 declaration, body or type completion of the entities. If this switch is
18302 set, the @code{gnatfind} will locate every reference to the entities in
18303 the files specified on the command line (or in every file in the search
18304 path if no file is given on the command line).
18305 @end table
18307 @geindex -s (gnatfind)
18310 @table @asis
18312 @item @code{-s}
18314 If this switch is set, then @code{gnatfind} will output the content
18315 of the Ada source file lines were the entity was found.
18316 @end table
18318 @geindex -t (gnatfind)
18321 @table @asis
18323 @item @code{-t}
18325 If this switch is set, then @code{gnatfind} will output the type hierarchy for
18326 the specified type. It act like -d option but recursively from parent
18327 type to parent type. When this switch is set it is not possible to
18328 specify more than one file.
18329 @end table
18331 All these switches may be in any order on the command line, and may even
18332 appear after the file names. They need not be separated by spaces, thus
18333 you can say @code{gnatxref -ag} instead of
18334 @code{gnatxref -a -g}.
18336 As stated previously, @code{gnatfind} will search in every directory in the
18337 search path. You can force it to look only in the current directory if
18338 you specify @code{*} at the end of the command line.
18340 @node Configuration Files for gnatxref and gnatfind,Regular Expressions in gnatfind and gnatxref,gnatfind Switches,The Cross-Referencing Tools gnatxref and gnatfind
18341 @anchor{gnat_ugn/gnat_utility_programs configuration-files-for-gnatxref-and-gnatfind}@anchor{154}@anchor{gnat_ugn/gnat_utility_programs id12}@anchor{15a}
18342 @subsection Configuration Files for @code{gnatxref} and @code{gnatfind}
18345 Configuration files are used by @code{gnatxref} and @code{gnatfind} to specify
18346 the list of source and object directories to consider. They can be
18347 specified via the @code{-p} switch.
18349 The following lines can be included, in any order in the file:
18352 @itemize *
18354 @item 
18356 @table @asis
18358 @item @emph{src_dir=DIR}
18360 [default: @code{"./"}].
18361 Specifies a directory where to look for source files. Multiple @code{src_dir}
18362 lines can be specified and they will be searched in the order they
18363 are specified.
18364 @end table
18366 @item 
18368 @table @asis
18370 @item @emph{obj_dir=DIR}
18372 [default: @code{"./"}].
18373 Specifies a directory where to look for object and library files. Multiple
18374 @code{obj_dir} lines can be specified, and they will be searched in the order
18375 they are specified
18376 @end table
18377 @end itemize
18379 Any other line will be silently ignored.
18381 @node Regular Expressions in gnatfind and gnatxref,Examples of gnatxref Usage,Configuration Files for gnatxref and gnatfind,The Cross-Referencing Tools gnatxref and gnatfind
18382 @anchor{gnat_ugn/gnat_utility_programs id13}@anchor{15b}@anchor{gnat_ugn/gnat_utility_programs regular-expressions-in-gnatfind-and-gnatxref}@anchor{158}
18383 @subsection Regular Expressions in @code{gnatfind} and @code{gnatxref}
18386 As specified in the section about @code{gnatfind}, the pattern can be a
18387 regular expression. Two kinds of regular expressions
18388 are recognized:
18391 @itemize *
18393 @item 
18395 @table @asis
18397 @item @emph{Globbing pattern}
18399 These are the most common regular expression. They are the same as are
18400 generally used in a Unix shell command line, or in a DOS session.
18402 Here is a more formal grammar:
18404 @example
18405 regexp ::= term
18406 term   ::= elmt            -- matches elmt
18407 term   ::= elmt elmt       -- concatenation (elmt then elmt)
18408 term   ::= *               -- any string of 0 or more characters
18409 term   ::= ?               -- matches any character
18410 term   ::= [char @{char@}]   -- matches any character listed
18411 term   ::= [char - char]   -- matches any character in range
18412 @end example
18413 @end table
18415 @item 
18417 @table @asis
18419 @item @emph{Full regular expression}
18421 The second set of regular expressions is much more powerful. This is the
18422 type of regular expressions recognized by utilities such as @code{grep}.
18424 The following is the form of a regular expression, expressed in same BNF
18425 style as is found in the Ada Reference Manual:
18427 @example
18428 regexp ::= term @{| term@}   -- alternation (term or term ...)
18430 term ::= item @{item@}       -- concatenation (item then item)
18432 item ::= elmt              -- match elmt
18433 item ::= elmt *            -- zero or more elmt's
18434 item ::= elmt +            -- one or more elmt's
18435 item ::= elmt ?            -- matches elmt or nothing
18437 elmt ::= nschar            -- matches given character
18438 elmt ::= [nschar @{nschar@}]   -- matches any character listed
18439 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
18440 elmt ::= [char - char]     -- matches chars in given range
18441 elmt ::= \\ char            -- matches given character
18442 elmt ::= .                 -- matches any single character
18443 elmt ::= ( regexp )        -- parens used for grouping
18445 char ::= any character, including special characters
18446 nschar ::= any character except ()[].*+?^
18447 @end example
18449 Here are a few examples:
18451 @quotation
18454 @table @asis
18456 @item @code{abcde|fghi}
18458 will match any of the two strings @code{abcde} and @code{fghi},
18460 @item @code{abc*d}
18462 will match any string like @code{abd}, @code{abcd}, @code{abccd},
18463 @code{abcccd}, and so on,
18465 @item @code{[a-z]+}
18467 will match any string which has only lowercase characters in it (and at
18468 least one character.
18469 @end table
18470 @end quotation
18471 @end table
18472 @end itemize
18474 @node Examples of gnatxref Usage,Examples of gnatfind Usage,Regular Expressions in gnatfind and gnatxref,The Cross-Referencing Tools gnatxref and gnatfind
18475 @anchor{gnat_ugn/gnat_utility_programs examples-of-gnatxref-usage}@anchor{155}@anchor{gnat_ugn/gnat_utility_programs id14}@anchor{15c}
18476 @subsection Examples of @code{gnatxref} Usage
18479 @menu
18480 * General Usage:: 
18481 * Using gnatxref with vi:: 
18483 @end menu
18485 @node General Usage,Using gnatxref with vi,,Examples of gnatxref Usage
18486 @anchor{gnat_ugn/gnat_utility_programs general-usage}@anchor{15d}
18487 @subsubsection General Usage
18490 For the following examples, we will consider the following units:
18492 @quotation
18494 @example
18495 main.ads:
18496 1: with Bar;
18497 2: package Main is
18498 3:     procedure Foo (B : in Integer);
18499 4:     C : Integer;
18500 5: private
18501 6:     D : Integer;
18502 7: end Main;
18504 main.adb:
18505 1: package body Main is
18506 2:     procedure Foo (B : in Integer) is
18507 3:     begin
18508 4:        C := B;
18509 5:        D := B;
18510 6:        Bar.Print (B);
18511 7:        Bar.Print (C);
18512 8:     end Foo;
18513 9: end Main;
18515 bar.ads:
18516 1: package Bar is
18517 2:     procedure Print (B : Integer);
18518 3: end bar;
18519 @end example
18520 @end quotation
18522 The first thing to do is to recompile your application (for instance, in
18523 that case just by doing a @code{gnatmake main}, so that GNAT generates
18524 the cross-referencing information.
18525 You can then issue any of the following commands:
18527 @quotation
18530 @itemize *
18532 @item 
18533 @code{gnatxref main.adb}
18534 @code{gnatxref} generates cross-reference information for main.adb
18535 and every unit 'with'ed by main.adb.
18537 The output would be:
18539 @quotation
18541 @example
18542 B                                                      Type: Integer
18543   Decl: bar.ads           2:22
18544 B                                                      Type: Integer
18545   Decl: main.ads          3:20
18546   Body: main.adb          2:20
18547   Ref:  main.adb          4:13     5:13     6:19
18548 Bar                                                    Type: Unit
18549   Decl: bar.ads           1:9
18550   Ref:  main.adb          6:8      7:8
18551        main.ads           1:6
18552 C                                                      Type: Integer
18553   Decl: main.ads          4:5
18554   Modi: main.adb          4:8
18555   Ref:  main.adb          7:19
18556 D                                                      Type: Integer
18557   Decl: main.ads          6:5
18558   Modi: main.adb          5:8
18559 Foo                                                    Type: Unit
18560   Decl: main.ads          3:15
18561   Body: main.adb          2:15
18562 Main                                                    Type: Unit
18563   Decl: main.ads          2:9
18564   Body: main.adb          1:14
18565 Print                                                   Type: Unit
18566   Decl: bar.ads           2:15
18567   Ref:  main.adb          6:12     7:12
18568 @end example
18569 @end quotation
18571 This shows that the entity @code{Main} is declared in main.ads, line 2, column 9,
18572 its body is in main.adb, line 1, column 14 and is not referenced any where.
18574 The entity @code{Print} is declared in @code{bar.ads}, line 2, column 15 and it
18575 is referenced in @code{main.adb}, line 6 column 12 and line 7 column 12.
18577 @item 
18578 @code{gnatxref package1.adb package2.ads}
18579 @code{gnatxref} will generates cross-reference information for
18580 @code{package1.adb}, @code{package2.ads} and any other package @code{with}ed by any
18581 of these.
18582 @end itemize
18583 @end quotation
18585 @node Using gnatxref with vi,,General Usage,Examples of gnatxref Usage
18586 @anchor{gnat_ugn/gnat_utility_programs using-gnatxref-with-vi}@anchor{15e}
18587 @subsubsection Using @code{gnatxref} with @code{vi}
18590 @code{gnatxref} can generate a tags file output, which can be used
18591 directly from @code{vi}. Note that the standard version of @code{vi}
18592 will not work properly with overloaded symbols. Consider using another
18593 free implementation of @code{vi}, such as @code{vim}.
18595 @quotation
18597 @example
18598 $ gnatxref -v gnatfind.adb > tags
18599 @end example
18600 @end quotation
18602 The following command will generate the tags file for @code{gnatfind} itself
18603 (if the sources are in the search path!):
18605 @quotation
18607 @example
18608 $ gnatxref -v gnatfind.adb > tags
18609 @end example
18610 @end quotation
18612 From @code{vi}, you can then use the command @code{:tag @emph{entity}}
18613 (replacing @code{entity} by whatever you are looking for), and vi will
18614 display a new file with the corresponding declaration of entity.
18616 @node Examples of gnatfind Usage,,Examples of gnatxref Usage,The Cross-Referencing Tools gnatxref and gnatfind
18617 @anchor{gnat_ugn/gnat_utility_programs id15}@anchor{15f}@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatfind-usage}@anchor{159}
18618 @subsection Examples of @code{gnatfind} Usage
18622 @itemize *
18624 @item 
18625 @code{gnatfind -f xyz:main.adb}
18626 Find declarations for all entities xyz referenced at least once in
18627 main.adb. The references are search in every library file in the search
18628 path.
18630 The directories will be printed as well (as the @code{-f}
18631 switch is set)
18633 The output will look like:
18635 @quotation
18637 @example
18638 directory/main.ads:106:14: xyz <= declaration
18639 directory/main.adb:24:10: xyz <= body
18640 directory/foo.ads:45:23: xyz <= declaration
18641 @end example
18642 @end quotation
18644 I.e., one of the entities xyz found in main.adb is declared at
18645 line 12 of main.ads (and its body is in main.adb), and another one is
18646 declared at line 45 of foo.ads
18648 @item 
18649 @code{gnatfind -fs xyz:main.adb}
18650 This is the same command as the previous one, but @code{gnatfind} will
18651 display the content of the Ada source file lines.
18653 The output will look like:
18655 @example
18656 directory/main.ads:106:14: xyz <= declaration
18657    procedure xyz;
18658 directory/main.adb:24:10: xyz <= body
18659    procedure xyz is
18660 directory/foo.ads:45:23: xyz <= declaration
18661    xyz : Integer;
18662 @end example
18664 This can make it easier to find exactly the location your are looking
18665 for.
18667 @item 
18668 @code{gnatfind -r "*x*":main.ads:123 foo.adb}
18669 Find references to all entities containing an x that are
18670 referenced on line 123 of main.ads.
18671 The references will be searched only in main.ads and foo.adb.
18673 @item 
18674 @code{gnatfind main.ads:123}
18675 Find declarations and bodies for all entities that are referenced on
18676 line 123 of main.ads.
18678 This is the same as @code{gnatfind "*":main.adb:123`}
18680 @item 
18681 @code{gnatfind mydir/main.adb:123:45}
18682 Find the declaration for the entity referenced at column 45 in
18683 line 123 of file main.adb in directory mydir. Note that it
18684 is usual to omit the identifier name when the column is given,
18685 since the column position identifies a unique reference.
18687 The column has to be the beginning of the identifier, and should not
18688 point to any character in the middle of the identifier.
18689 @end itemize
18691 @node The Ada to HTML Converter gnathtml,,The Cross-Referencing Tools gnatxref and gnatfind,GNAT Utility Programs
18692 @anchor{gnat_ugn/gnat_utility_programs the-ada-to-html-converter-gnathtml}@anchor{23}@anchor{gnat_ugn/gnat_utility_programs id16}@anchor{160}
18693 @section The Ada to HTML Converter @code{gnathtml}
18696 @geindex gnathtml
18698 @code{gnathtml} is a Perl script that allows Ada source files to be browsed using
18699 standard Web browsers. For installation information, see @ref{161,,Installing gnathtml}.
18701 Ada reserved keywords are highlighted in a bold font and Ada comments in
18702 a blue font. Unless your program was compiled with the gcc @code{-gnatx}
18703 switch to suppress the generation of cross-referencing information, user
18704 defined variables and types will appear in a different color; you will
18705 be able to click on any identifier and go to its declaration.
18707 @menu
18708 * Invoking gnathtml:: 
18709 * Installing gnathtml:: 
18711 @end menu
18713 @node Invoking gnathtml,Installing gnathtml,,The Ada to HTML Converter gnathtml
18714 @anchor{gnat_ugn/gnat_utility_programs invoking-gnathtml}@anchor{162}@anchor{gnat_ugn/gnat_utility_programs id17}@anchor{163}
18715 @subsection Invoking @code{gnathtml}
18718 The command line is as follows:
18720 @quotation
18722 @example
18723 $ perl gnathtml.pl [ switches ] ada-files
18724 @end example
18725 @end quotation
18727 You can specify as many Ada files as you want. @code{gnathtml} will generate
18728 an html file for every ada file, and a global file called @code{index.htm}.
18729 This file is an index of every identifier defined in the files.
18731 The following switches are available:
18733 @geindex -83 (gnathtml)
18736 @table @asis
18738 @item @code{83}
18740 Only the Ada 83 subset of keywords will be highlighted.
18741 @end table
18743 @geindex -cc (gnathtml)
18746 @table @asis
18748 @item @code{cc @emph{color}}
18750 This option allows you to change the color used for comments. The default
18751 value is green. The color argument can be any name accepted by html.
18752 @end table
18754 @geindex -d (gnathtml)
18757 @table @asis
18759 @item @code{d}
18761 If the Ada files depend on some other files (for instance through
18762 @code{with} clauses, the latter files will also be converted to html.
18763 Only the files in the user project will be converted to html, not the files
18764 in the run-time library itself.
18765 @end table
18767 @geindex -D (gnathtml)
18770 @table @asis
18772 @item @code{D}
18774 This command is the same as @code{-d} above, but @code{gnathtml} will
18775 also look for files in the run-time library, and generate html files for them.
18776 @end table
18778 @geindex -ext (gnathtml)
18781 @table @asis
18783 @item @code{ext @emph{extension}}
18785 This option allows you to change the extension of the generated HTML files.
18786 If you do not specify an extension, it will default to @code{htm}.
18787 @end table
18789 @geindex -f (gnathtml)
18792 @table @asis
18794 @item @code{f}
18796 By default, gnathtml will generate html links only for global entities
18797 ('with'ed units, global variables and types,...).  If you specify
18798 @code{-f} on the command line, then links will be generated for local
18799 entities too.
18800 @end table
18802 @geindex -l (gnathtml)
18805 @table @asis
18807 @item @code{l @emph{number}}
18809 If this switch is provided and @code{number} is not 0, then
18810 @code{gnathtml} will number the html files every @code{number} line.
18811 @end table
18813 @geindex -I (gnathtml)
18816 @table @asis
18818 @item @code{I @emph{dir}}
18820 Specify a directory to search for library files (@code{.ALI} files) and
18821 source files. You can provide several -I switches on the command line,
18822 and the directories will be parsed in the order of the command line.
18823 @end table
18825 @geindex -o (gnathtml)
18828 @table @asis
18830 @item @code{o @emph{dir}}
18832 Specify the output directory for html files. By default, gnathtml will
18833 saved the generated html files in a subdirectory named @code{html/}.
18834 @end table
18836 @geindex -p (gnathtml)
18839 @table @asis
18841 @item @code{p @emph{file}}
18843 If you are using Emacs and the most recent Emacs Ada mode, which provides
18844 a full Integrated Development Environment for compiling, checking,
18845 running and debugging applications, you may use @code{.gpr} files
18846 to give the directories where Emacs can find sources and object files.
18848 Using this switch, you can tell gnathtml to use these files.
18849 This allows you to get an html version of your application, even if it
18850 is spread over multiple directories.
18851 @end table
18853 @geindex -sc (gnathtml)
18856 @table @asis
18858 @item @code{sc @emph{color}}
18860 This switch allows you to change the color used for symbol
18861 definitions.
18862 The default value is red. The color argument can be any name accepted by html.
18863 @end table
18865 @geindex -t (gnathtml)
18868 @table @asis
18870 @item @code{t @emph{file}}
18872 This switch provides the name of a file. This file contains a list of
18873 file names to be converted, and the effect is exactly as though they had
18874 appeared explicitly on the command line. This
18875 is the recommended way to work around the command line length limit on some
18876 systems.
18877 @end table
18879 @node Installing gnathtml,,Invoking gnathtml,The Ada to HTML Converter gnathtml
18880 @anchor{gnat_ugn/gnat_utility_programs installing-gnathtml}@anchor{161}@anchor{gnat_ugn/gnat_utility_programs id18}@anchor{164}
18881 @subsection Installing @code{gnathtml}
18884 @code{Perl} needs to be installed on your machine to run this script.
18885 @code{Perl} is freely available for almost every architecture and
18886 operating system via the Internet.
18888 On Unix systems, you  may want to modify  the  first line of  the script
18889 @code{gnathtml},  to explicitly  specify  where Perl
18890 is located. The syntax of this line is:
18892 @quotation
18894 @example
18895 #!full_path_name_to_perl
18896 @end example
18897 @end quotation
18899 Alternatively, you may run the script using the following command line:
18901 @quotation
18903 @example
18904 $ perl gnathtml.pl [ switches ] files
18905 @end example
18906 @end quotation
18908 @c -- +---------------------------------------------------------------------+
18910 @c -- | The following sections are present only in the PRO and GPL editions |
18912 @c -- +---------------------------------------------------------------------+
18921 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
18923 @node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
18924 @anchor{gnat_ugn/gnat_and_program_execution gnat-and-program-execution}@anchor{c}@anchor{gnat_ugn/gnat_and_program_execution doc}@anchor{165}@anchor{gnat_ugn/gnat_and_program_execution id1}@anchor{166}
18925 @chapter GNAT and Program Execution
18928 This chapter covers several topics:
18931 @itemize *
18933 @item 
18934 @ref{167,,Running and Debugging Ada Programs}
18936 @item 
18937 @ref{168,,Code Coverage and Profiling}
18939 @item 
18940 @ref{169,,Improving Performance}
18942 @item 
18943 @ref{16a,,Overflow Check Handling in GNAT}
18945 @item 
18946 @ref{16b,,Performing Dimensionality Analysis in GNAT}
18948 @item 
18949 @ref{16c,,Stack Related Facilities}
18951 @item 
18952 @ref{16d,,Memory Management Issues}
18953 @end itemize
18955 @menu
18956 * Running and Debugging Ada Programs:: 
18957 * Code Coverage and Profiling:: 
18958 * Improving Performance:: 
18959 * Overflow Check Handling in GNAT:: 
18960 * Performing Dimensionality Analysis in GNAT:: 
18961 * Stack Related Facilities:: 
18962 * Memory Management Issues:: 
18964 @end menu
18966 @node Running and Debugging Ada Programs,Code Coverage and Profiling,,GNAT and Program Execution
18967 @anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{167}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{24}
18968 @section Running and Debugging Ada Programs
18971 @geindex Debugging
18973 This section discusses how to debug Ada programs.
18975 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18978 @itemize *
18980 @item 
18981 The illegality may be a violation of the static semantics of Ada. In
18982 that case GNAT diagnoses the constructs in the program that are illegal.
18983 It is then a straightforward matter for the user to modify those parts of
18984 the program.
18986 @item 
18987 The illegality may be a violation of the dynamic semantics of Ada. In
18988 that case the program compiles and executes, but may generate incorrect
18989 results, or may terminate abnormally with some exception.
18991 @item 
18992 When presented with a program that contains convoluted errors, GNAT
18993 itself may terminate abnormally without providing full diagnostics on
18994 the incorrect user program.
18995 @end itemize
18997 @geindex Debugger
18999 @geindex gdb
19001 @menu
19002 * The GNAT Debugger GDB:: 
19003 * Running GDB:: 
19004 * Introduction to GDB Commands:: 
19005 * Using Ada Expressions:: 
19006 * Calling User-Defined Subprograms:: 
19007 * Using the next Command in a Function:: 
19008 * Stopping When Ada Exceptions Are Raised:: 
19009 * Ada Tasks:: 
19010 * Debugging Generic Units:: 
19011 * Remote Debugging with gdbserver:: 
19012 * GNAT Abnormal Termination or Failure to Terminate:: 
19013 * Naming Conventions for GNAT Source Files:: 
19014 * Getting Internal Debugging Information:: 
19015 * Stack Traceback:: 
19016 * Pretty-Printers for the GNAT runtime:: 
19018 @end menu
19020 @node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
19021 @anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{16e}@anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{16f}
19022 @subsection The GNAT Debugger GDB
19025 @code{GDB} is a general purpose, platform-independent debugger that
19026 can be used to debug mixed-language programs compiled with @code{gcc},
19027 and in particular is capable of debugging Ada programs compiled with
19028 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19029 complex Ada data structures.
19031 See @cite{Debugging with GDB},
19032 for full details on the usage of @code{GDB}, including a section on
19033 its usage on programs. This manual should be consulted for full
19034 details. The section that follows is a brief introduction to the
19035 philosophy and use of @code{GDB}.
19037 When GNAT programs are compiled, the compiler optionally writes debugging
19038 information into the generated object file, including information on
19039 line numbers, and on declared types and variables. This information is
19040 separate from the generated code. It makes the object files considerably
19041 larger, but it does not add to the size of the actual executable that
19042 will be loaded into memory, and has no impact on run-time performance. The
19043 generation of debug information is triggered by the use of the
19044 @code{-g} switch in the @code{gcc} or @code{gnatmake} command
19045 used to carry out the compilations. It is important to emphasize that
19046 the use of these options does not change the generated code.
19048 The debugging information is written in standard system formats that
19049 are used by many tools, including debuggers and profilers. The format
19050 of the information is typically designed to describe C types and
19051 semantics, but GNAT implements a translation scheme which allows full
19052 details about Ada types and variables to be encoded into these
19053 standard C formats. Details of this encoding scheme may be found in
19054 the file exp_dbug.ads in the GNAT source distribution. However, the
19055 details of this encoding are, in general, of no interest to a user,
19056 since @code{GDB} automatically performs the necessary decoding.
19058 When a program is bound and linked, the debugging information is
19059 collected from the object files, and stored in the executable image of
19060 the program. Again, this process significantly increases the size of
19061 the generated executable file, but it does not increase the size of
19062 the executable program itself. Furthermore, if this program is run in
19063 the normal manner, it runs exactly as if the debug information were
19064 not present, and takes no more actual memory.
19066 However, if the program is run under control of @code{GDB}, the
19067 debugger is activated.  The image of the program is loaded, at which
19068 point it is ready to run.  If a run command is given, then the program
19069 will run exactly as it would have if @code{GDB} were not present. This
19070 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19071 entirely non-intrusive until a breakpoint is encountered.  If no
19072 breakpoint is ever hit, the program will run exactly as it would if no
19073 debugger were present. When a breakpoint is hit, @code{GDB} accesses
19074 the debugging information and can respond to user commands to inspect
19075 variables, and more generally to report on the state of execution.
19077 @node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
19078 @anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{170}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{171}
19079 @subsection Running GDB
19082 This section describes how to initiate the debugger.
19084 The debugger can be launched from a @code{GPS} menu or
19085 directly from the command line. The description below covers the latter use.
19086 All the commands shown can be used in the @code{GPS} debug console window,
19087 but there are usually more GUI-based ways to achieve the same effect.
19089 The command to run @code{GDB} is
19091 @quotation
19093 @example
19094 $ gdb program
19095 @end example
19096 @end quotation
19098 where @code{program} is the name of the executable file. This
19099 activates the debugger and results in a prompt for debugger commands.
19100 The simplest command is simply @code{run}, which causes the program to run
19101 exactly as if the debugger were not present. The following section
19102 describes some of the additional commands that can be given to @code{GDB}.
19104 @node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
19105 @anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{172}@anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{173}
19106 @subsection Introduction to GDB Commands
19109 @code{GDB} contains a large repertoire of commands.
19110 See @cite{Debugging with GDB} for extensive documentation on the use
19111 of these commands, together with examples of their use. Furthermore,
19112 the command @emph{help} invoked from within GDB activates a simple help
19113 facility which summarizes the available commands and their options.
19114 In this section we summarize a few of the most commonly
19115 used commands to give an idea of what @code{GDB} is about. You should create
19116 a simple program with debugging information and experiment with the use of
19117 these @code{GDB} commands on the program as you read through the
19118 following section.
19121 @itemize *
19123 @item 
19125 @table @asis
19127 @item @code{set args @emph{arguments}}
19129 The @emph{arguments} list above is a list of arguments to be passed to
19130 the program on a subsequent run command, just as though the arguments
19131 had been entered on a normal invocation of the program. The @code{set args}
19132 command is not needed if the program does not require arguments.
19133 @end table
19135 @item 
19137 @table @asis
19139 @item @code{run}
19141 The @code{run} command causes execution of the program to start from
19142 the beginning. If the program is already running, that is to say if
19143 you are currently positioned at a breakpoint, then a prompt will ask
19144 for confirmation that you want to abandon the current execution and
19145 restart.
19146 @end table
19148 @item 
19150 @table @asis
19152 @item @code{breakpoint @emph{location}}
19154 The breakpoint command sets a breakpoint, that is to say a point at which
19155 execution will halt and @code{GDB} will await further
19156 commands. @emph{location} is
19157 either a line number within a file, given in the format @code{file:linenumber},
19158 or it is the name of a subprogram. If you request that a breakpoint be set on
19159 a subprogram that is overloaded, a prompt will ask you to specify on which of
19160 those subprograms you want to breakpoint. You can also
19161 specify that all of them should be breakpointed. If the program is run
19162 and execution encounters the breakpoint, then the program
19163 stops and @code{GDB} signals that the breakpoint was encountered by
19164 printing the line of code before which the program is halted.
19165 @end table
19167 @item 
19169 @table @asis
19171 @item @code{catch exception @emph{name}}
19173 This command causes the program execution to stop whenever exception
19174 @code{name} is raised.  If @code{name} is omitted, then the execution is
19175 suspended when any exception is raised.
19176 @end table
19178 @item 
19180 @table @asis
19182 @item @code{print @emph{expression}}
19184 This will print the value of the given expression. Most simple
19185 Ada expression formats are properly handled by @code{GDB}, so the expression
19186 can contain function calls, variables, operators, and attribute references.
19187 @end table
19189 @item 
19191 @table @asis
19193 @item @code{continue}
19195 Continues execution following a breakpoint, until the next breakpoint or the
19196 termination of the program.
19197 @end table
19199 @item 
19201 @table @asis
19203 @item @code{step}
19205 Executes a single line after a breakpoint. If the next statement
19206 is a subprogram call, execution continues into (the first statement of)
19207 the called subprogram.
19208 @end table
19210 @item 
19212 @table @asis
19214 @item @code{next}
19216 Executes a single line. If this line is a subprogram call, executes and
19217 returns from the call.
19218 @end table
19220 @item 
19222 @table @asis
19224 @item @code{list}
19226 Lists a few lines around the current source location. In practice, it
19227 is usually more convenient to have a separate edit window open with the
19228 relevant source file displayed. Successive applications of this command
19229 print subsequent lines. The command can be given an argument which is a
19230 line number, in which case it displays a few lines around the specified one.
19231 @end table
19233 @item 
19235 @table @asis
19237 @item @code{backtrace}
19239 Displays a backtrace of the call chain. This command is typically
19240 used after a breakpoint has occurred, to examine the sequence of calls that
19241 leads to the current breakpoint. The display includes one line for each
19242 activation record (frame) corresponding to an active subprogram.
19243 @end table
19245 @item 
19247 @table @asis
19249 @item @code{up}
19251 At a breakpoint, @code{GDB} can display the values of variables local
19252 to the current frame. The command @code{up} can be used to
19253 examine the contents of other active frames, by moving the focus up
19254 the stack, that is to say from callee to caller, one frame at a time.
19255 @end table
19257 @item 
19259 @table @asis
19261 @item @code{down}
19263 Moves the focus of @code{GDB} down from the frame currently being
19264 examined to the frame of its callee (the reverse of the previous command),
19265 @end table
19267 @item 
19269 @table @asis
19271 @item @code{frame @emph{n}}
19273 Inspect the frame with the given number. The value 0 denotes the frame
19274 of the current breakpoint, that is to say the top of the call stack.
19275 @end table
19277 @item 
19279 @table @asis
19281 @item @code{kill}
19283 Kills the child process in which the program is running under GDB.
19284 This may be useful for several purposes:
19287 @itemize *
19289 @item 
19290 It allows you to recompile and relink your program, since on many systems
19291 you cannot regenerate an executable file while it is running in a process.
19293 @item 
19294 You can run your program outside the debugger, on systems that do not
19295 permit executing a program outside GDB while breakpoints are set
19296 within GDB.
19298 @item 
19299 It allows you to debug a core dump rather than a running process.
19300 @end itemize
19301 @end table
19302 @end itemize
19304 The above list is a very short introduction to the commands that
19305 @code{GDB} provides. Important additional capabilities, including conditional
19306 breakpoints, the ability to execute command sequences on a breakpoint,
19307 the ability to debug at the machine instruction level and many other
19308 features are described in detail in @cite{Debugging with GDB}.
19309 Note that most commands can be abbreviated
19310 (for example, c for continue, bt for backtrace).
19312 @node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
19313 @anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{174}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{175}
19314 @subsection Using Ada Expressions
19317 @geindex Ada expressions (in gdb)
19319 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
19320 extensions. The philosophy behind the design of this subset is
19322 @quotation
19325 @itemize *
19327 @item 
19328 That @code{GDB} should provide basic literals and access to operations for
19329 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19330 leaving more sophisticated computations to subprograms written into the
19331 program (which therefore may be called from @code{GDB}).
19333 @item 
19334 That type safety and strict adherence to Ada language restrictions
19335 are not particularly relevant in a debugging context.
19337 @item 
19338 That brevity is important to the @code{GDB} user.
19339 @end itemize
19340 @end quotation
19342 Thus, for brevity, the debugger acts as if there were
19343 implicit @code{with} and @code{use} clauses in effect for all user-written
19344 packages, thus making it unnecessary to fully qualify most names with
19345 their packages, regardless of context. Where this causes ambiguity,
19346 @code{GDB} asks the user's intent.
19348 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19350 @node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
19351 @anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{176}@anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{177}
19352 @subsection Calling User-Defined Subprograms
19355 An important capability of @code{GDB} is the ability to call user-defined
19356 subprograms while debugging. This is achieved simply by entering
19357 a subprogram call statement in the form:
19359 @quotation
19361 @example
19362 call subprogram-name (parameters)
19363 @end example
19364 @end quotation
19366 The keyword @code{call} can be omitted in the normal case where the
19367 @code{subprogram-name} does not coincide with any of the predefined
19368 @code{GDB} commands.
19370 The effect is to invoke the given subprogram, passing it the
19371 list of parameters that is supplied. The parameters can be expressions and
19372 can include variables from the program being debugged. The
19373 subprogram must be defined
19374 at the library level within your program, and @code{GDB} will call the
19375 subprogram within the environment of your program execution (which
19376 means that the subprogram is free to access or even modify variables
19377 within your program).
19379 The most important use of this facility is in allowing the inclusion of
19380 debugging routines that are tailored to particular data structures
19381 in your program. Such debugging routines can be written to provide a suitably
19382 high-level description of an abstract type, rather than a low-level dump
19383 of its physical layout. After all, the standard
19384 @code{GDB print} command only knows the physical layout of your
19385 types, not their abstract meaning. Debugging routines can provide information
19386 at the desired semantic level and are thus enormously useful.
19388 For example, when debugging GNAT itself, it is crucial to have access to
19389 the contents of the tree nodes used to represent the program internally.
19390 But tree nodes are represented simply by an integer value (which in turn
19391 is an index into a table of nodes).
19392 Using the @code{print} command on a tree node would simply print this integer
19393 value, which is not very useful. But the PN routine (defined in file
19394 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19395 a useful high level representation of the tree node, which includes the
19396 syntactic category of the node, its position in the source, the integers
19397 that denote descendant nodes and parent node, as well as varied
19398 semantic information. To study this example in more detail, you might want to
19399 look at the body of the PN procedure in the stated file.
19401 Another useful application of this capability is to deal with situations of
19402 complex data which are not handled suitably by GDB. For example, if you specify
19403 Convention Fortran for a multi-dimensional array, GDB does not know that
19404 the ordering of array elements has been switched and will not properly
19405 address the array elements. In such a case, instead of trying to print the
19406 elements directly from GDB, you can write a callable procedure that prints
19407 the elements in the desired format.
19409 @node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
19410 @anchor{gnat_ugn/gnat_and_program_execution using-the-next-command-in-a-function}@anchor{178}@anchor{gnat_ugn/gnat_and_program_execution id8}@anchor{179}
19411 @subsection Using the @emph{next} Command in a Function
19414 When you use the @code{next} command in a function, the current source
19415 location will advance to the next statement as usual. A special case
19416 arises in the case of a @code{return} statement.
19418 Part of the code for a return statement is the 'epilogue' of the function.
19419 This is the code that returns to the caller. There is only one copy of
19420 this epilogue code, and it is typically associated with the last return
19421 statement in the function if there is more than one return. In some
19422 implementations, this epilogue is associated with the first statement
19423 of the function.
19425 The result is that if you use the @code{next} command from a return
19426 statement that is not the last return statement of the function you
19427 may see a strange apparent jump to the last return statement or to
19428 the start of the function. You should simply ignore this odd jump.
19429 The value returned is always that from the first return statement
19430 that was stepped through.
19432 @node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
19433 @anchor{gnat_ugn/gnat_and_program_execution stopping-when-ada-exceptions-are-raised}@anchor{17a}@anchor{gnat_ugn/gnat_and_program_execution id9}@anchor{17b}
19434 @subsection Stopping When Ada Exceptions Are Raised
19437 @geindex Exceptions (in gdb)
19439 You can set catchpoints that stop the program execution when your program
19440 raises selected exceptions.
19443 @itemize *
19445 @item 
19447 @table @asis
19449 @item @code{catch exception}
19451 Set a catchpoint that stops execution whenever (any task in the) program
19452 raises any exception.
19453 @end table
19455 @item 
19457 @table @asis
19459 @item @code{catch exception @emph{name}}
19461 Set a catchpoint that stops execution whenever (any task in the) program
19462 raises the exception @emph{name}.
19463 @end table
19465 @item 
19467 @table @asis
19469 @item @code{catch exception unhandled}
19471 Set a catchpoint that stops executing whenever (any task in the) program
19472 raises an exception for which there is no handler.
19473 @end table
19475 @item 
19477 @table @asis
19479 @item @code{info exceptions}, @code{info exceptions @emph{regexp}}
19481 The @code{info exceptions} command permits the user to examine all defined
19482 exceptions within Ada programs. With a regular expression, @emph{regexp}, as
19483 argument, prints out only those exceptions whose name matches @emph{regexp}.
19484 @end table
19485 @end itemize
19487 @geindex Tasks (in gdb)
19489 @node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
19490 @anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{17c}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{17d}
19491 @subsection Ada Tasks
19494 @code{GDB} allows the following task-related commands:
19497 @itemize *
19499 @item 
19501 @table @asis
19503 @item @code{info tasks}
19505 This command shows a list of current Ada tasks, as in the following example:
19507 @example
19508 (gdb) info tasks
19509   ID       TID P-ID   Thread Pri State                 Name
19510    1   8088000   0   807e000  15 Child Activation Wait main_task
19511    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19512    3   809a800   1   80a4800  15 Child Activation Wait a
19513 *  4   80ae800   3   80b8000  15 Running               c
19514 @end example
19516 In this listing, the asterisk before the first task indicates it to be the
19517 currently running task. The first column lists the task ID that is used
19518 to refer to tasks in the following commands.
19519 @end table
19520 @end itemize
19522 @geindex Breakpoints and tasks
19525 @itemize *
19527 @item 
19528 @code{break`@w{`}*linespec* `@w{`}task} @emph{taskid}, @code{break} @emph{linespec} @code{task} @emph{taskid} @code{if} ...
19530 @quotation
19532 These commands are like the @code{break ... thread ...}.
19533 @emph{linespec} specifies source lines.
19535 Use the qualifier @code{task @emph{taskid}} with a breakpoint command
19536 to specify that you only want @code{GDB} to stop the program when a
19537 particular Ada task reaches this breakpoint. @emph{taskid} is one of the
19538 numeric task identifiers assigned by @code{GDB}, shown in the first
19539 column of the @code{info tasks} display.
19541 If you do not specify @code{task @emph{taskid}} when you set a
19542 breakpoint, the breakpoint applies to @emph{all} tasks of your
19543 program.
19545 You can use the @code{task} qualifier on conditional breakpoints as
19546 well; in this case, place @code{task @emph{taskid}} before the
19547 breakpoint condition (before the @code{if}).
19548 @end quotation
19549 @end itemize
19551 @geindex Task switching (in gdb)
19554 @itemize *
19556 @item 
19557 @code{task @emph{taskno}}
19559 @quotation
19561 This command allows switching to the task referred by @emph{taskno}. In
19562 particular, this allows browsing of the backtrace of the specified
19563 task. It is advisable to switch back to the original task before
19564 continuing execution otherwise the scheduling of the program may be
19565 perturbed.
19566 @end quotation
19567 @end itemize
19569 For more detailed information on the tasking support,
19570 see @cite{Debugging with GDB}.
19572 @geindex Debugging Generic Units
19574 @geindex Generics
19576 @node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
19577 @anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{17e}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{17f}
19578 @subsection Debugging Generic Units
19581 GNAT always uses code expansion for generic instantiation. This means that
19582 each time an instantiation occurs, a complete copy of the original code is
19583 made, with appropriate substitutions of formals by actuals.
19585 It is not possible to refer to the original generic entities in
19586 @code{GDB}, but it is always possible to debug a particular instance of
19587 a generic, by using the appropriate expanded names. For example, if we have
19589 @quotation
19591 @example
19592 procedure g is
19594    generic package k is
19595       procedure kp (v1 : in out integer);
19596    end k;
19598    package body k is
19599       procedure kp (v1 : in out integer) is
19600       begin
19601          v1 := v1 + 1;
19602       end kp;
19603    end k;
19605    package k1 is new k;
19606    package k2 is new k;
19608    var : integer := 1;
19610 begin
19611    k1.kp (var);
19612    k2.kp (var);
19613    k1.kp (var);
19614    k2.kp (var);
19615 end;
19616 @end example
19617 @end quotation
19619 Then to break on a call to procedure kp in the k2 instance, simply
19620 use the command:
19622 @quotation
19624 @example
19625 (gdb) break g.k2.kp
19626 @end example
19627 @end quotation
19629 When the breakpoint occurs, you can step through the code of the
19630 instance in the normal manner and examine the values of local variables, as for
19631 other units.
19633 @geindex Remote Debugging with gdbserver
19635 @node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
19636 @anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{180}@anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{181}
19637 @subsection Remote Debugging with gdbserver
19640 On platforms where gdbserver is supported, it is possible to use this tool
19641 to debug your application remotely.  This can be useful in situations
19642 where the program needs to be run on a target host that is different
19643 from the host used for development, particularly when the target has
19644 a limited amount of resources (either CPU and/or memory).
19646 To do so, start your program using gdbserver on the target machine.
19647 gdbserver then automatically suspends the execution of your program
19648 at its entry point, waiting for a debugger to connect to it.  The
19649 following commands starts an application and tells gdbserver to
19650 wait for a connection with the debugger on localhost port 4444.
19652 @quotation
19654 @example
19655 $ gdbserver localhost:4444 program
19656 Process program created; pid = 5685
19657 Listening on port 4444
19658 @end example
19659 @end quotation
19661 Once gdbserver has started listening, we can tell the debugger to establish
19662 a connection with this gdbserver, and then start the same debugging session
19663 as if the program was being debugged on the same host, directly under
19664 the control of GDB.
19666 @quotation
19668 @example
19669 $ gdb program
19670 (gdb) target remote targethost:4444
19671 Remote debugging using targethost:4444
19672 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19673 (gdb) b foo.adb:3
19674 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19675 (gdb) continue
19676 Continuing.
19678 Breakpoint 1, foo () at foo.adb:4
19679 4       end foo;
19680 @end example
19681 @end quotation
19683 It is also possible to use gdbserver to attach to an already running
19684 program, in which case the execution of that program is simply suspended
19685 until the connection between the debugger and gdbserver is established.
19687 For more information on how to use gdbserver, see the @emph{Using the gdbserver Program}
19688 section in @cite{Debugging with GDB}.
19689 GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
19691 @geindex Abnormal Termination or Failure to Terminate
19693 @node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
19694 @anchor{gnat_ugn/gnat_and_program_execution gnat-abnormal-termination-or-failure-to-terminate}@anchor{182}@anchor{gnat_ugn/gnat_and_program_execution id13}@anchor{183}
19695 @subsection GNAT Abnormal Termination or Failure to Terminate
19698 When presented with programs that contain serious errors in syntax
19699 or semantics,
19700 GNAT may on rare occasions  experience problems in operation, such
19701 as aborting with a
19702 segmentation fault or illegal memory access, raising an internal
19703 exception, terminating abnormally, or failing to terminate at all.
19704 In such cases, you can activate
19705 various features of GNAT that can help you pinpoint the construct in your
19706 program that is the likely source of the problem.
19708 The following strategies are presented in increasing order of
19709 difficulty, corresponding to your experience in using GNAT and your
19710 familiarity with compiler internals.
19713 @itemize *
19715 @item 
19716 Run @code{gcc} with the @code{-gnatf}. This first
19717 switch causes all errors on a given line to be reported. In its absence,
19718 only the first error on a line is displayed.
19720 The @code{-gnatdO} switch causes errors to be displayed as soon as they
19721 are encountered, rather than after compilation is terminated. If GNAT
19722 terminates prematurely or goes into an infinite loop, the last error
19723 message displayed may help to pinpoint the culprit.
19725 @item 
19726 Run @code{gcc} with the @code{-v} (verbose) switch. In this
19727 mode, @code{gcc} produces ongoing information about the progress of the
19728 compilation and provides the name of each procedure as code is
19729 generated. This switch allows you to find which Ada procedure was being
19730 compiled when it encountered a code generation problem.
19731 @end itemize
19733 @geindex -gnatdc switch
19736 @itemize *
19738 @item 
19739 Run @code{gcc} with the @code{-gnatdc} switch. This is a GNAT specific
19740 switch that does for the front-end what @code{-v} does
19741 for the back end. The system prints the name of each unit,
19742 either a compilation unit or nested unit, as it is being analyzed.
19744 @item 
19745 Finally, you can start
19746 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19747 front-end of GNAT, and can be run independently (normally it is just
19748 called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
19749 would on a C program (but @ref{16e,,The GNAT Debugger GDB} for caveats). The
19750 @code{where} command is the first line of attack; the variable
19751 @code{lineno} (seen by @code{print lineno}), used by the second phase of
19752 @code{gnat1} and by the @code{gcc} backend, indicates the source line at
19753 which the execution stopped, and @code{input_file name} indicates the name of
19754 the source file.
19755 @end itemize
19757 @node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
19758 @anchor{gnat_ugn/gnat_and_program_execution naming-conventions-for-gnat-source-files}@anchor{184}@anchor{gnat_ugn/gnat_and_program_execution id14}@anchor{185}
19759 @subsection Naming Conventions for GNAT Source Files
19762 In order to examine the workings of the GNAT system, the following
19763 brief description of its organization may be helpful:
19766 @itemize *
19768 @item 
19769 Files with prefix @code{sc} contain the lexical scanner.
19771 @item 
19772 All files prefixed with @code{par} are components of the parser. The
19773 numbers correspond to chapters of the Ada Reference Manual. For example,
19774 parsing of select statements can be found in @code{par-ch9.adb}.
19776 @item 
19777 All files prefixed with @code{sem} perform semantic analysis. The
19778 numbers correspond to chapters of the Ada standard. For example, all
19779 issues involving context clauses can be found in @code{sem_ch10.adb}. In
19780 addition, some features of the language require sufficient special processing
19781 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19782 dynamic dispatching, etc.
19784 @item 
19785 All files prefixed with @code{exp} perform normalization and
19786 expansion of the intermediate representation (abstract syntax tree, or AST).
19787 these files use the same numbering scheme as the parser and semantics files.
19788 For example, the construction of record initialization procedures is done in
19789 @code{exp_ch3.adb}.
19791 @item 
19792 The files prefixed with @code{bind} implement the binder, which
19793 verifies the consistency of the compilation, determines an order of
19794 elaboration, and generates the bind file.
19796 @item 
19797 The files @code{atree.ads} and @code{atree.adb} detail the low-level
19798 data structures used by the front-end.
19800 @item 
19801 The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
19802 the abstract syntax tree as produced by the parser.
19804 @item 
19805 The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
19806 all entities, computed during semantic analysis.
19808 @item 
19809 Library management issues are dealt with in files with prefix
19810 @code{lib}.
19812 @geindex Annex A (in Ada Reference Manual)
19814 @item 
19815 Ada files with the prefix @code{a-} are children of @code{Ada}, as
19816 defined in Annex A.
19818 @geindex Annex B (in Ada reference Manual)
19820 @item 
19821 Files with prefix @code{i-} are children of @code{Interfaces}, as
19822 defined in Annex B.
19824 @geindex System (package in Ada Reference Manual)
19826 @item 
19827 Files with prefix @code{s-} are children of @code{System}. This includes
19828 both language-defined children and GNAT run-time routines.
19830 @geindex GNAT (package)
19832 @item 
19833 Files with prefix @code{g-} are children of @code{GNAT}. These are useful
19834 general-purpose packages, fully documented in their specs. All
19835 the other @code{.c} files are modifications of common @code{gcc} files.
19836 @end itemize
19838 @node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
19839 @anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{186}@anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{187}
19840 @subsection Getting Internal Debugging Information
19843 Most compilers have internal debugging switches and modes. GNAT
19844 does also, except GNAT internal debugging switches and modes are not
19845 secret. A summary and full description of all the compiler and binder
19846 debug flags are in the file @code{debug.adb}. You must obtain the
19847 sources of the compiler to see the full detailed effects of these flags.
19849 The switches that print the source of the program (reconstructed from
19850 the internal tree) are of general interest for user programs, as are the
19851 options to print
19852 the full internal tree, and the entity table (the symbol table
19853 information). The reconstructed source provides a readable version of the
19854 program after the front-end has completed analysis and  expansion,
19855 and is useful when studying the performance of specific constructs.
19856 For example, constraint checks are indicated, complex aggregates
19857 are replaced with loops and assignments, and tasking primitives
19858 are replaced with run-time calls.
19860 @geindex traceback
19862 @geindex stack traceback
19864 @geindex stack unwinding
19866 @node Stack Traceback,Pretty-Printers for the GNAT runtime,Getting Internal Debugging Information,Running and Debugging Ada Programs
19867 @anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{188}@anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{189}
19868 @subsection Stack Traceback
19871 Traceback is a mechanism to display the sequence of subprogram calls that
19872 leads to a specified execution point in a program. Often (but not always)
19873 the execution point is an instruction at which an exception has been raised.
19874 This mechanism is also known as @emph{stack unwinding} because it obtains
19875 its information by scanning the run-time stack and recovering the activation
19876 records of all active subprograms. Stack unwinding is one of the most
19877 important tools for program debugging.
19879 The first entry stored in traceback corresponds to the deepest calling level,
19880 that is to say the subprogram currently executing the instruction
19881 from which we want to obtain the traceback.
19883 Note that there is no runtime performance penalty when stack traceback
19884 is enabled, and no exception is raised during program execution.
19886 @geindex traceback
19887 @geindex non-symbolic
19889 @menu
19890 * Non-Symbolic Traceback:: 
19891 * Symbolic Traceback:: 
19893 @end menu
19895 @node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
19896 @anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{18a}@anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{18b}
19897 @subsubsection Non-Symbolic Traceback
19900 Note: this feature is not supported on all platforms. See
19901 @code{GNAT.Traceback} spec in @code{g-traceb.ads}
19902 for a complete list of supported platforms.
19904 @subsubheading Tracebacks From an Unhandled Exception
19907 A runtime non-symbolic traceback is a list of addresses of call instructions.
19908 To enable this feature you must use the @code{-E}
19909 @code{gnatbind} option. With this option a stack traceback is stored as part
19910 of exception information. You can retrieve this information using the
19911 @code{addr2line} tool.
19913 Here is a simple example:
19915 @quotation
19917 @example
19918 procedure STB is
19920    procedure P1 is
19921    begin
19922       raise Constraint_Error;
19923    end P1;
19925    procedure P2 is
19926    begin
19927       P1;
19928    end P2;
19930 begin
19931    P2;
19932 end STB;
19933 @end example
19935 @example
19936 $ gnatmake stb -bargs -E
19937 $ stb
19939 Execution terminated by unhandled exception
19940 Exception name: CONSTRAINT_ERROR
19941 Message: stb.adb:5
19942 Call stack traceback locations:
19943 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19944 @end example
19945 @end quotation
19947 As we see the traceback lists a sequence of addresses for the unhandled
19948 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19949 guess that this exception come from procedure P1. To translate these
19950 addresses into the source lines where the calls appear, the
19951 @code{addr2line} tool, described below, is invaluable. The use of this tool
19952 requires the program to be compiled with debug information.
19954 @quotation
19956 @example
19957 $ gnatmake -g stb -bargs -E
19958 $ stb
19960 Execution terminated by unhandled exception
19961 Exception name: CONSTRAINT_ERROR
19962 Message: stb.adb:5
19963 Call stack traceback locations:
19964 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19966 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19967    0x4011f1 0x77e892a4
19969 00401373 at d:/stb/stb.adb:5
19970 0040138B at d:/stb/stb.adb:10
19971 0040139C at d:/stb/stb.adb:14
19972 00401335 at d:/stb/b~stb.adb:104
19973 004011C4 at /build/.../crt1.c:200
19974 004011F1 at /build/.../crt1.c:222
19975 77E892A4 in ?? at ??:0
19976 @end example
19977 @end quotation
19979 The @code{addr2line} tool has several other useful options:
19981 @quotation
19984 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
19985 @item
19987 @code{--functions}
19989 @tab
19991 to get the function name corresponding to any location
19993 @item
19995 @code{--demangle=gnat}
19997 @tab
19999 to use the gnat decoding mode for the function names.
20000 Note that for binutils version 2.9.x the option is
20001 simply @code{--demangle}.
20003 @end multitable
20006 @example
20007 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20008    0x40139c 0x401335 0x4011c4 0x4011f1
20010 00401373 in stb.p1 at d:/stb/stb.adb:5
20011 0040138B in stb.p2 at d:/stb/stb.adb:10
20012 0040139C in stb at d:/stb/stb.adb:14
20013 00401335 in main at d:/stb/b~stb.adb:104
20014 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
20015 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
20016 @end example
20017 @end quotation
20019 From this traceback we can see that the exception was raised in
20020 @code{stb.adb} at line 5, which was reached from a procedure call in
20021 @code{stb.adb} at line 10, and so on. The @code{b~std.adb} is the binder file,
20022 which contains the call to the main program.
20023 @ref{11c,,Running gnatbind}. The remaining entries are assorted runtime routines,
20024 and the output will vary from platform to platform.
20026 It is also possible to use @code{GDB} with these traceback addresses to debug
20027 the program. For example, we can break at a given code location, as reported
20028 in the stack traceback:
20030 @quotation
20032 @example
20033 $ gdb -nw stb
20034 @end example
20035 @end quotation
20037 Furthermore, this feature is not implemented inside Windows DLL. Only
20038 the non-symbolic traceback is reported in this case.
20040 @quotation
20042 @example
20043 (gdb) break *0x401373
20044 Breakpoint 1 at 0x401373: file stb.adb, line 5.
20045 @end example
20046 @end quotation
20048 It is important to note that the stack traceback addresses
20049 do not change when debug information is included. This is particularly useful
20050 because it makes it possible to release software without debug information (to
20051 minimize object size), get a field report that includes a stack traceback
20052 whenever an internal bug occurs, and then be able to retrieve the sequence
20053 of calls with the same program compiled with debug information.
20055 @subsubheading Tracebacks From Exception Occurrences
20058 Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
20059 The stack traceback is attached to the exception information string, and can
20060 be retrieved in an exception handler within the Ada program, by means of the
20061 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20063 @quotation
20065 @example
20066 with Ada.Text_IO;
20067 with Ada.Exceptions;
20069 procedure STB is
20071    use Ada;
20072    use Ada.Exceptions;
20074    procedure P1 is
20075       K : Positive := 1;
20076    begin
20077       K := K - 1;
20078    exception
20079       when E : others =>
20080          Text_IO.Put_Line (Exception_Information (E));
20081    end P1;
20083    procedure P2 is
20084    begin
20085       P1;
20086    end P2;
20088 begin
20089    P2;
20090 end STB;
20091 @end example
20092 @end quotation
20094 This program will output:
20096 @quotation
20098 @example
20099 $ stb
20101 Exception name: CONSTRAINT_ERROR
20102 Message: stb.adb:12
20103 Call stack traceback locations:
20104 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20105 @end example
20106 @end quotation
20108 @subsubheading Tracebacks From Anywhere in a Program
20111 It is also possible to retrieve a stack traceback from anywhere in a
20112 program. For this you need to
20113 use the @code{GNAT.Traceback} API. This package includes a procedure called
20114 @code{Call_Chain} that computes a complete stack traceback, as well as useful
20115 display procedures described below. It is not necessary to use the
20116 @code{-E} @code{gnatbind} option in this case, because the stack traceback mechanism
20117 is invoked explicitly.
20119 In the following example we compute a traceback at a specific location in
20120 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20121 convert addresses to strings:
20123 @quotation
20125 @example
20126 with Ada.Text_IO;
20127 with GNAT.Traceback;
20128 with GNAT.Debug_Utilities;
20130 procedure STB is
20132    use Ada;
20133    use GNAT;
20134    use GNAT.Traceback;
20136    procedure P1 is
20137       TB  : Tracebacks_Array (1 .. 10);
20138       --  We are asking for a maximum of 10 stack frames.
20139       Len : Natural;
20140       --  Len will receive the actual number of stack frames returned.
20141    begin
20142       Call_Chain (TB, Len);
20144       Text_IO.Put ("In STB.P1 : ");
20146       for K in 1 .. Len loop
20147          Text_IO.Put (Debug_Utilities.Image (TB (K)));
20148          Text_IO.Put (' ');
20149       end loop;
20151       Text_IO.New_Line;
20152    end P1;
20154    procedure P2 is
20155    begin
20156       P1;
20157    end P2;
20159 begin
20160    P2;
20161 end STB;
20162 @end example
20164 @example
20165 $ gnatmake -g stb
20166 $ stb
20168 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20169 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20170 @end example
20171 @end quotation
20173 You can then get further information by invoking the @code{addr2line}
20174 tool as described earlier (note that the hexadecimal addresses
20175 need to be specified in C format, with a leading '0x').
20177 @geindex traceback
20178 @geindex symbolic
20180 @node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
20181 @anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{18c}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{18d}
20182 @subsubsection Symbolic Traceback
20185 A symbolic traceback is a stack traceback in which procedure names are
20186 associated with each code location.
20188 Note that this feature is not supported on all platforms. See
20189 @code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
20190 list of currently supported platforms.
20192 Note that the symbolic traceback requires that the program be compiled
20193 with debug information. If it is not compiled with debug information
20194 only the non-symbolic information will be valid.
20196 @subsubheading Tracebacks From Exception Occurrences
20199 Here is an example:
20201 @quotation
20203 @example
20204 with Ada.Text_IO;
20205 with GNAT.Traceback.Symbolic;
20207 procedure STB is
20209    procedure P1 is
20210    begin
20211       raise Constraint_Error;
20212    end P1;
20214    procedure P2 is
20215    begin
20216       P1;
20217    end P2;
20219    procedure P3 is
20220    begin
20221       P2;
20222    end P3;
20224 begin
20225    P3;
20226 exception
20227    when E : others =>
20228       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20229 end STB;
20230 @end example
20232 @example
20233 $ gnatmake -g .\stb -bargs -E
20234 $ stb
20236 0040149F in stb.p1 at stb.adb:8
20237 004014B7 in stb.p2 at stb.adb:13
20238 004014CF in stb.p3 at stb.adb:18
20239 004015DD in ada.stb at stb.adb:22
20240 00401461 in main at b~stb.adb:168
20241 004011C4 in __mingw_CRTStartup at crt1.c:200
20242 004011F1 in mainCRTStartup at crt1.c:222
20243 77E892A4 in ?? at ??:0
20244 @end example
20245 @end quotation
20247 In the above example the @code{.\} syntax in the @code{gnatmake} command
20248 is currently required by @code{addr2line} for files that are in
20249 the current working directory.
20250 Moreover, the exact sequence of linker options may vary from platform
20251 to platform.
20252 The above @code{-largs} section is for Windows platforms. By contrast,
20253 under Unix there is no need for the @code{-largs} section.
20254 Differences across platforms are due to details of linker implementation.
20256 @subsubheading Tracebacks From Anywhere in a Program
20259 It is possible to get a symbolic stack traceback
20260 from anywhere in a program, just as for non-symbolic tracebacks.
20261 The first step is to obtain a non-symbolic
20262 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20263 information. Here is an example:
20265 @quotation
20267 @example
20268 with Ada.Text_IO;
20269 with GNAT.Traceback;
20270 with GNAT.Traceback.Symbolic;
20272 procedure STB is
20274    use Ada;
20275    use GNAT.Traceback;
20276    use GNAT.Traceback.Symbolic;
20278    procedure P1 is
20279       TB  : Tracebacks_Array (1 .. 10);
20280       --  We are asking for a maximum of 10 stack frames.
20281       Len : Natural;
20282       --  Len will receive the actual number of stack frames returned.
20283    begin
20284       Call_Chain (TB, Len);
20285       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20286    end P1;
20288    procedure P2 is
20289    begin
20290       P1;
20291    end P2;
20293 begin
20294    P2;
20295 end STB;
20296 @end example
20297 @end quotation
20299 @subsubheading Automatic Symbolic Tracebacks
20302 Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
20303 in @code{gprbuild -g ... -bargs -Es}).
20304 This will cause the Exception_Information to contain a symbolic traceback,
20305 which will also be printed if an unhandled exception terminates the
20306 program.
20308 @node Pretty-Printers for the GNAT runtime,,Stack Traceback,Running and Debugging Ada Programs
20309 @anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{18e}@anchor{gnat_ugn/gnat_and_program_execution pretty-printers-for-the-gnat-runtime}@anchor{18f}
20310 @subsection Pretty-Printers for the GNAT runtime
20313 As discussed in @cite{Calling User-Defined Subprograms}, GDB's
20314 @code{print} command only knows about the physical layout of program data
20315 structures and therefore normally displays only low-level dumps, which
20316 are often hard to understand.
20318 An example of this is when trying to display the contents of an Ada
20319 standard container, such as @code{Ada.Containers.Ordered_Maps.Map}:
20321 @quotation
20323 @example
20324 with Ada.Containers.Ordered_Maps;
20326 procedure PP is
20327    package Int_To_Nat is
20328       new Ada.Containers.Ordered_Maps (Integer, Natural);
20330    Map : Int_To_Nat.Map;
20331 begin
20332    Map.Insert (1, 10);
20333    Map.Insert (2, 20);
20334    Map.Insert (3, 30);
20336    Map.Clear; --  BREAK HERE
20337 end PP;
20338 @end example
20339 @end quotation
20341 When this program is built with debugging information and run under
20342 GDB up to the @code{Map.Clear} statement, trying to print @code{Map} will
20343 yield information that is only relevant to the developers of our standard
20344 containers:
20346 @quotation
20348 @example
20349 (gdb) print map
20350 $1 = (
20351   tree => (
20352     first => 0x64e010,
20353     last => 0x64e070,
20354     root => 0x64e040,
20355     length => 3,
20356     tc => (
20357       busy => 0,
20358       lock => 0
20359     )
20360   )
20362 @end example
20363 @end quotation
20365 Fortunately, GDB has a feature called pretty-printers@footnote{http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Introduction},
20366 which allows customizing how GDB displays data structures. The GDB
20367 shipped with GNAT embeds such pretty-printers for the most common
20368 containers in the standard library.  To enable them, either run the
20369 following command manually under GDB or add it to your @code{.gdbinit} file:
20371 @quotation
20373 @example
20374 python import gnatdbg; gnatdbg.setup()
20375 @end example
20376 @end quotation
20378 Once this is done, GDB's @code{print} command will automatically use
20379 these pretty-printers when appropriate. Using the previous example:
20381 @quotation
20383 @example
20384 (gdb) print map
20385 $1 = pp.int_to_nat.map of length 3 = @{
20386   [1] = 10,
20387   [2] = 20,
20388   [3] = 30
20390 @end example
20391 @end quotation
20393 Pretty-printers are invoked each time GDB tries to display a value,
20394 including when displaying the arguments of a called subprogram (in
20395 GDB's @code{backtrace} command) or when printing the value returned by a
20396 function (in GDB's @code{finish} command).
20398 To display a value without involving pretty-printers, @code{print} can be
20399 invoked with its @code{/r} option:
20401 @quotation
20403 @example
20404 (gdb) print/r map
20405 $1 = (
20406   tree => (...
20407 @end example
20408 @end quotation
20410 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}
20411 for more information.
20413 @geindex Code Coverage
20415 @geindex Profiling
20417 @node Code Coverage and Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
20418 @anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{168}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-and-profiling}@anchor{25}
20419 @section Code Coverage and Profiling
20422 This section describes how to use the @code{gcov} coverage testing tool and
20423 the @code{gprof} profiler tool on Ada programs.
20425 @geindex gcov
20427 @menu
20428 * Code Coverage of Ada Programs with gcov:: 
20429 * Profiling an Ada Program with gprof:: 
20431 @end menu
20433 @node Code Coverage of Ada Programs with gcov,Profiling an Ada Program with gprof,,Code Coverage and Profiling
20434 @anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{190}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-of-ada-programs-with-gcov}@anchor{191}
20435 @subsection Code Coverage of Ada Programs with gcov
20438 @code{gcov} is a test coverage program: it analyzes the execution of a given
20439 program on selected tests, to help you determine the portions of the program
20440 that are still untested.
20442 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20443 User's Guide. You can refer to this documentation for a more complete
20444 description.
20446 This chapter provides a quick startup guide, and
20447 details some GNAT-specific features.
20449 @menu
20450 * Quick startup guide:: 
20451 * GNAT specifics:: 
20453 @end menu
20455 @node Quick startup guide,GNAT specifics,,Code Coverage of Ada Programs with gcov
20456 @anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{192}@anchor{gnat_ugn/gnat_and_program_execution quick-startup-guide}@anchor{193}
20457 @subsubsection Quick startup guide
20460 In order to perform coverage analysis of a program using @code{gcov}, several
20461 steps are needed:
20464 @enumerate 
20466 @item 
20467 Instrument the code during the compilation process,
20469 @item 
20470 Execute the instrumented program, and
20472 @item 
20473 Invoke the @code{gcov} tool to generate the coverage results.
20474 @end enumerate
20476 @geindex -fprofile-arcs (gcc)
20478 @geindex -ftest-coverage (gcc
20480 @geindex -fprofile-arcs (gnatbind)
20482 The code instrumentation needed by gcov is created at the object level.
20483 The source code is not modified in any way, because the instrumentation code is
20484 inserted by gcc during the compilation process. To compile your code with code
20485 coverage activated, you need to recompile your whole project using the
20486 switches
20487 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20488 @code{-fprofile-arcs}.
20490 @quotation
20492 @example
20493 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \\
20494    -largs -fprofile-arcs
20495 @end example
20496 @end quotation
20498 This compilation process will create @code{.gcno} files together with
20499 the usual object files.
20501 Once the program is compiled with coverage instrumentation, you can
20502 run it as many times as needed -- on portions of a test suite for
20503 example. The first execution will produce @code{.gcda} files at the
20504 same location as the @code{.gcno} files.  Subsequent executions
20505 will update those files, so that a cumulative result of the covered
20506 portions of the program is generated.
20508 Finally, you need to call the @code{gcov} tool. The different options of
20509 @code{gcov} are described in the GCC User's Guide, section @emph{Invoking gcov}.
20511 This will create annotated source files with a @code{.gcov} extension:
20512 @code{my_main.adb} file will be analyzed in @code{my_main.adb.gcov}.
20514 @node GNAT specifics,,Quick startup guide,Code Coverage of Ada Programs with gcov
20515 @anchor{gnat_ugn/gnat_and_program_execution gnat-specifics}@anchor{194}@anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{195}
20516 @subsubsection GNAT specifics
20519 Because of Ada semantics, portions of the source code may be shared among
20520 several object files. This is the case for example when generics are
20521 involved, when inlining is active  or when declarations generate  initialisation
20522 calls. In order to take
20523 into account this shared code, you need to call @code{gcov} on all
20524 source files of the tested program at once.
20526 The list of source files might exceed the system's maximum command line
20527 length. In order to bypass this limitation, a new mechanism has been
20528 implemented in @code{gcov}: you can now list all your project's files into a
20529 text file, and provide this file to gcov as a parameter,  preceded by a @code{@@}
20530 (e.g. @code{gcov @@mysrclist.txt}).
20532 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20533 not supported as there can be unresolved symbols during the final link.
20535 @geindex gprof
20537 @geindex Profiling
20539 @node Profiling an Ada Program with gprof,,Code Coverage of Ada Programs with gcov,Code Coverage and Profiling
20540 @anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{196}@anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{197}
20541 @subsection Profiling an Ada Program with gprof
20544 This section is not meant to be an exhaustive documentation of @code{gprof}.
20545 Full documentation for it can be found in the @cite{GNU Profiler User's Guide}
20546 documentation that is part of this GNAT distribution.
20548 Profiling a program helps determine the parts of a program that are executed
20549 most often, and are therefore the most time-consuming.
20551 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20552 better handle Ada programs and multitasking.
20553 It is currently supported on the following platforms
20556 @itemize *
20558 @item 
20559 linux x86/x86_64
20561 @item 
20562 solaris sparc/sparc64/x86
20564 @item 
20565 windows x86
20566 @end itemize
20568 In order to profile a program using @code{gprof}, several steps are needed:
20571 @enumerate 
20573 @item 
20574 Instrument the code, which requires a full recompilation of the project with the
20575 proper switches.
20577 @item 
20578 Execute the program under the analysis conditions, i.e. with the desired
20579 input.
20581 @item 
20582 Analyze the results using the @code{gprof} tool.
20583 @end enumerate
20585 The following sections detail the different steps, and indicate how
20586 to interpret the results.
20588 @menu
20589 * Compilation for profiling:: 
20590 * Program execution:: 
20591 * Running gprof:: 
20592 * Interpretation of profiling results:: 
20594 @end menu
20596 @node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
20597 @anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{198}@anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{199}
20598 @subsubsection Compilation for profiling
20601 @geindex -pg (gcc)
20602 @geindex for profiling
20604 @geindex -pg (gnatlink)
20605 @geindex for profiling
20607 In order to profile a program the first step is to tell the compiler
20608 to generate the necessary profiling information. The compiler switch to be used
20609 is @code{-pg}, which must be added to other compilation switches. This
20610 switch needs to be specified both during compilation and link stages, and can
20611 be specified once when using gnatmake:
20613 @quotation
20615 @example
20616 $ gnatmake -f -pg -P my_project
20617 @end example
20618 @end quotation
20620 Note that only the objects that were compiled with the @code{-pg} switch will
20621 be profiled; if you need to profile your whole project, use the @code{-f}
20622 gnatmake switch to force full recompilation.
20624 @node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
20625 @anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{19a}@anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{19b}
20626 @subsubsection Program execution
20629 Once the program has been compiled for profiling, you can run it as usual.
20631 The only constraint imposed by profiling is that the program must terminate
20632 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20633 properly analyzed.
20635 Once the program completes execution, a data file called @code{gmon.out} is
20636 generated in the directory where the program was launched from. If this file
20637 already exists, it will be overwritten.
20639 @node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
20640 @anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{19c}@anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{19d}
20641 @subsubsection Running gprof
20644 The @code{gprof} tool is called as follow:
20646 @quotation
20648 @example
20649 $ gprof my_prog gmon.out
20650 @end example
20651 @end quotation
20653 or simply:
20655 @quotation
20657 @example
20658 $  gprof my_prog
20659 @end example
20660 @end quotation
20662 The complete form of the gprof command line is the following:
20664 @quotation
20666 @example
20667 $ gprof [switches] [executable [data-file]]
20668 @end example
20669 @end quotation
20671 @code{gprof} supports numerous switches. The order of these
20672 switch does not matter. The full list of options can be found in
20673 the GNU Profiler User's Guide documentation that comes with this documentation.
20675 The following is the subset of those switches that is most relevant:
20677 @geindex --demangle (gprof)
20680 @table @asis
20682 @item @code{--demangle[=@emph{style}]}, @code{--no-demangle}
20684 These options control whether symbol names should be demangled when
20685 printing output.  The default is to demangle C++ symbols.  The
20686 @code{--no-demangle} option may be used to turn off demangling. Different
20687 compilers have different mangling styles.  The optional demangling style
20688 argument can be used to choose an appropriate demangling style for your
20689 compiler, in particular Ada symbols generated by GNAT can be demangled using
20690 @code{--demangle=gnat}.
20691 @end table
20693 @geindex -e (gprof)
20696 @table @asis
20698 @item @code{-e @emph{function_name}}
20700 The @code{-e @emph{function}} option tells @code{gprof} not to print
20701 information about the function @code{function_name} (and its
20702 children...) in the call graph.  The function will still be listed
20703 as a child of any functions that call it, but its index number will be
20704 shown as @code{[not printed]}.  More than one @code{-e} option may be
20705 given; only one @code{function_name} may be indicated with each @code{-e}
20706 option.
20707 @end table
20709 @geindex -E (gprof)
20712 @table @asis
20714 @item @code{-E @emph{function_name}}
20716 The @code{-E @emph{function}} option works like the @code{-e} option, but
20717 execution time spent in the function (and children who were not called from
20718 anywhere else), will not be used to compute the percentages-of-time for
20719 the call graph.  More than one @code{-E} option may be given; only one
20720 @code{function_name} may be indicated with each @code{-E`} option.
20721 @end table
20723 @geindex -f (gprof)
20726 @table @asis
20728 @item @code{-f @emph{function_name}}
20730 The @code{-f @emph{function}} option causes @code{gprof} to limit the
20731 call graph to the function @code{function_name} and its children (and
20732 their children...).  More than one @code{-f} option may be given;
20733 only one @code{function_name} may be indicated with each @code{-f}
20734 option.
20735 @end table
20737 @geindex -F (gprof)
20740 @table @asis
20742 @item @code{-F @emph{function_name}}
20744 The @code{-F @emph{function}} option works like the @code{-f} option, but
20745 only time spent in the function and its children (and their
20746 children...) will be used to determine total-time and
20747 percentages-of-time for the call graph.  More than one @code{-F} option
20748 may be given; only one @code{function_name} may be indicated with each
20749 @code{-F} option.  The @code{-F} option overrides the @code{-E} option.
20750 @end table
20752 @node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
20753 @anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{19e}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{19f}
20754 @subsubsection Interpretation of profiling results
20757 The results of the profiling analysis are represented by two arrays: the
20758 'flat profile' and the 'call graph'. Full documentation of those outputs
20759 can be found in the GNU Profiler User's Guide.
20761 The flat profile shows the time spent in each function of the program, and how
20762 many time it has been called. This allows you to locate easily the most
20763 time-consuming functions.
20765 The call graph shows, for each subprogram, the subprograms that call it,
20766 and the subprograms that it calls. It also provides an estimate of the time
20767 spent in each of those callers/called subprograms.
20769 @node Improving Performance,Overflow Check Handling in GNAT,Code Coverage and Profiling,GNAT and Program Execution
20770 @anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{169}@anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{26}
20771 @section Improving Performance
20774 @geindex Improving performance
20776 This section presents several topics related to program performance.
20777 It first describes some of the tradeoffs that need to be considered
20778 and some of the techniques for making your program run faster.
20781 It then documents the unused subprogram/data elimination feature,
20782 which can reduce the size of program executables.
20784 @menu
20785 * Performance Considerations:: 
20786 * Text_IO Suggestions:: 
20787 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
20789 @end menu
20791 @node Performance Considerations,Text_IO Suggestions,,Improving Performance
20792 @anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{1a0}@anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{1a1}
20793 @subsection Performance Considerations
20796 The GNAT system provides a number of options that allow a trade-off
20797 between
20800 @itemize *
20802 @item 
20803 performance of the generated code
20805 @item 
20806 speed of compilation
20808 @item 
20809 minimization of dependences and recompilation
20811 @item 
20812 the degree of run-time checking.
20813 @end itemize
20815 The defaults (if no options are selected) aim at improving the speed
20816 of compilation and minimizing dependences, at the expense of performance
20817 of the generated code:
20820 @itemize *
20822 @item 
20823 no optimization
20825 @item 
20826 no inlining of subprogram calls
20828 @item 
20829 all run-time checks enabled except overflow and elaboration checks
20830 @end itemize
20832 These options are suitable for most program development purposes. This
20833 section describes how you can modify these choices, and also provides
20834 some guidelines on debugging optimized code.
20836 @menu
20837 * Controlling Run-Time Checks:: 
20838 * Use of Restrictions:: 
20839 * Optimization Levels:: 
20840 * Debugging Optimized Code:: 
20841 * Inlining of Subprograms:: 
20842 * Floating_Point_Operations:: 
20843 * Vectorization of loops:: 
20844 * Other Optimization Switches:: 
20845 * Optimization and Strict Aliasing:: 
20846 * Aliased Variables and Optimization:: 
20847 * Atomic Variables and Optimization:: 
20848 * Passive Task Optimization:: 
20850 @end menu
20852 @node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
20853 @anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{1a2}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{1a3}
20854 @subsubsection Controlling Run-Time Checks
20857 By default, GNAT generates all run-time checks, except stack overflow
20858 checks, and checks for access before elaboration on subprogram
20859 calls. The latter are not required in default mode, because all
20860 necessary checking is done at compile time.
20862 @geindex -gnatp (gcc)
20864 @geindex -gnato (gcc)
20866 The gnat switch, @code{-gnatp} allows this default to be modified. See
20867 @ref{f9,,Run-Time Checks}.
20869 Our experience is that the default is suitable for most development
20870 purposes.
20872 Elaboration checks are off by default, and also not needed by default, since
20873 GNAT uses a static elaboration analysis approach that avoids the need for
20874 run-time checking. This manual contains a full chapter discussing the issue
20875 of elaboration checks, and if the default is not satisfactory for your use,
20876 you should read this chapter.
20878 For validity checks, the minimal checks required by the Ada Reference
20879 Manual (for case statements and assignments to array elements) are on
20880 by default. These can be suppressed by use of the @code{-gnatVn} switch.
20881 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20882 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20883 it may be reasonable to routinely use @code{-gnatVn}. Validity checks
20884 are also suppressed entirely if @code{-gnatp} is used.
20886 @geindex Overflow checks
20888 @geindex Checks
20889 @geindex overflow
20891 @geindex Suppress
20893 @geindex Unsuppress
20895 @geindex pragma Suppress
20897 @geindex pragma Unsuppress
20899 Note that the setting of the switches controls the default setting of
20900 the checks. They may be modified using either @code{pragma Suppress} (to
20901 remove checks) or @code{pragma Unsuppress} (to add back suppressed
20902 checks) in the program source.
20904 @node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
20905 @anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{1a4}@anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{1a5}
20906 @subsubsection Use of Restrictions
20909 The use of pragma Restrictions allows you to control which features are
20910 permitted in your program. Apart from the obvious point that if you avoid
20911 relatively expensive features like finalization (enforceable by the use
20912 of pragma Restrictions (No_Finalization), the use of this pragma does not
20913 affect the generated code in most cases.
20915 One notable exception to this rule is that the possibility of task abort
20916 results in some distributed overhead, particularly if finalization or
20917 exception handlers are used. The reason is that certain sections of code
20918 have to be marked as non-abortable.
20920 If you use neither the @code{abort} statement, nor asynchronous transfer
20921 of control (@code{select ... then abort}), then this distributed overhead
20922 is removed, which may have a general positive effect in improving
20923 overall performance.  Especially code involving frequent use of tasking
20924 constructs and controlled types will show much improved performance.
20925 The relevant restrictions pragmas are
20927 @quotation
20929 @example
20930 pragma Restrictions (No_Abort_Statements);
20931 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
20932 @end example
20933 @end quotation
20935 It is recommended that these restriction pragmas be used if possible. Note
20936 that this also means that you can write code without worrying about the
20937 possibility of an immediate abort at any point.
20939 @node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
20940 @anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{1a6}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{fc}
20941 @subsubsection Optimization Levels
20944 @geindex -O (gcc)
20946 Without any optimization option,
20947 the compiler's goal is to reduce the cost of
20948 compilation and to make debugging produce the expected results.
20949 Statements are independent: if you stop the program with a breakpoint between
20950 statements, you can then assign a new value to any variable or change
20951 the program counter to any other statement in the subprogram and get exactly
20952 the results you would expect from the source code.
20954 Turning on optimization makes the compiler attempt to improve the
20955 performance and/or code size at the expense of compilation time and
20956 possibly the ability to debug the program.
20958 If you use multiple
20959 -O options, with or without level numbers,
20960 the last such option is the one that is effective.
20962 The default is optimization off. This results in the fastest compile
20963 times, but GNAT makes absolutely no attempt to optimize, and the
20964 generated programs are considerably larger and slower than when
20965 optimization is enabled. You can use the
20966 @code{-O} switch (the permitted forms are @code{-O0}, @code{-O1}
20967 @code{-O2}, @code{-O3}, and @code{-Os})
20968 to @code{gcc} to control the optimization level:
20971 @itemize *
20973 @item 
20975 @table @asis
20977 @item @code{-O0}
20979 No optimization (the default);
20980 generates unoptimized code but has
20981 the fastest compilation time.
20983 Note that many other compilers do substantial optimization even
20984 if 'no optimization' is specified. With gcc, it is very unusual
20985 to use @code{-O0} for production if execution time is of any concern,
20986 since @code{-O0} means (almost) no optimization. This difference
20987 between gcc and other compilers should be kept in mind when
20988 doing performance comparisons.
20989 @end table
20991 @item 
20993 @table @asis
20995 @item @code{-O1}
20997 Moderate optimization;
20998 optimizes reasonably well but does not
20999 degrade compilation time significantly.
21000 @end table
21002 @item 
21004 @table @asis
21006 @item @code{-O2}
21008 Full optimization;
21009 generates highly optimized code and has
21010 the slowest compilation time.
21011 @end table
21013 @item 
21015 @table @asis
21017 @item @code{-O3}
21019 Full optimization as in @code{-O2};
21020 also uses more aggressive automatic inlining of subprograms within a unit
21021 (@ref{10f,,Inlining of Subprograms}) and attempts to vectorize loops.
21022 @end table
21024 @item 
21026 @table @asis
21028 @item @code{-Os}
21030 Optimize space usage (code and data) of resulting program.
21031 @end table
21032 @end itemize
21034 Higher optimization levels perform more global transformations on the
21035 program and apply more expensive analysis algorithms in order to generate
21036 faster and more compact code. The price in compilation time, and the
21037 resulting improvement in execution time,
21038 both depend on the particular application and the hardware environment.
21039 You should experiment to find the best level for your application.
21041 Since the precise set of optimizations done at each level will vary from
21042 release to release (and sometime from target to target), it is best to think
21043 of the optimization settings in general terms.
21044 See the @emph{Options That Control Optimization} section in
21045 @cite{Using the GNU Compiler Collection (GCC)}
21046 for details about
21047 the @code{-O} settings and a number of @code{-f} options that
21048 individually enable or disable specific optimizations.
21050 Unlike some other compilation systems, @code{gcc} has
21051 been tested extensively at all optimization levels. There are some bugs
21052 which appear only with optimization turned on, but there have also been
21053 bugs which show up only in @emph{unoptimized} code. Selecting a lower
21054 level of optimization does not improve the reliability of the code
21055 generator, which in practice is highly reliable at all optimization
21056 levels.
21058 Note regarding the use of @code{-O3}: The use of this optimization level
21059 ought not to be automatically preferred over that of level @code{-O2},
21060 since it often results in larger executables which may run more slowly.
21061 See further discussion of this point in @ref{10f,,Inlining of Subprograms}.
21063 @node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
21064 @anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{1a7}@anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{1a8}
21065 @subsubsection Debugging Optimized Code
21068 @geindex Debugging optimized code
21070 @geindex Optimization and debugging
21072 Although it is possible to do a reasonable amount of debugging at
21073 nonzero optimization levels,
21074 the higher the level the more likely that
21075 source-level constructs will have been eliminated by optimization.
21076 For example, if a loop is strength-reduced, the loop
21077 control variable may be completely eliminated and thus cannot be
21078 displayed in the debugger.
21079 This can only happen at @code{-O2} or @code{-O3}.
21080 Explicit temporary variables that you code might be eliminated at
21081 level @code{-O1} or higher.
21083 @geindex -g (gcc)
21085 The use of the @code{-g} switch,
21086 which is needed for source-level debugging,
21087 affects the size of the program executable on disk,
21088 and indeed the debugging information can be quite large.
21089 However, it has no effect on the generated code (and thus does not
21090 degrade performance)
21092 Since the compiler generates debugging tables for a compilation unit before
21093 it performs optimizations, the optimizing transformations may invalidate some
21094 of the debugging data.  You therefore need to anticipate certain
21095 anomalous situations that may arise while debugging optimized code.
21096 These are the most common cases:
21099 @itemize *
21101 @item 
21102 @emph{The 'hopping Program Counter':}  Repeated @code{step} or @code{next}
21103 commands show
21104 the PC bouncing back and forth in the code.  This may result from any of
21105 the following optimizations:
21108 @itemize -
21110 @item 
21111 @emph{Common subexpression elimination:} using a single instance of code for a
21112 quantity that the source computes several times.  As a result you
21113 may not be able to stop on what looks like a statement.
21115 @item 
21116 @emph{Invariant code motion:} moving an expression that does not change within a
21117 loop, to the beginning of the loop.
21119 @item 
21120 @emph{Instruction scheduling:} moving instructions so as to
21121 overlap loads and stores (typically) with other code, or in
21122 general to move computations of values closer to their uses. Often
21123 this causes you to pass an assignment statement without the assignment
21124 happening and then later bounce back to the statement when the
21125 value is actually needed.  Placing a breakpoint on a line of code
21126 and then stepping over it may, therefore, not always cause all the
21127 expected side-effects.
21128 @end itemize
21130 @item 
21131 @emph{The 'big leap':} More commonly known as @emph{cross-jumping}, in which
21132 two identical pieces of code are merged and the program counter suddenly
21133 jumps to a statement that is not supposed to be executed, simply because
21134 it (and the code following) translates to the same thing as the code
21135 that @emph{was} supposed to be executed.  This effect is typically seen in
21136 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
21137 a @code{break} in a C @code{switch} statement.
21139 @item 
21140 @emph{The 'roving variable':} The symptom is an unexpected value in a variable.
21141 There are various reasons for this effect:
21144 @itemize -
21146 @item 
21147 In a subprogram prologue, a parameter may not yet have been moved to its
21148 'home'.
21150 @item 
21151 A variable may be dead, and its register re-used.  This is
21152 probably the most common cause.
21154 @item 
21155 As mentioned above, the assignment of a value to a variable may
21156 have been moved.
21158 @item 
21159 A variable may be eliminated entirely by value propagation or
21160 other means.  In this case, GCC may incorrectly generate debugging
21161 information for the variable
21162 @end itemize
21164 In general, when an unexpected value appears for a local variable or parameter
21165 you should first ascertain if that value was actually computed by
21166 your program, as opposed to being incorrectly reported by the debugger.
21167 Record fields or
21168 array elements in an object designated by an access value
21169 are generally less of a problem, once you have ascertained that the access
21170 value is sensible.
21171 Typically, this means checking variables in the preceding code and in the
21172 calling subprogram to verify that the value observed is explainable from other
21173 values (one must apply the procedure recursively to those
21174 other values); or re-running the code and stopping a little earlier
21175 (perhaps before the call) and stepping to better see how the variable obtained
21176 the value in question; or continuing to step @emph{from} the point of the
21177 strange value to see if code motion had simply moved the variable's
21178 assignments later.
21179 @end itemize
21181 In light of such anomalies, a recommended technique is to use @code{-O0}
21182 early in the software development cycle, when extensive debugging capabilities
21183 are most needed, and then move to @code{-O1} and later @code{-O2} as
21184 the debugger becomes less critical.
21185 Whether to use the @code{-g} switch in the release version is
21186 a release management issue.
21187 Note that if you use @code{-g} you can then use the @code{strip} program
21188 on the resulting executable,
21189 which removes both debugging information and global symbols.
21191 @node Inlining of Subprograms,Floating_Point_Operations,Debugging Optimized Code,Performance Considerations
21192 @anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{1a9}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{10f}
21193 @subsubsection Inlining of Subprograms
21196 A call to a subprogram in the current unit is inlined if all the
21197 following conditions are met:
21200 @itemize *
21202 @item 
21203 The optimization level is at least @code{-O1}.
21205 @item 
21206 The called subprogram is suitable for inlining: It must be small enough
21207 and not contain something that @code{gcc} cannot support in inlined
21208 subprograms.
21210 @geindex pragma Inline
21212 @geindex Inline
21214 @item 
21215 Any one of the following applies: @code{pragma Inline} is applied to the
21216 subprogram; the subprogram is local to the unit and called once from
21217 within it; the subprogram is small and optimization level @code{-O2} is
21218 specified; optimization level @code{-O3} is specified.
21219 @end itemize
21221 Calls to subprograms in @emph{with}ed units are normally not inlined.
21222 To achieve actual inlining (that is, replacement of the call by the code
21223 in the body of the subprogram), the following conditions must all be true:
21226 @itemize *
21228 @item 
21229 The optimization level is at least @code{-O1}.
21231 @item 
21232 The called subprogram is suitable for inlining: It must be small enough
21233 and not contain something that @code{gcc} cannot support in inlined
21234 subprograms.
21236 @item 
21237 There is a @code{pragma Inline} for the subprogram.
21239 @item 
21240 The @code{-gnatn} switch is used on the command line.
21241 @end itemize
21243 Even if all these conditions are met, it may not be possible for
21244 the compiler to inline the call, due to the length of the body,
21245 or features in the body that make it impossible for the compiler
21246 to do the inlining.
21248 Note that specifying the @code{-gnatn} switch causes additional
21249 compilation dependencies. Consider the following:
21251 @quotation
21253 @example
21254 package R is
21255    procedure Q;
21256    pragma Inline (Q);
21257 end R;
21258 package body R is
21259    ...
21260 end R;
21262 with R;
21263 procedure Main is
21264 begin
21265    ...
21266    R.Q;
21267 end Main;
21268 @end example
21269 @end quotation
21271 With the default behavior (no @code{-gnatn} switch specified), the
21272 compilation of the @code{Main} procedure depends only on its own source,
21273 @code{main.adb}, and the spec of the package in file @code{r.ads}. This
21274 means that editing the body of @code{R} does not require recompiling
21275 @code{Main}.
21277 On the other hand, the call @code{R.Q} is not inlined under these
21278 circumstances. If the @code{-gnatn} switch is present when @code{Main}
21279 is compiled, the call will be inlined if the body of @code{Q} is small
21280 enough, but now @code{Main} depends on the body of @code{R} in
21281 @code{r.adb} as well as on the spec. This means that if this body is edited,
21282 the main program must be recompiled. Note that this extra dependency
21283 occurs whether or not the call is in fact inlined by @code{gcc}.
21285 The use of front end inlining with @code{-gnatN} generates similar
21286 additional dependencies.
21288 @geindex -fno-inline (gcc)
21290 Note: The @code{-fno-inline} switch overrides all other conditions and ensures that
21291 no inlining occurs, unless requested with pragma Inline_Always for @code{gcc}
21292 back-ends. The extra dependences resulting from @code{-gnatn} will still be active,
21293 even if this switch is used to suppress the resulting inlining actions.
21295 @geindex -fno-inline-functions (gcc)
21297 Note: The @code{-fno-inline-functions} switch can be used to prevent
21298 automatic inlining of subprograms if @code{-O3} is used.
21300 @geindex -fno-inline-small-functions (gcc)
21302 Note: The @code{-fno-inline-small-functions} switch can be used to prevent
21303 automatic inlining of small subprograms if @code{-O2} is used.
21305 @geindex -fno-inline-functions-called-once (gcc)
21307 Note: The @code{-fno-inline-functions-called-once} switch
21308 can be used to prevent inlining of subprograms local to the unit
21309 and called once from within it if @code{-O1} is used.
21311 Note regarding the use of @code{-O3}: @code{-gnatn} is made up of two
21312 sub-switches @code{-gnatn1} and @code{-gnatn2} that can be directly
21313 specified in lieu of it, @code{-gnatn} being translated into one of them
21314 based on the optimization level. With @code{-O2} or below, @code{-gnatn}
21315 is equivalent to @code{-gnatn1} which activates pragma @code{Inline} with
21316 moderate inlining across modules. With @code{-O3}, @code{-gnatn} is
21317 equivalent to @code{-gnatn2} which activates pragma @code{Inline} with
21318 full inlining across modules. If you have used pragma @code{Inline} in
21319 appropriate cases, then it is usually much better to use @code{-O2}
21320 and @code{-gnatn} and avoid the use of @code{-O3} which has the additional
21321 effect of inlining subprograms you did not think should be inlined. We have
21322 found that the use of @code{-O3} may slow down the compilation and increase
21323 the code size by performing excessive inlining, leading to increased
21324 instruction cache pressure from the increased code size and thus minor
21325 performance improvements. So the bottom line here is that you should not
21326 automatically assume that @code{-O3} is better than @code{-O2}, and
21327 indeed you should use @code{-O3} only if tests show that it actually
21328 improves performance for your program.
21330 @node Floating_Point_Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
21331 @anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{1aa}@anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{1ab}
21332 @subsubsection Floating_Point_Operations
21335 @geindex Floating-Point Operations
21337 On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
21338 64-bit standard IEEE floating-point representations, and operations will
21339 use standard IEEE arithmetic as provided by the processor. On most, but
21340 not all, architectures, the attribute Machine_Overflows is False for these
21341 types, meaning that the semantics of overflow is implementation-defined.
21342 In the case of GNAT, these semantics correspond to the normal IEEE
21343 treatment of infinities and NaN (not a number) values. For example,
21344 1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
21345 avoiding explicit overflow checks, the performance is greatly improved
21346 on many targets. However, if required, floating-point overflow can be
21347 enabled by the use of the pragma Check_Float_Overflow.
21349 Another consideration that applies specifically to x86 32-bit
21350 architectures is which form of floating-point arithmetic is used.
21351 By default the operations use the old style x86 floating-point,
21352 which implements an 80-bit extended precision form (on these
21353 architectures the type Long_Long_Float corresponds to that form).
21354 In addition, generation of efficient code in this mode means that
21355 the extended precision form will be used for intermediate results.
21356 This may be helpful in improving the final precision of a complex
21357 expression. However it means that the results obtained on the x86
21358 will be different from those on other architectures, and for some
21359 algorithms, the extra intermediate precision can be detrimental.
21361 In addition to this old-style floating-point, all modern x86 chips
21362 implement an alternative floating-point operation model referred
21363 to as SSE2. In this model there is no extended form, and furthermore
21364 execution performance is significantly enhanced. To force GNAT to use
21365 this more modern form, use both of the switches:
21367 @quotation
21369 -msse2 -mfpmath=sse
21370 @end quotation
21372 A unit compiled with these switches will automatically use the more
21373 efficient SSE2 instruction set for Float and Long_Float operations.
21374 Note that the ABI has the same form for both floating-point models,
21375 so it is permissible to mix units compiled with and without these
21376 switches.
21378 @node Vectorization of loops,Other Optimization Switches,Floating_Point_Operations,Performance Considerations
21379 @anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{1ac}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{1ad}
21380 @subsubsection Vectorization of loops
21383 @geindex Optimization Switches
21385 You can take advantage of the auto-vectorizer present in the @code{gcc}
21386 back end to vectorize loops with GNAT.  The corresponding command line switch
21387 is @code{-ftree-vectorize} but, as it is enabled by default at @code{-O3}
21388 and other aggressive optimizations helpful for vectorization also are enabled
21389 by default at this level, using @code{-O3} directly is recommended.
21391 You also need to make sure that the target architecture features a supported
21392 SIMD instruction set.  For example, for the x86 architecture, you should at
21393 least specify @code{-msse2} to get significant vectorization (but you don't
21394 need to specify it for x86-64 as it is part of the base 64-bit architecture).
21395 Similarly, for the PowerPC architecture, you should specify @code{-maltivec}.
21397 The preferred loop form for vectorization is the @code{for} iteration scheme.
21398 Loops with a @code{while} iteration scheme can also be vectorized if they are
21399 very simple, but the vectorizer will quickly give up otherwise.  With either
21400 iteration scheme, the flow of control must be straight, in particular no
21401 @code{exit} statement may appear in the loop body.  The loop may however
21402 contain a single nested loop, if it can be vectorized when considered alone:
21404 @quotation
21406 @example
21407 A : array (1..4, 1..4) of Long_Float;
21408 S : array (1..4) of Long_Float;
21410 procedure Sum is
21411 begin
21412    for I in A'Range(1) loop
21413       for J in A'Range(2) loop
21414          S (I) := S (I) + A (I, J);
21415       end loop;
21416    end loop;
21417 end Sum;
21418 @end example
21419 @end quotation
21421 The vectorizable operations depend on the targeted SIMD instruction set, but
21422 the adding and some of the multiplying operators are generally supported, as
21423 well as the logical operators for modular types. Note that compiling
21424 with @code{-gnatp} might well reveal cases where some checks do thwart
21425 vectorization.
21427 Type conversions may also prevent vectorization if they involve semantics that
21428 are not directly supported by the code generator or the SIMD instruction set.
21429 A typical example is direct conversion from floating-point to integer types.
21430 The solution in this case is to use the following idiom:
21432 @quotation
21434 @example
21435 Integer (S'Truncation (F))
21436 @end example
21437 @end quotation
21439 if @code{S} is the subtype of floating-point object @code{F}.
21441 In most cases, the vectorizable loops are loops that iterate over arrays.
21442 All kinds of array types are supported, i.e. constrained array types with
21443 static bounds:
21445 @quotation
21447 @example
21448 type Array_Type is array (1 .. 4) of Long_Float;
21449 @end example
21450 @end quotation
21452 constrained array types with dynamic bounds:
21454 @quotation
21456 @example
21457 type Array_Type is array (1 .. Q.N) of Long_Float;
21459 type Array_Type is array (Q.K .. 4) of Long_Float;
21461 type Array_Type is array (Q.K .. Q.N) of Long_Float;
21462 @end example
21463 @end quotation
21465 or unconstrained array types:
21467 @quotation
21469 @example
21470 type Array_Type is array (Positive range <>) of Long_Float;
21471 @end example
21472 @end quotation
21474 The quality of the generated code decreases when the dynamic aspect of the
21475 array type increases, the worst code being generated for unconstrained array
21476 types.  This is so because, the less information the compiler has about the
21477 bounds of the array, the more fallback code it needs to generate in order to
21478 fix things up at run time.
21480 It is possible to specify that a given loop should be subject to vectorization
21481 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
21483 @quotation
21485 @example
21486 pragma Loop_Optimize (Vector);
21487 @end example
21488 @end quotation
21490 placed immediately within the loop will convey the appropriate hint to the
21491 compiler for this loop.
21493 It is also possible to help the compiler generate better vectorized code
21494 for a given loop by asserting that there are no loop-carried dependencies
21495 in the loop.  Consider for example the procedure:
21497 @quotation
21499 @example
21500 type Arr is array (1 .. 4) of Long_Float;
21502 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
21503 begin
21504   for I in Arr'Range loop
21505     R(I) := X(I) + Y(I);
21506   end loop;
21507 end;
21508 @end example
21509 @end quotation
21511 By default, the compiler cannot unconditionally vectorize the loop because
21512 assigning to a component of the array designated by R in one iteration could
21513 change the value read from the components of the array designated by X or Y
21514 in a later iteration.  As a result, the compiler will generate two versions
21515 of the loop in the object code, one vectorized and the other not vectorized,
21516 as well as a test to select the appropriate version at run time.  This can
21517 be overcome by another hint:
21519 @quotation
21521 @example
21522 pragma Loop_Optimize (Ivdep);
21523 @end example
21524 @end quotation
21526 placed immediately within the loop will tell the compiler that it can safely
21527 omit the non-vectorized version of the loop as well as the run-time test.
21529 @node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
21530 @anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{1ae}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{1af}
21531 @subsubsection Other Optimization Switches
21534 @geindex Optimization Switches
21536 Since GNAT uses the @code{gcc} back end, all the specialized
21537 @code{gcc} optimization switches are potentially usable. These switches
21538 have not been extensively tested with GNAT but can generally be expected
21539 to work. Examples of switches in this category are @code{-funroll-loops}
21540 and the various target-specific @code{-m} options (in particular, it has
21541 been observed that @code{-march=xxx} can significantly improve performance
21542 on appropriate machines). For full details of these switches, see
21543 the @emph{Submodel Options} section in the @emph{Hardware Models and Configurations}
21544 chapter of @cite{Using the GNU Compiler Collection (GCC)}.
21546 @node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
21547 @anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{f3}@anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{1b0}
21548 @subsubsection Optimization and Strict Aliasing
21551 @geindex Aliasing
21553 @geindex Strict Aliasing
21555 @geindex No_Strict_Aliasing
21557 The strong typing capabilities of Ada allow an optimizer to generate
21558 efficient code in situations where other languages would be forced to
21559 make worst case assumptions preventing such optimizations. Consider
21560 the following example:
21562 @quotation
21564 @example
21565 procedure R is
21566    type Int1 is new Integer;
21567    type Int2 is new Integer;
21568    type Int1A is access Int1;
21569    type Int2A is access Int2;
21570    Int1V : Int1A;
21571    Int2V : Int2A;
21572    ...
21574 begin
21575    ...
21576    for J in Data'Range loop
21577       if Data (J) = Int1V.all then
21578          Int2V.all := Int2V.all + 1;
21579       end if;
21580    end loop;
21581    ...
21582 end R;
21583 @end example
21584 @end quotation
21586 In this example, since the variable @code{Int1V} can only access objects
21587 of type @code{Int1}, and @code{Int2V} can only access objects of type
21588 @code{Int2}, there is no possibility that the assignment to
21589 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
21590 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
21591 for all iterations of the loop and avoid the extra memory reference
21592 required to dereference it each time through the loop.
21594 This kind of optimization, called strict aliasing analysis, is
21595 triggered by specifying an optimization level of @code{-O2} or
21596 higher or @code{-Os} and allows GNAT to generate more efficient code
21597 when access values are involved.
21599 However, although this optimization is always correct in terms of
21600 the formal semantics of the Ada Reference Manual, difficulties can
21601 arise if features like @code{Unchecked_Conversion} are used to break
21602 the typing system. Consider the following complete program example:
21604 @quotation
21606 @example
21607 package p1 is
21608    type int1 is new integer;
21609    type int2 is new integer;
21610    type a1 is access int1;
21611    type a2 is access int2;
21612 end p1;
21614 with p1; use p1;
21615 package p2 is
21616    function to_a2 (Input : a1) return a2;
21617 end p2;
21619 with Unchecked_Conversion;
21620 package body p2 is
21621    function to_a2 (Input : a1) return a2 is
21622       function to_a2u is
21623         new Unchecked_Conversion (a1, a2);
21624    begin
21625       return to_a2u (Input);
21626    end to_a2;
21627 end p2;
21629 with p2; use p2;
21630 with p1; use p1;
21631 with Text_IO; use Text_IO;
21632 procedure m is
21633    v1 : a1 := new int1;
21634    v2 : a2 := to_a2 (v1);
21635 begin
21636    v1.all := 1;
21637    v2.all := 0;
21638    put_line (int1'image (v1.all));
21639 end;
21640 @end example
21641 @end quotation
21643 This program prints out 0 in @code{-O0} or @code{-O1}
21644 mode, but it prints out 1 in @code{-O2} mode. That's
21645 because in strict aliasing mode, the compiler can and
21646 does assume that the assignment to @code{v2.all} could not
21647 affect the value of @code{v1.all}, since different types
21648 are involved.
21650 This behavior is not a case of non-conformance with the standard, since
21651 the Ada RM specifies that an unchecked conversion where the resulting
21652 bit pattern is not a correct value of the target type can result in an
21653 abnormal value and attempting to reference an abnormal value makes the
21654 execution of a program erroneous.  That's the case here since the result
21655 does not point to an object of type @code{int2}.  This means that the
21656 effect is entirely unpredictable.
21658 However, although that explanation may satisfy a language
21659 lawyer, in practice an applications programmer expects an
21660 unchecked conversion involving pointers to create true
21661 aliases and the behavior of printing 1 seems plain wrong.
21662 In this case, the strict aliasing optimization is unwelcome.
21664 Indeed the compiler recognizes this possibility, and the
21665 unchecked conversion generates a warning:
21667 @quotation
21669 @example
21670 p2.adb:5:07: warning: possible aliasing problem with type "a2"
21671 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
21672 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
21673 @end example
21674 @end quotation
21676 Unfortunately the problem is recognized when compiling the body of
21677 package @code{p2}, but the actual "bad" code is generated while
21678 compiling the body of @code{m} and this latter compilation does not see
21679 the suspicious @code{Unchecked_Conversion}.
21681 As implied by the warning message, there are approaches you can use to
21682 avoid the unwanted strict aliasing optimization in a case like this.
21684 One possibility is to simply avoid the use of @code{-O2}, but
21685 that is a bit drastic, since it throws away a number of useful
21686 optimizations that do not involve strict aliasing assumptions.
21688 A less drastic approach is to compile the program using the
21689 option @code{-fno-strict-aliasing}. Actually it is only the
21690 unit containing the dereferencing of the suspicious pointer
21691 that needs to be compiled. So in this case, if we compile
21692 unit @code{m} with this switch, then we get the expected
21693 value of zero printed. Analyzing which units might need
21694 the switch can be painful, so a more reasonable approach
21695 is to compile the entire program with options @code{-O2}
21696 and @code{-fno-strict-aliasing}. If the performance is
21697 satisfactory with this combination of options, then the
21698 advantage is that the entire issue of possible "wrong"
21699 optimization due to strict aliasing is avoided.
21701 To avoid the use of compiler switches, the configuration
21702 pragma @code{No_Strict_Aliasing} with no parameters may be
21703 used to specify that for all access types, the strict
21704 aliasing optimization should be suppressed.
21706 However, these approaches are still overkill, in that they causes
21707 all manipulations of all access values to be deoptimized. A more
21708 refined approach is to concentrate attention on the specific
21709 access type identified as problematic.
21711 First, if a careful analysis of uses of the pointer shows
21712 that there are no possible problematic references, then
21713 the warning can be suppressed by bracketing the
21714 instantiation of @code{Unchecked_Conversion} to turn
21715 the warning off:
21717 @quotation
21719 @example
21720 pragma Warnings (Off);
21721 function to_a2u is
21722   new Unchecked_Conversion (a1, a2);
21723 pragma Warnings (On);
21724 @end example
21725 @end quotation
21727 Of course that approach is not appropriate for this particular
21728 example, since indeed there is a problematic reference. In this
21729 case we can take one of two other approaches.
21731 The first possibility is to move the instantiation of unchecked
21732 conversion to the unit in which the type is declared. In
21733 this example, we would move the instantiation of
21734 @code{Unchecked_Conversion} from the body of package
21735 @code{p2} to the spec of package @code{p1}. Now the
21736 warning disappears. That's because any use of the
21737 access type knows there is a suspicious unchecked
21738 conversion, and the strict aliasing optimization
21739 is automatically suppressed for the type.
21741 If it is not practical to move the unchecked conversion to the same unit
21742 in which the destination access type is declared (perhaps because the
21743 source type is not visible in that unit), you may use pragma
21744 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
21745 same declarative sequence as the declaration of the access type:
21747 @quotation
21749 @example
21750 type a2 is access int2;
21751 pragma No_Strict_Aliasing (a2);
21752 @end example
21753 @end quotation
21755 Here again, the compiler now knows that the strict aliasing optimization
21756 should be suppressed for any reference to type @code{a2} and the
21757 expected behavior is obtained.
21759 Finally, note that although the compiler can generate warnings for
21760 simple cases of unchecked conversions, there are tricker and more
21761 indirect ways of creating type incorrect aliases which the compiler
21762 cannot detect. Examples are the use of address overlays and unchecked
21763 conversions involving composite types containing access types as
21764 components. In such cases, no warnings are generated, but there can
21765 still be aliasing problems. One safe coding practice is to forbid the
21766 use of address clauses for type overlaying, and to allow unchecked
21767 conversion only for primitive types. This is not really a significant
21768 restriction since any possible desired effect can be achieved by
21769 unchecked conversion of access values.
21771 The aliasing analysis done in strict aliasing mode can certainly
21772 have significant benefits. We have seen cases of large scale
21773 application code where the time is increased by up to 5% by turning
21774 this optimization off. If you have code that includes significant
21775 usage of unchecked conversion, you might want to just stick with
21776 @code{-O1} and avoid the entire issue. If you get adequate
21777 performance at this level of optimization level, that's probably
21778 the safest approach. If tests show that you really need higher
21779 levels of optimization, then you can experiment with @code{-O2}
21780 and @code{-O2 -fno-strict-aliasing} to see how much effect this
21781 has on size and speed of the code. If you really need to use
21782 @code{-O2} with strict aliasing in effect, then you should
21783 review any uses of unchecked conversion of access types,
21784 particularly if you are getting the warnings described above.
21786 @node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
21787 @anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{1b1}@anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{1b2}
21788 @subsubsection Aliased Variables and Optimization
21791 @geindex Aliasing
21793 There are scenarios in which programs may
21794 use low level techniques to modify variables
21795 that otherwise might be considered to be unassigned. For example,
21796 a variable can be passed to a procedure by reference, which takes
21797 the address of the parameter and uses the address to modify the
21798 variable's value, even though it is passed as an IN parameter.
21799 Consider the following example:
21801 @quotation
21803 @example
21804 procedure P is
21805    Max_Length : constant Natural := 16;
21806    type Char_Ptr is access all Character;
21808    procedure Get_String(Buffer: Char_Ptr; Size : Integer);
21809    pragma Import (C, Get_String, "get_string");
21811    Name : aliased String (1 .. Max_Length) := (others => ' ');
21812    Temp : Char_Ptr;
21814    function Addr (S : String) return Char_Ptr is
21815       function To_Char_Ptr is
21816         new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
21817    begin
21818       return To_Char_Ptr (S (S'First)'Address);
21819    end;
21821 begin
21822    Temp := Addr (Name);
21823    Get_String (Temp, Max_Length);
21824 end;
21825 @end example
21826 @end quotation
21828 where Get_String is a C function that uses the address in Temp to
21829 modify the variable @code{Name}. This code is dubious, and arguably
21830 erroneous, and the compiler would be entitled to assume that
21831 @code{Name} is never modified, and generate code accordingly.
21833 However, in practice, this would cause some existing code that
21834 seems to work with no optimization to start failing at high
21835 levels of optimzization.
21837 What the compiler does for such cases is to assume that marking
21838 a variable as aliased indicates that some "funny business" may
21839 be going on. The optimizer recognizes the aliased keyword and
21840 inhibits optimizations that assume the value cannot be assigned.
21841 This means that the above example will in fact "work" reliably,
21842 that is, it will produce the expected results.
21844 @node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
21845 @anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{1b3}@anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{1b4}
21846 @subsubsection Atomic Variables and Optimization
21849 @geindex Atomic
21851 There are two considerations with regard to performance when
21852 atomic variables are used.
21854 First, the RM only guarantees that access to atomic variables
21855 be atomic, it has nothing to say about how this is achieved,
21856 though there is a strong implication that this should not be
21857 achieved by explicit locking code. Indeed GNAT will never
21858 generate any locking code for atomic variable access (it will
21859 simply reject any attempt to make a variable or type atomic
21860 if the atomic access cannot be achieved without such locking code).
21862 That being said, it is important to understand that you cannot
21863 assume that the entire variable will always be accessed. Consider
21864 this example:
21866 @quotation
21868 @example
21869 type R is record
21870    A,B,C,D : Character;
21871 end record;
21872 for R'Size use 32;
21873 for R'Alignment use 4;
21875 RV : R;
21876 pragma Atomic (RV);
21877 X : Character;
21879 X := RV.B;
21880 @end example
21881 @end quotation
21883 You cannot assume that the reference to @code{RV.B}
21884 will read the entire 32-bit
21885 variable with a single load instruction. It is perfectly legitimate if
21886 the hardware allows it to do a byte read of just the B field. This read
21887 is still atomic, which is all the RM requires. GNAT can and does take
21888 advantage of this, depending on the architecture and optimization level.
21889 Any assumption to the contrary is non-portable and risky. Even if you
21890 examine the assembly language and see a full 32-bit load, this might
21891 change in a future version of the compiler.
21893 If your application requires that all accesses to @code{RV} in this
21894 example be full 32-bit loads, you need to make a copy for the access
21895 as in:
21897 @quotation
21899 @example
21900 declare
21901    RV_Copy : constant R := RV;
21902 begin
21903    X := RV_Copy.B;
21904 end;
21905 @end example
21906 @end quotation
21908 Now the reference to RV must read the whole variable.
21909 Actually one can imagine some compiler which figures
21910 out that the whole copy is not required (because only
21911 the B field is actually accessed), but GNAT
21912 certainly won't do that, and we don't know of any
21913 compiler that would not handle this right, and the
21914 above code will in practice work portably across
21915 all architectures (that permit the Atomic declaration).
21917 The second issue with atomic variables has to do with
21918 the possible requirement of generating synchronization
21919 code. For more details on this, consult the sections on
21920 the pragmas Enable/Disable_Atomic_Synchronization in the
21921 GNAT Reference Manual. If performance is critical, and
21922 such synchronization code is not required, it may be
21923 useful to disable it.
21925 @node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
21926 @anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{1b5}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{1b6}
21927 @subsubsection Passive Task Optimization
21930 @geindex Passive Task
21932 A passive task is one which is sufficiently simple that
21933 in theory a compiler could recognize it an implement it
21934 efficiently without creating a new thread. The original design
21935 of Ada 83 had in mind this kind of passive task optimization, but
21936 only a few Ada 83 compilers attempted it. The problem was that
21937 it was difficult to determine the exact conditions under which
21938 the optimization was possible. The result is a very fragile
21939 optimization where a very minor change in the program can
21940 suddenly silently make a task non-optimizable.
21942 With the revisiting of this issue in Ada 95, there was general
21943 agreement that this approach was fundamentally flawed, and the
21944 notion of protected types was introduced. When using protected
21945 types, the restrictions are well defined, and you KNOW that the
21946 operations will be optimized, and furthermore this optimized
21947 performance is fully portable.
21949 Although it would theoretically be possible for GNAT to attempt to
21950 do this optimization, but it really doesn't make sense in the
21951 context of Ada 95, and none of the Ada 95 compilers implement
21952 this optimization as far as we know. In particular GNAT never
21953 attempts to perform this optimization.
21955 In any new Ada 95 code that is written, you should always
21956 use protected types in place of tasks that might be able to
21957 be optimized in this manner.
21958 Of course this does not help if you have legacy Ada 83 code
21959 that depends on this optimization, but it is unusual to encounter
21960 a case where the performance gains from this optimization
21961 are significant.
21963 Your program should work correctly without this optimization. If
21964 you have performance problems, then the most practical
21965 approach is to figure out exactly where these performance problems
21966 arise, and update those particular tasks to be protected types. Note
21967 that typically clients of the tasks who call entries, will not have
21968 to be modified, only the task definition itself.
21970 @node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
21971 @anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{1b7}@anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{1b8}
21972 @subsection @code{Text_IO} Suggestions
21975 @geindex Text_IO and performance
21977 The @code{Ada.Text_IO} package has fairly high overheads due in part to
21978 the requirement of maintaining page and line counts. If performance
21979 is critical, a recommendation is to use @code{Stream_IO} instead of
21980 @code{Text_IO} for volume output, since this package has less overhead.
21982 If @code{Text_IO} must be used, note that by default output to the standard
21983 output and standard error files is unbuffered (this provides better
21984 behavior when output statements are used for debugging, or if the
21985 progress of a program is observed by tracking the output, e.g. by
21986 using the Unix @emph{tail -f} command to watch redirected output.
21988 If you are generating large volumes of output with @code{Text_IO} and
21989 performance is an important factor, use a designated file instead
21990 of the standard output file, or change the standard output file to
21991 be buffered using @code{Interfaces.C_Streams.setvbuf}.
21993 @node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
21994 @anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{1b9}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{1ba}
21995 @subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
21998 @geindex Uunused subprogram/data elimination
22000 This section describes how you can eliminate unused subprograms and data from
22001 your executable just by setting options at compilation time.
22003 @menu
22004 * About unused subprogram/data elimination:: 
22005 * Compilation options:: 
22006 * Example of unused subprogram/data elimination:: 
22008 @end menu
22010 @node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
22011 @anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{1bb}@anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{1bc}
22012 @subsubsection About unused subprogram/data elimination
22015 By default, an executable contains all code and data of its composing objects
22016 (directly linked or coming from statically linked libraries), even data or code
22017 never used by this executable.
22019 This feature will allow you to eliminate such unused code from your
22020 executable, making it smaller (in disk and in memory).
22022 This functionality is available on all Linux platforms except for the IA-64
22023 architecture and on all cross platforms using the ELF binary file format.
22024 In both cases GNU binutils version 2.16 or later are required to enable it.
22026 @node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
22027 @anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{1bd}@anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{1be}
22028 @subsubsection Compilation options
22031 The operation of eliminating the unused code and data from the final executable
22032 is directly performed by the linker.
22034 @geindex -ffunction-sections (gcc)
22036 @geindex -fdata-sections (gcc)
22038 In order to do this, it has to work with objects compiled with the
22039 following options:
22040 @code{-ffunction-sections} @code{-fdata-sections}.
22042 These options are usable with C and Ada files.
22043 They will place respectively each
22044 function or data in a separate section in the resulting object file.
22046 Once the objects and static libraries are created with these options, the
22047 linker can perform the dead code elimination. You can do this by setting
22048 the @code{-Wl,--gc-sections} option to gcc command or in the
22049 @code{-largs} section of @code{gnatmake}. This will perform a
22050 garbage collection of code and data never referenced.
22052 If the linker performs a partial link (@code{-r} linker option), then you
22053 will need to provide the entry point using the @code{-e} / @code{--entry}
22054 linker option.
22056 Note that objects compiled without the @code{-ffunction-sections} and
22057 @code{-fdata-sections} options can still be linked with the executable.
22058 However, no dead code elimination will be performed on those objects (they will
22059 be linked as is).
22061 The GNAT static library is now compiled with -ffunction-sections and
22062 -fdata-sections on some platforms. This allows you to eliminate the unused code
22063 and data of the GNAT library from your executable.
22065 @node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
22066 @anchor{gnat_ugn/gnat_and_program_execution id47}@anchor{1bf}@anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{1c0}
22067 @subsubsection Example of unused subprogram/data elimination
22070 Here is a simple example:
22072 @quotation
22074 @example
22075 with Aux;
22077 procedure Test is
22078 begin
22079    Aux.Used (10);
22080 end Test;
22082 package Aux is
22083    Used_Data   : Integer;
22084    Unused_Data : Integer;
22086    procedure Used   (Data : Integer);
22087    procedure Unused (Data : Integer);
22088 end Aux;
22090 package body Aux is
22091    procedure Used (Data : Integer) is
22092    begin
22093       Used_Data := Data;
22094    end Used;
22096    procedure Unused (Data : Integer) is
22097    begin
22098       Unused_Data := Data;
22099    end Unused;
22100 end Aux;
22101 @end example
22102 @end quotation
22104 @code{Unused} and @code{Unused_Data} are never referenced in this code
22105 excerpt, and hence they may be safely removed from the final executable.
22107 @quotation
22109 @example
22110 $ gnatmake test
22112 $ nm test | grep used
22113 020015f0 T aux__unused
22114 02005d88 B aux__unused_data
22115 020015cc T aux__used
22116 02005d84 B aux__used_data
22118 $ gnatmake test -cargs -fdata-sections -ffunction-sections \\
22119      -largs -Wl,--gc-sections
22121 $ nm test | grep used
22122 02005350 T aux__used
22123 0201ffe0 B aux__used_data
22124 @end example
22125 @end quotation
22127 It can be observed that the procedure @code{Unused} and the object
22128 @code{Unused_Data} are removed by the linker when using the
22129 appropriate options.
22131 @geindex Overflow checks
22133 @geindex Checks (overflow)
22136 @node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
22137 @anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{16a}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{27}
22138 @section Overflow Check Handling in GNAT
22141 This section explains how to control the handling of overflow checks.
22143 @menu
22144 * Background:: 
22145 * Management of Overflows in GNAT:: 
22146 * Specifying the Desired Mode:: 
22147 * Default Settings:: 
22148 * Implementation Notes:: 
22150 @end menu
22152 @node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
22153 @anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{1c1}@anchor{gnat_ugn/gnat_and_program_execution background}@anchor{1c2}
22154 @subsection Background
22157 Overflow checks are checks that the compiler may make to ensure
22158 that intermediate results are not out of range. For example:
22160 @quotation
22162 @example
22163 A : Integer;
22165 A := A + 1;
22166 @end example
22167 @end quotation
22169 If @code{A} has the value @code{Integer'Last}, then the addition may cause
22170 overflow since the result is out of range of the type @code{Integer}.
22171 In this case @code{Constraint_Error} will be raised if checks are
22172 enabled.
22174 A trickier situation arises in examples like the following:
22176 @quotation
22178 @example
22179 A, C : Integer;
22181 A := (A + 1) + C;
22182 @end example
22183 @end quotation
22185 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
22186 Now the final result of the expression on the right hand side is
22187 @code{Integer'Last} which is in range, but the question arises whether the
22188 intermediate addition of @code{(A + 1)} raises an overflow error.
22190 The (perhaps surprising) answer is that the Ada language
22191 definition does not answer this question. Instead it leaves
22192 it up to the implementation to do one of two things if overflow
22193 checks are enabled.
22196 @itemize *
22198 @item 
22199 raise an exception (@code{Constraint_Error}), or
22201 @item 
22202 yield the correct mathematical result which is then used in
22203 subsequent operations.
22204 @end itemize
22206 If the compiler chooses the first approach, then the assignment of this
22207 example will indeed raise @code{Constraint_Error} if overflow checking is
22208 enabled, or result in erroneous execution if overflow checks are suppressed.
22210 But if the compiler
22211 chooses the second approach, then it can perform both additions yielding
22212 the correct mathematical result, which is in range, so no exception
22213 will be raised, and the right result is obtained, regardless of whether
22214 overflow checks are suppressed.
22216 Note that in the first example an
22217 exception will be raised in either case, since if the compiler
22218 gives the correct mathematical result for the addition, it will
22219 be out of range of the target type of the assignment, and thus
22220 fails the range check.
22222 This lack of specified behavior in the handling of overflow for
22223 intermediate results is a source of non-portability, and can thus
22224 be problematic when programs are ported. Most typically this arises
22225 in a situation where the original compiler did not raise an exception,
22226 and then the application is moved to a compiler where the check is
22227 performed on the intermediate result and an unexpected exception is
22228 raised.
22230 Furthermore, when using Ada 2012's preconditions and other
22231 assertion forms, another issue arises. Consider:
22233 @quotation
22235 @example
22236 procedure P (A, B : Integer) with
22237   Pre => A + B <= Integer'Last;
22238 @end example
22239 @end quotation
22241 One often wants to regard arithmetic in a context like this from
22242 a mathematical point of view. So for example, if the two actual parameters
22243 for a call to @code{P} are both @code{Integer'Last}, then
22244 the precondition should be regarded as False. If we are executing
22245 in a mode with run-time checks enabled for preconditions, then we would
22246 like this precondition to fail, rather than raising an exception
22247 because of the intermediate overflow.
22249 However, the language definition leaves the specification of
22250 whether the above condition fails (raising @code{Assert_Error}) or
22251 causes an intermediate overflow (raising @code{Constraint_Error})
22252 up to the implementation.
22254 The situation is worse in a case such as the following:
22256 @quotation
22258 @example
22259 procedure Q (A, B, C : Integer) with
22260   Pre => A + B + C <= Integer'Last;
22261 @end example
22262 @end quotation
22264 Consider the call
22266 @quotation
22268 @example
22269 Q (A => Integer'Last, B => 1, C => -1);
22270 @end example
22271 @end quotation
22273 From a mathematical point of view the precondition
22274 is True, but at run time we may (but are not guaranteed to) get an
22275 exception raised because of the intermediate overflow (and we really
22276 would prefer this precondition to be considered True at run time).
22278 @node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
22279 @anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{1c3}@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{1c4}
22280 @subsection Management of Overflows in GNAT
22283 To deal with the portability issue, and with the problem of
22284 mathematical versus run-time interpretation of the expressions in
22285 assertions, GNAT provides comprehensive control over the handling
22286 of intermediate overflow. GNAT can operate in three modes, and
22287 furthemore, permits separate selection of operating modes for
22288 the expressions within assertions (here the term 'assertions'
22289 is used in the technical sense, which includes preconditions and so forth)
22290 and for expressions appearing outside assertions.
22292 The three modes are:
22295 @itemize *
22297 @item 
22298 @emph{Use base type for intermediate operations} (@code{STRICT})
22300 In this mode, all intermediate results for predefined arithmetic
22301 operators are computed using the base type, and the result must
22302 be in range of the base type. If this is not the
22303 case then either an exception is raised (if overflow checks are
22304 enabled) or the execution is erroneous (if overflow checks are suppressed).
22305 This is the normal default mode.
22307 @item 
22308 @emph{Most intermediate overflows avoided} (@code{MINIMIZED})
22310 In this mode, the compiler attempts to avoid intermediate overflows by
22311 using a larger integer type, typically @code{Long_Long_Integer},
22312 as the type in which arithmetic is
22313 performed for predefined arithmetic operators. This may be slightly more
22314 expensive at
22315 run time (compared to suppressing intermediate overflow checks), though
22316 the cost is negligible on modern 64-bit machines. For the examples given
22317 earlier, no intermediate overflows would have resulted in exceptions,
22318 since the intermediate results are all in the range of
22319 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
22320 of GNAT). In addition, if checks are enabled, this reduces the number of
22321 checks that must be made, so this choice may actually result in an
22322 improvement in space and time behavior.
22324 However, there are cases where @code{Long_Long_Integer} is not large
22325 enough, consider the following example:
22327 @quotation
22329 @example
22330 procedure R (A, B, C, D : Integer) with
22331   Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
22332 @end example
22333 @end quotation
22335 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
22336 Now the intermediate results are
22337 out of the range of @code{Long_Long_Integer} even though the final result
22338 is in range and the precondition is True (from a mathematical point
22339 of view). In such a case, operating in this mode, an overflow occurs
22340 for the intermediate computation (which is why this mode
22341 says @emph{most} intermediate overflows are avoided). In this case,
22342 an exception is raised if overflow checks are enabled, and the
22343 execution is erroneous if overflow checks are suppressed.
22345 @item 
22346 @emph{All intermediate overflows avoided} (@code{ELIMINATED})
22348 In this mode, the compiler  avoids all intermediate overflows
22349 by using arbitrary precision arithmetic as required. In this
22350 mode, the above example with @code{A**2 * B**2} would
22351 not cause intermediate overflow, because the intermediate result
22352 would be evaluated using sufficient precision, and the result
22353 of evaluating the precondition would be True.
22355 This mode has the advantage of avoiding any intermediate
22356 overflows, but at the expense of significant run-time overhead,
22357 including the use of a library (included automatically in this
22358 mode) for multiple-precision arithmetic.
22360 This mode provides cleaner semantics for assertions, since now
22361 the run-time behavior emulates true arithmetic behavior for the
22362 predefined arithmetic operators, meaning that there is never a
22363 conflict between the mathematical view of the assertion, and its
22364 run-time behavior.
22366 Note that in this mode, the behavior is unaffected by whether or
22367 not overflow checks are suppressed, since overflow does not occur.
22368 It is possible for gigantic intermediate expressions to raise
22369 @code{Storage_Error} as a result of attempting to compute the
22370 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
22371 but overflow is impossible.
22372 @end itemize
22374 Note that these modes apply only to the evaluation of predefined
22375 arithmetic, membership, and comparison operators for signed integer
22376 arithmetic.
22378 For fixed-point arithmetic, checks can be suppressed. But if checks
22379 are enabled
22380 then fixed-point values are always checked for overflow against the
22381 base type for intermediate expressions (that is such checks always
22382 operate in the equivalent of @code{STRICT} mode).
22384 For floating-point, on nearly all architectures, @code{Machine_Overflows}
22385 is False, and IEEE infinities are generated, so overflow exceptions
22386 are never raised. If you want to avoid infinities, and check that
22387 final results of expressions are in range, then you can declare a
22388 constrained floating-point type, and range checks will be carried
22389 out in the normal manner (with infinite values always failing all
22390 range checks).
22392 @node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
22393 @anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{f8}@anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{1c5}
22394 @subsection Specifying the Desired Mode
22397 @geindex pragma Overflow_Mode
22399 The desired mode of for handling intermediate overflow can be specified using
22400 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
22401 The pragma has the form
22403 @quotation
22405 @example
22406 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
22407 @end example
22408 @end quotation
22410 where @code{MODE} is one of
22413 @itemize *
22415 @item 
22416 @code{STRICT}:  intermediate overflows checked (using base type)
22418 @item 
22419 @code{MINIMIZED}: minimize intermediate overflows
22421 @item 
22422 @code{ELIMINATED}: eliminate intermediate overflows
22423 @end itemize
22425 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
22426 @code{minimized} all have the same effect.
22428 If only the @code{General} parameter is present, then the given @code{MODE} applies
22429 to expressions both within and outside assertions. If both arguments
22430 are present, then @code{General} applies to expressions outside assertions,
22431 and @code{Assertions} applies to expressions within assertions. For example:
22433 @quotation
22435 @example
22436 pragma Overflow_Mode
22437   (General => Minimized, Assertions => Eliminated);
22438 @end example
22439 @end quotation
22441 specifies that general expressions outside assertions be evaluated
22442 in 'minimize intermediate overflows' mode, and expressions within
22443 assertions be evaluated in 'eliminate intermediate overflows' mode.
22444 This is often a reasonable choice, avoiding excessive overhead
22445 outside assertions, but assuring a high degree of portability
22446 when importing code from another compiler, while incurring
22447 the extra overhead for assertion expressions to ensure that
22448 the behavior at run time matches the expected mathematical
22449 behavior.
22451 The @code{Overflow_Mode} pragma has the same scoping and placement
22452 rules as pragma @code{Suppress}, so it can occur either as a
22453 configuration pragma, specifying a default for the whole
22454 program, or in a declarative scope, where it applies to the
22455 remaining declarations and statements in that scope.
22457 Note that pragma @code{Overflow_Mode} does not affect whether
22458 overflow checks are enabled or suppressed. It only controls the
22459 method used to compute intermediate values. To control whether
22460 overflow checking is enabled or suppressed, use pragma @code{Suppress}
22461 or @code{Unsuppress} in the usual manner.
22463 @geindex -gnato? (gcc)
22465 @geindex -gnato?? (gcc)
22467 Additionally, a compiler switch @code{-gnato?} or @code{-gnato??}
22468 can be used to control the checking mode default (which can be subsequently
22469 overridden using pragmas).
22471 Here @code{?} is one of the digits @code{1} through @code{3}:
22473 @quotation
22476 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
22477 @item
22479 @code{1}
22481 @tab
22483 use base type for intermediate operations (@code{STRICT})
22485 @item
22487 @code{2}
22489 @tab
22491 minimize intermediate overflows (@code{MINIMIZED})
22493 @item
22495 @code{3}
22497 @tab
22499 eliminate intermediate overflows (@code{ELIMINATED})
22501 @end multitable
22503 @end quotation
22505 As with the pragma, if only one digit appears then it applies to all
22506 cases; if two digits are given, then the first applies outside
22507 assertions, and the second within assertions. Thus the equivalent
22508 of the example pragma above would be
22509 @code{-gnato23}.
22511 If no digits follow the @code{-gnato}, then it is equivalent to
22512 @code{-gnato11},
22513 causing all intermediate operations to be computed using the base
22514 type (@code{STRICT} mode).
22516 @node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
22517 @anchor{gnat_ugn/gnat_and_program_execution id59}@anchor{1c6}@anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{1c7}
22518 @subsection Default Settings
22521 The default mode for overflow checks is
22523 @quotation
22525 @example
22526 General => Strict
22527 @end example
22528 @end quotation
22530 which causes all computations both inside and outside assertions to use
22531 the base type.
22533 This retains compatibility with previous versions of
22534 GNAT which suppressed overflow checks by default and always
22535 used the base type for computation of intermediate results.
22537 @c Sphinx allows no emphasis within :index: role. As a workaround we
22538 @c point the index to "switch" and use emphasis for "-gnato".
22540 The 
22541 @geindex -gnato (gcc)
22542 switch @code{-gnato} (with no digits following)
22543 is equivalent to
22545 @quotation
22547 @example
22548 General => Strict
22549 @end example
22550 @end quotation
22552 which causes overflow checking of all intermediate overflows
22553 both inside and outside assertions against the base type.
22555 The pragma @code{Suppress (Overflow_Check)} disables overflow
22556 checking, but it has no effect on the method used for computing
22557 intermediate results.
22559 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
22560 checking, but it has no effect on the method used for computing
22561 intermediate results.
22563 @node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
22564 @anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{1c8}@anchor{gnat_ugn/gnat_and_program_execution id60}@anchor{1c9}
22565 @subsection Implementation Notes
22568 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
22569 reasonably efficient, and can be generally used. It also helps
22570 to ensure compatibility with code imported from some other
22571 compiler to GNAT.
22573 Setting all intermediate overflows checking (@code{CHECKED} mode)
22574 makes sense if you want to
22575 make sure that your code is compatible with any other possible
22576 Ada implementation. This may be useful in ensuring portability
22577 for code that is to be exported to some other compiler than GNAT.
22579 The Ada standard allows the reassociation of expressions at
22580 the same precedence level if no parentheses are present. For
22581 example, @code{A+B+C} parses as though it were @code{(A+B)+C}, but
22582 the compiler can reintepret this as @code{A+(B+C)}, possibly
22583 introducing or eliminating an overflow exception. The GNAT
22584 compiler never takes advantage of this freedom, and the
22585 expression @code{A+B+C} will be evaluated as @code{(A+B)+C}.
22586 If you need the other order, you can write the parentheses
22587 explicitly @code{A+(B+C)} and GNAT will respect this order.
22589 The use of @code{ELIMINATED} mode will cause the compiler to
22590 automatically include an appropriate arbitrary precision
22591 integer arithmetic package. The compiler will make calls
22592 to this package, though only in cases where it cannot be
22593 sure that @code{Long_Long_Integer} is sufficient to guard against
22594 intermediate overflows. This package does not use dynamic
22595 alllocation, but it does use the secondary stack, so an
22596 appropriate secondary stack package must be present (this
22597 is always true for standard full Ada, but may require
22598 specific steps for restricted run times such as ZFP).
22600 Although @code{ELIMINATED} mode causes expressions to use arbitrary
22601 precision arithmetic, avoiding overflow, the final result
22602 must be in an appropriate range. This is true even if the
22603 final result is of type @code{[Long_[Long_]]Integer'Base}, which
22604 still has the same bounds as its associated constrained
22605 type at run-time.
22607 Currently, the @code{ELIMINATED} mode is only available on target
22608 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
22609 platforms).
22611 @node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
22612 @anchor{gnat_ugn/gnat_and_program_execution id61}@anchor{16b}@anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{28}
22613 @section Performing Dimensionality Analysis in GNAT
22616 @geindex Dimensionality analysis
22618 The GNAT compiler supports dimensionality checking. The user can
22619 specify physical units for objects, and the compiler will verify that uses
22620 of these objects are compatible with their dimensions, in a fashion that is
22621 familiar to engineering practice. The dimensions of algebraic expressions
22622 (including powers with static exponents) are computed from their constituents.
22624 @geindex Dimension_System aspect
22626 @geindex Dimension aspect
22628 This feature depends on Ada 2012 aspect specifications, and is available from
22629 version 7.0.1 of GNAT onwards.
22630 The GNAT-specific aspect @code{Dimension_System}
22631 allows you to define a system of units; the aspect @code{Dimension}
22632 then allows the user to declare dimensioned quantities within a given system.
22633 (These aspects are described in the @emph{Implementation Defined Aspects}
22634 chapter of the @emph{GNAT Reference Manual}).
22636 The major advantage of this model is that it does not require the declaration of
22637 multiple operators for all possible combinations of types: it is only necessary
22638 to use the proper subtypes in object declarations.
22640 @geindex System.Dim.Mks package (GNAT library)
22642 @geindex MKS_Type type
22644 The simplest way to impose dimensionality checking on a computation is to make
22645 use of the package @code{System.Dim.Mks},
22646 which is part of the GNAT library. This
22647 package defines a floating-point type @code{MKS_Type},
22648 for which a sequence of
22649 dimension names are specified, together with their conventional abbreviations.
22650 The following should be read together with the full specification of the
22651 package, in file @code{s-dimmks.ads}.
22653 @quotation
22655 @geindex s-dimmks.ads file
22657 @example
22658 type Mks_Type is new Long_Long_Float
22659   with
22660    Dimension_System => (
22661      (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
22662      (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
22663      (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
22664      (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
22665      (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
22666      (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
22667      (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
22668 @end example
22669 @end quotation
22671 The package then defines a series of subtypes that correspond to these
22672 conventional units. For example:
22674 @quotation
22676 @example
22677 subtype Length is Mks_Type
22678   with
22679    Dimension => (Symbol => 'm', Meter  => 1, others => 0);
22680 @end example
22681 @end quotation
22683 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
22684 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
22685 @code{Luminous_Intensity} (the standard set of units of the SI system).
22687 The package also defines conventional names for values of each unit, for
22688 example:
22690 @quotation
22692 @example
22693 m   : constant Length           := 1.0;
22694 kg  : constant Mass             := 1.0;
22695 s   : constant Time             := 1.0;
22696 A   : constant Electric_Current := 1.0;
22697 @end example
22698 @end quotation
22700 as well as useful multiples of these units:
22702 @quotation
22704 @example
22705  cm  : constant Length := 1.0E-02;
22706  g   : constant Mass   := 1.0E-03;
22707  min : constant Time   := 60.0;
22708  day : constant Time   := 60.0 * 24.0 * min;
22710 @end example
22711 @end quotation
22713 Using this package, you can then define a derived unit by
22714 providing the aspect that
22715 specifies its dimensions within the MKS system, as well as the string to
22716 be used for output of a value of that unit:
22718 @quotation
22720 @example
22721 subtype Acceleration is Mks_Type
22722   with Dimension => ("m/sec^2",
22723                      Meter => 1,
22724                      Second => -2,
22725                      others => 0);
22726 @end example
22727 @end quotation
22729 Here is a complete example of use:
22731 @quotation
22733 @example
22734 with System.Dim.MKS; use System.Dim.Mks;
22735 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
22736 with Text_IO; use Text_IO;
22737 procedure Free_Fall is
22738   subtype Acceleration is Mks_Type
22739     with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
22740   G : constant acceleration := 9.81 * m / (s ** 2);
22741   T : Time := 10.0*s;
22742   Distance : Length;
22744 begin
22745   Put ("Gravitational constant: ");
22746   Put (G, Aft => 2, Exp => 0); Put_Line ("");
22747   Distance := 0.5 * G * T ** 2;
22748   Put ("distance travelled in 10 seconds of free fall ");
22749   Put (Distance, Aft => 2, Exp => 0);
22750   Put_Line ("");
22751 end Free_Fall;
22752 @end example
22753 @end quotation
22755 Execution of this program yields:
22757 @quotation
22759 @example
22760 Gravitational constant:  9.81 m/sec^2
22761 distance travelled in 10 seconds of free fall 490.50 m
22762 @end example
22763 @end quotation
22765 However, incorrect assignments such as:
22767 @quotation
22769 @example
22770 Distance := 5.0;
22771 Distance := 5.0 * kg;
22772 @end example
22773 @end quotation
22775 are rejected with the following diagnoses:
22777 @quotation
22779 @example
22780 Distance := 5.0;
22781    >>> dimensions mismatch in assignment
22782    >>> left-hand side has dimension [L]
22783    >>> right-hand side is dimensionless
22785 Distance := 5.0 * kg:
22786    >>> dimensions mismatch in assignment
22787    >>> left-hand side has dimension [L]
22788    >>> right-hand side has dimension [M]
22789 @end example
22790 @end quotation
22792 The dimensions of an expression are properly displayed, even if there is
22793 no explicit subtype for it. If we add to the program:
22795 @quotation
22797 @example
22798 Put ("Final velocity: ");
22799 Put (G * T, Aft =>2, Exp =>0);
22800 Put_Line ("");
22801 @end example
22802 @end quotation
22804 then the output includes:
22806 @quotation
22808 @example
22809 Final velocity: 98.10 m.s**(-1)
22810 @end example
22812 @geindex Dimensionable type
22814 @geindex Dimensioned subtype
22815 @end quotation
22817 The type @code{Mks_Type} is said to be a @emph{dimensionable type} since it has a
22818 @code{Dimension_System} aspect, and the subtypes @code{Length}, @code{Mass}, etc.,
22819 are said to be @emph{dimensioned subtypes} since each one has a @code{Dimension}
22820 aspect.
22822 @quotation
22824 @geindex Dimension Vector (for a dimensioned subtype)
22826 @geindex Dimension aspect
22828 @geindex Dimension_System aspect
22829 @end quotation
22831 The @code{Dimension} aspect of a dimensioned subtype @code{S} defines a mapping
22832 from the base type's Unit_Names to integer (or, more generally, rational)
22833 values. This mapping is the @emph{dimension vector} (also referred to as the
22834 @emph{dimensionality}) for that subtype, denoted by @code{DV(S)}, and thus for each
22835 object of that subtype. Intuitively, the value specified for each
22836 @code{Unit_Name} is the exponent associated with that unit; a zero value
22837 means that the unit is not used. For example:
22839 @quotation
22841 @example
22842 declare
22843    Acc : Acceleration;
22844    ...
22845 begin
22846    ...
22847 end;
22848 @end example
22849 @end quotation
22851 Here @code{DV(Acc)} = @code{DV(Acceleration)} =
22852 @code{(Meter=>1, Kilogram=>0, Second=>-2, Ampere=>0, Kelvin=>0, Mole=>0, Candela=>0)}.
22853 Symbolically, we can express this as @code{Meter / Second**2}.
22855 The dimension vector of an arithmetic expression is synthesized from the
22856 dimension vectors of its components, with compile-time dimensionality checks
22857 that help prevent mismatches such as using an @code{Acceleration} where a
22858 @code{Length} is required.
22860 The dimension vector of the result of an arithmetic expression @emph{expr}, or
22861 @code{DV(@emph{expr})}, is defined as follows, assuming conventional
22862 mathematical definitions for the vector operations that are used:
22865 @itemize *
22867 @item 
22868 If @emph{expr} is of the type @emph{universal_real}, or is not of a dimensioned subtype,
22869 then @emph{expr} is dimensionless; @code{DV(@emph{expr})} is the empty vector.
22871 @item 
22872 @code{DV(@emph{op expr})}, where @emph{op} is a unary operator, is @code{DV(@emph{expr})}
22874 @item 
22875 @code{DV(@emph{expr1 op expr2})} where @emph{op} is "+" or "-" is @code{DV(@emph{expr1})}
22876 provided that @code{DV(@emph{expr1})} = @code{DV(@emph{expr2})}.
22877 If this condition is not met then the construct is illegal.
22879 @item 
22880 @code{DV(@emph{expr1} * @emph{expr2})} is @code{DV(@emph{expr1})} + @code{DV(@emph{expr2})},
22881 and @code{DV(@emph{expr1} / @emph{expr2})} = @code{DV(@emph{expr1})} - @code{DV(@emph{expr2})}.
22882 In this context if one of the @emph{expr}s is dimensionless then its empty
22883 dimension vector is treated as @code{(others => 0)}.
22885 @item 
22886 @code{DV(@emph{expr} ** @emph{power})} is @emph{power} * @code{DV(@emph{expr})},
22887 provided that @emph{power} is a static rational value. If this condition is not
22888 met then the construct is illegal.
22889 @end itemize
22891 Note that, by the above rules, it is illegal to use binary "+" or "-" to
22892 combine a dimensioned and dimensionless value.  Thus an expression such as
22893 @code{acc-10.0} is illegal, where @code{acc} is an object of subtype
22894 @code{Acceleration}.
22896 The dimensionality checks for relationals use the same rules as
22897 for "+" and "-", except when comparing to a literal; thus
22899 @quotation
22901 @example
22902 acc > len
22903 @end example
22904 @end quotation
22906 is equivalent to
22908 @quotation
22910 @example
22911 acc-len > 0.0
22912 @end example
22913 @end quotation
22915 and is thus illegal, but
22917 @quotation
22919 @example
22920 acc > 10.0
22921 @end example
22922 @end quotation
22924 is accepted with a warning. Analogously a conditional expression requires the
22925 same dimension vector for each branch (with no exception for literals).
22927 The dimension vector of a type conversion @code{T(@emph{expr})} is defined
22928 as follows, based on the nature of @code{T}:
22931 @itemize *
22933 @item 
22934 If @code{T} is a dimensioned subtype then @code{DV(T(@emph{expr}))} is @code{DV(T)}
22935 provided that either @emph{expr} is dimensionless or
22936 @code{DV(T)} = @code{DV(@emph{expr})}. The conversion is illegal
22937 if @emph{expr} is dimensioned and @code{DV(@emph{expr})} /= @code{DV(T)}.
22938 Note that vector equality does not require that the corresponding
22939 Unit_Names be the same.
22941 As a consequence of the above rule, it is possible to convert between
22942 different dimension systems that follow the same international system
22943 of units, with the seven physical components given in the standard order
22944 (length, mass, time, etc.). Thus a length in meters can be converted to
22945 a length in inches (with a suitable conversion factor) but cannot be
22946 converted, for example, to a mass in pounds.
22948 @item 
22949 If @code{T} is the base type for @emph{expr} (and the dimensionless root type of
22950 the dimension system), then @code{DV(T(@emph{expr}))} is @code{DV(expr)}.
22951 Thus, if @emph{expr} is of a dimensioned subtype of @code{T}, the conversion may
22952 be regarded as a "view conversion" that preserves dimensionality.
22954 This rule makes it possible to write generic code that can be instantiated
22955 with compatible dimensioned subtypes.  The generic unit will contain
22956 conversions that will consequently be present in instantiations, but
22957 conversions to the base type will preserve dimensionality and make it
22958 possible to write generic code that is correct with respect to
22959 dimensionality.
22961 @item 
22962 Otherwise (i.e., @code{T} is neither a dimensioned subtype nor a dimensionable
22963 base type), @code{DV(T(@emph{expr}))} is the empty vector. Thus a dimensioned
22964 value can be explicitly converted to a non-dimensioned subtype, which
22965 of course then escapes dimensionality analysis.
22966 @end itemize
22968 The dimension vector for a type qualification @code{T'(@emph{expr})} is the same
22969 as for the type conversion @code{T(@emph{expr})}.
22971 An assignment statement
22973 @quotation
22975 @example
22976 Source := Target;
22977 @end example
22978 @end quotation
22980 requires @code{DV(Source)} = @code{DV(Target)}, and analogously for parameter
22981 passing (the dimension vector for the actual parameter must be equal to the
22982 dimension vector for the formal parameter).
22984 @node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
22985 @anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{29}@anchor{gnat_ugn/gnat_and_program_execution id62}@anchor{16c}
22986 @section Stack Related Facilities
22989 This section describes some useful tools associated with stack
22990 checking and analysis. In
22991 particular, it deals with dynamic and static stack usage measurements.
22993 @menu
22994 * Stack Overflow Checking:: 
22995 * Static Stack Usage Analysis:: 
22996 * Dynamic Stack Usage Analysis:: 
22998 @end menu
23000 @node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
23001 @anchor{gnat_ugn/gnat_and_program_execution id63}@anchor{1ca}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{f4}
23002 @subsection Stack Overflow Checking
23005 @geindex Stack Overflow Checking
23007 @geindex -fstack-check (gcc)
23009 For most operating systems, @code{gcc} does not perform stack overflow
23010 checking by default. This means that if the main environment task or
23011 some other task exceeds the available stack space, then unpredictable
23012 behavior will occur. Most native systems offer some level of protection by
23013 adding a guard page at the end of each task stack. This mechanism is usually
23014 not enough for dealing properly with stack overflow situations because
23015 a large local variable could "jump" above the guard page.
23016 Furthermore, when the
23017 guard page is hit, there may not be any space left on the stack for executing
23018 the exception propagation code. Enabling stack checking avoids
23019 such situations.
23021 To activate stack checking, compile all units with the @code{gcc} option
23022 @code{-fstack-check}. For example:
23024 @quotation
23026 @example
23027 $ gcc -c -fstack-check package1.adb
23028 @end example
23029 @end quotation
23031 Units compiled with this option will generate extra instructions to check
23032 that any use of the stack (for procedure calls or for declaring local
23033 variables in declare blocks) does not exceed the available stack space.
23034 If the space is exceeded, then a @code{Storage_Error} exception is raised.
23036 For declared tasks, the stack size is controlled by the size
23037 given in an applicable @code{Storage_Size} pragma or by the value specified
23038 at bind time with @code{-d} (@ref{11f,,Switches for gnatbind}) or is set to
23039 the default size as defined in the GNAT runtime otherwise.
23041 @geindex GNAT_STACK_LIMIT
23043 For the environment task, the stack size depends on
23044 system defaults and is unknown to the compiler. Stack checking
23045 may still work correctly if a fixed
23046 size stack is allocated, but this cannot be guaranteed.
23047 To ensure that a clean exception is signalled for stack
23048 overflow, set the environment variable
23049 @geindex GNAT_STACK_LIMIT
23050 @geindex environment variable; GNAT_STACK_LIMIT
23051 @code{GNAT_STACK_LIMIT} to indicate the maximum
23052 stack area that can be used, as in:
23054 @quotation
23056 @example
23057 $ SET GNAT_STACK_LIMIT 1600
23058 @end example
23059 @end quotation
23061 The limit is given in kilobytes, so the above declaration would
23062 set the stack limit of the environment task to 1.6 megabytes.
23063 Note that the only purpose of this usage is to limit the amount
23064 of stack used by the environment task. If it is necessary to
23065 increase the amount of stack for the environment task, then this
23066 is an operating systems issue, and must be addressed with the
23067 appropriate operating systems commands.
23069 @node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
23070 @anchor{gnat_ugn/gnat_and_program_execution id64}@anchor{1cb}@anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{f5}
23071 @subsection Static Stack Usage Analysis
23074 @geindex Static Stack Usage Analysis
23076 @geindex -fstack-usage
23078 A unit compiled with @code{-fstack-usage} will generate an extra file
23079 that specifies
23080 the maximum amount of stack used, on a per-function basis.
23081 The file has the same
23082 basename as the target object file with a @code{.su} extension.
23083 Each line of this file is made up of three fields:
23086 @itemize *
23088 @item 
23089 The name of the function.
23091 @item 
23092 A number of bytes.
23094 @item 
23095 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
23096 @end itemize
23098 The second field corresponds to the size of the known part of the function
23099 frame.
23101 The qualifier @code{static} means that the function frame size
23102 is purely static.
23103 It usually means that all local variables have a static size.
23104 In this case, the second field is a reliable measure of the function stack
23105 utilization.
23107 The qualifier @code{dynamic} means that the function frame size is not static.
23108 It happens mainly when some local variables have a dynamic size. When this
23109 qualifier appears alone, the second field is not a reliable measure
23110 of the function stack analysis. When it is qualified with  @code{bounded}, it
23111 means that the second field is a reliable maximum of the function stack
23112 utilization.
23114 A unit compiled with @code{-Wstack-usage} will issue a warning for each
23115 subprogram whose stack usage might be larger than the specified amount of
23116 bytes.  The wording is in keeping with the qualifier documented above.
23118 @node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
23119 @anchor{gnat_ugn/gnat_and_program_execution id65}@anchor{1cc}@anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{121}
23120 @subsection Dynamic Stack Usage Analysis
23123 It is possible to measure the maximum amount of stack used by a task, by
23124 adding a switch to @code{gnatbind}, as:
23126 @quotation
23128 @example
23129 $ gnatbind -u0 file
23130 @end example
23131 @end quotation
23133 With this option, at each task termination, its stack usage is  output on
23134 @code{stderr}.
23135 It is not always convenient to output the stack usage when the program
23136 is still running. Hence, it is possible to delay this output until program
23137 termination. for a given number of tasks specified as the argument of the
23138 @code{-u} option. For instance:
23140 @quotation
23142 @example
23143 $ gnatbind -u100 file
23144 @end example
23145 @end quotation
23147 will buffer the stack usage information of the first 100 tasks to terminate and
23148 output this info at program termination. Results are displayed in four
23149 columns:
23151 @quotation
23153 @example
23154 Index | Task Name | Stack Size | Stack Usage
23155 @end example
23156 @end quotation
23158 where:
23161 @itemize *
23163 @item 
23164 @emph{Index} is a number associated with each task.
23166 @item 
23167 @emph{Task Name} is the name of the task analyzed.
23169 @item 
23170 @emph{Stack Size} is the maximum size for the stack.
23172 @item 
23173 @emph{Stack Usage} is the measure done by the stack analyzer.
23174 In order to prevent overflow, the stack
23175 is not entirely analyzed, and it's not possible to know exactly how
23176 much has actually been used.
23177 @end itemize
23179 The environment task stack, e.g., the stack that contains the main unit, is
23180 only processed when the environment variable GNAT_STACK_LIMIT is set.
23182 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
23183 stack usage reports at run-time. See its body for the details.
23185 @node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
23186 @anchor{gnat_ugn/gnat_and_program_execution id66}@anchor{16d}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{2a}
23187 @section Memory Management Issues
23190 This section describes some useful memory pools provided in the GNAT library
23191 and in particular the GNAT Debug Pool facility, which can be used to detect
23192 incorrect uses of access values (including 'dangling references').
23195 @menu
23196 * Some Useful Memory Pools:: 
23197 * The GNAT Debug Pool Facility:: 
23199 @end menu
23201 @node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
23202 @anchor{gnat_ugn/gnat_and_program_execution id67}@anchor{1cd}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{1ce}
23203 @subsection Some Useful Memory Pools
23206 @geindex Memory Pool
23208 @geindex storage
23209 @geindex pool
23211 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
23212 storage pool. Allocations use the standard system call @code{malloc} while
23213 deallocations use the standard system call @code{free}. No reclamation is
23214 performed when the pool goes out of scope. For performance reasons, the
23215 standard default Ada allocators/deallocators do not use any explicit storage
23216 pools but if they did, they could use this storage pool without any change in
23217 behavior. That is why this storage pool is used  when the user
23218 manages to make the default implicit allocator explicit as in this example:
23220 @quotation
23222 @example
23223 type T1 is access Something;
23224  -- no Storage pool is defined for T2
23226 type T2 is access Something_Else;
23227 for T2'Storage_Pool use T1'Storage_Pool;
23228 -- the above is equivalent to
23229 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
23230 @end example
23231 @end quotation
23233 The @code{System.Pool_Local} package offers the @code{Unbounded_Reclaim_Pool} storage
23234 pool. The allocation strategy is similar to @code{Pool_Local}
23235 except that the all
23236 storage allocated with this pool is reclaimed when the pool object goes out of
23237 scope. This pool provides a explicit mechanism similar to the implicit one
23238 provided by several Ada 83 compilers for allocations performed through a local
23239 access type and whose purpose was to reclaim memory when exiting the
23240 scope of a given local access. As an example, the following program does not
23241 leak memory even though it does not perform explicit deallocation:
23243 @quotation
23245 @example
23246 with System.Pool_Local;
23247 procedure Pooloc1 is
23248    procedure Internal is
23249       type A is access Integer;
23250       X : System.Pool_Local.Unbounded_Reclaim_Pool;
23251       for A'Storage_Pool use X;
23252       v : A;
23253    begin
23254       for I in  1 .. 50 loop
23255          v := new Integer;
23256       end loop;
23257    end Internal;
23258 begin
23259    for I in  1 .. 100 loop
23260       Internal;
23261    end loop;
23262 end Pooloc1;
23263 @end example
23264 @end quotation
23266 The @code{System.Pool_Size} package implements the @code{Stack_Bounded_Pool} used when
23267 @code{Storage_Size} is specified for an access type.
23268 The whole storage for the pool is
23269 allocated at once, usually on the stack at the point where the access type is
23270 elaborated. It is automatically reclaimed when exiting the scope where the
23271 access type is defined. This package is not intended to be used directly by the
23272 user and it is implicitly used for each such declaration:
23274 @quotation
23276 @example
23277 type T1 is access Something;
23278 for T1'Storage_Size use 10_000;
23279 @end example
23280 @end quotation
23282 @node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
23283 @anchor{gnat_ugn/gnat_and_program_execution id68}@anchor{1cf}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{1d0}
23284 @subsection The GNAT Debug Pool Facility
23287 @geindex Debug Pool
23289 @geindex storage
23290 @geindex pool
23291 @geindex memory corruption
23293 The use of unchecked deallocation and unchecked conversion can easily
23294 lead to incorrect memory references. The problems generated by such
23295 references are usually difficult to tackle because the symptoms can be
23296 very remote from the origin of the problem. In such cases, it is
23297 very helpful to detect the problem as early as possible. This is the
23298 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
23300 In order to use the GNAT specific debugging pool, the user must
23301 associate a debug pool object with each of the access types that may be
23302 related to suspected memory problems. See Ada Reference Manual 13.11.
23304 @quotation
23306 @example
23307 type Ptr is access Some_Type;
23308 Pool : GNAT.Debug_Pools.Debug_Pool;
23309 for Ptr'Storage_Pool use Pool;
23310 @end example
23311 @end quotation
23313 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
23314 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
23315 allow the user to redefine allocation and deallocation strategies. They
23316 also provide a checkpoint for each dereference, through the use of
23317 the primitive operation @code{Dereference} which is implicitly called at
23318 each dereference of an access value.
23320 Once an access type has been associated with a debug pool, operations on
23321 values of the type may raise four distinct exceptions,
23322 which correspond to four potential kinds of memory corruption:
23325 @itemize *
23327 @item 
23328 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
23330 @item 
23331 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
23333 @item 
23334 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
23336 @item 
23337 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
23338 @end itemize
23340 For types associated with a Debug_Pool, dynamic allocation is performed using
23341 the standard GNAT allocation routine. References to all allocated chunks of
23342 memory are kept in an internal dictionary. Several deallocation strategies are
23343 provided, whereupon the user can choose to release the memory to the system,
23344 keep it allocated for further invalid access checks, or fill it with an easily
23345 recognizable pattern for debug sessions. The memory pattern is the old IBM
23346 hexadecimal convention: @code{16#DEADBEEF#}.
23348 See the documentation in the file g-debpoo.ads for more information on the
23349 various strategies.
23351 Upon each dereference, a check is made that the access value denotes a
23352 properly allocated memory location. Here is a complete example of use of
23353 @code{Debug_Pools}, that includes typical instances of  memory corruption:
23355 @quotation
23357 @example
23358 with Gnat.Io; use Gnat.Io;
23359 with Unchecked_Deallocation;
23360 with Unchecked_Conversion;
23361 with GNAT.Debug_Pools;
23362 with System.Storage_Elements;
23363 with Ada.Exceptions; use Ada.Exceptions;
23364 procedure Debug_Pool_Test is
23366    type T is access Integer;
23367    type U is access all T;
23369    P : GNAT.Debug_Pools.Debug_Pool;
23370    for T'Storage_Pool use P;
23372    procedure Free is new Unchecked_Deallocation (Integer, T);
23373    function UC is new Unchecked_Conversion (U, T);
23374    A, B : aliased T;
23376    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
23378 begin
23379    Info (P);
23380    A := new Integer;
23381    B := new Integer;
23382    B := A;
23383    Info (P);
23384    Free (A);
23385    begin
23386       Put_Line (Integer'Image(B.all));
23387    exception
23388       when E : others => Put_Line ("raised: " & Exception_Name (E));
23389    end;
23390    begin
23391       Free (B);
23392    exception
23393       when E : others => Put_Line ("raised: " & Exception_Name (E));
23394    end;
23395    B := UC(A'Access);
23396    begin
23397       Put_Line (Integer'Image(B.all));
23398    exception
23399       when E : others => Put_Line ("raised: " & Exception_Name (E));
23400    end;
23401    begin
23402       Free (B);
23403    exception
23404       when E : others => Put_Line ("raised: " & Exception_Name (E));
23405    end;
23406    Info (P);
23407 end Debug_Pool_Test;
23408 @end example
23409 @end quotation
23411 The debug pool mechanism provides the following precise diagnostics on the
23412 execution of this erroneous program:
23414 @quotation
23416 @example
23417 Debug Pool info:
23418   Total allocated bytes :  0
23419   Total deallocated bytes :  0
23420   Current Water Mark:  0
23421   High Water Mark:  0
23423 Debug Pool info:
23424   Total allocated bytes :  8
23425   Total deallocated bytes :  0
23426   Current Water Mark:  8
23427   High Water Mark:  8
23429 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
23430 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
23431 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
23432 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
23433 Debug Pool info:
23434   Total allocated bytes :  8
23435   Total deallocated bytes :  4
23436   Current Water Mark:  4
23437   High Water Mark:  8
23438 @end example
23439 @end quotation
23442 @c -- Non-breaking space in running text
23443 @c -- E.g. Ada |nbsp| 95
23445 @node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
23446 @anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{d}@anchor{gnat_ugn/platform_specific_information doc}@anchor{1d1}@anchor{gnat_ugn/platform_specific_information id1}@anchor{1d2}
23447 @chapter Platform-Specific Information
23450 This appendix contains information relating to the implementation
23451 of run-time libraries on various platforms and also covers
23452 topics related to the GNAT implementation on Windows and Mac OS.
23454 @menu
23455 * Run-Time Libraries:: 
23456 * Specifying a Run-Time Library:: 
23457 * GNU/Linux Topics:: 
23458 * Microsoft Windows Topics:: 
23459 * Mac OS Topics:: 
23461 @end menu
23463 @node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
23464 @anchor{gnat_ugn/platform_specific_information id2}@anchor{1d3}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{2b}
23465 @section Run-Time Libraries
23468 @geindex Tasking and threads libraries
23470 @geindex Threads libraries and tasking
23472 @geindex Run-time libraries (platform-specific information)
23474 The GNAT run-time implementation may vary with respect to both the
23475 underlying threads library and the exception-handling scheme.
23476 For threads support, the default run-time will bind to the thread
23477 package of the underlying operating system.
23479 For exception handling, either or both of two models are supplied:
23481 @quotation
23483 @geindex Zero-Cost Exceptions
23485 @geindex ZCX (Zero-Cost Exceptions)
23486 @end quotation
23489 @itemize *
23491 @item 
23492 @strong{Zero-Cost Exceptions} ("ZCX"),
23493 which uses binder-generated tables that
23494 are interrogated at run time to locate a handler.
23496 @geindex setjmp/longjmp Exception Model
23498 @geindex SJLJ (setjmp/longjmp Exception Model)
23500 @item 
23501 @strong{setjmp / longjmp} ('SJLJ'),
23502 which uses dynamically-set data to establish
23503 the set of handlers
23504 @end itemize
23506 Most programs should experience a substantial speed improvement by
23507 being compiled with a ZCX run-time.
23508 This is especially true for
23509 tasking applications or applications with many exception handlers.@}
23511 This section summarizes which combinations of threads and exception support
23512 are supplied on various GNAT platforms.
23513 It then shows how to select a particular library either
23514 permanently or temporarily,
23515 explains the properties of (and tradeoffs among) the various threads
23516 libraries, and provides some additional
23517 information about several specific platforms.
23519 @menu
23520 * Summary of Run-Time Configurations:: 
23522 @end menu
23524 @node Summary of Run-Time Configurations,,,Run-Time Libraries
23525 @anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{1d4}@anchor{gnat_ugn/platform_specific_information id3}@anchor{1d5}
23526 @subsection Summary of Run-Time Configurations
23530 @multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
23531 @headitem
23533 Platform
23535 @tab
23537 Run-Time
23539 @tab
23541 Tasking
23543 @tab
23545 Exceptions
23547 @item
23549 GNU/Linux
23551 @tab
23553 rts-native
23554 (default)
23556 @tab
23558 pthread library
23560 @tab
23564 @item
23566 rts-sjlj
23568 @tab
23570 pthread library
23572 @tab
23574 SJLJ
23576 @item
23578 Windows
23580 @tab
23582 rts-native
23583 (default)
23585 @tab
23587 native Win32 threads
23589 @tab
23593 @item
23595 rts-sjlj
23597 @tab
23599 native Win32 threads
23601 @tab
23603 SJLJ
23605 @item
23607 Mac OS
23609 @tab
23611 rts-native
23613 @tab
23615 pthread library
23617 @tab
23621 @end multitable
23624 @node Specifying a Run-Time Library,GNU/Linux Topics,Run-Time Libraries,Platform-Specific Information
23625 @anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{1d6}@anchor{gnat_ugn/platform_specific_information id4}@anchor{1d7}
23626 @section Specifying a Run-Time Library
23629 The @code{adainclude} subdirectory containing the sources of the GNAT
23630 run-time library, and the @code{adalib} subdirectory containing the
23631 @code{ALI} files and the static and/or shared GNAT library, are located
23632 in the gcc target-dependent area:
23634 @quotation
23636 @example
23637 target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
23638 @end example
23639 @end quotation
23641 As indicated above, on some platforms several run-time libraries are supplied.
23642 These libraries are installed in the target dependent area and
23643 contain a complete source and binary subdirectory. The detailed description
23644 below explains the differences between the different libraries in terms of
23645 their thread support.
23647 The default run-time library (when GNAT is installed) is @emph{rts-native}.
23648 This default run-time is selected by the means of soft links.
23649 For example on x86-linux:
23651 @c --
23652 @c --  $(target-dir)
23653 @c --      |
23654 @c --      +--- adainclude----------+
23655 @c --      |                        |
23656 @c --      +--- adalib-----------+  |
23657 @c --      |                     |  |
23658 @c --      +--- rts-native       |  |
23659 @c --      |    |                |  |
23660 @c --      |    +--- adainclude <---+
23661 @c --      |    |                |
23662 @c --      |    +--- adalib <----+
23663 @c --      |
23664 @c --      +--- rts-sjlj
23665 @c --           |
23666 @c --           +--- adainclude
23667 @c --           |
23668 @c --           +--- adalib
23671 @example
23672                $(target-dir)
23673               __/ /      \ \___
23674       _______/   /        \    \_________________
23675      /          /          \                     \
23676     /          /            \                     \
23677 ADAINCLUDE  ADALIB      rts-native             rts-sjlj
23678    :          :            /    \                 /   \
23679    :          :           /      \               /     \
23680    :          :          /        \             /       \
23681    :          :         /          \           /         \
23682    +-------------> adainclude     adalib   adainclude   adalib
23683               :                     ^
23684               :                     :
23685               +---------------------+
23687               Run-Time Library Directory Structure
23688    (Upper-case names and dotted/dashed arrows represent soft links)
23689 @end example
23691 If the @emph{rts-sjlj} library is to be selected on a permanent basis,
23692 these soft links can be modified with the following commands:
23694 @quotation
23696 @example
23697 $ cd $target
23698 $ rm -f adainclude adalib
23699 $ ln -s rts-sjlj/adainclude adainclude
23700 $ ln -s rts-sjlj/adalib adalib
23701 @end example
23702 @end quotation
23704 Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
23705 @code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
23706 @code{$target/ada_object_path}.
23708 @geindex --RTS option
23710 Selecting another run-time library temporarily can be
23711 achieved by using the @code{--RTS} switch, e.g., @code{--RTS=sjlj}
23712 @anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{1d8}
23713 @geindex SCHED_FIFO scheduling policy
23715 @geindex SCHED_RR scheduling policy
23717 @geindex SCHED_OTHER scheduling policy
23719 @menu
23720 * Choosing the Scheduling Policy:: 
23722 @end menu
23724 @node Choosing the Scheduling Policy,,,Specifying a Run-Time Library
23725 @anchor{gnat_ugn/platform_specific_information id5}@anchor{1d9}
23726 @subsection Choosing the Scheduling Policy
23729 When using a POSIX threads implementation, you have a choice of several
23730 scheduling policies: @code{SCHED_FIFO}, @code{SCHED_RR} and @code{SCHED_OTHER}.
23732 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
23733 or @code{SCHED_RR} requires special (e.g., root) privileges.
23735 @geindex pragma Time_Slice
23737 @geindex -T0 option
23739 @geindex pragma Task_Dispatching_Policy
23741 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
23742 @code{SCHED_FIFO},
23743 you can use one of the following:
23746 @itemize *
23748 @item 
23749 @code{pragma Time_Slice (0.0)}
23751 @item 
23752 the corresponding binder option @code{-T0}
23754 @item 
23755 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23756 @end itemize
23758 To specify @code{SCHED_RR},
23759 you should use @code{pragma Time_Slice} with a
23760 value greater than 0.0, or else use the corresponding @code{-T}
23761 binder option.
23763 To make sure a program is running as root, you can put something like
23764 this in a library package body in your application:
23766 @quotation
23768 @example
23769 function geteuid return Integer;
23770 pragma Import (C, geteuid, "geteuid");
23771 Ignore : constant Boolean :=
23772   (if geteuid = 0 then True else raise Program_Error with "must be root");
23773 @end example
23774 @end quotation
23776 It gets the effective user id, and if it's not 0 (i.e. root), it raises
23777 Program_Error.
23779 @geindex Linux
23781 @geindex GNU/Linux
23783 @node GNU/Linux Topics,Microsoft Windows Topics,Specifying a Run-Time Library,Platform-Specific Information
23784 @anchor{gnat_ugn/platform_specific_information id6}@anchor{1da}@anchor{gnat_ugn/platform_specific_information gnu-linux-topics}@anchor{1db}
23785 @section GNU/Linux Topics
23788 This section describes topics that are specific to GNU/Linux platforms.
23790 @menu
23791 * Required Packages on GNU/Linux;: Required Packages on GNU/Linux. 
23793 @end menu
23795 @node Required Packages on GNU/Linux,,,GNU/Linux Topics
23796 @anchor{gnat_ugn/platform_specific_information id7}@anchor{1dc}@anchor{gnat_ugn/platform_specific_information required-packages-on-gnu-linux}@anchor{1dd}
23797 @subsection Required Packages on GNU/Linux:
23800 GNAT requires the C library developer's package to be installed.
23801 The name of of that package depends on your GNU/Linux distribution:
23804 @itemize *
23806 @item 
23807 RedHat, SUSE: @code{glibc-devel};
23809 @item 
23810 Debian, Ubuntu: @code{libc6-dev} (normally installed by default).
23811 @end itemize
23813 If using the 32-bit version of GNAT on a 64-bit version of GNU/Linux,
23814 you'll need the 32-bit version of that package instead:
23817 @itemize *
23819 @item 
23820 RedHat, SUSE: @code{glibc-devel.i686};
23822 @item 
23823 Debian, Ubuntu: @code{libc6-dev:i386}.
23824 @end itemize
23826 Other GNU/Linux distributions might be choosing a different name
23827 for that package.
23829 @geindex Windows
23831 @node Microsoft Windows Topics,Mac OS Topics,GNU/Linux Topics,Platform-Specific Information
23832 @anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{2c}@anchor{gnat_ugn/platform_specific_information id8}@anchor{1de}
23833 @section Microsoft Windows Topics
23836 This section describes topics that are specific to the Microsoft Windows
23837 platforms.
23843 @menu
23844 * Using GNAT on Windows:: 
23845 * Using a network installation of GNAT:: 
23846 * CONSOLE and WINDOWS subsystems:: 
23847 * Temporary Files:: 
23848 * Disabling Command Line Argument Expansion:: 
23849 * Mixed-Language Programming on Windows:: 
23850 * Windows Specific Add-Ons:: 
23852 @end menu
23854 @node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
23855 @anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{1df}@anchor{gnat_ugn/platform_specific_information id9}@anchor{1e0}
23856 @subsection Using GNAT on Windows
23859 One of the strengths of the GNAT technology is that its tool set
23860 (@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
23861 @code{gdb} debugger, etc.) is used in the same way regardless of the
23862 platform.
23864 On Windows this tool set is complemented by a number of Microsoft-specific
23865 tools that have been provided to facilitate interoperability with Windows
23866 when this is required. With these tools:
23869 @itemize *
23871 @item 
23872 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
23873 subsystems.
23875 @item 
23876 You can use any Dynamically Linked Library (DLL) in your Ada code (both
23877 relocatable and non-relocatable DLLs are supported).
23879 @item 
23880 You can build Ada DLLs for use in other applications. These applications
23881 can be written in a language other than Ada (e.g., C, C++, etc). Again both
23882 relocatable and non-relocatable Ada DLLs are supported.
23884 @item 
23885 You can include Windows resources in your Ada application.
23887 @item 
23888 You can use or create COM/DCOM objects.
23889 @end itemize
23891 Immediately below are listed all known general GNAT-for-Windows restrictions.
23892 Other restrictions about specific features like Windows Resources and DLLs
23893 are listed in separate sections below.
23896 @itemize *
23898 @item 
23899 It is not possible to use @code{GetLastError} and @code{SetLastError}
23900 when tasking, protected records, or exceptions are used. In these
23901 cases, in order to implement Ada semantics, the GNAT run-time system
23902 calls certain Win32 routines that set the last error variable to 0 upon
23903 success. It should be possible to use @code{GetLastError} and
23904 @code{SetLastError} when tasking, protected record, and exception
23905 features are not used, but it is not guaranteed to work.
23907 @item 
23908 It is not possible to link against Microsoft C++ libraries except for
23909 import libraries. Interfacing must be done by the mean of DLLs.
23911 @item 
23912 It is possible to link against Microsoft C libraries. Yet the preferred
23913 solution is to use C/C++ compiler that comes with GNAT, since it
23914 doesn't require having two different development environments and makes the
23915 inter-language debugging experience smoother.
23917 @item 
23918 When the compilation environment is located on FAT32 drives, users may
23919 experience recompilations of the source files that have not changed if
23920 Daylight Saving Time (DST) state has changed since the last time files
23921 were compiled. NTFS drives do not have this problem.
23923 @item 
23924 No components of the GNAT toolset use any entries in the Windows
23925 registry. The only entries that can be created are file associations and
23926 PATH settings, provided the user has chosen to create them at installation
23927 time, as well as some minimal book-keeping information needed to correctly
23928 uninstall or integrate different GNAT products.
23929 @end itemize
23931 @node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
23932 @anchor{gnat_ugn/platform_specific_information id10}@anchor{1e1}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{1e2}
23933 @subsection Using a network installation of GNAT
23936 Make sure the system on which GNAT is installed is accessible from the
23937 current machine, i.e., the install location is shared over the network.
23938 Shared resources are accessed on Windows by means of UNC paths, which
23939 have the format @code{\\\\server\\sharename\\path}
23941 In order to use such a network installation, simply add the UNC path of the
23942 @code{bin} directory of your GNAT installation in front of your PATH. For
23943 example, if GNAT is installed in @code{\GNAT} directory of a share location
23944 called @code{c-drive} on a machine @code{LOKI}, the following command will
23945 make it available:
23947 @quotation
23949 @example
23950 $ path \\loki\c-drive\gnat\bin;%path%`
23951 @end example
23952 @end quotation
23954 Be aware that every compilation using the network installation results in the
23955 transfer of large amounts of data across the network and will likely cause
23956 serious performance penalty.
23958 @node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
23959 @anchor{gnat_ugn/platform_specific_information id11}@anchor{1e3}@anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{1e4}
23960 @subsection CONSOLE and WINDOWS subsystems
23963 @geindex CONSOLE Subsystem
23965 @geindex WINDOWS Subsystem
23967 @geindex -mwindows
23969 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
23970 (which is the default subsystem) will always create a console when
23971 launching the application. This is not something desirable when the
23972 application has a Windows GUI. To get rid of this console the
23973 application must be using the @code{WINDOWS} subsystem. To do so
23974 the @code{-mwindows} linker option must be specified.
23976 @quotation
23978 @example
23979 $ gnatmake winprog -largs -mwindows
23980 @end example
23981 @end quotation
23983 @node Temporary Files,Disabling Command Line Argument Expansion,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
23984 @anchor{gnat_ugn/platform_specific_information id12}@anchor{1e5}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{1e6}
23985 @subsection Temporary Files
23988 @geindex Temporary files
23990 It is possible to control where temporary files gets created by setting
23991 the 
23992 @geindex TMP
23993 @geindex environment variable; TMP
23994 @code{TMP} environment variable. The file will be created:
23997 @itemize *
23999 @item 
24000 Under the directory pointed to by the 
24001 @geindex TMP
24002 @geindex environment variable; TMP
24003 @code{TMP} environment variable if
24004 this directory exists.
24006 @item 
24007 Under @code{c:\temp}, if the 
24008 @geindex TMP
24009 @geindex environment variable; TMP
24010 @code{TMP} environment variable is not
24011 set (or not pointing to a directory) and if this directory exists.
24013 @item 
24014 Under the current working directory otherwise.
24015 @end itemize
24017 This allows you to determine exactly where the temporary
24018 file will be created. This is particularly useful in networked
24019 environments where you may not have write access to some
24020 directories.
24022 @node Disabling Command Line Argument Expansion,Mixed-Language Programming on Windows,Temporary Files,Microsoft Windows Topics
24023 @anchor{gnat_ugn/platform_specific_information disabling-command-line-argument-expansion}@anchor{1e7}
24024 @subsection Disabling Command Line Argument Expansion
24027 @geindex Command Line Argument Expansion
24029 By default, an executable compiled for the Windows platform will do
24030 the following postprocessing on the arguments passed on the command
24031 line:
24034 @itemize *
24036 @item 
24037 If the argument contains the characters @code{*} and/or @code{?}, then
24038 file expansion will be attempted. For example, if the current directory
24039 contains @code{a.txt} and @code{b.txt}, then when calling:
24041 @example
24042 $ my_ada_program *.txt
24043 @end example
24045 The following arguments will effectively be passed to the main program
24046 (for example when using @code{Ada.Command_Line.Argument}):
24048 @example
24049 Ada.Command_Line.Argument (1) -> "a.txt"
24050 Ada.Command_Line.Argument (2) -> "b.txt"
24051 @end example
24053 @item 
24054 Filename expansion can be disabled for a given argument by using single
24055 quotes. Thus, calling:
24057 @example
24058 $ my_ada_program '*.txt'
24059 @end example
24061 will result in:
24063 @example
24064 Ada.Command_Line.Argument (1) -> "*.txt"
24065 @end example
24066 @end itemize
24068 Note that if the program is launched from a shell such as Cygwin Bash
24069 then quote removal might be performed by the shell.
24071 In some contexts it might be useful to disable this feature (for example if
24072 the program performs its own argument expansion). In order to do this, a C
24073 symbol needs to be defined and set to @code{0}. You can do this by
24074 adding the following code fragment in one of your Ada units:
24076 @example
24077 Do_Argv_Expansion : Integer := 0;
24078 pragma Export (C, Do_Argv_Expansion, "__gnat_do_argv_expansion");
24079 @end example
24081 The results of previous examples will be respectively:
24083 @example
24084 Ada.Command_Line.Argument (1) -> "*.txt"
24085 @end example
24087 and:
24089 @example
24090 Ada.Command_Line.Argument (1) -> "'*.txt'"
24091 @end example
24093 @node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Disabling Command Line Argument Expansion,Microsoft Windows Topics
24094 @anchor{gnat_ugn/platform_specific_information id13}@anchor{1e8}@anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{1e9}
24095 @subsection Mixed-Language Programming on Windows
24098 Developing pure Ada applications on Windows is no different than on
24099 other GNAT-supported platforms. However, when developing or porting an
24100 application that contains a mix of Ada and C/C++, the choice of your
24101 Windows C/C++ development environment conditions your overall
24102 interoperability strategy.
24104 If you use @code{gcc} or Microsoft C to compile the non-Ada part of
24105 your application, there are no Windows-specific restrictions that
24106 affect the overall interoperability with your Ada code. If you do want
24107 to use the Microsoft tools for your C++ code, you have two choices:
24110 @itemize *
24112 @item 
24113 Encapsulate your C++ code in a DLL to be linked with your Ada
24114 application. In this case, use the Microsoft or whatever environment to
24115 build the DLL and use GNAT to build your executable
24116 (@ref{1ea,,Using DLLs with GNAT}).
24118 @item 
24119 Or you can encapsulate your Ada code in a DLL to be linked with the
24120 other part of your application. In this case, use GNAT to build the DLL
24121 (@ref{1eb,,Building DLLs with GNAT Project files}) and use the Microsoft
24122 or whatever environment to build your executable.
24123 @end itemize
24125 In addition to the description about C main in
24126 @ref{44,,Mixed Language Programming} section, if the C main uses a
24127 stand-alone library it is required on x86-windows to
24128 setup the SEH context. For this the C main must looks like this:
24130 @quotation
24132 @example
24133 /* main.c */
24134 extern void adainit (void);
24135 extern void adafinal (void);
24136 extern void __gnat_initialize(void*);
24137 extern void call_to_ada (void);
24139 int main (int argc, char *argv[])
24141   int SEH [2];
24143   /* Initialize the SEH context */
24144   __gnat_initialize (&SEH);
24146   adainit();
24148   /* Then call Ada services in the stand-alone library */
24150   call_to_ada();
24152   adafinal();
24154 @end example
24155 @end quotation
24157 Note that this is not needed on x86_64-windows where the Windows
24158 native SEH support is used.
24160 @menu
24161 * Windows Calling Conventions:: 
24162 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
24163 * Using DLLs with GNAT:: 
24164 * Building DLLs with GNAT Project files:: 
24165 * Building DLLs with GNAT:: 
24166 * Building DLLs with gnatdll:: 
24167 * Ada DLLs and Finalization:: 
24168 * Creating a Spec for Ada DLLs:: 
24169 * GNAT and Windows Resources:: 
24170 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
24171 * Debugging a DLL:: 
24172 * Setting Stack Size from gnatlink:: 
24173 * Setting Heap Size from gnatlink:: 
24175 @end menu
24177 @node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
24178 @anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{1ec}@anchor{gnat_ugn/platform_specific_information id14}@anchor{1ed}
24179 @subsubsection Windows Calling Conventions
24182 @geindex Stdcall
24184 @geindex APIENTRY
24186 This section pertain only to Win32. On Win64 there is a single native
24187 calling convention. All convention specifiers are ignored on this
24188 platform.
24190 When a subprogram @code{F} (caller) calls a subprogram @code{G}
24191 (callee), there are several ways to push @code{G}'s parameters on the
24192 stack and there are several possible scenarios to clean up the stack
24193 upon @code{G}'s return. A calling convention is an agreed upon software
24194 protocol whereby the responsibilities between the caller (@code{F}) and
24195 the callee (@code{G}) are clearly defined. Several calling conventions
24196 are available for Windows:
24199 @itemize *
24201 @item 
24202 @code{C} (Microsoft defined)
24204 @item 
24205 @code{Stdcall} (Microsoft defined)
24207 @item 
24208 @code{Win32} (GNAT specific)
24210 @item 
24211 @code{DLL} (GNAT specific)
24212 @end itemize
24214 @menu
24215 * C Calling Convention:: 
24216 * Stdcall Calling Convention:: 
24217 * Win32 Calling Convention:: 
24218 * DLL Calling Convention:: 
24220 @end menu
24222 @node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
24223 @anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{1ee}@anchor{gnat_ugn/platform_specific_information id15}@anchor{1ef}
24224 @subsubsection @code{C} Calling Convention
24227 This is the default calling convention used when interfacing to C/C++
24228 routines compiled with either @code{gcc} or Microsoft Visual C++.
24230 In the @code{C} calling convention subprogram parameters are pushed on the
24231 stack by the caller from right to left. The caller itself is in charge of
24232 cleaning up the stack after the call. In addition, the name of a routine
24233 with @code{C} calling convention is mangled by adding a leading underscore.
24235 The name to use on the Ada side when importing (or exporting) a routine
24236 with @code{C} calling convention is the name of the routine. For
24237 instance the C function:
24239 @quotation
24241 @example
24242 int get_val (long);
24243 @end example
24244 @end quotation
24246 should be imported from Ada as follows:
24248 @quotation
24250 @example
24251 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24252 pragma Import (C, Get_Val, External_Name => "get_val");
24253 @end example
24254 @end quotation
24256 Note that in this particular case the @code{External_Name} parameter could
24257 have been omitted since, when missing, this parameter is taken to be the
24258 name of the Ada entity in lower case. When the @code{Link_Name} parameter
24259 is missing, as in the above example, this parameter is set to be the
24260 @code{External_Name} with a leading underscore.
24262 When importing a variable defined in C, you should always use the @code{C}
24263 calling convention unless the object containing the variable is part of a
24264 DLL (in which case you should use the @code{Stdcall} calling
24265 convention, @ref{1f0,,Stdcall Calling Convention}).
24267 @node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
24268 @anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{1f0}@anchor{gnat_ugn/platform_specific_information id16}@anchor{1f1}
24269 @subsubsection @code{Stdcall} Calling Convention
24272 This convention, which was the calling convention used for Pascal
24273 programs, is used by Microsoft for all the routines in the Win32 API for
24274 efficiency reasons. It must be used to import any routine for which this
24275 convention was specified.
24277 In the @code{Stdcall} calling convention subprogram parameters are pushed
24278 on the stack by the caller from right to left. The callee (and not the
24279 caller) is in charge of cleaning the stack on routine exit. In addition,
24280 the name of a routine with @code{Stdcall} calling convention is mangled by
24281 adding a leading underscore (as for the @code{C} calling convention) and a
24282 trailing @code{@@@emph{nn}}, where @code{nn} is the overall size (in
24283 bytes) of the parameters passed to the routine.
24285 The name to use on the Ada side when importing a C routine with a
24286 @code{Stdcall} calling convention is the name of the C routine. The leading
24287 underscore and trailing @code{@@@emph{nn}} are added automatically by
24288 the compiler. For instance the Win32 function:
24290 @quotation
24292 @example
24293 APIENTRY int get_val (long);
24294 @end example
24295 @end quotation
24297 should be imported from Ada as follows:
24299 @quotation
24301 @example
24302 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24303 pragma Import (Stdcall, Get_Val);
24304 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
24305 @end example
24306 @end quotation
24308 As for the @code{C} calling convention, when the @code{External_Name}
24309 parameter is missing, it is taken to be the name of the Ada entity in lower
24310 case. If instead of writing the above import pragma you write:
24312 @quotation
24314 @example
24315 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24316 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
24317 @end example
24318 @end quotation
24320 then the imported routine is @code{_retrieve_val@@4}. However, if instead
24321 of specifying the @code{External_Name} parameter you specify the
24322 @code{Link_Name} as in the following example:
24324 @quotation
24326 @example
24327 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24328 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
24329 @end example
24330 @end quotation
24332 then the imported routine is @code{retrieve_val}, that is, there is no
24333 decoration at all. No leading underscore and no Stdcall suffix
24334 @code{@@@emph{nn}}.
24336 This is especially important as in some special cases a DLL's entry
24337 point name lacks a trailing @code{@@@emph{nn}} while the exported
24338 name generated for a call has it.
24340 It is also possible to import variables defined in a DLL by using an
24341 import pragma for a variable. As an example, if a DLL contains a
24342 variable defined as:
24344 @quotation
24346 @example
24347 int my_var;
24348 @end example
24349 @end quotation
24351 then, to access this variable from Ada you should write:
24353 @quotation
24355 @example
24356 My_Var : Interfaces.C.int;
24357 pragma Import (Stdcall, My_Var);
24358 @end example
24359 @end quotation
24361 Note that to ease building cross-platform bindings this convention
24362 will be handled as a @code{C} calling convention on non-Windows platforms.
24364 @node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
24365 @anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{1f2}@anchor{gnat_ugn/platform_specific_information id17}@anchor{1f3}
24366 @subsubsection @code{Win32} Calling Convention
24369 This convention, which is GNAT-specific is fully equivalent to the
24370 @code{Stdcall} calling convention described above.
24372 @node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
24373 @anchor{gnat_ugn/platform_specific_information id18}@anchor{1f4}@anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{1f5}
24374 @subsubsection @code{DLL} Calling Convention
24377 This convention, which is GNAT-specific is fully equivalent to the
24378 @code{Stdcall} calling convention described above.
24380 @node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
24381 @anchor{gnat_ugn/platform_specific_information id19}@anchor{1f6}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{1f7}
24382 @subsubsection Introduction to Dynamic Link Libraries (DLLs)
24385 @geindex DLL
24387 A Dynamically Linked Library (DLL) is a library that can be shared by
24388 several applications running under Windows. A DLL can contain any number of
24389 routines and variables.
24391 One advantage of DLLs is that you can change and enhance them without
24392 forcing all the applications that depend on them to be relinked or
24393 recompiled. However, you should be aware than all calls to DLL routines are
24394 slower since, as you will understand below, such calls are indirect.
24396 To illustrate the remainder of this section, suppose that an application
24397 wants to use the services of a DLL @code{API.dll}. To use the services
24398 provided by @code{API.dll} you must statically link against the DLL or
24399 an import library which contains a jump table with an entry for each
24400 routine and variable exported by the DLL. In the Microsoft world this
24401 import library is called @code{API.lib}. When using GNAT this import
24402 library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
24403 @code{libAPI.a} or @code{libapi.a} (names are case insensitive).
24405 After you have linked your application with the DLL or the import library
24406 and you run your application, here is what happens:
24409 @itemize *
24411 @item 
24412 Your application is loaded into memory.
24414 @item 
24415 The DLL @code{API.dll} is mapped into the address space of your
24416 application. This means that:
24419 @itemize -
24421 @item 
24422 The DLL will use the stack of the calling thread.
24424 @item 
24425 The DLL will use the virtual address space of the calling process.
24427 @item 
24428 The DLL will allocate memory from the virtual address space of the calling
24429 process.
24431 @item 
24432 Handles (pointers) can be safely exchanged between routines in the DLL
24433 routines and routines in the application using the DLL.
24434 @end itemize
24436 @item 
24437 The entries in the jump table (from the import library @code{libAPI.dll.a}
24438 or @code{API.lib} or automatically created when linking against a DLL)
24439 which is part of your application are initialized with the addresses
24440 of the routines and variables in @code{API.dll}.
24442 @item 
24443 If present in @code{API.dll}, routines @code{DllMain} or
24444 @code{DllMainCRTStartup} are invoked. These routines typically contain
24445 the initialization code needed for the well-being of the routines and
24446 variables exported by the DLL.
24447 @end itemize
24449 There is an additional point which is worth mentioning. In the Windows
24450 world there are two kind of DLLs: relocatable and non-relocatable
24451 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
24452 in the target application address space. If the addresses of two
24453 non-relocatable DLLs overlap and these happen to be used by the same
24454 application, a conflict will occur and the application will run
24455 incorrectly. Hence, when possible, it is always preferable to use and
24456 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
24457 supported by GNAT. Note that the @code{-s} linker option (see GNU Linker
24458 User's Guide) removes the debugging symbols from the DLL but the DLL can
24459 still be relocated.
24461 As a side note, an interesting difference between Microsoft DLLs and
24462 Unix shared libraries, is the fact that on most Unix systems all public
24463 routines are exported by default in a Unix shared library, while under
24464 Windows it is possible (but not required) to list exported routines in
24465 a definition file (see @ref{1f8,,The Definition File}).
24467 @node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
24468 @anchor{gnat_ugn/platform_specific_information id20}@anchor{1f9}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{1ea}
24469 @subsubsection Using DLLs with GNAT
24472 To use the services of a DLL, say @code{API.dll}, in your Ada application
24473 you must have:
24476 @itemize *
24478 @item 
24479 The Ada spec for the routines and/or variables you want to access in
24480 @code{API.dll}. If not available this Ada spec must be built from the C/C++
24481 header files provided with the DLL.
24483 @item 
24484 The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
24485 mentioned an import library is a statically linked library containing the
24486 import table which will be filled at load time to point to the actual
24487 @code{API.dll} routines. Sometimes you don't have an import library for the
24488 DLL you want to use. The following sections will explain how to build
24489 one. Note that this is optional.
24491 @item 
24492 The actual DLL, @code{API.dll}.
24493 @end itemize
24495 Once you have all the above, to compile an Ada application that uses the
24496 services of @code{API.dll} and whose main subprogram is @code{My_Ada_App},
24497 you simply issue the command
24499 @quotation
24501 @example
24502 $ gnatmake my_ada_app -largs -lAPI
24503 @end example
24504 @end quotation
24506 The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
24507 tells the GNAT linker to look for an import library. The linker will
24508 look for a library name in this specific order:
24511 @itemize *
24513 @item 
24514 @code{libAPI.dll.a}
24516 @item 
24517 @code{API.dll.a}
24519 @item 
24520 @code{libAPI.a}
24522 @item 
24523 @code{API.lib}
24525 @item 
24526 @code{libAPI.dll}
24528 @item 
24529 @code{API.dll}
24530 @end itemize
24532 The first three are the GNU style import libraries. The third is the
24533 Microsoft style import libraries. The last two are the actual DLL names.
24535 Note that if the Ada package spec for @code{API.dll} contains the
24536 following pragma
24538 @quotation
24540 @example
24541 pragma Linker_Options ("-lAPI");
24542 @end example
24543 @end quotation
24545 you do not have to add @code{-largs -lAPI} at the end of the
24546 @code{gnatmake} command.
24548 If any one of the items above is missing you will have to create it
24549 yourself. The following sections explain how to do so using as an
24550 example a fictitious DLL called @code{API.dll}.
24552 @menu
24553 * Creating an Ada Spec for the DLL Services:: 
24554 * Creating an Import Library:: 
24556 @end menu
24558 @node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
24559 @anchor{gnat_ugn/platform_specific_information id21}@anchor{1fa}@anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{1fb}
24560 @subsubsection Creating an Ada Spec for the DLL Services
24563 A DLL typically comes with a C/C++ header file which provides the
24564 definitions of the routines and variables exported by the DLL. The Ada
24565 equivalent of this header file is a package spec that contains definitions
24566 for the imported entities. If the DLL you intend to use does not come with
24567 an Ada spec you have to generate one such spec yourself. For example if
24568 the header file of @code{API.dll} is a file @code{api.h} containing the
24569 following two definitions:
24571 @quotation
24573 @example
24574 int some_var;
24575 int get (char *);
24576 @end example
24577 @end quotation
24579 then the equivalent Ada spec could be:
24581 @quotation
24583 @example
24584 with Interfaces.C.Strings;
24585 package API is
24586    use Interfaces;
24588    Some_Var : C.int;
24589    function Get (Str : C.Strings.Chars_Ptr) return C.int;
24591 private
24592    pragma Import (C, Get);
24593    pragma Import (DLL, Some_Var);
24594 end API;
24595 @end example
24596 @end quotation
24598 @node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
24599 @anchor{gnat_ugn/platform_specific_information id22}@anchor{1fc}@anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{1fd}
24600 @subsubsection Creating an Import Library
24603 @geindex Import library
24605 If a Microsoft-style import library @code{API.lib} or a GNAT-style
24606 import library @code{libAPI.dll.a} or @code{libAPI.a} is available
24607 with @code{API.dll} you can skip this section. You can also skip this
24608 section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
24609 as in this case it is possible to link directly against the
24610 DLL. Otherwise read on.
24612 @geindex Definition file
24613 @anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{1f8}
24614 @subsubheading The Definition File
24617 As previously mentioned, and unlike Unix systems, the list of symbols
24618 that are exported from a DLL must be provided explicitly in Windows.
24619 The main goal of a definition file is precisely that: list the symbols
24620 exported by a DLL. A definition file (usually a file with a @code{.def}
24621 suffix) has the following structure:
24623 @quotation
24625 @example
24626 [LIBRARY `@w{`}name`@w{`}]
24627 [DESCRIPTION `@w{`}string`@w{`}]
24628 EXPORTS
24629    `@w{`}symbol1`@w{`}
24630    `@w{`}symbol2`@w{`}
24631    ...
24632 @end example
24633 @end quotation
24636 @table @asis
24638 @item @emph{LIBRARY name}
24640 This section, which is optional, gives the name of the DLL.
24642 @item @emph{DESCRIPTION string}
24644 This section, which is optional, gives a description string that will be
24645 embedded in the import library.
24647 @item @emph{EXPORTS}
24649 This section gives the list of exported symbols (procedures, functions or
24650 variables). For instance in the case of @code{API.dll} the @code{EXPORTS}
24651 section of @code{API.def} looks like:
24653 @example
24654 EXPORTS
24655    some_var
24656    get
24657 @end example
24658 @end table
24660 Note that you must specify the correct suffix (@code{@@@emph{nn}})
24661 (see @ref{1ec,,Windows Calling Conventions}) for a Stdcall
24662 calling convention function in the exported symbols list.
24664 There can actually be other sections in a definition file, but these
24665 sections are not relevant to the discussion at hand.
24666 @anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{1fe}
24667 @subsubheading Creating a Definition File Automatically
24670 You can automatically create the definition file @code{API.def}
24671 (see @ref{1f8,,The Definition File}) from a DLL.
24672 For that use the @code{dlltool} program as follows:
24674 @quotation
24676 @example
24677 $ dlltool API.dll -z API.def --export-all-symbols
24678 @end example
24680 Note that if some routines in the DLL have the @code{Stdcall} convention
24681 (@ref{1ec,,Windows Calling Conventions}) with stripped @code{@@@emph{nn}}
24682 suffix then you'll have to edit @code{api.def} to add it, and specify
24683 @code{-k} to @code{gnatdll} when creating the import library.
24685 Here are some hints to find the right @code{@@@emph{nn}} suffix.
24688 @itemize -
24690 @item 
24691 If you have the Microsoft import library (.lib), it is possible to get
24692 the right symbols by using Microsoft @code{dumpbin} tool (see the
24693 corresponding Microsoft documentation for further details).
24695 @example
24696 $ dumpbin /exports api.lib
24697 @end example
24699 @item 
24700 If you have a message about a missing symbol at link time the compiler
24701 tells you what symbol is expected. You just have to go back to the
24702 definition file and add the right suffix.
24703 @end itemize
24704 @end quotation
24705 @anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{1ff}
24706 @subsubheading GNAT-Style Import Library
24709 To create a static import library from @code{API.dll} with the GNAT tools
24710 you should create the .def file, then use @code{gnatdll} tool
24711 (see @ref{200,,Using gnatdll}) as follows:
24713 @quotation
24715 @example
24716 $ gnatdll -e API.def -d API.dll
24717 @end example
24719 @code{gnatdll} takes as input a definition file @code{API.def} and the
24720 name of the DLL containing the services listed in the definition file
24721 @code{API.dll}. The name of the static import library generated is
24722 computed from the name of the definition file as follows: if the
24723 definition file name is @code{xyz.def}, the import library name will
24724 be @code{libxyz.a}. Note that in the previous example option
24725 @code{-e} could have been removed because the name of the definition
24726 file (before the @code{.def} suffix) is the same as the name of the
24727 DLL (@ref{200,,Using gnatdll} for more information about @code{gnatdll}).
24728 @end quotation
24729 @anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{201}
24730 @subsubheading Microsoft-Style Import Library
24733 A Microsoft import library is needed only if you plan to make an
24734 Ada DLL available to applications developed with Microsoft
24735 tools (@ref{1e9,,Mixed-Language Programming on Windows}).
24737 To create a Microsoft-style import library for @code{API.dll} you
24738 should create the .def file, then build the actual import library using
24739 Microsoft's @code{lib} utility:
24741 @quotation
24743 @example
24744 $ lib -machine:IX86 -def:API.def -out:API.lib
24745 @end example
24747 If you use the above command the definition file @code{API.def} must
24748 contain a line giving the name of the DLL:
24750 @example
24751 LIBRARY      "API"
24752 @end example
24754 See the Microsoft documentation for further details about the usage of
24755 @code{lib}.
24756 @end quotation
24758 @node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
24759 @anchor{gnat_ugn/platform_specific_information id23}@anchor{202}@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{1eb}
24760 @subsubsection Building DLLs with GNAT Project files
24763 @geindex DLLs
24764 @geindex building
24766 There is nothing specific to Windows in the build process.
24767 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24768 chapter of the @emph{GPRbuild User's Guide}.
24770 Due to a system limitation, it is not possible under Windows to create threads
24771 when inside the @code{DllMain} routine which is used for auto-initialization
24772 of shared libraries, so it is not possible to have library level tasks in SALs.
24774 @node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
24775 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{203}@anchor{gnat_ugn/platform_specific_information id24}@anchor{204}
24776 @subsubsection Building DLLs with GNAT
24779 @geindex DLLs
24780 @geindex building
24782 This section explain how to build DLLs using the GNAT built-in DLL
24783 support. With the following procedure it is straight forward to build
24784 and use DLLs with GNAT.
24787 @itemize *
24789 @item 
24790 Building object files.
24791 The first step is to build all objects files that are to be included
24792 into the DLL. This is done by using the standard @code{gnatmake} tool.
24794 @item 
24795 Building the DLL.
24796 To build the DLL you must use the @code{gcc} @code{-shared} and
24797 @code{-shared-libgcc} options. It is quite simple to use this method:
24799 @example
24800 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
24801 @end example
24803 It is important to note that in this case all symbols found in the
24804 object files are automatically exported. It is possible to restrict
24805 the set of symbols to export by passing to @code{gcc} a definition
24806 file (see @ref{1f8,,The Definition File}).
24807 For example:
24809 @example
24810 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
24811 @end example
24813 If you use a definition file you must export the elaboration procedures
24814 for every package that required one. Elaboration procedures are named
24815 using the package name followed by "_E".
24817 @item 
24818 Preparing DLL to be used.
24819 For the DLL to be used by client programs the bodies must be hidden
24820 from it and the .ali set with read-only attribute. This is very important
24821 otherwise GNAT will recompile all packages and will not actually use
24822 the code in the DLL. For example:
24824 @example
24825 $ mkdir apilib
24826 $ copy *.ads *.ali api.dll apilib
24827 $ attrib +R apilib\\*.ali
24828 @end example
24829 @end itemize
24831 At this point it is possible to use the DLL by directly linking
24832 against it. Note that you must use the GNAT shared runtime when using
24833 GNAT shared libraries. This is achieved by using the @code{-shared} binder
24834 option.
24836 @quotation
24838 @example
24839 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
24840 @end example
24841 @end quotation
24843 @node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
24844 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{205}@anchor{gnat_ugn/platform_specific_information id25}@anchor{206}
24845 @subsubsection Building DLLs with gnatdll
24848 @geindex DLLs
24849 @geindex building
24851 Note that it is preferred to use GNAT Project files
24852 (@ref{1eb,,Building DLLs with GNAT Project files}) or the built-in GNAT
24853 DLL support (@ref{203,,Building DLLs with GNAT}) or to build DLLs.
24855 This section explains how to build DLLs containing Ada code using
24856 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
24857 remainder of this section.
24859 The steps required to build an Ada DLL that is to be used by Ada as well as
24860 non-Ada applications are as follows:
24863 @itemize *
24865 @item 
24866 You need to mark each Ada entity exported by the DLL with a @code{C} or
24867 @code{Stdcall} calling convention to avoid any Ada name mangling for the
24868 entities exported by the DLL
24869 (see @ref{207,,Exporting Ada Entities}). You can
24870 skip this step if you plan to use the Ada DLL only from Ada applications.
24872 @item 
24873 Your Ada code must export an initialization routine which calls the routine
24874 @code{adainit} generated by @code{gnatbind} to perform the elaboration of
24875 the Ada code in the DLL (@ref{208,,Ada DLLs and Elaboration}). The initialization
24876 routine exported by the Ada DLL must be invoked by the clients of the DLL
24877 to initialize the DLL.
24879 @item 
24880 When useful, the DLL should also export a finalization routine which calls
24881 routine @code{adafinal} generated by @code{gnatbind} to perform the
24882 finalization of the Ada code in the DLL (@ref{209,,Ada DLLs and Finalization}).
24883 The finalization routine exported by the Ada DLL must be invoked by the
24884 clients of the DLL when the DLL services are no further needed.
24886 @item 
24887 You must provide a spec for the services exported by the Ada DLL in each
24888 of the programming languages to which you plan to make the DLL available.
24890 @item 
24891 You must provide a definition file listing the exported entities
24892 (@ref{1f8,,The Definition File}).
24894 @item 
24895 Finally you must use @code{gnatdll} to produce the DLL and the import
24896 library (@ref{200,,Using gnatdll}).
24897 @end itemize
24899 Note that a relocatable DLL stripped using the @code{strip}
24900 binutils tool will not be relocatable anymore. To build a DLL without
24901 debug information pass @code{-largs -s} to @code{gnatdll}. This
24902 restriction does not apply to a DLL built using a Library Project.
24903 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24904 chapter of the @emph{GPRbuild User's Guide}.
24906 @c Limitations_When_Using_Ada_DLLs_from Ada:
24908 @menu
24909 * Limitations When Using Ada DLLs from Ada:: 
24910 * Exporting Ada Entities:: 
24911 * Ada DLLs and Elaboration:: 
24913 @end menu
24915 @node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
24916 @anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{20a}
24917 @subsubsection Limitations When Using Ada DLLs from Ada
24920 When using Ada DLLs from Ada applications there is a limitation users
24921 should be aware of. Because on Windows the GNAT run-time is not in a DLL of
24922 its own, each Ada DLL includes a part of the GNAT run-time. Specifically,
24923 each Ada DLL includes the services of the GNAT run-time that are necessary
24924 to the Ada code inside the DLL. As a result, when an Ada program uses an
24925 Ada DLL there are two independent GNAT run-times: one in the Ada DLL and
24926 one in the main program.
24928 It is therefore not possible to exchange GNAT run-time objects between the
24929 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
24930 handles (e.g., @code{Text_IO.File_Type}), tasks types, protected objects
24931 types, etc.
24933 It is completely safe to exchange plain elementary, array or record types,
24934 Windows object handles, etc.
24936 @node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
24937 @anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{207}@anchor{gnat_ugn/platform_specific_information id26}@anchor{20b}
24938 @subsubsection Exporting Ada Entities
24941 @geindex Export table
24943 Building a DLL is a way to encapsulate a set of services usable from any
24944 application. As a result, the Ada entities exported by a DLL should be
24945 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
24946 any Ada name mangling. As an example here is an Ada package
24947 @code{API}, spec and body, exporting two procedures, a function, and a
24948 variable:
24950 @quotation
24952 @example
24953 with Interfaces.C; use Interfaces;
24954 package API is
24955    Count : C.int := 0;
24956    function Factorial (Val : C.int) return C.int;
24958    procedure Initialize_API;
24959    procedure Finalize_API;
24960    --  Initialization & Finalization routines. More in the next section.
24961 private
24962    pragma Export (C, Initialize_API);
24963    pragma Export (C, Finalize_API);
24964    pragma Export (C, Count);
24965    pragma Export (C, Factorial);
24966 end API;
24967 @end example
24969 @example
24970 package body API is
24971    function Factorial (Val : C.int) return C.int is
24972       Fact : C.int := 1;
24973    begin
24974       Count := Count + 1;
24975       for K in 1 .. Val loop
24976          Fact := Fact * K;
24977       end loop;
24978       return Fact;
24979    end Factorial;
24981    procedure Initialize_API is
24982       procedure Adainit;
24983       pragma Import (C, Adainit);
24984    begin
24985       Adainit;
24986    end Initialize_API;
24988    procedure Finalize_API is
24989       procedure Adafinal;
24990       pragma Import (C, Adafinal);
24991    begin
24992       Adafinal;
24993    end Finalize_API;
24994 end API;
24995 @end example
24996 @end quotation
24998 If the Ada DLL you are building will only be used by Ada applications
24999 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
25000 convention. As an example, the previous package could be written as
25001 follows:
25003 @quotation
25005 @example
25006 package API is
25007    Count : Integer := 0;
25008    function Factorial (Val : Integer) return Integer;
25010    procedure Initialize_API;
25011    procedure Finalize_API;
25012    --  Initialization and Finalization routines.
25013 end API;
25014 @end example
25016 @example
25017 package body API is
25018    function Factorial (Val : Integer) return Integer is
25019       Fact : Integer := 1;
25020    begin
25021       Count := Count + 1;
25022       for K in 1 .. Val loop
25023          Fact := Fact * K;
25024       end loop;
25025       return Fact;
25026    end Factorial;
25028    ...
25029    --  The remainder of this package body is unchanged.
25030 end API;
25031 @end example
25032 @end quotation
25034 Note that if you do not export the Ada entities with a @code{C} or
25035 @code{Stdcall} convention you will have to provide the mangled Ada names
25036 in the definition file of the Ada DLL
25037 (@ref{20c,,Creating the Definition File}).
25039 @node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
25040 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{208}@anchor{gnat_ugn/platform_specific_information id27}@anchor{20d}
25041 @subsubsection Ada DLLs and Elaboration
25044 @geindex DLLs and elaboration
25046 The DLL that you are building contains your Ada code as well as all the
25047 routines in the Ada library that are needed by it. The first thing a
25048 user of your DLL must do is elaborate the Ada code
25049 (@ref{f,,Elaboration Order Handling in GNAT}).
25051 To achieve this you must export an initialization routine
25052 (@code{Initialize_API} in the previous example), which must be invoked
25053 before using any of the DLL services. This elaboration routine must call
25054 the Ada elaboration routine @code{adainit} generated by the GNAT binder
25055 (@ref{b4,,Binding with Non-Ada Main Programs}). See the body of
25056 @code{Initialize_Api} for an example. Note that the GNAT binder is
25057 automatically invoked during the DLL build process by the @code{gnatdll}
25058 tool (@ref{200,,Using gnatdll}).
25060 When a DLL is loaded, Windows systematically invokes a routine called
25061 @code{DllMain}. It would therefore be possible to call @code{adainit}
25062 directly from @code{DllMain} without having to provide an explicit
25063 initialization routine. Unfortunately, it is not possible to call
25064 @code{adainit} from the @code{DllMain} if your program has library level
25065 tasks because access to the @code{DllMain} entry point is serialized by
25066 the system (that is, only a single thread can execute 'through' it at a
25067 time), which means that the GNAT run-time will deadlock waiting for the
25068 newly created task to complete its initialization.
25070 @node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
25071 @anchor{gnat_ugn/platform_specific_information id28}@anchor{20e}@anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{209}
25072 @subsubsection Ada DLLs and Finalization
25075 @geindex DLLs and finalization
25077 When the services of an Ada DLL are no longer needed, the client code should
25078 invoke the DLL finalization routine, if available. The DLL finalization
25079 routine is in charge of releasing all resources acquired by the DLL. In the
25080 case of the Ada code contained in the DLL, this is achieved by calling
25081 routine @code{adafinal} generated by the GNAT binder
25082 (@ref{b4,,Binding with Non-Ada Main Programs}).
25083 See the body of @code{Finalize_Api} for an
25084 example. As already pointed out the GNAT binder is automatically invoked
25085 during the DLL build process by the @code{gnatdll} tool
25086 (@ref{200,,Using gnatdll}).
25088 @node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
25089 @anchor{gnat_ugn/platform_specific_information id29}@anchor{20f}@anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{210}
25090 @subsubsection Creating a Spec for Ada DLLs
25093 To use the services exported by the Ada DLL from another programming
25094 language (e.g., C), you have to translate the specs of the exported Ada
25095 entities in that language. For instance in the case of @code{API.dll},
25096 the corresponding C header file could look like:
25098 @quotation
25100 @example
25101 extern int *_imp__count;
25102 #define count (*_imp__count)
25103 int factorial (int);
25104 @end example
25105 @end quotation
25107 It is important to understand that when building an Ada DLL to be used by
25108 other Ada applications, you need two different specs for the packages
25109 contained in the DLL: one for building the DLL and the other for using
25110 the DLL. This is because the @code{DLL} calling convention is needed to
25111 use a variable defined in a DLL, but when building the DLL, the variable
25112 must have either the @code{Ada} or @code{C} calling convention. As an
25113 example consider a DLL comprising the following package @code{API}:
25115 @quotation
25117 @example
25118 package API is
25119    Count : Integer := 0;
25120    ...
25121    --  Remainder of the package omitted.
25122 end API;
25123 @end example
25124 @end quotation
25126 After producing a DLL containing package @code{API}, the spec that
25127 must be used to import @code{API.Count} from Ada code outside of the
25128 DLL is:
25130 @quotation
25132 @example
25133 package API is
25134    Count : Integer;
25135    pragma Import (DLL, Count);
25136 end API;
25137 @end example
25138 @end quotation
25140 @menu
25141 * Creating the Definition File:: 
25142 * Using gnatdll:: 
25144 @end menu
25146 @node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
25147 @anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{20c}@anchor{gnat_ugn/platform_specific_information id30}@anchor{211}
25148 @subsubsection Creating the Definition File
25151 The definition file is the last file needed to build the DLL. It lists
25152 the exported symbols. As an example, the definition file for a DLL
25153 containing only package @code{API} (where all the entities are exported
25154 with a @code{C} calling convention) is:
25156 @quotation
25158 @example
25159 EXPORTS
25160     count
25161     factorial
25162     finalize_api
25163     initialize_api
25164 @end example
25165 @end quotation
25167 If the @code{C} calling convention is missing from package @code{API},
25168 then the definition file contains the mangled Ada names of the above
25169 entities, which in this case are:
25171 @quotation
25173 @example
25174 EXPORTS
25175     api__count
25176     api__factorial
25177     api__finalize_api
25178     api__initialize_api
25179 @end example
25180 @end quotation
25182 @node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
25183 @anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{200}@anchor{gnat_ugn/platform_specific_information id31}@anchor{212}
25184 @subsubsection Using @code{gnatdll}
25187 @geindex gnatdll
25189 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
25190 and non-Ada sources that make up your DLL have been compiled.
25191 @code{gnatdll} is actually in charge of two distinct tasks: build the
25192 static import library for the DLL and the actual DLL. The form of the
25193 @code{gnatdll} command is
25195 @quotation
25197 @example
25198 $ gnatdll [ switches ] list-of-files [ -largs opts ]
25199 @end example
25200 @end quotation
25202 where @code{list-of-files} is a list of ALI and object files. The object
25203 file list must be the exact list of objects corresponding to the non-Ada
25204 sources whose services are to be included in the DLL. The ALI file list
25205 must be the exact list of ALI files for the corresponding Ada sources
25206 whose services are to be included in the DLL. If @code{list-of-files} is
25207 missing, only the static import library is generated.
25209 You may specify any of the following switches to @code{gnatdll}:
25211 @quotation
25213 @geindex -a (gnatdll)
25214 @end quotation
25217 @table @asis
25219 @item @code{-a[@emph{address}]}
25221 Build a non-relocatable DLL at @code{address}. If @code{address} is not
25222 specified the default address @code{0x11000000} will be used. By default,
25223 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
25224 advise the reader to build relocatable DLL.
25226 @geindex -b (gnatdll)
25228 @item @code{-b @emph{address}}
25230 Set the relocatable DLL base address. By default the address is
25231 @code{0x11000000}.
25233 @geindex -bargs (gnatdll)
25235 @item @code{-bargs @emph{opts}}
25237 Binder options. Pass @code{opts} to the binder.
25239 @geindex -d (gnatdll)
25241 @item @code{-d @emph{dllfile}}
25243 @code{dllfile} is the name of the DLL. This switch must be present for
25244 @code{gnatdll} to do anything. The name of the generated import library is
25245 obtained algorithmically from @code{dllfile} as shown in the following
25246 example: if @code{dllfile} is @code{xyz.dll}, the import library name is
25247 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
25248 by option @code{-e}) is obtained algorithmically from @code{dllfile}
25249 as shown in the following example:
25250 if @code{dllfile} is @code{xyz.dll}, the definition
25251 file used is @code{xyz.def}.
25253 @geindex -e (gnatdll)
25255 @item @code{-e @emph{deffile}}
25257 @code{deffile} is the name of the definition file.
25259 @geindex -g (gnatdll)
25261 @item @code{-g}
25263 Generate debugging information. This information is stored in the object
25264 file and copied from there to the final DLL file by the linker,
25265 where it can be read by the debugger. You must use the
25266 @code{-g} switch if you plan on using the debugger or the symbolic
25267 stack traceback.
25269 @geindex -h (gnatdll)
25271 @item @code{-h}
25273 Help mode. Displays @code{gnatdll} switch usage information.
25275 @geindex -I (gnatdll)
25277 @item @code{-I@emph{dir}}
25279 Direct @code{gnatdll} to search the @code{dir} directory for source and
25280 object files needed to build the DLL.
25281 (@ref{89,,Search Paths and the Run-Time Library (RTL)}).
25283 @geindex -k (gnatdll)
25285 @item @code{-k}
25287 Removes the @code{@@@emph{nn}} suffix from the import library's exported
25288 names, but keeps them for the link names. You must specify this
25289 option if you want to use a @code{Stdcall} function in a DLL for which
25290 the @code{@@@emph{nn}} suffix has been removed. This is the case for most
25291 of the Windows NT DLL for example. This option has no effect when
25292 @code{-n} option is specified.
25294 @geindex -l (gnatdll)
25296 @item @code{-l @emph{file}}
25298 The list of ALI and object files used to build the DLL are listed in
25299 @code{file}, instead of being given in the command line. Each line in
25300 @code{file} contains the name of an ALI or object file.
25302 @geindex -n (gnatdll)
25304 @item @code{-n}
25306 No Import. Do not create the import library.
25308 @geindex -q (gnatdll)
25310 @item @code{-q}
25312 Quiet mode. Do not display unnecessary messages.
25314 @geindex -v (gnatdll)
25316 @item @code{-v}
25318 Verbose mode. Display extra information.
25320 @geindex -largs (gnatdll)
25322 @item @code{-largs @emph{opts}}
25324 Linker options. Pass @code{opts} to the linker.
25325 @end table
25327 @subsubheading @code{gnatdll} Example
25330 As an example the command to build a relocatable DLL from @code{api.adb}
25331 once @code{api.adb} has been compiled and @code{api.def} created is
25333 @quotation
25335 @example
25336 $ gnatdll -d api.dll api.ali
25337 @end example
25338 @end quotation
25340 The above command creates two files: @code{libapi.dll.a} (the import
25341 library) and @code{api.dll} (the actual DLL). If you want to create
25342 only the DLL, just type:
25344 @quotation
25346 @example
25347 $ gnatdll -d api.dll -n api.ali
25348 @end example
25349 @end quotation
25351 Alternatively if you want to create just the import library, type:
25353 @quotation
25355 @example
25356 $ gnatdll -d api.dll
25357 @end example
25358 @end quotation
25360 @subsubheading @code{gnatdll} behind the Scenes
25363 This section details the steps involved in creating a DLL. @code{gnatdll}
25364 does these steps for you. Unless you are interested in understanding what
25365 goes on behind the scenes, you should skip this section.
25367 We use the previous example of a DLL containing the Ada package @code{API},
25368 to illustrate the steps necessary to build a DLL. The starting point is a
25369 set of objects that will make up the DLL and the corresponding ALI
25370 files. In the case of this example this means that @code{api.o} and
25371 @code{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
25372 the following:
25375 @itemize *
25377 @item 
25378 @code{gnatdll} builds the base file (@code{api.base}). A base file gives
25379 the information necessary to generate relocation information for the
25380 DLL.
25382 @example
25383 $ gnatbind -n api
25384 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
25385 @end example
25387 In addition to the base file, the @code{gnatlink} command generates an
25388 output file @code{api.jnk} which can be discarded. The @code{-mdll} switch
25389 asks @code{gnatlink} to generate the routines @code{DllMain} and
25390 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
25391 is loaded into memory.
25393 @item 
25394 @code{gnatdll} uses @code{dlltool} (see @ref{213,,Using dlltool}) to build the
25395 export table (@code{api.exp}). The export table contains the relocation
25396 information in a form which can be used during the final link to ensure
25397 that the Windows loader is able to place the DLL anywhere in memory.
25399 @example
25400 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
25401           --output-exp api.exp
25402 @end example
25404 @item 
25405 @code{gnatdll} builds the base file using the new export table. Note that
25406 @code{gnatbind} must be called once again since the binder generated file
25407 has been deleted during the previous call to @code{gnatlink}.
25409 @example
25410 $ gnatbind -n api
25411 $ gnatlink api -o api.jnk api.exp -mdll
25412       -Wl,--base-file,api.base
25413 @end example
25415 @item 
25416 @code{gnatdll} builds the new export table using the new base file and
25417 generates the DLL import library @code{libAPI.dll.a}.
25419 @example
25420 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
25421           --output-exp api.exp --output-lib libAPI.a
25422 @end example
25424 @item 
25425 Finally @code{gnatdll} builds the relocatable DLL using the final export
25426 table.
25428 @example
25429 $ gnatbind -n api
25430 $ gnatlink api api.exp -o api.dll -mdll
25431 @end example
25432 @end itemize
25433 @anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{213}
25434 @subsubheading Using @code{dlltool}
25437 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
25438 DLLs and static import libraries. This section summarizes the most
25439 common @code{dlltool} switches. The form of the @code{dlltool} command
25442 @quotation
25444 @example
25445 $ dlltool [`switches`]
25446 @end example
25447 @end quotation
25449 @code{dlltool} switches include:
25451 @geindex --base-file (dlltool)
25454 @table @asis
25456 @item @code{--base-file @emph{basefile}}
25458 Read the base file @code{basefile} generated by the linker. This switch
25459 is used to create a relocatable DLL.
25460 @end table
25462 @geindex --def (dlltool)
25465 @table @asis
25467 @item @code{--def @emph{deffile}}
25469 Read the definition file.
25470 @end table
25472 @geindex --dllname (dlltool)
25475 @table @asis
25477 @item @code{--dllname @emph{name}}
25479 Gives the name of the DLL. This switch is used to embed the name of the
25480 DLL in the static import library generated by @code{dlltool} with switch
25481 @code{--output-lib}.
25482 @end table
25484 @geindex -k (dlltool)
25487 @table @asis
25489 @item @code{-k}
25491 Kill @code{@@@emph{nn}} from exported names
25492 (@ref{1ec,,Windows Calling Conventions}
25493 for a discussion about @code{Stdcall}-style symbols.
25494 @end table
25496 @geindex --help (dlltool)
25499 @table @asis
25501 @item @code{--help}
25503 Prints the @code{dlltool} switches with a concise description.
25504 @end table
25506 @geindex --output-exp (dlltool)
25509 @table @asis
25511 @item @code{--output-exp @emph{exportfile}}
25513 Generate an export file @code{exportfile}. The export file contains the
25514 export table (list of symbols in the DLL) and is used to create the DLL.
25515 @end table
25517 @geindex --output-lib (dlltool)
25520 @table @asis
25522 @item @code{--output-lib @emph{libfile}}
25524 Generate a static import library @code{libfile}.
25525 @end table
25527 @geindex -v (dlltool)
25530 @table @asis
25532 @item @code{-v}
25534 Verbose mode.
25535 @end table
25537 @geindex --as (dlltool)
25540 @table @asis
25542 @item @code{--as @emph{assembler-name}}
25544 Use @code{assembler-name} as the assembler. The default is @code{as}.
25545 @end table
25547 @node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
25548 @anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{214}@anchor{gnat_ugn/platform_specific_information id32}@anchor{215}
25549 @subsubsection GNAT and Windows Resources
25552 @geindex Resources
25553 @geindex windows
25555 Resources are an easy way to add Windows specific objects to your
25556 application. The objects that can be added as resources include:
25559 @itemize *
25561 @item 
25562 menus
25564 @item 
25565 accelerators
25567 @item 
25568 dialog boxes
25570 @item 
25571 string tables
25573 @item 
25574 bitmaps
25576 @item 
25577 cursors
25579 @item 
25580 icons
25582 @item 
25583 fonts
25585 @item 
25586 version information
25587 @end itemize
25589 For example, a version information resource can be defined as follow and
25590 embedded into an executable or DLL:
25592 A version information resource can be used to embed information into an
25593 executable or a DLL. These information can be viewed using the file properties
25594 from the Windows Explorer. Here is an example of a version information
25595 resource:
25597 @quotation
25599 @example
25600 1 VERSIONINFO
25601 FILEVERSION     1,0,0,0
25602 PRODUCTVERSION  1,0,0,0
25603 BEGIN
25604   BLOCK "StringFileInfo"
25605   BEGIN
25606     BLOCK "080904E4"
25607     BEGIN
25608       VALUE "CompanyName", "My Company Name"
25609       VALUE "FileDescription", "My application"
25610       VALUE "FileVersion", "1.0"
25611       VALUE "InternalName", "my_app"
25612       VALUE "LegalCopyright", "My Name"
25613       VALUE "OriginalFilename", "my_app.exe"
25614       VALUE "ProductName", "My App"
25615       VALUE "ProductVersion", "1.0"
25616     END
25617   END
25619   BLOCK "VarFileInfo"
25620   BEGIN
25621     VALUE "Translation", 0x809, 1252
25622   END
25624 @end example
25625 @end quotation
25627 The value @code{0809} (langID) is for the U.K English language and
25628 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
25629 multilingual.
25631 This section explains how to build, compile and use resources. Note that this
25632 section does not cover all resource objects, for a complete description see
25633 the corresponding Microsoft documentation.
25635 @menu
25636 * Building Resources:: 
25637 * Compiling Resources:: 
25638 * Using Resources:: 
25640 @end menu
25642 @node Building Resources,Compiling Resources,,GNAT and Windows Resources
25643 @anchor{gnat_ugn/platform_specific_information building-resources}@anchor{216}@anchor{gnat_ugn/platform_specific_information id33}@anchor{217}
25644 @subsubsection Building Resources
25647 @geindex Resources
25648 @geindex building
25650 A resource file is an ASCII file. By convention resource files have an
25651 @code{.rc} extension.
25652 The easiest way to build a resource file is to use Microsoft tools
25653 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
25654 @code{dlgedit.exe} to build dialogs.
25655 It is always possible to build an @code{.rc} file yourself by writing a
25656 resource script.
25658 It is not our objective to explain how to write a resource file. A
25659 complete description of the resource script language can be found in the
25660 Microsoft documentation.
25662 @node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
25663 @anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{218}@anchor{gnat_ugn/platform_specific_information id34}@anchor{219}
25664 @subsubsection Compiling Resources
25667 @geindex rc
25669 @geindex windres
25671 @geindex Resources
25672 @geindex compiling
25674 This section describes how to build a GNAT-compatible (COFF) object file
25675 containing the resources. This is done using the Resource Compiler
25676 @code{windres} as follows:
25678 @quotation
25680 @example
25681 $ windres -i myres.rc -o myres.o
25682 @end example
25683 @end quotation
25685 By default @code{windres} will run @code{gcc} to preprocess the @code{.rc}
25686 file. You can specify an alternate preprocessor (usually named
25687 @code{cpp.exe}) using the @code{windres} @code{--preprocessor}
25688 parameter. A list of all possible options may be obtained by entering
25689 the command @code{windres} @code{--help}.
25691 It is also possible to use the Microsoft resource compiler @code{rc.exe}
25692 to produce a @code{.res} file (binary resource file). See the
25693 corresponding Microsoft documentation for further details. In this case
25694 you need to use @code{windres} to translate the @code{.res} file to a
25695 GNAT-compatible object file as follows:
25697 @quotation
25699 @example
25700 $ windres -i myres.res -o myres.o
25701 @end example
25702 @end quotation
25704 @node Using Resources,,Compiling Resources,GNAT and Windows Resources
25705 @anchor{gnat_ugn/platform_specific_information using-resources}@anchor{21a}@anchor{gnat_ugn/platform_specific_information id35}@anchor{21b}
25706 @subsubsection Using Resources
25709 @geindex Resources
25710 @geindex using
25712 To include the resource file in your program just add the
25713 GNAT-compatible object file for the resource(s) to the linker
25714 arguments. With @code{gnatmake} this is done by using the @code{-largs}
25715 option:
25717 @quotation
25719 @example
25720 $ gnatmake myprog -largs myres.o
25721 @end example
25722 @end quotation
25724 @node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
25725 @anchor{gnat_ugn/platform_specific_information using-gnat-dll-from-msvs}@anchor{21c}@anchor{gnat_ugn/platform_specific_information using-gnat-dlls-from-microsoft-visual-studio-applications}@anchor{21d}
25726 @subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
25729 @geindex Microsoft Visual Studio
25730 @geindex use with GNAT DLLs
25732 This section describes a common case of mixed GNAT/Microsoft Visual Studio
25733 application development, where the main program is developed using MSVS, and
25734 is linked with a DLL developed using GNAT. Such a mixed application should
25735 be developed following the general guidelines outlined above; below is the
25736 cookbook-style sequence of steps to follow:
25739 @enumerate 
25741 @item 
25742 First develop and build the GNAT shared library using a library project
25743 (let's assume the project is @code{mylib.gpr}, producing the library @code{libmylib.dll}):
25744 @end enumerate
25746 @quotation
25748 @example
25749 $ gprbuild -p mylib.gpr
25750 @end example
25751 @end quotation
25754 @enumerate 2
25756 @item 
25757 Produce a .def file for the symbols you need to interface with, either by
25758 hand or automatically with possibly some manual adjustments
25759 (see @ref{1fe,,Creating Definition File Automatically}):
25760 @end enumerate
25762 @quotation
25764 @example
25765 $ dlltool libmylib.dll -z libmylib.def --export-all-symbols
25766 @end example
25767 @end quotation
25770 @enumerate 3
25772 @item 
25773 Make sure that MSVS command-line tools are accessible on the path.
25775 @item 
25776 Create the Microsoft-style import library (see @ref{201,,MSVS-Style Import Library}):
25777 @end enumerate
25779 @quotation
25781 @example
25782 $ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
25783 @end example
25784 @end quotation
25786 If you are using a 64-bit toolchain, the above becomes...
25788 @quotation
25790 @example
25791 $ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
25792 @end example
25793 @end quotation
25796 @enumerate 5
25798 @item 
25799 Build the C main
25800 @end enumerate
25802 @quotation
25804 @example
25805 $ cl /O2 /MD main.c libmylib.lib
25806 @end example
25807 @end quotation
25810 @enumerate 6
25812 @item 
25813 Before running the executable, make sure you have set the PATH to the DLL,
25814 or copy the DLL into into the directory containing the .exe.
25815 @end enumerate
25817 @node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
25818 @anchor{gnat_ugn/platform_specific_information id36}@anchor{21e}@anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{21f}
25819 @subsubsection Debugging a DLL
25822 @geindex DLL debugging
25824 Debugging a DLL is similar to debugging a standard program. But
25825 we have to deal with two different executable parts: the DLL and the
25826 program that uses it. We have the following four possibilities:
25829 @itemize *
25831 @item 
25832 The program and the DLL are built with GCC/GNAT.
25834 @item 
25835 The program is built with foreign tools and the DLL is built with
25836 GCC/GNAT.
25838 @item 
25839 The program is built with GCC/GNAT and the DLL is built with
25840 foreign tools.
25841 @end itemize
25843 In this section we address only cases one and two above.
25844 There is no point in trying to debug
25845 a DLL with GNU/GDB, if there is no GDB-compatible debugging
25846 information in it. To do so you must use a debugger compatible with the
25847 tools suite used to build the DLL.
25849 @menu
25850 * Program and DLL Both Built with GCC/GNAT:: 
25851 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
25853 @end menu
25855 @node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
25856 @anchor{gnat_ugn/platform_specific_information id37}@anchor{220}@anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{221}
25857 @subsubsection Program and DLL Both Built with GCC/GNAT
25860 This is the simplest case. Both the DLL and the program have @code{GDB}
25861 compatible debugging information. It is then possible to break anywhere in
25862 the process. Let's suppose here that the main procedure is named
25863 @code{ada_main} and that in the DLL there is an entry point named
25864 @code{ada_dll}.
25866 The DLL (@ref{1f7,,Introduction to Dynamic Link Libraries (DLLs)}) and
25867 program must have been built with the debugging information (see GNAT -g
25868 switch). Here are the step-by-step instructions for debugging it:
25871 @itemize *
25873 @item 
25874 Launch @code{GDB} on the main program.
25876 @example
25877 $ gdb -nw ada_main
25878 @end example
25880 @item 
25881 Start the program and stop at the beginning of the main procedure
25883 @example
25884 (gdb) start
25885 @end example
25887 This step is required to be able to set a breakpoint inside the DLL. As long
25888 as the program is not run, the DLL is not loaded. This has the
25889 consequence that the DLL debugging information is also not loaded, so it is not
25890 possible to set a breakpoint in the DLL.
25892 @item 
25893 Set a breakpoint inside the DLL
25895 @example
25896 (gdb) break ada_dll
25897 (gdb) cont
25898 @end example
25899 @end itemize
25901 At this stage a breakpoint is set inside the DLL. From there on
25902 you can use the standard approach to debug the whole program
25903 (@ref{24,,Running and Debugging Ada Programs}).
25905 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
25906 @anchor{gnat_ugn/platform_specific_information program-built-with-foreign-tools-and-dll-built-with-gcc-gnat}@anchor{222}@anchor{gnat_ugn/platform_specific_information id38}@anchor{223}
25907 @subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
25910 In this case things are slightly more complex because it is not possible to
25911 start the main program and then break at the beginning to load the DLL and the
25912 associated DLL debugging information. It is not possible to break at the
25913 beginning of the program because there is no @code{GDB} debugging information,
25914 and therefore there is no direct way of getting initial control. This
25915 section addresses this issue by describing some methods that can be used
25916 to break somewhere in the DLL to debug it.
25918 First suppose that the main procedure is named @code{main} (this is for
25919 example some C code built with Microsoft Visual C) and that there is a
25920 DLL named @code{test.dll} containing an Ada entry point named
25921 @code{ada_dll}.
25923 The DLL (see @ref{1f7,,Introduction to Dynamic Link Libraries (DLLs)}) must have
25924 been built with debugging information (see the GNAT @code{-g} option).
25926 @subsubheading Debugging the DLL Directly
25930 @itemize *
25932 @item 
25933 Find out the executable starting address
25935 @example
25936 $ objdump --file-header main.exe
25937 @end example
25939 The starting address is reported on the last line. For example:
25941 @example
25942 main.exe:     file format pei-i386
25943 architecture: i386, flags 0x0000010a:
25944 EXEC_P, HAS_DEBUG, D_PAGED
25945 start address 0x00401010
25946 @end example
25948 @item 
25949 Launch the debugger on the executable.
25951 @example
25952 $ gdb main.exe
25953 @end example
25955 @item 
25956 Set a breakpoint at the starting address, and launch the program.
25958 @example
25959 $ (gdb) break *0x00401010
25960 $ (gdb) run
25961 @end example
25963 The program will stop at the given address.
25965 @item 
25966 Set a breakpoint on a DLL subroutine.
25968 @example
25969 (gdb) break ada_dll.adb:45
25970 @end example
25972 Or if you want to break using a symbol on the DLL, you need first to
25973 select the Ada language (language used by the DLL).
25975 @example
25976 (gdb) set language ada
25977 (gdb) break ada_dll
25978 @end example
25980 @item 
25981 Continue the program.
25983 @example
25984 (gdb) cont
25985 @end example
25987 This will run the program until it reaches the breakpoint that has been
25988 set. From that point you can use the standard way to debug a program
25989 as described in (@ref{24,,Running and Debugging Ada Programs}).
25990 @end itemize
25992 It is also possible to debug the DLL by attaching to a running process.
25994 @subsubheading Attaching to a Running Process
25997 @geindex DLL debugging
25998 @geindex attach to process
26000 With @code{GDB} it is always possible to debug a running process by
26001 attaching to it. It is possible to debug a DLL this way. The limitation
26002 of this approach is that the DLL must run long enough to perform the
26003 attach operation. It may be useful for instance to insert a time wasting
26004 loop in the code of the DLL to meet this criterion.
26007 @itemize *
26009 @item 
26010 Launch the main program @code{main.exe}.
26012 @example
26013 $ main
26014 @end example
26016 @item 
26017 Use the Windows @emph{Task Manager} to find the process ID. Let's say
26018 that the process PID for @code{main.exe} is 208.
26020 @item 
26021 Launch gdb.
26023 @example
26024 $ gdb
26025 @end example
26027 @item 
26028 Attach to the running process to be debugged.
26030 @example
26031 (gdb) attach 208
26032 @end example
26034 @item 
26035 Load the process debugging information.
26037 @example
26038 (gdb) symbol-file main.exe
26039 @end example
26041 @item 
26042 Break somewhere in the DLL.
26044 @example
26045 (gdb) break ada_dll
26046 @end example
26048 @item 
26049 Continue process execution.
26051 @example
26052 (gdb) cont
26053 @end example
26054 @end itemize
26056 This last step will resume the process execution, and stop at
26057 the breakpoint we have set. From there you can use the standard
26058 approach to debug a program as described in
26059 @ref{24,,Running and Debugging Ada Programs}.
26061 @node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
26062 @anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{136}@anchor{gnat_ugn/platform_specific_information id39}@anchor{224}
26063 @subsubsection Setting Stack Size from @code{gnatlink}
26066 It is possible to specify the program stack size at link time. On modern
26067 versions of Windows, starting with XP, this is mostly useful to set the size of
26068 the main stack (environment task). The other task stacks are set with pragma
26069 Storage_Size or with the @emph{gnatbind -d} command.
26071 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
26072 reserve size of individual tasks, the link-time stack size applies to all
26073 tasks, and pragma Storage_Size has no effect.
26074 In particular, Stack Overflow checks are made against this
26075 link-time specified size.
26077 This setting can be done with @code{gnatlink} using either of the following:
26080 @itemize *
26082 @item 
26083 @code{-Xlinker} linker option
26085 @example
26086 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
26087 @end example
26089 This sets the stack reserve size to 0x10000 bytes and the stack commit
26090 size to 0x1000 bytes.
26092 @item 
26093 @code{-Wl} linker option
26095 @example
26096 $ gnatlink hello -Wl,--stack=0x1000000
26097 @end example
26099 This sets the stack reserve size to 0x1000000 bytes. Note that with
26100 @code{-Wl} option it is not possible to set the stack commit size
26101 because the comma is a separator for this option.
26102 @end itemize
26104 @node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
26105 @anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{137}@anchor{gnat_ugn/platform_specific_information id40}@anchor{225}
26106 @subsubsection Setting Heap Size from @code{gnatlink}
26109 Under Windows systems, it is possible to specify the program heap size from
26110 @code{gnatlink} using either of the following:
26113 @itemize *
26115 @item 
26116 @code{-Xlinker} linker option
26118 @example
26119 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
26120 @end example
26122 This sets the heap reserve size to 0x10000 bytes and the heap commit
26123 size to 0x1000 bytes.
26125 @item 
26126 @code{-Wl} linker option
26128 @example
26129 $ gnatlink hello -Wl,--heap=0x1000000
26130 @end example
26132 This sets the heap reserve size to 0x1000000 bytes. Note that with
26133 @code{-Wl} option it is not possible to set the heap commit size
26134 because the comma is a separator for this option.
26135 @end itemize
26137 @node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
26138 @anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{226}@anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{227}
26139 @subsection Windows Specific Add-Ons
26142 This section describes the Windows specific add-ons.
26144 @menu
26145 * Win32Ada:: 
26146 * wPOSIX:: 
26148 @end menu
26150 @node Win32Ada,wPOSIX,,Windows Specific Add-Ons
26151 @anchor{gnat_ugn/platform_specific_information win32ada}@anchor{228}@anchor{gnat_ugn/platform_specific_information id41}@anchor{229}
26152 @subsubsection Win32Ada
26155 Win32Ada is a binding for the Microsoft Win32 API. This binding can be
26156 easily installed from the provided installer. To use the Win32Ada
26157 binding you need to use a project file, and adding a single with_clause
26158 will give you full access to the Win32Ada binding sources and ensure
26159 that the proper libraries are passed to the linker.
26161 @quotation
26163 @example
26164 with "win32ada";
26165 project P is
26166    for Sources use ...;
26167 end P;
26168 @end example
26169 @end quotation
26171 To build the application you just need to call gprbuild for the
26172 application's project, here p.gpr:
26174 @quotation
26176 @example
26177 gprbuild p.gpr
26178 @end example
26179 @end quotation
26181 @node wPOSIX,,Win32Ada,Windows Specific Add-Ons
26182 @anchor{gnat_ugn/platform_specific_information id42}@anchor{22a}@anchor{gnat_ugn/platform_specific_information wposix}@anchor{22b}
26183 @subsubsection wPOSIX
26186 wPOSIX is a minimal POSIX binding whose goal is to help with building
26187 cross-platforms applications. This binding is not complete though, as
26188 the Win32 API does not provide the necessary support for all POSIX APIs.
26190 To use the wPOSIX binding you need to use a project file, and adding
26191 a single with_clause will give you full access to the wPOSIX binding
26192 sources and ensure that the proper libraries are passed to the linker.
26194 @quotation
26196 @example
26197 with "wposix";
26198 project P is
26199    for Sources use ...;
26200 end P;
26201 @end example
26202 @end quotation
26204 To build the application you just need to call gprbuild for the
26205 application's project, here p.gpr:
26207 @quotation
26209 @example
26210 gprbuild p.gpr
26211 @end example
26212 @end quotation
26214 @node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
26215 @anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{2d}@anchor{gnat_ugn/platform_specific_information id43}@anchor{22c}
26216 @section Mac OS Topics
26219 @geindex OS X
26221 This section describes topics that are specific to Apple's OS X
26222 platform.
26224 @menu
26225 * Codesigning the Debugger:: 
26227 @end menu
26229 @node Codesigning the Debugger,,,Mac OS Topics
26230 @anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{22d}
26231 @subsection Codesigning the Debugger
26234 The Darwin Kernel requires the debugger to have special permissions
26235 before it is allowed to control other processes. These permissions
26236 are granted by codesigning the GDB executable. Without these
26237 permissions, the debugger will report error messages such as:
26239 @example
26240 Starting program: /x/y/foo
26241 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
26242 (please check gdb is codesigned - see taskgated(8))
26243 @end example
26245 Codesigning requires a certificate.  The following procedure explains
26246 how to create one:
26249 @itemize *
26251 @item 
26252 Start the Keychain Access application (in
26253 /Applications/Utilities/Keychain Access.app)
26255 @item 
26256 Select the Keychain Access -> Certificate Assistant ->
26257 Create a Certificate... menu
26259 @item 
26260 Then:
26263 @itemize *
26265 @item 
26266 Choose a name for the new certificate (this procedure will use
26267 "gdb-cert" as an example)
26269 @item 
26270 Set "Identity Type" to "Self Signed Root"
26272 @item 
26273 Set "Certificate Type" to "Code Signing"
26275 @item 
26276 Activate the "Let me override defaults" option
26277 @end itemize
26279 @item 
26280 Click several times on "Continue" until the "Specify a Location
26281 For The Certificate" screen appears, then set "Keychain" to "System"
26283 @item 
26284 Click on "Continue" until the certificate is created
26286 @item 
26287 Finally, in the view, double-click on the new certificate,
26288 and set "When using this certificate" to "Always Trust"
26290 @item 
26291 Exit the Keychain Access application and restart the computer
26292 (this is unfortunately required)
26293 @end itemize
26295 Once a certificate has been created, the debugger can be codesigned
26296 as follow. In a Terminal, run the following command:
26298 @quotation
26300 @example
26301 $ codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
26302 @end example
26303 @end quotation
26305 where "gdb-cert" should be replaced by the actual certificate
26306 name chosen above, and <gnat_install_prefix> should be replaced by
26307 the location where you installed GNAT.  Also, be sure that users are
26308 in the Unix group @code{_developer}.
26310 @node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
26311 @anchor{gnat_ugn/example_of_binder_output example-of-binder-output-file}@anchor{e}@anchor{gnat_ugn/example_of_binder_output doc}@anchor{22e}@anchor{gnat_ugn/example_of_binder_output id1}@anchor{22f}
26312 @chapter Example of Binder Output File
26315 @geindex Binder output (example)
26317 This Appendix displays the source code for the output file
26318 generated by @emph{gnatbind} for a simple 'Hello World' program.
26319 Comments have been added for clarification purposes.
26321 @example
26322 --  The package is called Ada_Main unless this name is actually used
26323 --  as a unit name in the partition, in which case some other unique
26324 --  name is used.
26326 pragma Ada_95;
26327 with System;
26328 package ada_main is
26329    pragma Warnings (Off);
26331    --  The main program saves the parameters (argument count,
26332    --  argument values, environment pointer) in global variables
26333    --  for later access by other units including
26334    --  Ada.Command_Line.
26336    gnat_argc : Integer;
26337    gnat_argv : System.Address;
26338    gnat_envp : System.Address;
26340    --  The actual variables are stored in a library routine. This
26341    --  is useful for some shared library situations, where there
26342    --  are problems if variables are not in the library.
26344    pragma Import (C, gnat_argc);
26345    pragma Import (C, gnat_argv);
26346    pragma Import (C, gnat_envp);
26348    --  The exit status is similarly an external location
26350    gnat_exit_status : Integer;
26351    pragma Import (C, gnat_exit_status);
26353    GNAT_Version : constant String :=
26354                     "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
26355    pragma Export (C, GNAT_Version, "__gnat_version");
26357    Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
26358    pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
26360    --  This is the generated adainit routine that performs
26361    --  initialization at the start of execution. In the case
26362    --  where Ada is the main program, this main program makes
26363    --  a call to adainit at program startup.
26365    procedure adainit;
26366    pragma Export (C, adainit, "adainit");
26368    --  This is the generated adafinal routine that performs
26369    --  finalization at the end of execution. In the case where
26370    --  Ada is the main program, this main program makes a call
26371    --  to adafinal at program termination.
26373    procedure adafinal;
26374    pragma Export (C, adafinal, "adafinal");
26376    --  This routine is called at the start of execution. It is
26377    --  a dummy routine that is used by the debugger to breakpoint
26378    --  at the start of execution.
26380    --  This is the actual generated main program (it would be
26381    --  suppressed if the no main program switch were used). As
26382    --  required by standard system conventions, this program has
26383    --  the external name main.
26385    function main
26386      (argc : Integer;
26387       argv : System.Address;
26388       envp : System.Address)
26389       return Integer;
26390    pragma Export (C, main, "main");
26392    --  The following set of constants give the version
26393    --  identification values for every unit in the bound
26394    --  partition. This identification is computed from all
26395    --  dependent semantic units, and corresponds to the
26396    --  string that would be returned by use of the
26397    --  Body_Version or Version attributes.
26399    --  The following Export pragmas export the version numbers
26400    --  with symbolic names ending in B (for body) or S
26401    --  (for spec) so that they can be located in a link. The
26402    --  information provided here is sufficient to track down
26403    --  the exact versions of units used in a given build.
26405    type Version_32 is mod 2 ** 32;
26406    u00001 : constant Version_32 := 16#8ad6e54a#;
26407    pragma Export (C, u00001, "helloB");
26408    u00002 : constant Version_32 := 16#fbff4c67#;
26409    pragma Export (C, u00002, "system__standard_libraryB");
26410    u00003 : constant Version_32 := 16#1ec6fd90#;
26411    pragma Export (C, u00003, "system__standard_libraryS");
26412    u00004 : constant Version_32 := 16#3ffc8e18#;
26413    pragma Export (C, u00004, "adaS");
26414    u00005 : constant Version_32 := 16#28f088c2#;
26415    pragma Export (C, u00005, "ada__text_ioB");
26416    u00006 : constant Version_32 := 16#f372c8ac#;
26417    pragma Export (C, u00006, "ada__text_ioS");
26418    u00007 : constant Version_32 := 16#2c143749#;
26419    pragma Export (C, u00007, "ada__exceptionsB");
26420    u00008 : constant Version_32 := 16#f4f0cce8#;
26421    pragma Export (C, u00008, "ada__exceptionsS");
26422    u00009 : constant Version_32 := 16#a46739c0#;
26423    pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
26424    u00010 : constant Version_32 := 16#3aac8c92#;
26425    pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
26426    u00011 : constant Version_32 := 16#1d274481#;
26427    pragma Export (C, u00011, "systemS");
26428    u00012 : constant Version_32 := 16#a207fefe#;
26429    pragma Export (C, u00012, "system__soft_linksB");
26430    u00013 : constant Version_32 := 16#467d9556#;
26431    pragma Export (C, u00013, "system__soft_linksS");
26432    u00014 : constant Version_32 := 16#b01dad17#;
26433    pragma Export (C, u00014, "system__parametersB");
26434    u00015 : constant Version_32 := 16#630d49fe#;
26435    pragma Export (C, u00015, "system__parametersS");
26436    u00016 : constant Version_32 := 16#b19b6653#;
26437    pragma Export (C, u00016, "system__secondary_stackB");
26438    u00017 : constant Version_32 := 16#b6468be8#;
26439    pragma Export (C, u00017, "system__secondary_stackS");
26440    u00018 : constant Version_32 := 16#39a03df9#;
26441    pragma Export (C, u00018, "system__storage_elementsB");
26442    u00019 : constant Version_32 := 16#30e40e85#;
26443    pragma Export (C, u00019, "system__storage_elementsS");
26444    u00020 : constant Version_32 := 16#41837d1e#;
26445    pragma Export (C, u00020, "system__stack_checkingB");
26446    u00021 : constant Version_32 := 16#93982f69#;
26447    pragma Export (C, u00021, "system__stack_checkingS");
26448    u00022 : constant Version_32 := 16#393398c1#;
26449    pragma Export (C, u00022, "system__exception_tableB");
26450    u00023 : constant Version_32 := 16#b33e2294#;
26451    pragma Export (C, u00023, "system__exception_tableS");
26452    u00024 : constant Version_32 := 16#ce4af020#;
26453    pragma Export (C, u00024, "system__exceptionsB");
26454    u00025 : constant Version_32 := 16#75442977#;
26455    pragma Export (C, u00025, "system__exceptionsS");
26456    u00026 : constant Version_32 := 16#37d758f1#;
26457    pragma Export (C, u00026, "system__exceptions__machineS");
26458    u00027 : constant Version_32 := 16#b895431d#;
26459    pragma Export (C, u00027, "system__exceptions_debugB");
26460    u00028 : constant Version_32 := 16#aec55d3f#;
26461    pragma Export (C, u00028, "system__exceptions_debugS");
26462    u00029 : constant Version_32 := 16#570325c8#;
26463    pragma Export (C, u00029, "system__img_intB");
26464    u00030 : constant Version_32 := 16#1ffca443#;
26465    pragma Export (C, u00030, "system__img_intS");
26466    u00031 : constant Version_32 := 16#b98c3e16#;
26467    pragma Export (C, u00031, "system__tracebackB");
26468    u00032 : constant Version_32 := 16#831a9d5a#;
26469    pragma Export (C, u00032, "system__tracebackS");
26470    u00033 : constant Version_32 := 16#9ed49525#;
26471    pragma Export (C, u00033, "system__traceback_entriesB");
26472    u00034 : constant Version_32 := 16#1d7cb2f1#;
26473    pragma Export (C, u00034, "system__traceback_entriesS");
26474    u00035 : constant Version_32 := 16#8c33a517#;
26475    pragma Export (C, u00035, "system__wch_conB");
26476    u00036 : constant Version_32 := 16#065a6653#;
26477    pragma Export (C, u00036, "system__wch_conS");
26478    u00037 : constant Version_32 := 16#9721e840#;
26479    pragma Export (C, u00037, "system__wch_stwB");
26480    u00038 : constant Version_32 := 16#2b4b4a52#;
26481    pragma Export (C, u00038, "system__wch_stwS");
26482    u00039 : constant Version_32 := 16#92b797cb#;
26483    pragma Export (C, u00039, "system__wch_cnvB");
26484    u00040 : constant Version_32 := 16#09eddca0#;
26485    pragma Export (C, u00040, "system__wch_cnvS");
26486    u00041 : constant Version_32 := 16#6033a23f#;
26487    pragma Export (C, u00041, "interfacesS");
26488    u00042 : constant Version_32 := 16#ece6fdb6#;
26489    pragma Export (C, u00042, "system__wch_jisB");
26490    u00043 : constant Version_32 := 16#899dc581#;
26491    pragma Export (C, u00043, "system__wch_jisS");
26492    u00044 : constant Version_32 := 16#10558b11#;
26493    pragma Export (C, u00044, "ada__streamsB");
26494    u00045 : constant Version_32 := 16#2e6701ab#;
26495    pragma Export (C, u00045, "ada__streamsS");
26496    u00046 : constant Version_32 := 16#db5c917c#;
26497    pragma Export (C, u00046, "ada__io_exceptionsS");
26498    u00047 : constant Version_32 := 16#12c8cd7d#;
26499    pragma Export (C, u00047, "ada__tagsB");
26500    u00048 : constant Version_32 := 16#ce72c228#;
26501    pragma Export (C, u00048, "ada__tagsS");
26502    u00049 : constant Version_32 := 16#c3335bfd#;
26503    pragma Export (C, u00049, "system__htableB");
26504    u00050 : constant Version_32 := 16#99e5f76b#;
26505    pragma Export (C, u00050, "system__htableS");
26506    u00051 : constant Version_32 := 16#089f5cd0#;
26507    pragma Export (C, u00051, "system__string_hashB");
26508    u00052 : constant Version_32 := 16#3bbb9c15#;
26509    pragma Export (C, u00052, "system__string_hashS");
26510    u00053 : constant Version_32 := 16#807fe041#;
26511    pragma Export (C, u00053, "system__unsigned_typesS");
26512    u00054 : constant Version_32 := 16#d27be59e#;
26513    pragma Export (C, u00054, "system__val_lluB");
26514    u00055 : constant Version_32 := 16#fa8db733#;
26515    pragma Export (C, u00055, "system__val_lluS");
26516    u00056 : constant Version_32 := 16#27b600b2#;
26517    pragma Export (C, u00056, "system__val_utilB");
26518    u00057 : constant Version_32 := 16#b187f27f#;
26519    pragma Export (C, u00057, "system__val_utilS");
26520    u00058 : constant Version_32 := 16#d1060688#;
26521    pragma Export (C, u00058, "system__case_utilB");
26522    u00059 : constant Version_32 := 16#392e2d56#;
26523    pragma Export (C, u00059, "system__case_utilS");
26524    u00060 : constant Version_32 := 16#84a27f0d#;
26525    pragma Export (C, u00060, "interfaces__c_streamsB");
26526    u00061 : constant Version_32 := 16#8bb5f2c0#;
26527    pragma Export (C, u00061, "interfaces__c_streamsS");
26528    u00062 : constant Version_32 := 16#6db6928f#;
26529    pragma Export (C, u00062, "system__crtlS");
26530    u00063 : constant Version_32 := 16#4e6a342b#;
26531    pragma Export (C, u00063, "system__file_ioB");
26532    u00064 : constant Version_32 := 16#ba56a5e4#;
26533    pragma Export (C, u00064, "system__file_ioS");
26534    u00065 : constant Version_32 := 16#b7ab275c#;
26535    pragma Export (C, u00065, "ada__finalizationB");
26536    u00066 : constant Version_32 := 16#19f764ca#;
26537    pragma Export (C, u00066, "ada__finalizationS");
26538    u00067 : constant Version_32 := 16#95817ed8#;
26539    pragma Export (C, u00067, "system__finalization_rootB");
26540    u00068 : constant Version_32 := 16#52d53711#;
26541    pragma Export (C, u00068, "system__finalization_rootS");
26542    u00069 : constant Version_32 := 16#769e25e6#;
26543    pragma Export (C, u00069, "interfaces__cB");
26544    u00070 : constant Version_32 := 16#4a38bedb#;
26545    pragma Export (C, u00070, "interfaces__cS");
26546    u00071 : constant Version_32 := 16#07e6ee66#;
26547    pragma Export (C, u00071, "system__os_libB");
26548    u00072 : constant Version_32 := 16#d7b69782#;
26549    pragma Export (C, u00072, "system__os_libS");
26550    u00073 : constant Version_32 := 16#1a817b8e#;
26551    pragma Export (C, u00073, "system__stringsB");
26552    u00074 : constant Version_32 := 16#639855e7#;
26553    pragma Export (C, u00074, "system__stringsS");
26554    u00075 : constant Version_32 := 16#e0b8de29#;
26555    pragma Export (C, u00075, "system__file_control_blockS");
26556    u00076 : constant Version_32 := 16#b5b2aca1#;
26557    pragma Export (C, u00076, "system__finalization_mastersB");
26558    u00077 : constant Version_32 := 16#69316dc1#;
26559    pragma Export (C, u00077, "system__finalization_mastersS");
26560    u00078 : constant Version_32 := 16#57a37a42#;
26561    pragma Export (C, u00078, "system__address_imageB");
26562    u00079 : constant Version_32 := 16#bccbd9bb#;
26563    pragma Export (C, u00079, "system__address_imageS");
26564    u00080 : constant Version_32 := 16#7268f812#;
26565    pragma Export (C, u00080, "system__img_boolB");
26566    u00081 : constant Version_32 := 16#e8fe356a#;
26567    pragma Export (C, u00081, "system__img_boolS");
26568    u00082 : constant Version_32 := 16#d7aac20c#;
26569    pragma Export (C, u00082, "system__ioB");
26570    u00083 : constant Version_32 := 16#8365b3ce#;
26571    pragma Export (C, u00083, "system__ioS");
26572    u00084 : constant Version_32 := 16#6d4d969a#;
26573    pragma Export (C, u00084, "system__storage_poolsB");
26574    u00085 : constant Version_32 := 16#e87cc305#;
26575    pragma Export (C, u00085, "system__storage_poolsS");
26576    u00086 : constant Version_32 := 16#e34550ca#;
26577    pragma Export (C, u00086, "system__pool_globalB");
26578    u00087 : constant Version_32 := 16#c88d2d16#;
26579    pragma Export (C, u00087, "system__pool_globalS");
26580    u00088 : constant Version_32 := 16#9d39c675#;
26581    pragma Export (C, u00088, "system__memoryB");
26582    u00089 : constant Version_32 := 16#445a22b5#;
26583    pragma Export (C, u00089, "system__memoryS");
26584    u00090 : constant Version_32 := 16#6a859064#;
26585    pragma Export (C, u00090, "system__storage_pools__subpoolsB");
26586    u00091 : constant Version_32 := 16#e3b008dc#;
26587    pragma Export (C, u00091, "system__storage_pools__subpoolsS");
26588    u00092 : constant Version_32 := 16#63f11652#;
26589    pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
26590    u00093 : constant Version_32 := 16#fe2f4b3a#;
26591    pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
26593    --  BEGIN ELABORATION ORDER
26594    --  ada%s
26595    --  interfaces%s
26596    --  system%s
26597    --  system.case_util%s
26598    --  system.case_util%b
26599    --  system.htable%s
26600    --  system.img_bool%s
26601    --  system.img_bool%b
26602    --  system.img_int%s
26603    --  system.img_int%b
26604    --  system.io%s
26605    --  system.io%b
26606    --  system.parameters%s
26607    --  system.parameters%b
26608    --  system.crtl%s
26609    --  interfaces.c_streams%s
26610    --  interfaces.c_streams%b
26611    --  system.standard_library%s
26612    --  system.exceptions_debug%s
26613    --  system.exceptions_debug%b
26614    --  system.storage_elements%s
26615    --  system.storage_elements%b
26616    --  system.stack_checking%s
26617    --  system.stack_checking%b
26618    --  system.string_hash%s
26619    --  system.string_hash%b
26620    --  system.htable%b
26621    --  system.strings%s
26622    --  system.strings%b
26623    --  system.os_lib%s
26624    --  system.traceback_entries%s
26625    --  system.traceback_entries%b
26626    --  ada.exceptions%s
26627    --  system.soft_links%s
26628    --  system.unsigned_types%s
26629    --  system.val_llu%s
26630    --  system.val_util%s
26631    --  system.val_util%b
26632    --  system.val_llu%b
26633    --  system.wch_con%s
26634    --  system.wch_con%b
26635    --  system.wch_cnv%s
26636    --  system.wch_jis%s
26637    --  system.wch_jis%b
26638    --  system.wch_cnv%b
26639    --  system.wch_stw%s
26640    --  system.wch_stw%b
26641    --  ada.exceptions.last_chance_handler%s
26642    --  ada.exceptions.last_chance_handler%b
26643    --  system.address_image%s
26644    --  system.exception_table%s
26645    --  system.exception_table%b
26646    --  ada.io_exceptions%s
26647    --  ada.tags%s
26648    --  ada.streams%s
26649    --  ada.streams%b
26650    --  interfaces.c%s
26651    --  system.exceptions%s
26652    --  system.exceptions%b
26653    --  system.exceptions.machine%s
26654    --  system.finalization_root%s
26655    --  system.finalization_root%b
26656    --  ada.finalization%s
26657    --  ada.finalization%b
26658    --  system.storage_pools%s
26659    --  system.storage_pools%b
26660    --  system.finalization_masters%s
26661    --  system.storage_pools.subpools%s
26662    --  system.storage_pools.subpools.finalization%s
26663    --  system.storage_pools.subpools.finalization%b
26664    --  system.memory%s
26665    --  system.memory%b
26666    --  system.standard_library%b
26667    --  system.pool_global%s
26668    --  system.pool_global%b
26669    --  system.file_control_block%s
26670    --  system.file_io%s
26671    --  system.secondary_stack%s
26672    --  system.file_io%b
26673    --  system.storage_pools.subpools%b
26674    --  system.finalization_masters%b
26675    --  interfaces.c%b
26676    --  ada.tags%b
26677    --  system.soft_links%b
26678    --  system.os_lib%b
26679    --  system.secondary_stack%b
26680    --  system.address_image%b
26681    --  system.traceback%s
26682    --  ada.exceptions%b
26683    --  system.traceback%b
26684    --  ada.text_io%s
26685    --  ada.text_io%b
26686    --  hello%b
26687    --  END ELABORATION ORDER
26689 end ada_main;
26690 @end example
26692 @example
26693 pragma Ada_95;
26694 --  The following source file name pragmas allow the generated file
26695 --  names to be unique for different main programs. They are needed
26696 --  since the package name will always be Ada_Main.
26698 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26699 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26701 pragma Suppress (Overflow_Check);
26702 with Ada.Exceptions;
26704 --  Generated package body for Ada_Main starts here
26706 package body ada_main is
26707    pragma Warnings (Off);
26709    --  These values are reference counter associated to units which have
26710    --  been elaborated. It is also used to avoid elaborating the
26711    --  same unit twice.
26713    E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
26714    E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
26715    E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
26716    E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
26717    E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
26718    E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
26719    E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
26720    E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
26721    E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
26722    E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
26723    E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
26724    E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
26725    E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
26726    E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
26727    E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
26728    E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
26729    E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
26730    E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
26732    Local_Priority_Specific_Dispatching : constant String := "";
26733    Local_Interrupt_States : constant String := "";
26735    Is_Elaborated : Boolean := False;
26737    procedure finalize_library is
26738    begin
26739       E06 := E06 - 1;
26740       declare
26741          procedure F1;
26742          pragma Import (Ada, F1, "ada__text_io__finalize_spec");
26743       begin
26744          F1;
26745       end;
26746       E77 := E77 - 1;
26747       E91 := E91 - 1;
26748       declare
26749          procedure F2;
26750          pragma Import (Ada, F2, "system__file_io__finalize_body");
26751       begin
26752          E64 := E64 - 1;
26753          F2;
26754       end;
26755       declare
26756          procedure F3;
26757          pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
26758       begin
26759          E75 := E75 - 1;
26760          F3;
26761       end;
26762       E87 := E87 - 1;
26763       declare
26764          procedure F4;
26765          pragma Import (Ada, F4, "system__pool_global__finalize_spec");
26766       begin
26767          F4;
26768       end;
26769       declare
26770          procedure F5;
26771          pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
26772       begin
26773          F5;
26774       end;
26775       declare
26776          procedure F6;
26777          pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
26778       begin
26779          F6;
26780       end;
26781       declare
26782          procedure Reraise_Library_Exception_If_Any;
26783          pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
26784       begin
26785          Reraise_Library_Exception_If_Any;
26786       end;
26787    end finalize_library;
26789    -------------
26790    -- adainit --
26791    -------------
26793    procedure adainit is
26795       Main_Priority : Integer;
26796       pragma Import (C, Main_Priority, "__gl_main_priority");
26797       Time_Slice_Value : Integer;
26798       pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
26799       WC_Encoding : Character;
26800       pragma Import (C, WC_Encoding, "__gl_wc_encoding");
26801       Locking_Policy : Character;
26802       pragma Import (C, Locking_Policy, "__gl_locking_policy");
26803       Queuing_Policy : Character;
26804       pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
26805       Task_Dispatching_Policy : Character;
26806       pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
26807       Priority_Specific_Dispatching : System.Address;
26808       pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
26809       Num_Specific_Dispatching : Integer;
26810       pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
26811       Main_CPU : Integer;
26812       pragma Import (C, Main_CPU, "__gl_main_cpu");
26813       Interrupt_States : System.Address;
26814       pragma Import (C, Interrupt_States, "__gl_interrupt_states");
26815       Num_Interrupt_States : Integer;
26816       pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
26817       Unreserve_All_Interrupts : Integer;
26818       pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
26819       Detect_Blocking : Integer;
26820       pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
26821       Default_Stack_Size : Integer;
26822       pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
26823       Leap_Seconds_Support : Integer;
26824       pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
26826       procedure Runtime_Initialize;
26827       pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
26829       Finalize_Library_Objects : No_Param_Proc;
26830       pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
26832    --  Start of processing for adainit
26834    begin
26836       --  Record various information for this partition.  The values
26837       --  are derived by the binder from information stored in the ali
26838       --  files by the compiler.
26840       if Is_Elaborated then
26841          return;
26842       end if;
26843       Is_Elaborated := True;
26844       Main_Priority := -1;
26845       Time_Slice_Value := -1;
26846       WC_Encoding := 'b';
26847       Locking_Policy := ' ';
26848       Queuing_Policy := ' ';
26849       Task_Dispatching_Policy := ' ';
26850       Priority_Specific_Dispatching :=
26851         Local_Priority_Specific_Dispatching'Address;
26852       Num_Specific_Dispatching := 0;
26853       Main_CPU := -1;
26854       Interrupt_States := Local_Interrupt_States'Address;
26855       Num_Interrupt_States := 0;
26856       Unreserve_All_Interrupts := 0;
26857       Detect_Blocking := 0;
26858       Default_Stack_Size := -1;
26859       Leap_Seconds_Support := 0;
26861       Runtime_Initialize;
26863       Finalize_Library_Objects := finalize_library'access;
26865       --  Now we have the elaboration calls for all units in the partition.
26866       --  The Elab_Spec and Elab_Body attributes generate references to the
26867       --  implicit elaboration procedures generated by the compiler for
26868       --  each unit that requires elaboration. Increment a counter of
26869       --  reference for each unit.
26871       System.Soft_Links'Elab_Spec;
26872       System.Exception_Table'Elab_Body;
26873       E23 := E23 + 1;
26874       Ada.Io_Exceptions'Elab_Spec;
26875       E46 := E46 + 1;
26876       Ada.Tags'Elab_Spec;
26877       Ada.Streams'Elab_Spec;
26878       E45 := E45 + 1;
26879       Interfaces.C'Elab_Spec;
26880       System.Exceptions'Elab_Spec;
26881       E25 := E25 + 1;
26882       System.Finalization_Root'Elab_Spec;
26883       E68 := E68 + 1;
26884       Ada.Finalization'Elab_Spec;
26885       E66 := E66 + 1;
26886       System.Storage_Pools'Elab_Spec;
26887       E85 := E85 + 1;
26888       System.Finalization_Masters'Elab_Spec;
26889       System.Storage_Pools.Subpools'Elab_Spec;
26890       System.Pool_Global'Elab_Spec;
26891       E87 := E87 + 1;
26892       System.File_Control_Block'Elab_Spec;
26893       E75 := E75 + 1;
26894       System.File_Io'Elab_Body;
26895       E64 := E64 + 1;
26896       E91 := E91 + 1;
26897       System.Finalization_Masters'Elab_Body;
26898       E77 := E77 + 1;
26899       E70 := E70 + 1;
26900       Ada.Tags'Elab_Body;
26901       E48 := E48 + 1;
26902       System.Soft_Links'Elab_Body;
26903       E13 := E13 + 1;
26904       System.Os_Lib'Elab_Body;
26905       E72 := E72 + 1;
26906       System.Secondary_Stack'Elab_Body;
26907       E17 := E17 + 1;
26908       Ada.Text_Io'Elab_Spec;
26909       Ada.Text_Io'Elab_Body;
26910       E06 := E06 + 1;
26911    end adainit;
26913    --------------
26914    -- adafinal --
26915    --------------
26917    procedure adafinal is
26918       procedure s_stalib_adafinal;
26919       pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
26921       procedure Runtime_Finalize;
26922       pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
26924    begin
26925       if not Is_Elaborated then
26926          return;
26927       end if;
26928       Is_Elaborated := False;
26929       Runtime_Finalize;
26930       s_stalib_adafinal;
26931    end adafinal;
26933    --  We get to the main program of the partition by using
26934    --  pragma Import because if we try to with the unit and
26935    --  call it Ada style, then not only do we waste time
26936    --  recompiling it, but also, we don't really know the right
26937    --  switches (e.g.@@: identifier character set) to be used
26938    --  to compile it.
26940    procedure Ada_Main_Program;
26941    pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26943    ----------
26944    -- main --
26945    ----------
26947    --  main is actually a function, as in the ANSI C standard,
26948    --  defined to return the exit status. The three parameters
26949    --  are the argument count, argument values and environment
26950    --  pointer.
26952    function main
26953      (argc : Integer;
26954       argv : System.Address;
26955       envp : System.Address)
26956       return Integer
26957    is
26958       --  The initialize routine performs low level system
26959       --  initialization using a standard library routine which
26960       --  sets up signal handling and performs any other
26961       --  required setup. The routine can be found in file
26962       --  a-init.c.
26964       procedure initialize;
26965       pragma Import (C, initialize, "__gnat_initialize");
26967       --  The finalize routine performs low level system
26968       --  finalization using a standard library routine. The
26969       --  routine is found in file a-final.c and in the standard
26970       --  distribution is a dummy routine that does nothing, so
26971       --  really this is a hook for special user finalization.
26973       procedure finalize;
26974       pragma Import (C, finalize, "__gnat_finalize");
26976       --  The following is to initialize the SEH exceptions
26978       SEH : aliased array (1 .. 2) of Integer;
26980       Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
26981       pragma Volatile (Ensure_Reference);
26983    --  Start of processing for main
26985    begin
26986       --  Save global variables
26988       gnat_argc := argc;
26989       gnat_argv := argv;
26990       gnat_envp := envp;
26992       --  Call low level system initialization
26994       Initialize (SEH'Address);
26996       --  Call our generated Ada initialization routine
26998       adainit;
27000       --  Now we call the main program of the partition
27002       Ada_Main_Program;
27004       --  Perform Ada finalization
27006       adafinal;
27008       --  Perform low level system finalization
27010       Finalize;
27012       --  Return the proper exit status
27013       return (gnat_exit_status);
27014    end;
27016 --  This section is entirely comments, so it has no effect on the
27017 --  compilation of the Ada_Main package. It provides the list of
27018 --  object files and linker options, as well as some standard
27019 --  libraries needed for the link. The gnatlink utility parses
27020 --  this b~hello.adb file to read these comment lines to generate
27021 --  the appropriate command line arguments for the call to the
27022 --  system linker. The BEGIN/END lines are used for sentinels for
27023 --  this parsing operation.
27025 --  The exact file names will of course depend on the environment,
27026 --  host/target and location of files on the host system.
27028 -- BEGIN Object file/option list
27029    --   ./hello.o
27030    --   -L./
27031    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27032    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27033 -- END Object file/option list
27035 end ada_main;
27036 @end example
27038 The Ada code in the above example is exactly what is generated by the
27039 binder. We have added comments to more clearly indicate the function
27040 of each part of the generated @code{Ada_Main} package.
27042 The code is standard Ada in all respects, and can be processed by any
27043 tools that handle Ada. In particular, it is possible to use the debugger
27044 in Ada mode to debug the generated @code{Ada_Main} package. For example,
27045 suppose that for reasons that you do not understand, your program is crashing
27046 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27047 you can place a breakpoint on the call:
27049 @quotation
27051 @example
27052 Ada.Text_Io'Elab_Body;
27053 @end example
27054 @end quotation
27056 and trace the elaboration routine for this package to find out where
27057 the problem might be (more usually of course you would be debugging
27058 elaboration code in your own application).
27060 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
27062 @node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
27063 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order-handling-in-gnat}@anchor{f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat doc}@anchor{230}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id1}@anchor{231}
27064 @chapter Elaboration Order Handling in GNAT
27067 @geindex Order of elaboration
27069 @geindex Elaboration control
27071 This appendix describes the handling of elaboration code in Ada and GNAT, and
27072 discusses how the order of elaboration of program units can be controlled in
27073 GNAT, either automatically or with explicit programming features.
27075 @menu
27076 * Elaboration Code:: 
27077 * Elaboration Order:: 
27078 * Checking the Elaboration Order:: 
27079 * Controlling the Elaboration Order in Ada:: 
27080 * Controlling the Elaboration Order in GNAT:: 
27081 * Common Elaboration-model Traits:: 
27082 * Dynamic Elaboration Model in GNAT:: 
27083 * Static Elaboration Model in GNAT:: 
27084 * SPARK Elaboration Model in GNAT:: 
27085 * Mixing Elaboration Models:: 
27086 * Elaboration Circularities:: 
27087 * Resolving Elaboration Circularities:: 
27088 * Resolving Task Issues:: 
27089 * Elaboration-related Compiler Switches:: 
27090 * Summary of Procedures for Elaboration Control:: 
27091 * Inspecting the Chosen Elaboration Order:: 
27093 @end menu
27095 @node Elaboration Code,Elaboration Order,,Elaboration Order Handling in GNAT
27096 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{232}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{233}
27097 @section Elaboration Code
27100 Ada defines the term @emph{execution} as the process by which a construct achieves
27101 its run-time effect. This process is also referred to as @strong{elaboration} for
27102 declarations and @emph{evaluation} for expressions.
27104 The execution model in Ada allows for certain sections of an Ada program to be
27105 executed prior to execution of the program itself, primarily with the intent of
27106 initializing data. These sections are referred to as @strong{elaboration code}.
27107 Elaboration code is executed as follows:
27110 @itemize *
27112 @item 
27113 All partitions of an Ada program are executed in parallel with one another,
27114 possibly in a separate address space, and possibly on a separate computer.
27116 @item 
27117 The execution of a partition involves running the environment task for that
27118 partition.
27120 @item 
27121 The environment task executes all elaboration code (if available) for all
27122 units within that partition. This code is said to be executed at
27123 @strong{elaboration time}.
27125 @item 
27126 The environment task executes the Ada program (if available) for that
27127 partition.
27128 @end itemize
27130 In addition to the Ada terminology, this appendix defines the following terms:
27133 @itemize *
27135 @item 
27136 @emph{Scenario}
27138 A construct that is elaborated or executed by elaboration code is referred to
27139 as an @emph{elaboration scenario} or simply a @strong{scenario}. GNAT recognizes the
27140 following scenarios:
27143 @itemize -
27145 @item 
27146 @code{'Access} of entries, operators, and subprograms
27148 @item 
27149 Activation of tasks
27151 @item 
27152 Calls to entries, operators, and subprograms
27154 @item 
27155 Instantiations of generic templates
27156 @end itemize
27158 @item 
27159 @emph{Target}
27161 A construct elaborated by a scenario is referred to as @emph{elaboration target}
27162 or simply @strong{target}. GNAT recognizes the following targets:
27165 @itemize -
27167 @item 
27168 For @code{'Access} of entries, operators, and subprograms, the target is the
27169 entry, operator, or subprogram being aliased.
27171 @item 
27172 For activation of tasks, the target is the task body
27174 @item 
27175 For calls to entries, operators, and subprograms, the target is the entry,
27176 operator, or subprogram being invoked.
27178 @item 
27179 For instantiations of generic templates, the target is the generic template
27180 being instantiated.
27181 @end itemize
27182 @end itemize
27184 Elaboration code may appear in two distinct contexts:
27187 @itemize *
27189 @item 
27190 @emph{Library level}
27192 A scenario appears at the library level when it is encapsulated by a package
27193 [body] compilation unit, ignoring any other package [body] declarations in
27194 between.
27196 @example
27197 with Server;
27198 package Client is
27199    procedure Proc;
27201    package Nested is
27202       Val : ... := Server.Func;
27203    end Nested;
27204 end Client;
27205 @end example
27207 In the example above, the call to @code{Server.Func} is an elaboration scenario
27208 because it appears at the library level of package @code{Client}. Note that the
27209 declaration of package @code{Nested} is ignored according to the definition
27210 given above. As a result, the call to @code{Server.Func} will be executed when
27211 the spec of unit @code{Client} is elaborated.
27213 @item 
27214 @emph{Package body statements}
27216 A scenario appears within the statement sequence of a package body when it is
27217 bounded by the region starting from the @code{begin} keyword of the package body
27218 and ending at the @code{end} keyword of the package body.
27220 @example
27221 package body Client is
27222    procedure Proc is
27223    begin
27224       ...
27225    end Proc;
27226 begin
27227    Proc;
27228 end Client;
27229 @end example
27231 In the example above, the call to @code{Proc} is an elaboration scenario because
27232 it appears within the statement sequence of package body @code{Client}. As a
27233 result, the call to @code{Proc} will be executed when the body of @code{Client} is
27234 elaborated.
27235 @end itemize
27237 @node Elaboration Order,Checking the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
27238 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order}@anchor{234}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{235}
27239 @section Elaboration Order
27242 The sequence by which the elaboration code of all units within a partition is
27243 executed is referred to as @strong{elaboration order}.
27245 Within a single unit, elaboration code is executed in sequential order.
27247 @example
27248 package body Client is
27249    Result : ... := Server.Func;
27251    procedure Proc is
27252       package Inst is new Server.Gen;
27253    begin
27254       Inst.Eval (Result);
27255    end Proc;
27256 begin
27257    Proc;
27258 end Client;
27259 @end example
27261 In the example above, the elaboration order within package body @code{Client} is
27262 as follows:
27265 @enumerate 
27267 @item 
27268 The object declaration of @code{Result} is elaborated.
27271 @itemize *
27273 @item 
27274 Function @code{Server.Func} is invoked.
27275 @end itemize
27277 @item 
27278 The subprogram body of @code{Proc} is elaborated.
27280 @item 
27281 Procedure @code{Proc} is invoked.
27284 @itemize *
27286 @item 
27287 Generic unit @code{Server.Gen} is instantiated as @code{Inst}.
27289 @item 
27290 Instance @code{Inst} is elaborated.
27292 @item 
27293 Procedure @code{Inst.Eval} is invoked.
27294 @end itemize
27295 @end enumerate
27297 The elaboration order of all units within a partition depends on the following
27298 factors:
27301 @itemize *
27303 @item 
27304 @emph{with}ed units
27306 @item 
27307 purity of units
27309 @item 
27310 preelaborability of units
27312 @item 
27313 presence of elaboration control pragmas
27314 @end itemize
27316 A program may have several elaboration orders depending on its structure.
27318 @example
27319 package Server is
27320    function Func (Index : Integer) return Integer;
27321 end Server;
27322 @end example
27324 @example
27325 package body Server is
27326    Results : array (1 .. 5) of Integer := (1, 2, 3, 4, 5);
27328    function Func (Index : Integer) return Integer is
27329    begin
27330       return Results (Index);
27331    end Func;
27332 end Server;
27333 @end example
27335 @example
27336 with Server;
27337 package Client is
27338    Val : constant Integer := Server.Func (3);
27339 end Client;
27340 @end example
27342 @example
27343 with Client;
27344 procedure Main is begin null; end Main;
27345 @end example
27347 The following elaboration order exhibits a fundamental problem referred to as
27348 @emph{access-before-elaboration} or simply @strong{ABE}.
27350 @example
27351 spec of Server
27352 spec of Client
27353 body of Server
27354 body of Main
27355 @end example
27357 The elaboration of @code{Server}'s spec materializes function @code{Func}, making it
27358 callable. The elaboration of @code{Client}'s spec elaborates the declaration of
27359 @code{Val}. This invokes function @code{Server.Func}, however the body of
27360 @code{Server.Func} has not been elaborated yet because @code{Server}'s body comes
27361 after @code{Client}'s spec in the elaboration order. As a result, the value of
27362 constant @code{Val} is now undefined.
27364 Without any guarantees from the language, an undetected ABE problem may hinder
27365 proper initialization of data, which in turn may lead to undefined behavior at
27366 run time. To prevent such ABE problems, Ada employs dynamic checks in the same
27367 vein as index or null exclusion checks. A failed ABE check raises exception
27368 @code{Program_Error}.
27370 The following elaboration order avoids the ABE problem and the program can be
27371 successfully elaborated.
27373 @example
27374 spec of Server
27375 body of Server
27376 spec of Client
27377 body of Main
27378 @end example
27380 Ada states that a total elaboration order must exist, but it does not define
27381 what this order is. A compiler is thus tasked with choosing a suitable
27382 elaboration order which satisfies the dependencies imposed by @emph{with} clauses,
27383 unit categorization, and elaboration control pragmas. Ideally an order which
27384 avoids ABE problems should be chosen, however a compiler may not always find
27385 such an order due to complications with respect to control and data flow.
27387 @node Checking the Elaboration Order,Controlling the Elaboration Order in Ada,Elaboration Order,Elaboration Order Handling in GNAT
27388 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{236}@anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{237}
27389 @section Checking the Elaboration Order
27392 To avoid placing the entire elaboration order burden on the programmer, Ada
27393 provides three lines of defense:
27396 @itemize *
27398 @item 
27399 @emph{Static semantics}
27401 Static semantic rules restrict the possible choice of elaboration order. For
27402 instance, if unit Client @emph{with}s unit Server, then the spec of Server is
27403 always elaborated prior to Client. The same principle applies to child units
27404 - the spec of a parent unit is always elaborated prior to the child unit.
27406 @item 
27407 @emph{Dynamic semantics}
27409 Dynamic checks are performed at run time, to ensure that a target is
27410 elaborated prior to a scenario that executes it, thus avoiding ABE problems.
27411 A failed run-time check raises exception @code{Program_Error}. The following
27412 restrictions apply:
27415 @itemize -
27417 @item 
27418 @emph{Restrictions on calls}
27420 An entry, operator, or subprogram can be called from elaboration code only
27421 when the corresponding body has been elaborated.
27423 @item 
27424 @emph{Restrictions on instantiations}
27426 A generic unit can be instantiated by elaboration code only when the
27427 corresponding body has been elaborated.
27429 @item 
27430 @emph{Restrictions on task activation}
27432 A task can be activated by elaboration code only when the body of the
27433 associated task type has been elaborated.
27434 @end itemize
27436 The restrictions above can be summarized by the following rule:
27438 @emph{If a target has a body, then this body must be elaborated prior to the
27439 execution of the scenario that invokes, instantiates, or activates the
27440 target.}
27442 @item 
27443 @emph{Elaboration control}
27445 Pragmas are provided for the programmer to specify the desired elaboration
27446 order.
27447 @end itemize
27449 @node Controlling the Elaboration Order in Ada,Controlling the Elaboration Order in GNAT,Checking the Elaboration Order,Elaboration Order Handling in GNAT
27450 @anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-ada}@anchor{238}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{239}
27451 @section Controlling the Elaboration Order in Ada
27454 Ada provides several idioms and pragmas to aid the programmer with specifying
27455 the desired elaboration order and avoiding ABE problems altogether.
27458 @itemize *
27460 @item 
27461 @emph{Packages without a body}
27463 A library package which does not require a completing body does not suffer
27464 from ABE problems.
27466 @example
27467 package Pack is
27468    generic
27469       type Element is private;
27470    package Containers is
27471       type Element_Array is array (1 .. 10) of Element;
27472    end Containers;
27473 end Pack;
27474 @end example
27476 In the example above, package @code{Pack} does not require a body because it
27477 does not contain any constructs which require completion in a body. As a
27478 result, generic @code{Pack.Containers} can be instantiated without encountering
27479 any ABE problems.
27480 @end itemize
27482 @geindex pragma Pure
27485 @itemize *
27487 @item 
27488 @emph{pragma Pure}
27490 Pragma @code{Pure} places sufficient restrictions on a unit to guarantee that no
27491 scenario within the unit can result in an ABE problem.
27492 @end itemize
27494 @geindex pragma Preelaborate
27497 @itemize *
27499 @item 
27500 @emph{pragma Preelaborate}
27502 Pragma @code{Preelaborate} is slightly less restrictive than pragma @code{Pure},
27503 but still strong enough to prevent ABE problems within a unit.
27504 @end itemize
27506 @geindex pragma Elaborate_Body
27509 @itemize *
27511 @item 
27512 @emph{pragma Elaborate_Body}
27514 Pragma @code{Elaborate_Body} requires that the body of a unit is elaborated
27515 immediately after its spec. This restriction guarantees that no client
27516 scenario can execute a server target before the target body has been
27517 elaborated because the spec and body are effectively "glued" together.
27519 @example
27520 package Server is
27521    pragma Elaborate_Body;
27523    function Func return Integer;
27524 end Server;
27525 @end example
27527 @example
27528 package body Server is
27529    function Func return Integer is
27530    begin
27531       ...
27532    end Func;
27533 end Server;
27534 @end example
27536 @example
27537 with Server;
27538 package Client is
27539    Val : constant Integer := Server.Func;
27540 end Client;
27541 @end example
27543 In the example above, pragma @code{Elaborate_Body} guarantees the following
27544 elaboration order:
27546 @example
27547 spec of Server
27548 body of Server
27549 spec of Client
27550 @end example
27552 because the spec of @code{Server} must be elaborated prior to @code{Client} by
27553 virtue of the @emph{with} clause, and in addition the body of @code{Server} must be
27554 elaborated immediately after the spec of @code{Server}.
27556 Removing pragma @code{Elaborate_Body} could result in the following incorrect
27557 elaboration order:
27559 @example
27560 spec of Server
27561 spec of Client
27562 body of Server
27563 @end example
27565 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func} has
27566 not been elaborated yet.
27567 @end itemize
27569 The pragmas outlined above allow a server unit to guarantee safe elaboration
27570 use by client units. Thus it is a good rule to mark units as @code{Pure} or
27571 @code{Preelaborate}, and if this is not possible, mark them as @code{Elaborate_Body}.
27573 There are however situations where @code{Pure}, @code{Preelaborate}, and
27574 @code{Elaborate_Body} are not applicable. Ada provides another set of pragmas for
27575 use by client units to help ensure the elaboration safety of server units they
27576 depend on.
27578 @geindex pragma Elaborate (Unit)
27581 @itemize *
27583 @item 
27584 @emph{pragma Elaborate (Unit)}
27586 Pragma @code{Elaborate} can be placed in the context clauses of a unit, after a
27587 @emph{with} clause. It guarantees that both the spec and body of its argument will
27588 be elaborated prior to the unit with the pragma. Note that other unrelated
27589 units may be elaborated in between the spec and the body.
27591 @example
27592 package Server is
27593    function Func return Integer;
27594 end Server;
27595 @end example
27597 @example
27598 package body Server is
27599    function Func return Integer is
27600    begin
27601       ...
27602    end Func;
27603 end Server;
27604 @end example
27606 @example
27607 with Server;
27608 pragma Elaborate (Server);
27609 package Client is
27610    Val : constant Integer := Server.Func;
27611 end Client;
27612 @end example
27614 In the example above, pragma @code{Elaborate} guarantees the following
27615 elaboration order:
27617 @example
27618 spec of Server
27619 body of Server
27620 spec of Client
27621 @end example
27623 Removing pragma @code{Elaborate} could result in the following incorrect
27624 elaboration order:
27626 @example
27627 spec of Server
27628 spec of Client
27629 body of Server
27630 @end example
27632 where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func}
27633 has not been elaborated yet.
27634 @end itemize
27636 @geindex pragma Elaborate_All (Unit)
27639 @itemize *
27641 @item 
27642 @emph{pragma Elaborate_All (Unit)}
27644 Pragma @code{Elaborate_All} is placed in the context clauses of a unit, after
27645 a @emph{with} clause. It guarantees that both the spec and body of its argument
27646 will be elaborated prior to the unit with the pragma, as well as all units
27647 @emph{with}ed by the spec and body of the argument, recursively. Note that other
27648 unrelated units may be elaborated in between the spec and the body.
27650 @example
27651 package Math is
27652    function Factorial (Val : Natural) return Natural;
27653 end Math;
27654 @end example
27656 @example
27657 package body Math is
27658    function Factorial (Val : Natural) return Natural is
27659    begin
27660       ...;
27661    end Factorial;
27662 end Math;
27663 @end example
27665 @example
27666 package Computer is
27667    type Operation_Kind is (None, Op_Factorial);
27669    function Compute
27670      (Val : Natural;
27671       Op  : Operation_Kind) return Natural;
27672 end Computer;
27673 @end example
27675 @example
27676 with Math;
27677 package body Computer is
27678    function Compute
27679      (Val : Natural;
27680       Op  : Operation_Kind) return Natural
27681    is
27682       if Op = Op_Factorial then
27683          return Math.Factorial (Val);
27684       end if;
27686       return 0;
27687    end Compute;
27688 end Computer;
27689 @end example
27691 @example
27692 with Computer;
27693 pragma Elaborate_All (Computer);
27694 package Client is
27695    Val : constant Natural :=
27696            Computer.Compute (123, Computer.Op_Factorial);
27697 end Client;
27698 @end example
27700 In the example above, pragma @code{Elaborate_All} can result in the following
27701 elaboration order:
27703 @example
27704 spec of Math
27705 body of Math
27706 spec of Computer
27707 body of Computer
27708 spec of Client
27709 @end example
27711 Note that there are several allowable suborders for the specs and bodies of
27712 @code{Math} and @code{Computer}, but the point is that these specs and bodies will
27713 be elaborated prior to @code{Client}.
27715 Removing pragma @code{Elaborate_All} could result in the following incorrect
27716 elaboration order
27718 @example
27719 spec of Math
27720 spec of Computer
27721 body of Computer
27722 spec of Client
27723 body of Math
27724 @end example
27726 where @code{Client} invokes @code{Computer.Compute}, which in turn invokes
27727 @code{Math.Factorial}, but the body of @code{Math.Factorial} has not been
27728 elaborated yet.
27729 @end itemize
27731 All pragmas shown above can be summarized by the following rule:
27733 @emph{If a client unit elaborates a server target directly or indirectly, then if
27734 the server unit requires a body and does not have pragma Pure, Preelaborate,
27735 or Elaborate_Body, then the client unit should have pragma Elaborate or
27736 Elaborate_All for the server unit.}
27738 If the rule outlined above is not followed, then a program may fall in one of
27739 the following states:
27742 @itemize *
27744 @item 
27745 @emph{No elaboration order exists}
27747 In this case a compiler must diagnose the situation, and refuse to build an
27748 executable program.
27750 @item 
27751 @emph{One or more incorrect elaboration orders exist}
27753 In this case a compiler can build an executable program, but
27754 @code{Program_Error} will be raised when the program is run.
27756 @item 
27757 @emph{Several elaboration orders exist, some correct, some incorrect}
27759 In this case the programmer has not controlled the elaboration order. As a
27760 result, a compiler may or may not pick one of the correct orders, and the
27761 program may or may not raise @code{Program_Error} when it is run. This is the
27762 worst possible state because the program may fail on another compiler, or
27763 even another version of the same compiler.
27765 @item 
27766 @emph{One or more correct orders exist}
27768 In this case a compiler can build an executable program, and the program is
27769 run successfully. This state may be guaranteed by following the outlined
27770 rules, or may be the result of good program architecture.
27771 @end itemize
27773 Note that one additional advantage of using @code{Elaborate} and @code{Elaborate_All}
27774 is that the program continues to stay in the last state (one or more correct
27775 orders exist) even if maintenance changes the bodies of targets.
27777 @node Controlling the Elaboration Order in GNAT,Common Elaboration-model Traits,Controlling the Elaboration Order in Ada,Elaboration Order Handling in GNAT
27778 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{23a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-gnat}@anchor{23b}
27779 @section Controlling the Elaboration Order in GNAT
27782 In addition to Ada semantics and rules synthesized from them, GNAT offers
27783 three elaboration models to aid the programmer with specifying the correct
27784 elaboration order and to diagnose elaboration problems.
27786 @geindex Dynamic elaboration model
27789 @itemize *
27791 @item 
27792 @emph{Dynamic elaboration model}
27794 This is the most permissive of the three elaboration models. When the
27795 dynamic model is in effect, GNAT assumes that all code within all units in
27796 a partition is elaboration code. GNAT performs very few diagnostics and
27797 generates run-time checks to verify the elaboration order of a program. This
27798 behavior is identical to that specified by the Ada Reference Manual. The
27799 dynamic model is enabled with compiler switch @code{-gnatE}.
27800 @end itemize
27802 @geindex Static elaboration model
27805 @itemize *
27807 @item 
27808 @emph{Static elaboration model}
27810 This is the middle ground of the three models. When the static model is in
27811 effect, GNAT performs extensive diagnostics on a unit-by-unit basis for all
27812 scenarios that elaborate or execute internal targets. GNAT also generates
27813 run-time checks for all external targets and for all scenarios that may
27814 exhibit ABE problems. Finally, GNAT installs implicit @code{Elaborate} and
27815 @code{Elaborate_All} pragmas for server units based on the dependencies of
27816 client units. The static model is the default model in GNAT.
27817 @end itemize
27819 @geindex SPARK elaboration model
27822 @itemize *
27824 @item 
27825 @emph{SPARK elaboration model}
27827 This is the most conservative of the three models and enforces the SPARK
27828 rules of elaboration as defined in the SPARK Reference Manual, section 7.7.
27829 The SPARK model is in effect only when a scenario and a target reside in a
27830 region subject to SPARK_Mode On, otherwise the dynamic or static model is in
27831 effect.
27832 @end itemize
27834 @node Common Elaboration-model Traits,Dynamic Elaboration Model in GNAT,Controlling the Elaboration Order in GNAT,Elaboration Order Handling in GNAT
27835 @anchor{gnat_ugn/elaboration_order_handling_in_gnat common-elaboration-model-traits}@anchor{23c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{23d}
27836 @section Common Elaboration-model Traits
27839 All three GNAT models are able to detect elaboration problems related to
27840 dispatching calls and a particular kind of ABE referred to as @emph{guaranteed ABE}.
27843 @itemize *
27845 @item 
27846 @emph{Dispatching calls}
27848 GNAT installs run-time checks for each primitive subprogram of each tagged
27849 type defined in a partition on the assumption that a dispatching call
27850 invoked at elaboration time will execute one of these primitives. As a
27851 result, a dispatching call that executes a primitive whose body has not
27852 been elaborated yet will raise exception @code{Program_Error} at run time. The
27853 checks can be suppressed using pragma @code{Suppress (Elaboration_Check)}.
27855 @item 
27856 @emph{Guaranteed ABE}
27858 A guaranteed ABE arises when the body of a target is not elaborated early
27859 enough, and causes all scenarios that directly execute the target to fail.
27861 @example
27862 package body Guaranteed_ABE is
27863    function ABE return Integer;
27865    Val : constant Integer := ABE;
27867    function ABE return Integer is
27868    begin
27869       ...
27870    end ABE;
27871 end Guaranteed_ABE;
27872 @end example
27874 In the example above, the elaboration of @code{Guaranteed_ABE}'s body elaborates
27875 the declaration of @code{Val}. This invokes function @code{ABE}, however the body
27876 of @code{ABE} has not been elaborated yet. GNAT emits similar diagnostics in all
27877 three models:
27879 @example
27880 1. package body Guaranteed_ABE is
27881 2.    function ABE return Integer;
27883 4.    Val : constant Integer := ABE;
27884                                 |
27885    >>> warning: cannot call "ABE" before body seen
27886    >>> warning: Program_Error will be raised at run time
27889 6.    function ABE return Integer is
27890 7.    begin
27891 8.       ...
27892 9.    end ABE;
27893 10. end Guaranteed_ABE;
27894 @end example
27895 @end itemize
27897 Note that GNAT emits warnings rather than hard errors whenever it encounters an
27898 elaboration problem. This is because the elaboration model in effect may be too
27899 conservative, or a particular scenario may not be elaborated or executed due to
27900 data and control flow. The warnings can be suppressed with compiler switch
27901 @code{-gnatws}.
27903 @node Dynamic Elaboration Model in GNAT,Static Elaboration Model in GNAT,Common Elaboration-model Traits,Elaboration Order Handling in GNAT
27904 @anchor{gnat_ugn/elaboration_order_handling_in_gnat dynamic-elaboration-model-in-gnat}@anchor{23e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{23f}
27905 @section Dynamic Elaboration Model in GNAT
27908 The dynamic model assumes that all code within all units in a partition is
27909 elaboration code. As a result, run-time checks are installed for each scenario
27910 regardless of whether the target is internal or external. The checks can be
27911 suppressed using pragma @code{Suppress (Elaboration_Check)}. This behavior is
27912 identical to that specified by the Ada Reference Manual. The following example
27913 showcases run-time checks installed by GNAT to verify the elaboration state of
27914 package @code{Dynamic_Model}.
27916 @example
27917 with Server;
27918 package body Dynamic_Model is
27919    procedure API is
27920    begin
27921       ...
27922    end API;
27924    <check that the body of Server.Gen is elaborated>
27925    package Inst is new Server.Gen;
27927    T : Server.Task_Type;
27929 begin
27930    <check that the body of Server.Task_Type is elaborated>
27932    <check that the body of Server.Proc is elaborated>
27933    Server.Proc;
27934 end Dynamic_Model;
27935 @end example
27937 The checks verify that the body of a target has been successfully elaborated
27938 before a scenario activates, calls, or instantiates a target.
27940 Note that no scenario within package @code{Dynamic_Model} calls procedure @code{API}.
27941 In fact, procedure @code{API} may not be invoked by elaboration code within the
27942 partition, however the dynamic model assumes that this can happen.
27944 The dynamic model emits very few diagnostics, but can make suggestions on
27945 missing @code{Elaborate} and @code{Elaborate_All} pragmas for library-level
27946 scenarios. This information is available when compiler switch @code{-gnatel}
27947 is in effect.
27949 @example
27950 1. with Server;
27951 2. package body Dynamic_Model is
27952 3.    Val : constant Integer := Server.Func;
27953                                       |
27954    >>> info: call to "Func" during elaboration
27955    >>> info: missing pragma "Elaborate_All" for unit "Server"
27957 4. end Dynamic_Model;
27958 @end example
27960 @node Static Elaboration Model in GNAT,SPARK Elaboration Model in GNAT,Dynamic Elaboration Model in GNAT,Elaboration Order Handling in GNAT
27961 @anchor{gnat_ugn/elaboration_order_handling_in_gnat static-elaboration-model-in-gnat}@anchor{240}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{241}
27962 @section Static Elaboration Model in GNAT
27965 In contrast to the dynamic model, the static model is more precise in its
27966 analysis of elaboration code. The model makes a clear distinction between
27967 internal and external targets, and resorts to different diagnostics and
27968 run-time checks based on the nature of the target.
27971 @itemize *
27973 @item 
27974 @emph{Internal targets}
27976 The static model performs extensive diagnostics on scenarios which elaborate
27977 or execute internal targets. The warnings resulting from these diagnostics
27978 are enabled by default, but can be suppressed using compiler switch
27979 @code{-gnatws}.
27981 @example
27982  1. package body Static_Model is
27983  2.    generic
27984  3.       with function Func return Integer;
27985  4.    package Gen is
27986  5.       Val : constant Integer := Func;
27987  6.    end Gen;
27988  7.
27989  8.    function ABE return Integer;
27990  9.
27991 10.    function Cause_ABE return Boolean is
27992 11.       package Inst is new Gen (ABE);
27993           |
27994     >>> warning: in instantiation at line 5
27995     >>> warning: cannot call "ABE" before body seen
27996     >>> warning: Program_Error may be raised at run time
27997     >>> warning:   body of unit "Static_Model" elaborated
27998     >>> warning:   function "Cause_ABE" called at line 16
27999     >>> warning:   function "ABE" called at line 5, instance at line 11
28001 12.    begin
28002 13.       ...
28003 14.    end Cause_ABE;
28005 16.    Val : constant Boolean := Cause_ABE;
28007 18.    function ABE return Integer is
28008 19.    begin
28009 20.       ...
28010 21.    end ABE;
28011 22. end Static_Model;
28012 @end example
28014 The example above illustrates an ABE problem within package @code{Static_Model},
28015 which is hidden by several layers of indirection. The elaboration of package
28016 body @code{Static_Model} elaborates the declaration of @code{Val}. This invokes
28017 function @code{Cause_ABE}, which instantiates generic unit @code{Gen} as @code{Inst}.
28018 The elaboration of @code{Inst} invokes function @code{ABE}, however the body of
28019 @code{ABE} has not been elaborated yet.
28021 @item 
28022 @emph{External targets}
28024 The static model installs run-time checks to verify the elaboration status
28025 of server targets only when the scenario that elaborates or executes that
28026 target is part of the elaboration code of the client unit. The checks can be
28027 suppressed using pragma @code{Suppress (Elaboration_Check)}.
28029 @example
28030 with Server;
28031 package body Static_Model is
28032    generic
28033       with function Func return Integer;
28034    package Gen is
28035       Val : constant Integer := Func;
28036    end Gen;
28038    function Call_Func return Boolean is
28039       <check that the body of Server.Func is elaborated>
28040       package Inst is new Gen (Server.Func);
28041    begin
28042       ...
28043    end Call_Func;
28045    Val : constant Boolean := Call_Func;
28046 end Static_Model;
28047 @end example
28049 In the example above, the elaboration of package body @code{Static_Model}
28050 elaborates the declaration of @code{Val}. This invokes function @code{Call_Func},
28051 which instantiates generic unit @code{Gen} as @code{Inst}. The elaboration of
28052 @code{Inst} invokes function @code{Server.Func}. Since @code{Server.Func} is an
28053 external target, GNAT installs a run-time check to verify that its body has
28054 been elaborated.
28056 In addition to checks, the static model installs implicit @code{Elaborate} and
28057 @code{Elaborate_All} pragmas to guarantee safe elaboration use of server units.
28058 This information is available when compiler switch @code{-gnatel} is in
28059 effect.
28061 @example
28062  1. with Server;
28063  2. package body Static_Model is
28064  3.    generic
28065  4.       with function Func return Integer;
28066  5.    package Gen is
28067  6.       Val : constant Integer := Func;
28068  7.    end Gen;
28069  8.
28070  9.    function Call_Func return Boolean is
28071 10.       package Inst is new Gen (Server.Func);
28072           |
28073     >>> info: instantiation of "Gen" during elaboration
28074     >>> info: in instantiation at line 6
28075     >>> info: call to "Func" during elaboration
28076     >>> info: in instantiation at line 6
28077     >>> info: implicit pragma "Elaborate_All" generated for unit "Server"
28078     >>> info:   body of unit "Static_Model" elaborated
28079     >>> info:   function "Call_Func" called at line 15
28080     >>> info:   function "Func" called at line 6, instance at line 10
28082 11.    begin
28083 12.       ...
28084 13.    end Call_Func;
28086 15.    Val : constant Boolean := Call_Func;
28087                                  |
28088     >>> info: call to "Call_Func" during elaboration
28090 16. end Static_Model;
28091 @end example
28093 In the example above, the elaboration of package body @code{Static_Model}
28094 elaborates the declaration of @code{Val}. This invokes function @code{Call_Func},
28095 which instantiates generic unit @code{Gen} as @code{Inst}. The elaboration of
28096 @code{Inst} invokes function @code{Server.Func}. Since @code{Server.Func} is an
28097 external target, GNAT installs an implicit @code{Elaborate_All} pragma for unit
28098 @code{Server}. The pragma guarantees that both the spec and body of @code{Server},
28099 along with any additional dependencies that @code{Server} may require, are
28100 elaborated prior to the body of @code{Static_Model}.
28101 @end itemize
28103 @node SPARK Elaboration Model in GNAT,Mixing Elaboration Models,Static Elaboration Model in GNAT,Elaboration Order Handling in GNAT
28104 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{242}@anchor{gnat_ugn/elaboration_order_handling_in_gnat spark-elaboration-model-in-gnat}@anchor{243}
28105 @section SPARK Elaboration Model in GNAT
28108 The SPARK model is identical to the static model in its handling of internal
28109 targets. The SPARK model, however, requires explicit @code{Elaborate} or
28110 @code{Elaborate_All} pragmas to be present in the program when a target is
28111 external, and compiler switch @code{-gnatd.v} is in effect.
28113 @example
28114 1. with Server;
28115 2. package body SPARK_Model with SPARK_Mode is
28116 3.    Val : constant Integer := Server.Func;
28117                                       |
28118    >>> call to "Func" during elaboration in SPARK
28119    >>> unit "SPARK_Model" requires pragma "Elaborate_All" for "Server"
28120    >>>   body of unit "SPARK_Model" elaborated
28121    >>>   function "Func" called at line 3
28123 4. end SPARK_Model;
28124 @end example
28126 @node Mixing Elaboration Models,Elaboration Circularities,SPARK Elaboration Model in GNAT,Elaboration Order Handling in GNAT
28127 @anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{244}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{245}
28128 @section Mixing Elaboration Models
28131 It is possible to mix units compiled with a different elaboration model,
28132 however the following rules must be observed:
28135 @itemize *
28137 @item 
28138 A client unit compiled with the dynamic model can only @emph{with} a server unit
28139 that meets at least one of the following criteria:
28142 @itemize -
28144 @item 
28145 The server unit is compiled with the dynamic model.
28147 @item 
28148 The server unit is a GNAT implementation unit from the Ada, GNAT,
28149 Interfaces, or System hierarchies.
28151 @item 
28152 The server unit has pragma @code{Pure} or @code{Preelaborate}.
28154 @item 
28155 The client unit has an explicit @code{Elaborate_All} pragma for the server
28156 unit.
28157 @end itemize
28158 @end itemize
28160 These rules ensure that elaboration checks are not omitted. If the rules are
28161 violated, the binder emits a warning:
28163 @example
28164 warning: "x.ads" has dynamic elaboration checks and with's
28165 warning:   "y.ads" which has static elaboration checks
28166 @end example
28168 The warnings can be suppressed by binder switch @code{-ws}.
28170 @node Elaboration Circularities,Resolving Elaboration Circularities,Mixing Elaboration Models,Elaboration Order Handling in GNAT
28171 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{246}@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-circularities}@anchor{247}
28172 @section Elaboration Circularities
28175 If the binder cannot find an acceptable elaboration order, it outputs detailed
28176 diagnostics describing an @strong{elaboration circularity}.
28178 @example
28179 package Server is
28180    function Func return Integer;
28181 end Server;
28182 @end example
28184 @example
28185 with Client;
28186 package body Server is
28187    function Func return Integer is
28188    begin
28189       ...
28190    end Func;
28191 end Server;
28192 @end example
28194 @example
28195 with Server;
28196 package Client is
28197    Val : constant Integer := Server.Func;
28198 end Client;
28199 @end example
28201 @example
28202 with Client;
28203 procedure Main is begin null; end Main;
28204 @end example
28206 @example
28207 error: elaboration circularity detected
28208 info:    "server (body)" must be elaborated before "client (spec)"
28209 info:       reason: implicit Elaborate_All in unit "client (spec)"
28210 info:       recompile "client (spec)" with -gnatel for full details
28211 info:          "server (body)"
28212 info:             must be elaborated along with its spec:
28213 info:          "server (spec)"
28214 info:             which is withed by:
28215 info:          "client (spec)"
28216 info:    "client (spec)" must be elaborated before "server (body)"
28217 info:       reason: with clause
28218 @end example
28220 In the example above, @code{Client} must be elaborated prior to @code{Main} by virtue
28221 of a @emph{with} clause. The elaboration of @code{Client} invokes @code{Server.Func}, and
28222 static model generates an implicit @code{Elaborate_All} pragma for @code{Server}. The
28223 pragma implies that both the spec and body of @code{Server}, along with any units
28224 they @emph{with}, must be elaborated prior to @code{Client}. However, @code{Server}'s body
28225 @emph{with}s @code{Client}, implying that @code{Client} must be elaborated prior to
28226 @code{Server}. The end result is that @code{Client} must be elaborated prior to
28227 @code{Client}, and this leads to a circularity.
28229 @node Resolving Elaboration Circularities,Resolving Task Issues,Elaboration Circularities,Elaboration Order Handling in GNAT
28230 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{248}@anchor{gnat_ugn/elaboration_order_handling_in_gnat resolving-elaboration-circularities}@anchor{249}
28231 @section Resolving Elaboration Circularities
28234 When faced with an elaboration circularity, a programmer has several options
28235 available.
28238 @itemize *
28240 @item 
28241 @emph{Fix the program}
28243 The most desirable option from the point of view of long-term maintenance
28244 is to rearrange the program so that the elaboration problems are avoided.
28245 One useful technique is to place the elaboration code into separate child
28246 packages. Another is to move some of the initialization code to explicitly
28247 invoked subprograms, where the program controls the order of initialization
28248 explicitly. Although this is the most desirable option, it may be impractical
28249 and involve too much modification, especially in the case of complex legacy
28250 code.
28252 @item 
28253 @emph{Switch to more permissive elaboration model}
28255 If the compilation was performed using the static model, enable the dynamic
28256 model with compiler switch @code{-gnatE}. GNAT will no longer generate
28257 implicit @code{Elaborate} and @code{Elaborate_All} pragmas, resulting in a behavior
28258 identical to that specified by the Ada Reference Manual. The binder will
28259 generate an executable program that may or may not raise @code{Program_Error},
28260 and it is the programmer's responsibility to ensure that it does not raise
28261 @code{Program_Error}.
28263 @item 
28264 @emph{Suppress all elaboration checks}
28266 The drawback of run-time checks is that they generate overhead at run time,
28267 both in space and time. If the programmer is absolutely sure that a program
28268 will not raise an elaboration-related @code{Program_Error}, then using the
28269 pragma @code{Suppress (Elaboration_Check)} globally (as a configuration pragma)
28270 will eliminate all run-time checks.
28272 @item 
28273 @emph{Suppress elaboration checks selectively}
28275 If a scenario cannot possibly lead to an elaboration @code{Program_Error},
28276 and the binder nevertheless complains about implicit @code{Elaborate} and
28277 @code{Elaborate_All} pragmas that lead to elaboration circularities, it
28278 is possible to suppress the generation of implicit @code{Elaborate} and
28279 @code{Elaborate_All} pragmas, as well as run-time checks. Clearly this can
28280 be unsafe, and it is the responsibility of the programmer to make sure
28281 that the resulting program has no elaboration anomalies. Pragma
28282 @code{Suppress (Elaboration_Check)} can be used with different levels of
28283 granularity to achieve these effects.
28286 @itemize -
28288 @item 
28289 @emph{Target suppression}
28291 When the pragma is placed in a declarative part, without a second argument
28292 naming an entity, it will suppress implicit @code{Elaborate} and
28293 @code{Elaborate_All} pragma generation, as well as run-time checks, on all
28294 targets within the region.
28296 @example
28297 package Range_Suppress is
28298    pragma Suppress (Elaboration_Check);
28300    function Func return Integer;
28302    generic
28303    procedure Gen;
28305    pragma Unsuppress (Elaboration_Check);
28307    task type Tsk;
28308 end Range_Suppress;
28309 @end example
28311 In the example above, a pair of Suppress/Unsuppress pragmas define a region
28312 of suppression within package @code{Range_Suppress}. As a result, no implicit
28313 @code{Elaborate} and @code{Elaborate_All} pragmas, nor any run-time checks, will
28314 be generated by callers of @code{Func} and instantiators of @code{Gen}. Note that
28315 task type @code{Tsk} is not within this region.
28317 An alternative to the region-based suppression is to use multiple
28318 @code{Suppress} pragmas with arguments naming specific entities for which
28319 elaboration checks should be suppressed:
28321 @example
28322 package Range_Suppress is
28323    function Func return Integer;
28324    pragma Suppress (Elaboration_Check, Func);
28326    generic
28327    procedure Gen;
28328    pragma Suppress (Elaboration_Check, Gen);
28330    task type Tsk;
28331 end Range_Suppress;
28332 @end example
28334 @item 
28335 @emph{Scenario suppression}
28337 When the pragma @code{Suppress} is placed in a declarative or statement
28338 part, without an entity argument, it will suppress implicit @code{Elaborate}
28339 and @code{Elaborate_All} pragma generation, as well as run-time checks, on
28340 all scenarios within the region.
28342 @example
28343 with Server;
28344 package body Range_Suppress is
28345    pragma Suppress (Elaboration_Check);
28347    function Func return Integer is
28348    begin
28349       return Server.Func;
28350    end Func;
28352    procedure Gen is
28353    begin
28354       Server.Proc;
28355    end Gen;
28357    pragma Unsuppress (Elaboration_Check);
28359    task body Tsk is
28360    begin
28361       Server.Proc;
28362    end Tsk;
28363 end Range_Suppress;
28364 @end example
28366 In the example above, a pair of Suppress/Unsuppress pragmas define a region
28367 of suppression within package body @code{Range_Suppress}. As a result, the
28368 calls to @code{Server.Func} in @code{Func} and @code{Server.Proc} in @code{Gen} will
28369 not generate any implicit @code{Elaborate} and @code{Elaborate_All} pragmas or
28370 run-time checks.
28371 @end itemize
28372 @end itemize
28374 @node Resolving Task Issues,Elaboration-related Compiler Switches,Resolving Elaboration Circularities,Elaboration Order Handling in GNAT
28375 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{24a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat resolving-task-issues}@anchor{24b}
28376 @section Resolving Task Issues
28379 The model of execution in Ada dictates that elaboration must first take place,
28380 and only then can the main program be started. Tasks which are activated during
28381 elaboration violate this model and may lead to serious concurrent problems at
28382 elaboration time.
28384 A task can be activated in two different ways:
28387 @itemize *
28389 @item 
28390 The task is created by an allocator in which case it is activated immediately
28391 after the allocator is evaluated.
28393 @item 
28394 The task is declared at the library level or within some nested master in
28395 which case it is activated before starting execution of the statement
28396 sequence of the master defining the task.
28397 @end itemize
28399 Since the elaboration of a partition is performed by the environment task
28400 servicing that partition, any tasks activated during elaboration may be in
28401 a race with the environment task, and lead to unpredictable state and behavior.
28402 The static model seeks to avoid such interactions by assuming that all code in
28403 the task body is executed at elaboration time, if the task was activated by
28404 elaboration code.
28406 @example
28407 package Decls is
28408    task Lib_Task is
28409       entry Start;
28410    end Lib_Task;
28412    type My_Int is new Integer;
28414    function Ident (M : My_Int) return My_Int;
28415 end Decls;
28416 @end example
28418 @example
28419 with Utils;
28420 package body Decls is
28421    task body Lib_Task is
28422    begin
28423       accept Start;
28424       Utils.Put_Val (2);
28425    end Lib_Task;
28427    function Ident (M : My_Int) return My_Int is
28428    begin
28429       return M;
28430    end Ident;
28431 end Decls;
28432 @end example
28434 @example
28435 with Decls;
28436 package Utils is
28437    procedure Put_Val (Arg : Decls.My_Int);
28438 end Utils;
28439 @end example
28441 @example
28442 with Ada.Text_IO; use Ada.Text_IO;
28443 package body Utils is
28444    procedure Put_Val (Arg : Decls.My_Int) is
28445    begin
28446       Put_Line (Arg'Img);
28447    end Put_Val;
28448 end Utils;
28449 @end example
28451 @example
28452 with Decls;
28453 procedure Main is
28454 begin
28455    Decls.Lib_Task.Start;
28456 end Main;
28457 @end example
28459 When the above example is compiled with the static model, an elaboration
28460 circularity arises:
28462 @example
28463 error: elaboration circularity detected
28464 info:    "decls (body)" must be elaborated before "decls (body)"
28465 info:       reason: implicit Elaborate_All in unit "decls (body)"
28466 info:       recompile "decls (body)" with -gnatel for full details
28467 info:          "decls (body)"
28468 info:             must be elaborated along with its spec:
28469 info:          "decls (spec)"
28470 info:             which is withed by:
28471 info:          "utils (spec)"
28472 info:             which is withed by:
28473 info:          "decls (body)"
28474 @end example
28476 In the above example, @code{Decls} must be elaborated prior to @code{Main} by virtue
28477 of a with clause. The elaboration of @code{Decls} activates task @code{Lib_Task}. The
28478 static model conservatibely assumes that all code within the body of
28479 @code{Lib_Task} is executed, and generates an implicit @code{Elaborate_All} pragma
28480 for @code{Units} due to the call to @code{Utils.Put_Val}. The pragma implies that
28481 both the spec and body of @code{Utils}, along with any units they @emph{with},
28482 must be elaborated prior to @code{Decls}. However, @code{Utils}'s spec @emph{with}s
28483 @code{Decls}, implying that @code{Decls} must be elaborated before @code{Utils}. The end
28484 result is that @code{Utils} must be elaborated prior to @code{Utils}, and this
28485 leads to a circularity.
28487 In reality, the example above will not exhibit an ABE problem at run time.
28488 When the body of task @code{Lib_Task} is activated, execution will wait for entry
28489 @code{Start} to be accepted, and the call to @code{Utils.Put_Val} will not take place
28490 at elaboration time. Task @code{Lib_Task} will resume its execution after the main
28491 program is executed because @code{Main} performs a rendezvous with
28492 @code{Lib_Task.Start}, and at that point all units have already been elaborated.
28493 As a result, the static model may seem overly conservative, partly because it
28494 does not take control and data flow into account.
28496 When faced with a task elaboration circularity, a programmer has several
28497 options available:
28500 @itemize *
28502 @item 
28503 @emph{Use the dynamic model}
28505 The dynamic model does not generate implicit @code{Elaborate} and
28506 @code{Elaborate_All} pragmas. Instead, it will install checks prior to every
28507 call in the example above, thus verifying the successful elaboration of
28508 @code{Utils.Put_Val} in case the call to it takes place at elaboration time.
28509 The dynamic model is enabled with compiler switch @code{-gnatE}.
28511 @item 
28512 @emph{Isolate the tasks}
28514 Relocating tasks in their own separate package could decouple them from
28515 dependencies that would otherwise cause an elaboration circularity. The
28516 example above can be rewritten as follows:
28518 @example
28519 package Decls1 is                --  new
28520    task Lib_Task is
28521       entry Start;
28522    end Lib_Task;
28523 end Decls1;
28524 @end example
28526 @example
28527 with Utils;
28528 package body Decls1 is           --  new
28529    task body Lib_Task is
28530    begin
28531       accept Start;
28532       Utils.Put_Val (2);
28533    end Lib_Task;
28534 end Decls1;
28535 @end example
28537 @example
28538 package Decls2 is                --  new
28539    type My_Int is new Integer;
28540    function Ident (M : My_Int) return My_Int;
28541 end Decls2;
28542 @end example
28544 @example
28545 with Utils;
28546 package body Decls2 is           --  new
28547    function Ident (M : My_Int) return My_Int is
28548    begin
28549       return M;
28550    end Ident;
28551 end Decls2;
28552 @end example
28554 @example
28555 with Decls2;
28556 package Utils is
28557    procedure Put_Val (Arg : Decls2.My_Int);
28558 end Utils;
28559 @end example
28561 @example
28562 with Ada.Text_IO; use Ada.Text_IO;
28563 package body Utils is
28564    procedure Put_Val (Arg : Decls2.My_Int) is
28565    begin
28566       Put_Line (Arg'Img);
28567    end Put_Val;
28568 end Utils;
28569 @end example
28571 @example
28572 with Decls1;
28573 procedure Main is
28574 begin
28575    Decls1.Lib_Task.Start;
28576 end Main;
28577 @end example
28579 @item 
28580 @emph{Declare the tasks}
28582 The original example uses a single task declaration for @code{Lib_Task}. An
28583 explicit task type declaration and a properly placed task object could avoid
28584 the dependencies that would otherwise cause an elaboration circularity. The
28585 example can be rewritten as follows:
28587 @example
28588 package Decls is
28589    task type Lib_Task is         --  new
28590       entry Start;
28591    end Lib_Task;
28593    type My_Int is new Integer;
28595    function Ident (M : My_Int) return My_Int;
28596 end Decls;
28597 @end example
28599 @example
28600 with Utils;
28601 package body Decls is
28602    task body Lib_Task is
28603    begin
28604       accept Start;
28605       Utils.Put_Val (2);
28606    end Lib_Task;
28608    function Ident (M : My_Int) return My_Int is
28609    begin
28610       return M;
28611    end Ident;
28612 end Decls;
28613 @end example
28615 @example
28616 with Decls;
28617 package Utils is
28618    procedure Put_Val (Arg : Decls.My_Int);
28619 end Utils;
28620 @end example
28622 @example
28623 with Ada.Text_IO; use Ada.Text_IO;
28624 package body Utils is
28625    procedure Put_Val (Arg : Decls.My_Int) is
28626    begin
28627       Put_Line (Arg'Img);
28628    end Put_Val;
28629 end Utils;
28630 @end example
28632 @example
28633 with Decls;
28634 package Obj_Decls is             --  new
28635    Task_Obj : Decls.Lib_Task;
28636 end Obj_Decls;
28637 @end example
28639 @example
28640 with Obj_Decls;
28641 procedure Main is
28642 begin
28643    Obj_Decls.Task_Obj.Start;     --  new
28644 end Main;
28645 @end example
28647 @item 
28648 @emph{Use restriction No_Entry_Calls_In_Elaboration_Code}
28650 The issue exhibited in the original example under this section revolves
28651 around the body of @code{Lib_Task} blocking on an accept statement. There is
28652 no rule to prevent elaboration code from performing entry calls, however in
28653 practice this is highly unusual. In addition, the pattern of starting tasks
28654 at elaboration time and then immediately blocking on accept or select
28655 statements is quite common.
28657 If a programmer knows that elaboration code will not perform any entry
28658 calls, then the programmer can indicate that the static model should not
28659 process the remainder of a task body once an accept or select statement has
28660 been encountered. This behavior can be specified by a configuration pragma:
28662 @example
28663 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28664 @end example
28666 In addition to the change in behavior with respect to task bodies, the
28667 static model will verify that no entry calls take place at elaboration time.
28668 @end itemize
28670 @node Elaboration-related Compiler Switches,Summary of Procedures for Elaboration Control,Resolving Task Issues,Elaboration Order Handling in GNAT
28671 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-related-compiler-switches}@anchor{24c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id15}@anchor{24d}
28672 @section Elaboration-related Compiler Switches
28675 GNAT has several switches that affect the elaboration model and consequently
28676 the elaboration order chosen by the binder.
28678 @geindex -gnatdE (gnat)
28681 @table @asis
28683 @item @code{-gnatdE}
28685 Elaboration checks on predefined units
28687 When this switch is in effect, GNAT will consider scenarios and targets that
28688 come from the Ada, GNAT, Interfaces, and System hierarchies. This switch is
28689 useful when a programmer has defined a custom grandchild of those packages.
28690 @end table
28692 @geindex -gnatd.G (gnat)
28695 @table @asis
28697 @item @code{-gnatd.G}
28699 Ignore calls through generic formal parameters for elaboration
28701 When this switch is in effect, GNAT will ignore calls that invoke generic
28702 actual entries, operators, or subprograms via generic formal subprograms. As
28703 a result, GNAT will not generate implicit @code{Elaborate} and @code{Elaborate_All}
28704 pragmas, and run-time checks for such calls. Note that this switch does not
28705 overlap with @code{-gnatdL}.
28707 @example
28708 package body Ignore_Calls is
28709    function ABE return Integer;
28711    generic
28712       with function Gen_Formal return Integer;
28713    package Gen is
28714       Val : constant Integer := Gen_Formal;
28715    end Gen;
28717    package Inst is new Gen (ABE);
28719    function ABE return Integer is
28720    begin
28721       ...
28722    end ABE;
28723 end Ignore_Calls;
28724 @end example
28726 In the example above, the call to function @code{ABE} will be ignored because it
28727 occurs during the elaboration of instance @code{Inst}, through a call to generic
28728 formal subprogram @code{Gen_Formal}.
28729 @end table
28731 @geindex -gnatdL (gnat)
28734 @table @asis
28736 @item @code{-gnatdL}
28738 Ignore external calls from instances for elaboration
28740 When this switch is in effect, GNAT will ignore calls that originate from
28741 within an instance and directly target an entry, operator, or subprogram
28742 defined outside the instance. As a result, GNAT will not generate implicit
28743 @code{Elaborate} and @code{Elaborate_All} pragmas, and run-time checks for such
28744 calls.  Note that this switch does not overlap with @code{-gnatd.G}.
28746 @example
28747 package body Ignore_Calls is
28748    function ABE return Integer;
28750    generic
28751    package Gen is
28752       Val : constant Integer := ABE;
28753    end Gen;
28755    package Inst is new Gen;
28757    function ABE return Integer is
28758    begin
28759       ...
28760    end ABE;
28761 end Ignore_Calls;
28762 @end example
28764 In the example above, the call to function @code{ABE} will be ignored because it
28765 originates from within an instance and targets a subprogram defined outside
28766 the instance.
28767 @end table
28769 @geindex -gnatd.o (gnat)
28772 @table @asis
28774 @item @code{-gnatd.o}
28776 Conservative elaboration order for indirect calls
28778 When this switch is in effect, GNAT will treat @code{'Access} of an entry,
28779 operator, or subprogram as an immediate call to that target. As a result,
28780 GNAT will generate implicit @code{Elaborate} and @code{Elaborate_All} pragmas as
28781 well as run-time checks for such attribute references.
28783 @example
28784  1. package body Attribute_Call is
28785  2.    function Func return Integer;
28786  3.    type Func_Ptr is access function return Integer;
28787  4.
28788  5.    Ptr : constant Func_Ptr := Func'Access;
28789                                       |
28790     >>> warning: cannot call "Func" before body seen
28791     >>> warning: Program_Error may be raised at run time
28792     >>> warning:   body of unit "Attribute_Call" elaborated
28793     >>> warning:   "Access" of "Func" taken at line 5
28794     >>> warning:   function "Func" called at line 5
28796  6.
28797  7.    function Func return Integer is
28798  8.    begin
28799  9.       ...
28800 10.    end Func;
28801 11. end Attribute_Call;
28802 @end example
28804 In the example above, the elaboration of declaration @code{Ptr} is assigned
28805 @code{Func'Access} before the body of @code{Func} has been elaborated.
28806 @end table
28808 @geindex -gnatd.U (gnat)
28811 @table @asis
28813 @item @code{-gnatd.U}
28815 Ignore indirect calls for static elaboration
28817 When this switch is in effect, GNAT will ignore @code{'Access} of an entry,
28818 operator, or subprogram when the static model is in effect.
28819 @end table
28821 @geindex -gnatd.v (gnat)
28824 @table @asis
28826 @item @code{-gnatd.v}
28828 Enforce SPARK elaboration rules in SPARK code
28830 When this switch is in effect, GNAT will enforce the SPARK rules of
28831 elaboration as defined in the SPARK Reference Manual, section 7.7. As a
28832 result, constructs which violate the SPARK elaboration rules are no longer
28833 accepted, even if GNAT is able to statically ensure that these constructs
28834 will not lead to ABE problems.
28835 @end table
28837 @geindex -gnatd.y (gnat)
28840 @table @asis
28842 @item @code{-gnatd.y}
28844 Disable implicit pragma Elaborate[_All] on task bodies
28846 When this switch is in effect, GNAT will not generate @code{Elaborate} and
28847 @code{Elaborate_All} pragmas if the need for the pragma came directly or
28848 indirectly from a task body.
28850 @example
28851 with Server;
28852 package body Disable_Task is
28853    task T;
28855    task body T is
28856    begin
28857       Server.Proc;
28858    end T;
28859 end Disable_Task;
28860 @end example
28862 In the example above, the activation of single task @code{T} invokes
28863 @code{Server.Proc}, which implies that @code{Server} requires @code{Elaborate_All},
28864 however GNAT will not generate the pragma.
28865 @end table
28867 @geindex -gnatE (gnat)
28870 @table @asis
28872 @item @code{-gnatE}
28874 Dynamic elaboration checking mode enabled
28876 When this switch is in effect, GNAT activates the dynamic elaboration model.
28877 @end table
28879 @geindex -gnatel (gnat)
28882 @table @asis
28884 @item @code{-gnatel}
28886 Turn on info messages on generated Elaborate[_All] pragmas
28888 When this switch is in effect, GNAT will emit the following supplementary
28889 information depending on the elaboration model in effect.
28892 @itemize -
28894 @item 
28895 @emph{Dynamic model}
28897 GNAT will indicate missing @code{Elaborate} and @code{Elaborate_All} pragmas for
28898 all library-level scenarios within the partition.
28900 @item 
28901 @emph{Static model}
28903 GNAT will indicate all scenarios executed during elaboration. In addition,
28904 it will provide detailed traceback when an implicit @code{Elaborate} or
28905 @code{Elaborate_All} pragma is generated.
28907 @item 
28908 @emph{SPARK model}
28910 GNAT will indicate how an elaboration requirement is met by the context of
28911 a unit. This diagnostic requires compiler switch @code{-gnatd.v}.
28913 @example
28914 1. with Server; pragma Elaborate_All (Server);
28915 2. package Client with SPARK_Mode is
28916 3.    Val : constant Integer := Server.Func;
28917                                       |
28918    >>> info: call to "Func" during elaboration in SPARK
28919    >>> info: "Elaborate_All" requirement for unit "Server" met by pragma at line 1
28921 4. end Client;
28922 @end example
28923 @end itemize
28924 @end table
28926 @geindex -gnatw.f (gnat)
28929 @table @asis
28931 @item @code{-gnatw.f}
28933 Turn on warnings for suspicious Subp'Access
28935 When this switch is in effect, GNAT will treat @code{'Access} of an entry,
28936 operator, or subprogram as a potential call to the target and issue warnings:
28938 @example
28939  1. package body Attribute_Call is
28940  2.    function Func return Integer;
28941  3.    type Func_Ptr is access function return Integer;
28942  4.
28943  5.    Ptr : constant Func_Ptr := Func'Access;
28944                                       |
28945     >>> warning: "Access" attribute of "Func" before body seen
28946     >>> warning: possible Program_Error on later references
28947     >>> warning:   body of unit "Attribute_Call" elaborated
28948     >>> warning:   "Access" of "Func" taken at line 5
28950  6.
28951  7.    function Func return Integer is
28952  8.    begin
28953  9.       ...
28954 10.    end Func;
28955 11. end Attribute_Call;
28956 @end example
28958 In the example above, the elaboration of declaration @code{Ptr} is assigned
28959 @code{Func'Access} before the body of @code{Func} has been elaborated.
28960 @end table
28962 @node Summary of Procedures for Elaboration Control,Inspecting the Chosen Elaboration Order,Elaboration-related Compiler Switches,Elaboration Order Handling in GNAT
28963 @anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{24e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id16}@anchor{24f}
28964 @section Summary of Procedures for Elaboration Control
28967 A programmer should first compile the program with the default options, using
28968 none of the binder or compiler switches. If the binder succeeds in finding an
28969 elaboration order, then apart from possible cases involing dispatching calls
28970 and access-to-subprogram types, the program is free of elaboration errors.
28971 If it is important for the program to be portable to compilers other than GNAT,
28972 then the programmer should use compiler switch @code{-gnatel} and consider
28973 the messages about missing or implicitly created @code{Elaborate} and
28974 @code{Elaborate_All} pragmas.
28976 If the binder reports an elaboration circularity, the programmer has several
28977 options:
28980 @itemize *
28982 @item 
28983 Ensure that warnings are enabled. This will allow the static model to output
28984 trace information of elaboration issues. The trace information could shed
28985 light on previously unforeseen dependencies, as well as their origins.
28987 @item 
28988 Use switch @code{-gnatel} to obtain messages on generated implicit
28989 @code{Elaborate} and @code{Elaborate_All} pragmas. The trace information could
28990 indicate why a server unit must be elaborated prior to a client unit.
28992 @item 
28993 If the warnings produced by the static model indicate that a task is
28994 involved, consider the options in the section on resolving task issues as
28995 well as compiler switch @code{-gnatd.y}.
28997 @item 
28998 If the warnings produced by the static model indicate that an generic
28999 instantiations are involved, consider using compiler switches
29000 @code{-gnatd.G} and @code{-gnatdL}.
29002 @item 
29003 If none of the steps outlined above resolve the circularity, recompile the
29004 program using the dynamic model by using compiler switch @code{-gnatE}.
29005 @end itemize
29007 @node Inspecting the Chosen Elaboration Order,,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
29008 @anchor{gnat_ugn/elaboration_order_handling_in_gnat inspecting-the-chosen-elaboration-order}@anchor{250}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id17}@anchor{251}
29009 @section Inspecting the Chosen Elaboration Order
29012 To see the elaboration order chosen by the binder, inspect the contents of file
29013 @cite{b~xxx.adb}. On certain targets, this file appears as @cite{b_xxx.adb}. The
29014 elaboration order appears as a sequence of calls to @code{Elab_Body} and
29015 @code{Elab_Spec}, interspersed with assignments to @cite{Exxx} which indicates that a
29016 particular unit is elaborated. For example:
29018 @example
29019 System.Soft_Links'Elab_Body;
29020 E14 := True;
29021 System.Secondary_Stack'Elab_Body;
29022 E18 := True;
29023 System.Exception_Table'Elab_Body;
29024 E24 := True;
29025 Ada.Io_Exceptions'Elab_Spec;
29026 E67 := True;
29027 Ada.Tags'Elab_Spec;
29028 Ada.Streams'Elab_Spec;
29029 E43 := True;
29030 Interfaces.C'Elab_Spec;
29031 E69 := True;
29032 System.Finalization_Root'Elab_Spec;
29033 E60 := True;
29034 System.Os_Lib'Elab_Body;
29035 E71 := True;
29036 System.Finalization_Implementation'Elab_Spec;
29037 System.Finalization_Implementation'Elab_Body;
29038 E62 := True;
29039 Ada.Finalization'Elab_Spec;
29040 E58 := True;
29041 Ada.Finalization.List_Controller'Elab_Spec;
29042 E76 := True;
29043 System.File_Control_Block'Elab_Spec;
29044 E74 := True;
29045 System.File_Io'Elab_Body;
29046 E56 := True;
29047 Ada.Tags'Elab_Body;
29048 E45 := True;
29049 Ada.Text_Io'Elab_Spec;
29050 Ada.Text_Io'Elab_Body;
29051 E07 := True;
29052 @end example
29054 Note also binder switch @code{-l}, which outputs the chosen elaboration
29055 order and provides a more readable form of the above:
29057 @example
29058 ada (spec)
29059 interfaces (spec)
29060 system (spec)
29061 system.case_util (spec)
29062 system.case_util (body)
29063 system.concat_2 (spec)
29064 system.concat_2 (body)
29065 system.concat_3 (spec)
29066 system.concat_3 (body)
29067 system.htable (spec)
29068 system.parameters (spec)
29069 system.parameters (body)
29070 system.crtl (spec)
29071 interfaces.c_streams (spec)
29072 interfaces.c_streams (body)
29073 system.restrictions (spec)
29074 system.restrictions (body)
29075 system.standard_library (spec)
29076 system.exceptions (spec)
29077 system.exceptions (body)
29078 system.storage_elements (spec)
29079 system.storage_elements (body)
29080 system.secondary_stack (spec)
29081 system.stack_checking (spec)
29082 system.stack_checking (body)
29083 system.string_hash (spec)
29084 system.string_hash (body)
29085 system.htable (body)
29086 system.strings (spec)
29087 system.strings (body)
29088 system.traceback (spec)
29089 system.traceback (body)
29090 system.traceback_entries (spec)
29091 system.traceback_entries (body)
29092 ada.exceptions (spec)
29093 ada.exceptions.last_chance_handler (spec)
29094 system.soft_links (spec)
29095 system.soft_links (body)
29096 ada.exceptions.last_chance_handler (body)
29097 system.secondary_stack (body)
29098 system.exception_table (spec)
29099 system.exception_table (body)
29100 ada.io_exceptions (spec)
29101 ada.tags (spec)
29102 ada.streams (spec)
29103 interfaces.c (spec)
29104 interfaces.c (body)
29105 system.finalization_root (spec)
29106 system.finalization_root (body)
29107 system.memory (spec)
29108 system.memory (body)
29109 system.standard_library (body)
29110 system.os_lib (spec)
29111 system.os_lib (body)
29112 system.unsigned_types (spec)
29113 system.stream_attributes (spec)
29114 system.stream_attributes (body)
29115 system.finalization_implementation (spec)
29116 system.finalization_implementation (body)
29117 ada.finalization (spec)
29118 ada.finalization (body)
29119 ada.finalization.list_controller (spec)
29120 ada.finalization.list_controller (body)
29121 system.file_control_block (spec)
29122 system.file_io (spec)
29123 system.file_io (body)
29124 system.val_uns (spec)
29125 system.val_util (spec)
29126 system.val_util (body)
29127 system.val_uns (body)
29128 system.wch_con (spec)
29129 system.wch_con (body)
29130 system.wch_cnv (spec)
29131 system.wch_jis (spec)
29132 system.wch_jis (body)
29133 system.wch_cnv (body)
29134 system.wch_stw (spec)
29135 system.wch_stw (body)
29136 ada.tags (body)
29137 ada.exceptions (body)
29138 ada.text_io (spec)
29139 ada.text_io (body)
29140 text_io (spec)
29141 gdbstr (body)
29142 @end example
29144 @node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
29145 @anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{10}@anchor{gnat_ugn/inline_assembler doc}@anchor{252}@anchor{gnat_ugn/inline_assembler id1}@anchor{253}
29146 @chapter Inline Assembler
29149 @geindex Inline Assembler
29151 If you need to write low-level software that interacts directly
29152 with the hardware, Ada provides two ways to incorporate assembly
29153 language code into your program.  First, you can import and invoke
29154 external routines written in assembly language, an Ada feature fully
29155 supported by GNAT.  However, for small sections of code it may be simpler
29156 or more efficient to include assembly language statements directly
29157 in your Ada source program, using the facilities of the implementation-defined
29158 package @code{System.Machine_Code}, which incorporates the gcc
29159 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
29160 including the following:
29163 @itemize *
29165 @item 
29166 No need to use non-Ada tools
29168 @item 
29169 Consistent interface over different targets
29171 @item 
29172 Automatic usage of the proper calling conventions
29174 @item 
29175 Access to Ada constants and variables
29177 @item 
29178 Definition of intrinsic routines
29180 @item 
29181 Possibility of inlining a subprogram comprising assembler code
29183 @item 
29184 Code optimizer can take Inline Assembler code into account
29185 @end itemize
29187 This appendix presents a series of examples to show you how to use
29188 the Inline Assembler.  Although it focuses on the Intel x86,
29189 the general approach applies also to other processors.
29190 It is assumed that you are familiar with Ada
29191 and with assembly language programming.
29193 @menu
29194 * Basic Assembler Syntax:: 
29195 * A Simple Example of Inline Assembler:: 
29196 * Output Variables in Inline Assembler:: 
29197 * Input Variables in Inline Assembler:: 
29198 * Inlining Inline Assembler Code:: 
29199 * Other Asm Functionality:: 
29201 @end menu
29203 @node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
29204 @anchor{gnat_ugn/inline_assembler id2}@anchor{254}@anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{255}
29205 @section Basic Assembler Syntax
29208 The assembler used by GNAT and gcc is based not on the Intel assembly
29209 language, but rather on a language that descends from the AT&T Unix
29210 assembler @code{as} (and which is often referred to as 'AT&T syntax').
29211 The following table summarizes the main features of @code{as} syntax
29212 and points out the differences from the Intel conventions.
29213 See the gcc @code{as} and @code{gas} (an @code{as} macro
29214 pre-processor) documentation for further information.
29217 @display
29218 @emph{Register names}@w{ }
29219 @display
29220 gcc / @code{as}: Prefix with '%'; for example @code{%eax}@w{ }
29221 Intel: No extra punctuation; for example @code{eax}@w{ }
29222 @end display
29223 @end display
29228 @display
29229 @emph{Immediate operand}@w{ }
29230 @display
29231 gcc / @code{as}: Prefix with '$'; for example @code{$4}@w{ }
29232 Intel: No extra punctuation; for example @code{4}@w{ }
29233 @end display
29234 @end display
29239 @display
29240 @emph{Address}@w{ }
29241 @display
29242 gcc / @code{as}: Prefix with '$'; for example @code{$loc}@w{ }
29243 Intel: No extra punctuation; for example @code{loc}@w{ }
29244 @end display
29245 @end display
29250 @display
29251 @emph{Memory contents}@w{ }
29252 @display
29253 gcc / @code{as}: No extra punctuation; for example @code{loc}@w{ }
29254 Intel: Square brackets; for example @code{[loc]}@w{ }
29255 @end display
29256 @end display
29261 @display
29262 @emph{Register contents}@w{ }
29263 @display
29264 gcc / @code{as}: Parentheses; for example @code{(%eax)}@w{ }
29265 Intel: Square brackets; for example @code{[eax]}@w{ }
29266 @end display
29267 @end display
29272 @display
29273 @emph{Hexadecimal numbers}@w{ }
29274 @display
29275 gcc / @code{as}: Leading '0x' (C language syntax); for example @code{0xA0}@w{ }
29276 Intel: Trailing 'h'; for example @code{A0h}@w{ }
29277 @end display
29278 @end display
29283 @display
29284 @emph{Operand size}@w{ }
29285 @display
29286 gcc / @code{as}: Explicit in op code; for example @code{movw} to move a 16-bit word@w{ }
29287 Intel: Implicit, deduced by assembler; for example @code{mov}@w{ }
29288 @end display
29289 @end display
29294 @display
29295 @emph{Instruction repetition}@w{ }
29296 @display
29297 gcc / @code{as}: Split into two lines; for example@w{ }
29298 @display
29299 @code{rep}@w{ }
29300 @code{stosl}@w{ }
29301 @end display
29302 Intel: Keep on one line; for example @code{rep stosl}@w{ }
29303 @end display
29304 @end display
29309 @display
29310 @emph{Order of operands}@w{ }
29311 @display
29312 gcc / @code{as}: Source first; for example @code{movw $4, %eax}@w{ }
29313 Intel: Destination first; for example @code{mov eax, 4}@w{ }
29314 @end display
29315 @end display
29319 @node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
29320 @anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{256}@anchor{gnat_ugn/inline_assembler id3}@anchor{257}
29321 @section A Simple Example of Inline Assembler
29324 The following example will generate a single assembly language statement,
29325 @code{nop}, which does nothing.  Despite its lack of run-time effect,
29326 the example will be useful in illustrating the basics of
29327 the Inline Assembler facility.
29329 @quotation
29331 @example
29332 with System.Machine_Code; use System.Machine_Code;
29333 procedure Nothing is
29334 begin
29335    Asm ("nop");
29336 end Nothing;
29337 @end example
29338 @end quotation
29340 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
29341 here it takes one parameter, a @emph{template string} that must be a static
29342 expression and that will form the generated instruction.
29343 @code{Asm} may be regarded as a compile-time procedure that parses
29344 the template string and additional parameters (none here),
29345 from which it generates a sequence of assembly language instructions.
29347 The examples in this chapter will illustrate several of the forms
29348 for invoking @code{Asm}; a complete specification of the syntax
29349 is found in the @code{Machine_Code_Insertions} section of the
29350 @cite{GNAT Reference Manual}.
29352 Under the standard GNAT conventions, the @code{Nothing} procedure
29353 should be in a file named @code{nothing.adb}.
29354 You can build the executable in the usual way:
29356 @quotation
29358 @example
29359 $ gnatmake nothing
29360 @end example
29361 @end quotation
29363 However, the interesting aspect of this example is not its run-time behavior
29364 but rather the generated assembly code.
29365 To see this output, invoke the compiler as follows:
29367 @quotation
29369 @example
29370 $  gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
29371 @end example
29372 @end quotation
29374 where the options are:
29377 @itemize *
29379 @item 
29381 @table @asis
29383 @item @code{-c}
29385 compile only (no bind or link)
29386 @end table
29388 @item 
29390 @table @asis
29392 @item @code{-S}
29394 generate assembler listing
29395 @end table
29397 @item 
29399 @table @asis
29401 @item @code{-fomit-frame-pointer}
29403 do not set up separate stack frames
29404 @end table
29406 @item 
29408 @table @asis
29410 @item @code{-gnatp}
29412 do not add runtime checks
29413 @end table
29414 @end itemize
29416 This gives a human-readable assembler version of the code. The resulting
29417 file will have the same name as the Ada source file, but with a @code{.s}
29418 extension. In our example, the file @code{nothing.s} has the following
29419 contents:
29421 @quotation
29423 @example
29424 .file "nothing.adb"
29425 gcc2_compiled.:
29426 ___gnu_compiled_ada:
29427 .text
29428    .align 4
29429 .globl __ada_nothing
29430 __ada_nothing:
29431 #APP
29432    nop
29433 #NO_APP
29434    jmp L1
29435    .align 2,0x90
29437    ret
29438 @end example
29439 @end quotation
29441 The assembly code you included is clearly indicated by
29442 the compiler, between the @code{#APP} and @code{#NO_APP}
29443 delimiters. The character before the 'APP' and 'NOAPP'
29444 can differ on different targets. For example, GNU/Linux uses '#APP' while
29445 on NT you will see '/APP'.
29447 If you make a mistake in your assembler code (such as using the
29448 wrong size modifier, or using a wrong operand for the instruction) GNAT
29449 will report this error in a temporary file, which will be deleted when
29450 the compilation is finished.  Generating an assembler file will help
29451 in such cases, since you can assemble this file separately using the
29452 @code{as} assembler that comes with gcc.
29454 Assembling the file using the command
29456 @quotation
29458 @example
29459 $ as nothing.s
29460 @end example
29461 @end quotation
29463 will give you error messages whose lines correspond to the assembler
29464 input file, so you can easily find and correct any mistakes you made.
29465 If there are no errors, @code{as} will generate an object file
29466 @code{nothing.out}.
29468 @node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
29469 @anchor{gnat_ugn/inline_assembler id4}@anchor{258}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{259}
29470 @section Output Variables in Inline Assembler
29473 The examples in this section, showing how to access the processor flags,
29474 illustrate how to specify the destination operands for assembly language
29475 statements.
29477 @quotation
29479 @example
29480 with Interfaces; use Interfaces;
29481 with Ada.Text_IO; use Ada.Text_IO;
29482 with System.Machine_Code; use System.Machine_Code;
29483 procedure Get_Flags is
29484    Flags : Unsigned_32;
29485    use ASCII;
29486 begin
29487    Asm ("pushfl"          & LF & HT & -- push flags on stack
29488         "popl %%eax"      & LF & HT & -- load eax with flags
29489         "movl %%eax, %0",             -- store flags in variable
29490         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29491    Put_Line ("Flags register:" & Flags'Img);
29492 end Get_Flags;
29493 @end example
29494 @end quotation
29496 In order to have a nicely aligned assembly listing, we have separated
29497 multiple assembler statements in the Asm template string with linefeed
29498 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29499 The resulting section of the assembly output file is:
29501 @quotation
29503 @example
29504 #APP
29505    pushfl
29506    popl %eax
29507    movl %eax, -40(%ebp)
29508 #NO_APP
29509 @end example
29510 @end quotation
29512 It would have been legal to write the Asm invocation as:
29514 @quotation
29516 @example
29517 Asm ("pushfl popl %%eax movl %%eax, %0")
29518 @end example
29519 @end quotation
29521 but in the generated assembler file, this would come out as:
29523 @quotation
29525 @example
29526 #APP
29527    pushfl popl %eax movl %eax, -40(%ebp)
29528 #NO_APP
29529 @end example
29530 @end quotation
29532 which is not so convenient for the human reader.
29534 We use Ada comments
29535 at the end of each line to explain what the assembler instructions
29536 actually do.  This is a useful convention.
29538 When writing Inline Assembler instructions, you need to precede each register
29539 and variable name with a percent sign.  Since the assembler already requires
29540 a percent sign at the beginning of a register name, you need two consecutive
29541 percent signs for such names in the Asm template string, thus @code{%%eax}.
29542 In the generated assembly code, one of the percent signs will be stripped off.
29544 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29545 variables: operands you later define using @code{Input} or @code{Output}
29546 parameters to @code{Asm}.
29547 An output variable is illustrated in
29548 the third statement in the Asm template string:
29550 @quotation
29552 @example
29553 movl %%eax, %0
29554 @end example
29555 @end quotation
29557 The intent is to store the contents of the eax register in a variable that can
29558 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
29559 necessarily work, since the compiler might optimize by using a register
29560 to hold Flags, and the expansion of the @code{movl} instruction would not be
29561 aware of this optimization.  The solution is not to store the result directly
29562 but rather to advise the compiler to choose the correct operand form;
29563 that is the purpose of the @code{%0} output variable.
29565 Information about the output variable is supplied in the @code{Outputs}
29566 parameter to @code{Asm}:
29568 @quotation
29570 @example
29571 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29572 @end example
29573 @end quotation
29575 The output is defined by the @code{Asm_Output} attribute of the target type;
29576 the general format is
29578 @quotation
29580 @example
29581 Type'Asm_Output (constraint_string, variable_name)
29582 @end example
29583 @end quotation
29585 The constraint string directs the compiler how
29586 to store/access the associated variable.  In the example
29588 @quotation
29590 @example
29591 Unsigned_32'Asm_Output ("=m", Flags);
29592 @end example
29593 @end quotation
29595 the @code{"m"} (memory) constraint tells the compiler that the variable
29596 @code{Flags} should be stored in a memory variable, thus preventing
29597 the optimizer from keeping it in a register.  In contrast,
29599 @quotation
29601 @example
29602 Unsigned_32'Asm_Output ("=r", Flags);
29603 @end example
29604 @end quotation
29606 uses the @code{"r"} (register) constraint, telling the compiler to
29607 store the variable in a register.
29609 If the constraint is preceded by the equal character '=', it tells
29610 the compiler that the variable will be used to store data into it.
29612 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29613 allowing the optimizer to choose whatever it deems best.
29615 There are a fairly large number of constraints, but the ones that are
29616 most useful (for the Intel x86 processor) are the following:
29618 @quotation
29621 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
29622 @item
29624 @emph{=}
29626 @tab
29628 output constraint
29630 @item
29632 @emph{g}
29634 @tab
29636 global (i.e., can be stored anywhere)
29638 @item
29640 @emph{m}
29642 @tab
29644 in memory
29646 @item
29648 @emph{I}
29650 @tab
29652 a constant
29654 @item
29656 @emph{a}
29658 @tab
29660 use eax
29662 @item
29664 @emph{b}
29666 @tab
29668 use ebx
29670 @item
29672 @emph{c}
29674 @tab
29676 use ecx
29678 @item
29680 @emph{d}
29682 @tab
29684 use edx
29686 @item
29688 @emph{S}
29690 @tab
29692 use esi
29694 @item
29696 @emph{D}
29698 @tab
29700 use edi
29702 @item
29704 @emph{r}
29706 @tab
29708 use one of eax, ebx, ecx or edx
29710 @item
29712 @emph{q}
29714 @tab
29716 use one of eax, ebx, ecx, edx, esi or edi
29718 @end multitable
29720 @end quotation
29722 The full set of constraints is described in the gcc and @code{as}
29723 documentation; note that it is possible to combine certain constraints
29724 in one constraint string.
29726 You specify the association of an output variable with an assembler operand
29727 through the @code{%@emph{n}} notation, where @emph{n} is a non-negative
29728 integer.  Thus in
29730 @quotation
29732 @example
29733 Asm ("pushfl"          & LF & HT & -- push flags on stack
29734      "popl %%eax"      & LF & HT & -- load eax with flags
29735      "movl %%eax, %0",             -- store flags in variable
29736      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29737 @end example
29738 @end quotation
29740 @code{%0} will be replaced in the expanded code by the appropriate operand,
29741 whatever
29742 the compiler decided for the @code{Flags} variable.
29744 In general, you may have any number of output variables:
29747 @itemize *
29749 @item 
29750 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
29752 @item 
29753 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
29754 of @code{Asm_Output} attributes
29755 @end itemize
29757 For example:
29759 @quotation
29761 @example
29762 Asm ("movl %%eax, %0" & LF & HT &
29763      "movl %%ebx, %1" & LF & HT &
29764      "movl %%ecx, %2",
29765      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
29766                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
29767                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
29768 @end example
29769 @end quotation
29771 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
29772 in the Ada program.
29774 As a variation on the @code{Get_Flags} example, we can use the constraints
29775 string to direct the compiler to store the eax register into the @code{Flags}
29776 variable, instead of including the store instruction explicitly in the
29777 @code{Asm} template string:
29779 @quotation
29781 @example
29782 with Interfaces; use Interfaces;
29783 with Ada.Text_IO; use Ada.Text_IO;
29784 with System.Machine_Code; use System.Machine_Code;
29785 procedure Get_Flags_2 is
29786    Flags : Unsigned_32;
29787    use ASCII;
29788 begin
29789    Asm ("pushfl"      & LF & HT & -- push flags on stack
29790         "popl %%eax",             -- save flags in eax
29791         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29792    Put_Line ("Flags register:" & Flags'Img);
29793 end Get_Flags_2;
29794 @end example
29795 @end quotation
29797 The @code{"a"} constraint tells the compiler that the @code{Flags}
29798 variable will come from the eax register. Here is the resulting code:
29800 @quotation
29802 @example
29803 #APP
29804    pushfl
29805    popl %eax
29806 #NO_APP
29807    movl %eax,-40(%ebp)
29808 @end example
29809 @end quotation
29811 The compiler generated the store of eax into Flags after
29812 expanding the assembler code.
29814 Actually, there was no need to pop the flags into the eax register;
29815 more simply, we could just pop the flags directly into the program variable:
29817 @quotation
29819 @example
29820 with Interfaces; use Interfaces;
29821 with Ada.Text_IO; use Ada.Text_IO;
29822 with System.Machine_Code; use System.Machine_Code;
29823 procedure Get_Flags_3 is
29824    Flags : Unsigned_32;
29825    use ASCII;
29826 begin
29827    Asm ("pushfl"  & LF & HT & -- push flags on stack
29828         "pop %0",             -- save flags in Flags
29829         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29830    Put_Line ("Flags register:" & Flags'Img);
29831 end Get_Flags_3;
29832 @end example
29833 @end quotation
29835 @node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
29836 @anchor{gnat_ugn/inline_assembler id5}@anchor{25a}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{25b}
29837 @section Input Variables in Inline Assembler
29840 The example in this section illustrates how to specify the source operands
29841 for assembly language statements.
29842 The program simply increments its input value by 1:
29844 @quotation
29846 @example
29847 with Interfaces; use Interfaces;
29848 with Ada.Text_IO; use Ada.Text_IO;
29849 with System.Machine_Code; use System.Machine_Code;
29850 procedure Increment is
29852    function Incr (Value : Unsigned_32) return Unsigned_32 is
29853       Result : Unsigned_32;
29854    begin
29855       Asm ("incl %0",
29856            Outputs => Unsigned_32'Asm_Output ("=a", Result),
29857            Inputs  => Unsigned_32'Asm_Input ("a", Value));
29858       return Result;
29859    end Incr;
29861    Value : Unsigned_32;
29863 begin
29864    Value := 5;
29865    Put_Line ("Value before is" & Value'Img);
29866    Value := Incr (Value);
29867   Put_Line ("Value after is" & Value'Img);
29868 end Increment;
29869 @end example
29870 @end quotation
29872 The @code{Outputs} parameter to @code{Asm} specifies
29873 that the result will be in the eax register and that it is to be stored
29874 in the @code{Result} variable.
29876 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
29877 but with an @code{Asm_Input} attribute.
29878 The @code{"="} constraint, indicating an output value, is not present.
29880 You can have multiple input variables, in the same way that you can have more
29881 than one output variable.
29883 The parameter count (%0, %1) etc, still starts at the first output statement,
29884 and continues with the input statements.
29886 Just as the @code{Outputs} parameter causes the register to be stored into the
29887 target variable after execution of the assembler statements, so does the
29888 @code{Inputs} parameter cause its variable to be loaded into the register
29889 before execution of the assembler statements.
29891 Thus the effect of the @code{Asm} invocation is:
29894 @itemize *
29896 @item 
29897 load the 32-bit value of @code{Value} into eax
29899 @item 
29900 execute the @code{incl %eax} instruction
29902 @item 
29903 store the contents of eax into the @code{Result} variable
29904 @end itemize
29906 The resulting assembler file (with @code{-O2} optimization) contains:
29908 @quotation
29910 @example
29911 _increment__incr.1:
29912    subl $4,%esp
29913    movl 8(%esp),%eax
29914 #APP
29915    incl %eax
29916 #NO_APP
29917    movl %eax,%edx
29918    movl %ecx,(%esp)
29919    addl $4,%esp
29920    ret
29921 @end example
29922 @end quotation
29924 @node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
29925 @anchor{gnat_ugn/inline_assembler id6}@anchor{25c}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{25d}
29926 @section Inlining Inline Assembler Code
29929 For a short subprogram such as the @code{Incr} function in the previous
29930 section, the overhead of the call and return (creating / deleting the stack
29931 frame) can be significant, compared to the amount of code in the subprogram
29932 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
29933 which directs the compiler to expand invocations of the subprogram at the
29934 point(s) of call, instead of setting up a stack frame for out-of-line calls.
29935 Here is the resulting program:
29937 @quotation
29939 @example
29940 with Interfaces; use Interfaces;
29941 with Ada.Text_IO; use Ada.Text_IO;
29942 with System.Machine_Code; use System.Machine_Code;
29943 procedure Increment_2 is
29945    function Incr (Value : Unsigned_32) return Unsigned_32 is
29946       Result : Unsigned_32;
29947    begin
29948       Asm ("incl %0",
29949            Outputs => Unsigned_32'Asm_Output ("=a", Result),
29950            Inputs  => Unsigned_32'Asm_Input ("a", Value));
29951       return Result;
29952    end Incr;
29953    pragma Inline (Increment);
29955    Value : Unsigned_32;
29957 begin
29958    Value := 5;
29959    Put_Line ("Value before is" & Value'Img);
29960    Value := Increment (Value);
29961    Put_Line ("Value after is" & Value'Img);
29962 end Increment_2;
29963 @end example
29964 @end quotation
29966 Compile the program with both optimization (@code{-O2}) and inlining
29967 (@code{-gnatn}) enabled.
29969 The @code{Incr} function is still compiled as usual, but at the
29970 point in @code{Increment} where our function used to be called:
29972 @quotation
29974 @example
29975 pushl %edi
29976 call _increment__incr.1
29977 @end example
29978 @end quotation
29980 the code for the function body directly appears:
29982 @quotation
29984 @example
29985 movl %esi,%eax
29986 #APP
29987    incl %eax
29988 #NO_APP
29989    movl %eax,%edx
29990 @end example
29991 @end quotation
29993 thus saving the overhead of stack frame setup and an out-of-line call.
29995 @node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
29996 @anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{25e}@anchor{gnat_ugn/inline_assembler id7}@anchor{25f}
29997 @section Other @code{Asm} Functionality
30000 This section describes two important parameters to the @code{Asm}
30001 procedure: @code{Clobber}, which identifies register usage;
30002 and @code{Volatile}, which inhibits unwanted optimizations.
30004 @menu
30005 * The Clobber Parameter:: 
30006 * The Volatile Parameter:: 
30008 @end menu
30010 @node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
30011 @anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{260}@anchor{gnat_ugn/inline_assembler id8}@anchor{261}
30012 @subsection The @code{Clobber} Parameter
30015 One of the dangers of intermixing assembly language and a compiled language
30016 such as Ada is that the compiler needs to be aware of which registers are
30017 being used by the assembly code.  In some cases, such as the earlier examples,
30018 the constraint string is sufficient to indicate register usage (e.g.,
30019 @code{"a"} for
30020 the eax register).  But more generally, the compiler needs an explicit
30021 identification of the registers that are used by the Inline Assembly
30022 statements.
30024 Using a register that the compiler doesn't know about
30025 could be a side effect of an instruction (like @code{mull}
30026 storing its result in both eax and edx).
30027 It can also arise from explicit register usage in your
30028 assembly code; for example:
30030 @quotation
30032 @example
30033 Asm ("movl %0, %%ebx" & LF & HT &
30034      "movl %%ebx, %1",
30035      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30036      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
30037 @end example
30038 @end quotation
30040 where the compiler (since it does not analyze the @code{Asm} template string)
30041 does not know you are using the ebx register.
30043 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30044 to identify the registers that will be used by your assembly code:
30046 @quotation
30048 @example
30049 Asm ("movl %0, %%ebx" & LF & HT &
30050      "movl %%ebx, %1",
30051      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30052      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30053      Clobber => "ebx");
30054 @end example
30055 @end quotation
30057 The Clobber parameter is a static string expression specifying the
30058 register(s) you are using.  Note that register names are @emph{not} prefixed
30059 by a percent sign. Also, if more than one register is used then their names
30060 are separated by commas; e.g., @code{"eax, ebx"}
30062 The @code{Clobber} parameter has several additional uses:
30065 @itemize *
30067 @item 
30068 Use 'register' name @code{cc} to indicate that flags might have changed
30070 @item 
30071 Use 'register' name @code{memory} if you changed a memory location
30072 @end itemize
30074 @node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
30075 @anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{262}@anchor{gnat_ugn/inline_assembler id9}@anchor{263}
30076 @subsection The @code{Volatile} Parameter
30079 @geindex Volatile parameter
30081 Compiler optimizations in the presence of Inline Assembler may sometimes have
30082 unwanted effects.  For example, when an @code{Asm} invocation with an input
30083 variable is inside a loop, the compiler might move the loading of the input
30084 variable outside the loop, regarding it as a one-time initialization.
30086 If this effect is not desired, you can disable such optimizations by setting
30087 the @code{Volatile} parameter to @code{True}; for example:
30089 @quotation
30091 @example
30092 Asm ("movl %0, %%ebx" & LF & HT &
30093      "movl %%ebx, %1",
30094      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
30095      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
30096      Clobber  => "ebx",
30097      Volatile => True);
30098 @end example
30099 @end quotation
30101 By default, @code{Volatile} is set to @code{False} unless there is no
30102 @code{Outputs} parameter.
30104 Although setting @code{Volatile} to @code{True} prevents unwanted
30105 optimizations, it will also disable other optimizations that might be
30106 important for efficiency. In general, you should set @code{Volatile}
30107 to @code{True} only if the compiler's optimizations have created
30108 problems.
30110 @node GNU Free Documentation License,Index,Inline Assembler,Top
30111 @anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license doc}@anchor{264}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{265}
30112 @chapter GNU Free Documentation License
30115 Version 1.3, 3 November 2008
30117 Copyright  2000, 2001, 2002, 2007, 2008  Free Software Foundation, Inc
30118 @indicateurl{http://fsf.org/}
30120 Everyone is permitted to copy and distribute verbatim copies of this
30121 license document, but changing it is not allowed.
30123 @strong{Preamble}
30125 The purpose of this License is to make a manual, textbook, or other
30126 functional and useful document "free" in the sense of freedom: to
30127 assure everyone the effective freedom to copy and redistribute it,
30128 with or without modifying it, either commercially or noncommercially.
30129 Secondarily, this License preserves for the author and publisher a way
30130 to get credit for their work, while not being considered responsible
30131 for modifications made by others.
30133 This License is a kind of "copyleft", which means that derivative
30134 works of the document must themselves be free in the same sense.  It
30135 complements the GNU General Public License, which is a copyleft
30136 license designed for free software.
30138 We have designed this License in order to use it for manuals for free
30139 software, because free software needs free documentation: a free
30140 program should come with manuals providing the same freedoms that the
30141 software does.  But this License is not limited to software manuals;
30142 it can be used for any textual work, regardless of subject matter or
30143 whether it is published as a printed book.  We recommend this License
30144 principally for works whose purpose is instruction or reference.
30146 @strong{1. APPLICABILITY AND DEFINITIONS}
30148 This License applies to any manual or other work, in any medium, that
30149 contains a notice placed by the copyright holder saying it can be
30150 distributed under the terms of this License.  Such a notice grants a
30151 world-wide, royalty-free license, unlimited in duration, to use that
30152 work under the conditions stated herein.  The @strong{Document}, below,
30153 refers to any such manual or work.  Any member of the public is a
30154 licensee, and is addressed as "@strong{you}".  You accept the license if you
30155 copy, modify or distribute the work in a way requiring permission
30156 under copyright law.
30158 A "@strong{Modified Version}" of the Document means any work containing the
30159 Document or a portion of it, either copied verbatim, or with
30160 modifications and/or translated into another language.
30162 A "@strong{Secondary Section}" is a named appendix or a front-matter section of
30163 the Document that deals exclusively with the relationship of the
30164 publishers or authors of the Document to the Document's overall subject
30165 (or to related matters) and contains nothing that could fall directly
30166 within that overall subject.  (Thus, if the Document is in part a
30167 textbook of mathematics, a Secondary Section may not explain any
30168 mathematics.)  The relationship could be a matter of historical
30169 connection with the subject or with related matters, or of legal,
30170 commercial, philosophical, ethical or political position regarding
30171 them.
30173 The "@strong{Invariant Sections}" are certain Secondary Sections whose titles
30174 are designated, as being those of Invariant Sections, in the notice
30175 that says that the Document is released under this License.  If a
30176 section does not fit the above definition of Secondary then it is not
30177 allowed to be designated as Invariant.  The Document may contain zero
30178 Invariant Sections.  If the Document does not identify any Invariant
30179 Sections then there are none.
30181 The "@strong{Cover Texts}" are certain short passages of text that are listed,
30182 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
30183 the Document is released under this License.  A Front-Cover Text may
30184 be at most 5 words, and a Back-Cover Text may be at most 25 words.
30186 A "@strong{Transparent}" copy of the Document means a machine-readable copy,
30187 represented in a format whose specification is available to the
30188 general public, that is suitable for revising the document
30189 straightforwardly with generic text editors or (for images composed of
30190 pixels) generic paint programs or (for drawings) some widely available
30191 drawing editor, and that is suitable for input to text formatters or
30192 for automatic translation to a variety of formats suitable for input
30193 to text formatters.  A copy made in an otherwise Transparent file
30194 format whose markup, or absence of markup, has been arranged to thwart
30195 or discourage subsequent modification by readers is not Transparent.
30196 An image format is not Transparent if used for any substantial amount
30197 of text.  A copy that is not "Transparent" is called @strong{Opaque}.
30199 Examples of suitable formats for Transparent copies include plain
30200 ASCII without markup, Texinfo input format, LaTeX input format, SGML
30201 or XML using a publicly available DTD, and standard-conforming simple
30202 HTML, PostScript or PDF designed for human modification.  Examples of
30203 transparent image formats include PNG, XCF and JPG.  Opaque formats
30204 include proprietary formats that can be read and edited only by
30205 proprietary word processors, SGML or XML for which the DTD and/or
30206 processing tools are not generally available, and the
30207 machine-generated HTML, PostScript or PDF produced by some word
30208 processors for output purposes only.
30210 The "@strong{Title Page}" means, for a printed book, the title page itself,
30211 plus such following pages as are needed to hold, legibly, the material
30212 this License requires to appear in the title page.  For works in
30213 formats which do not have any title page as such, "Title Page" means
30214 the text near the most prominent appearance of the work's title,
30215 preceding the beginning of the body of the text.
30217 The "@strong{publisher}" means any person or entity that distributes
30218 copies of the Document to the public.
30220 A section "@strong{Entitled XYZ}" means a named subunit of the Document whose
30221 title either is precisely XYZ or contains XYZ in parentheses following
30222 text that translates XYZ in another language.  (Here XYZ stands for a
30223 specific section name mentioned below, such as "@strong{Acknowledgements}",
30224 "@strong{Dedications}", "@strong{Endorsements}", or "@strong{History}".)
30225 To "@strong{Preserve the Title}"
30226 of such a section when you modify the Document means that it remains a
30227 section "Entitled XYZ" according to this definition.
30229 The Document may include Warranty Disclaimers next to the notice which
30230 states that this License applies to the Document.  These Warranty
30231 Disclaimers are considered to be included by reference in this
30232 License, but only as regards disclaiming warranties: any other
30233 implication that these Warranty Disclaimers may have is void and has
30234 no effect on the meaning of this License.
30236 @strong{2. VERBATIM COPYING}
30238 You may copy and distribute the Document in any medium, either
30239 commercially or noncommercially, provided that this License, the
30240 copyright notices, and the license notice saying this License applies
30241 to the Document are reproduced in all copies, and that you add no other
30242 conditions whatsoever to those of this License.  You may not use
30243 technical measures to obstruct or control the reading or further
30244 copying of the copies you make or distribute.  However, you may accept
30245 compensation in exchange for copies.  If you distribute a large enough
30246 number of copies you must also follow the conditions in section 3.
30248 You may also lend copies, under the same conditions stated above, and
30249 you may publicly display copies.
30251 @strong{3. COPYING IN QUANTITY}
30253 If you publish printed copies (or copies in media that commonly have
30254 printed covers) of the Document, numbering more than 100, and the
30255 Document's license notice requires Cover Texts, you must enclose the
30256 copies in covers that carry, clearly and legibly, all these Cover
30257 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
30258 the back cover.  Both covers must also clearly and legibly identify
30259 you as the publisher of these copies.  The front cover must present
30260 the full title with all words of the title equally prominent and
30261 visible.  You may add other material on the covers in addition.
30262 Copying with changes limited to the covers, as long as they preserve
30263 the title of the Document and satisfy these conditions, can be treated
30264 as verbatim copying in other respects.
30266 If the required texts for either cover are too voluminous to fit
30267 legibly, you should put the first ones listed (as many as fit
30268 reasonably) on the actual cover, and continue the rest onto adjacent
30269 pages.
30271 If you publish or distribute Opaque copies of the Document numbering
30272 more than 100, you must either include a machine-readable Transparent
30273 copy along with each Opaque copy, or state in or with each Opaque copy
30274 a computer-network location from which the general network-using
30275 public has access to download using public-standard network protocols
30276 a complete Transparent copy of the Document, free of added material.
30277 If you use the latter option, you must take reasonably prudent steps,
30278 when you begin distribution of Opaque copies in quantity, to ensure
30279 that this Transparent copy will remain thus accessible at the stated
30280 location until at least one year after the last time you distribute an
30281 Opaque copy (directly or through your agents or retailers) of that
30282 edition to the public.
30284 It is requested, but not required, that you contact the authors of the
30285 Document well before redistributing any large number of copies, to give
30286 them a chance to provide you with an updated version of the Document.
30288 @strong{4. MODIFICATIONS}
30290 You may copy and distribute a Modified Version of the Document under
30291 the conditions of sections 2 and 3 above, provided that you release
30292 the Modified Version under precisely this License, with the Modified
30293 Version filling the role of the Document, thus licensing distribution
30294 and modification of the Modified Version to whoever possesses a copy
30295 of it.  In addition, you must do these things in the Modified Version:
30298 @enumerate A
30300 @item 
30301 Use in the Title Page (and on the covers, if any) a title distinct
30302 from that of the Document, and from those of previous versions
30303 (which should, if there were any, be listed in the History section
30304 of the Document).  You may use the same title as a previous version
30305 if the original publisher of that version gives permission.
30307 @item 
30308 List on the Title Page, as authors, one or more persons or entities
30309 responsible for authorship of the modifications in the Modified
30310 Version, together with at least five of the principal authors of the
30311 Document (all of its principal authors, if it has fewer than five),
30312 unless they release you from this requirement.
30314 @item 
30315 State on the Title page the name of the publisher of the
30316 Modified Version, as the publisher.
30318 @item 
30319 Preserve all the copyright notices of the Document.
30321 @item 
30322 Add an appropriate copyright notice for your modifications
30323 adjacent to the other copyright notices.
30325 @item 
30326 Include, immediately after the copyright notices, a license notice
30327 giving the public permission to use the Modified Version under the
30328 terms of this License, in the form shown in the Addendum below.
30330 @item 
30331 Preserve in that license notice the full lists of Invariant Sections
30332 and required Cover Texts given in the Document's license notice.
30334 @item 
30335 Include an unaltered copy of this License.
30337 @item 
30338 Preserve the section Entitled "History", Preserve its Title, and add
30339 to it an item stating at least the title, year, new authors, and
30340 publisher of the Modified Version as given on the Title Page.  If
30341 there is no section Entitled "History" in the Document, create one
30342 stating the title, year, authors, and publisher of the Document as
30343 given on its Title Page, then add an item describing the Modified
30344 Version as stated in the previous sentence.
30346 @item 
30347 Preserve the network location, if any, given in the Document for
30348 public access to a Transparent copy of the Document, and likewise
30349 the network locations given in the Document for previous versions
30350 it was based on.  These may be placed in the "History" section.
30351 You may omit a network location for a work that was published at
30352 least four years before the Document itself, or if the original
30353 publisher of the version it refers to gives permission.
30355 @item 
30356 For any section Entitled "Acknowledgements" or "Dedications",
30357 Preserve the Title of the section, and preserve in the section all
30358 the substance and tone of each of the contributor acknowledgements
30359 and/or dedications given therein.
30361 @item 
30362 Preserve all the Invariant Sections of the Document,
30363 unaltered in their text and in their titles.  Section numbers
30364 or the equivalent are not considered part of the section titles.
30366 @item 
30367 Delete any section Entitled "Endorsements".  Such a section
30368 may not be included in the Modified Version.
30370 @item 
30371 Do not retitle any existing section to be Entitled "Endorsements"
30372 or to conflict in title with any Invariant Section.
30374 @item 
30375 Preserve any Warranty Disclaimers.
30376 @end enumerate
30378 If the Modified Version includes new front-matter sections or
30379 appendices that qualify as Secondary Sections and contain no material
30380 copied from the Document, you may at your option designate some or all
30381 of these sections as invariant.  To do this, add their titles to the
30382 list of Invariant Sections in the Modified Version's license notice.
30383 These titles must be distinct from any other section titles.
30385 You may add a section Entitled "Endorsements", provided it contains
30386 nothing but endorsements of your Modified Version by various
30387 parties---for example, statements of peer review or that the text has
30388 been approved by an organization as the authoritative definition of a
30389 standard.
30391 You may add a passage of up to five words as a Front-Cover Text, and a
30392 passage of up to 25 words as a Back-Cover Text, to the end of the list
30393 of Cover Texts in the Modified Version.  Only one passage of
30394 Front-Cover Text and one of Back-Cover Text may be added by (or
30395 through arrangements made by) any one entity.  If the Document already
30396 includes a cover text for the same cover, previously added by you or
30397 by arrangement made by the same entity you are acting on behalf of,
30398 you may not add another; but you may replace the old one, on explicit
30399 permission from the previous publisher that added the old one.
30401 The author(s) and publisher(s) of the Document do not by this License
30402 give permission to use their names for publicity for or to assert or
30403 imply endorsement of any Modified Version.
30405 @strong{5. COMBINING DOCUMENTS}
30407 You may combine the Document with other documents released under this
30408 License, under the terms defined in section 4 above for modified
30409 versions, provided that you include in the combination all of the
30410 Invariant Sections of all of the original documents, unmodified, and
30411 list them all as Invariant Sections of your combined work in its
30412 license notice, and that you preserve all their Warranty Disclaimers.
30414 The combined work need only contain one copy of this License, and
30415 multiple identical Invariant Sections may be replaced with a single
30416 copy.  If there are multiple Invariant Sections with the same name but
30417 different contents, make the title of each such section unique by
30418 adding at the end of it, in parentheses, the name of the original
30419 author or publisher of that section if known, or else a unique number.
30420 Make the same adjustment to the section titles in the list of
30421 Invariant Sections in the license notice of the combined work.
30423 In the combination, you must combine any sections Entitled "History"
30424 in the various original documents, forming one section Entitled
30425 "History"; likewise combine any sections Entitled "Acknowledgements",
30426 and any sections Entitled "Dedications".  You must delete all sections
30427 Entitled "Endorsements".
30429 @strong{6. COLLECTIONS OF DOCUMENTS}
30431 You may make a collection consisting of the Document and other documents
30432 released under this License, and replace the individual copies of this
30433 License in the various documents with a single copy that is included in
30434 the collection, provided that you follow the rules of this License for
30435 verbatim copying of each of the documents in all other respects.
30437 You may extract a single document from such a collection, and distribute
30438 it individually under this License, provided you insert a copy of this
30439 License into the extracted document, and follow this License in all
30440 other respects regarding verbatim copying of that document.
30442 @strong{7. AGGREGATION WITH INDEPENDENT WORKS}
30444 A compilation of the Document or its derivatives with other separate
30445 and independent documents or works, in or on a volume of a storage or
30446 distribution medium, is called an "aggregate" if the copyright
30447 resulting from the compilation is not used to limit the legal rights
30448 of the compilation's users beyond what the individual works permit.
30449 When the Document is included in an aggregate, this License does not
30450 apply to the other works in the aggregate which are not themselves
30451 derivative works of the Document.
30453 If the Cover Text requirement of section 3 is applicable to these
30454 copies of the Document, then if the Document is less than one half of
30455 the entire aggregate, the Document's Cover Texts may be placed on
30456 covers that bracket the Document within the aggregate, or the
30457 electronic equivalent of covers if the Document is in electronic form.
30458 Otherwise they must appear on printed covers that bracket the whole
30459 aggregate.
30461 @strong{8. TRANSLATION}
30463 Translation is considered a kind of modification, so you may
30464 distribute translations of the Document under the terms of section 4.
30465 Replacing Invariant Sections with translations requires special
30466 permission from their copyright holders, but you may include
30467 translations of some or all Invariant Sections in addition to the
30468 original versions of these Invariant Sections.  You may include a
30469 translation of this License, and all the license notices in the
30470 Document, and any Warranty Disclaimers, provided that you also include
30471 the original English version of this License and the original versions
30472 of those notices and disclaimers.  In case of a disagreement between
30473 the translation and the original version of this License or a notice
30474 or disclaimer, the original version will prevail.
30476 If a section in the Document is Entitled "Acknowledgements",
30477 "Dedications", or "History", the requirement (section 4) to Preserve
30478 its Title (section 1) will typically require changing the actual
30479 title.
30481 @strong{9. TERMINATION}
30483 You may not copy, modify, sublicense, or distribute the Document
30484 except as expressly provided under this License.  Any attempt
30485 otherwise to copy, modify, sublicense, or distribute it is void, and
30486 will automatically terminate your rights under this License.
30488 However, if you cease all violation of this License, then your license
30489 from a particular copyright holder is reinstated (a) provisionally,
30490 unless and until the copyright holder explicitly and finally
30491 terminates your license, and (b) permanently, if the copyright holder
30492 fails to notify you of the violation by some reasonable means prior to
30493 60 days after the cessation.
30495 Moreover, your license from a particular copyright holder is
30496 reinstated permanently if the copyright holder notifies you of the
30497 violation by some reasonable means, this is the first time you have
30498 received notice of violation of this License (for any work) from that
30499 copyright holder, and you cure the violation prior to 30 days after
30500 your receipt of the notice.
30502 Termination of your rights under this section does not terminate the
30503 licenses of parties who have received copies or rights from you under
30504 this License.  If your rights have been terminated and not permanently
30505 reinstated, receipt of a copy of some or all of the same material does
30506 not give you any rights to use it.
30508 @strong{10. FUTURE REVISIONS OF THIS LICENSE}
30510 The Free Software Foundation may publish new, revised versions
30511 of the GNU Free Documentation License from time to time.  Such new
30512 versions will be similar in spirit to the present version, but may
30513 differ in detail to address new problems or concerns.  See
30514 @indicateurl{http://www.gnu.org/copyleft/}.
30516 Each version of the License is given a distinguishing version number.
30517 If the Document specifies that a particular numbered version of this
30518 License "or any later version" applies to it, you have the option of
30519 following the terms and conditions either of that specified version or
30520 of any later version that has been published (not as a draft) by the
30521 Free Software Foundation.  If the Document does not specify a version
30522 number of this License, you may choose any version ever published (not
30523 as a draft) by the Free Software Foundation.  If the Document
30524 specifies that a proxy can decide which future versions of this
30525 License can be used, that proxy's public statement of acceptance of a
30526 version permanently authorizes you to choose that version for the
30527 Document.
30529 @strong{11. RELICENSING}
30531 "Massive Multiauthor Collaboration Site" (or "MMC Site") means any
30532 World Wide Web server that publishes copyrightable works and also
30533 provides prominent facilities for anybody to edit those works.  A
30534 public wiki that anybody can edit is an example of such a server.  A
30535 "Massive Multiauthor Collaboration" (or "MMC") contained in the
30536 site means any set of copyrightable works thus published on the MMC
30537 site.
30539 "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0
30540 license published by Creative Commons Corporation, a not-for-profit
30541 corporation with a principal place of business in San Francisco,
30542 California, as well as future copyleft versions of that license
30543 published by that same organization.
30545 "Incorporate" means to publish or republish a Document, in whole or
30546 in part, as part of another Document.
30548 An MMC is "eligible for relicensing" if it is licensed under this
30549 License, and if all works that were first published under this License
30550 somewhere other than this MMC, and subsequently incorporated in whole
30551 or in part into the MMC, (1) had no cover texts or invariant sections,
30552 and (2) were thus incorporated prior to November 1, 2008.
30554 The operator of an MMC Site may republish an MMC contained in the site
30555 under CC-BY-SA on the same site at any time before August 1, 2009,
30556 provided the MMC is eligible for relicensing.
30558 @strong{ADDENDUM: How to use this License for your documents}
30560 To use this License in a document you have written, include a copy of
30561 the License in the document and put the following copyright and
30562 license notices just after the title page:
30564 @quotation
30566 Copyright © YEAR  YOUR NAME.
30567 Permission is granted to copy, distribute and/or modify this document
30568 under the terms of the GNU Free Documentation License, Version 1.3
30569 or any later version published by the Free Software Foundation;
30570 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
30571 A copy of the license is included in the section entitled "GNU
30572 Free Documentation License".
30573 @end quotation
30575 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
30576 replace the "with ... Texts." line with this:
30578 @quotation
30580 with the Invariant Sections being LIST THEIR TITLES, with the
30581 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
30582 @end quotation
30584 If you have Invariant Sections without Cover Texts, or some other
30585 combination of the three, merge those two alternatives to suit the
30586 situation.
30588 If your document contains nontrivial examples of program code, we
30589 recommend releasing these examples in parallel under your choice of
30590 free software license, such as the GNU General Public License,
30591 to permit their use in free software.
30593 @node Index,,GNU Free Documentation License,Top
30594 @unnumbered Index
30597 @printindex ge
30599 @anchor{de}@w{                              }
30600 @anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{                              }
30602 @c %**end of body
30603 @bye