PR target/79080
[official-gcc.git] / gcc / ada / gnat_ugn.texi
blob421419f5bfa90eb3f92830c260ea21d5dbeee4f7
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.3b2.@*
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 , January 13, 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 * Project 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:: 
376 Stack Traceback
378 * Non-Symbolic Traceback:: 
379 * Symbolic Traceback:: 
381 Code Coverage and Profiling
383 * Code Coverage of Ada Programs with gcov:: 
384 * Profiling an Ada Program with gprof:: 
386 Code Coverage of Ada Programs with gcov
388 * Quick startup guide:: 
389 * GNAT specifics:: 
391 Profiling an Ada Program with gprof
393 * Compilation for profiling:: 
394 * Program execution:: 
395 * Running gprof:: 
396 * Interpretation of profiling results:: 
398 Improving Performance
400 * Performance Considerations:: 
401 * Text_IO Suggestions:: 
402 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
404 Performance Considerations
406 * Controlling Run-Time Checks:: 
407 * Use of Restrictions:: 
408 * Optimization Levels:: 
409 * Debugging Optimized Code:: 
410 * Inlining of Subprograms:: 
411 * Floating_Point_Operations:: 
412 * Vectorization of loops:: 
413 * Other Optimization Switches:: 
414 * Optimization and Strict Aliasing:: 
415 * Aliased Variables and Optimization:: 
416 * Atomic Variables and Optimization:: 
417 * Passive Task Optimization:: 
419 Reducing Size of Executables with Unused Subprogram/Data Elimination
421 * About unused subprogram/data elimination:: 
422 * Compilation options:: 
423 * Example of unused subprogram/data elimination:: 
425 Overflow Check Handling in GNAT
427 * Background:: 
428 * Management of Overflows in GNAT:: 
429 * Specifying the Desired Mode:: 
430 * Default Settings:: 
431 * Implementation Notes:: 
433 Stack Related Facilities
435 * Stack Overflow Checking:: 
436 * Static Stack Usage Analysis:: 
437 * Dynamic Stack Usage Analysis:: 
439 Memory Management Issues
441 * Some Useful Memory Pools:: 
442 * The GNAT Debug Pool Facility:: 
444 Platform-Specific Information
446 * Run-Time Libraries:: 
447 * Specifying a Run-Time Library:: 
448 * Microsoft Windows Topics:: 
449 * Mac OS Topics:: 
451 Run-Time Libraries
453 * Summary of Run-Time Configurations:: 
455 Specifying a Run-Time Library
457 * Choosing the Scheduling Policy:: 
458 * Solaris-Specific Considerations:: 
459 * Solaris Threads Issues:: 
460 * AIX-Specific Considerations:: 
462 Microsoft Windows Topics
464 * Using GNAT on Windows:: 
465 * Using a network installation of GNAT:: 
466 * CONSOLE and WINDOWS subsystems:: 
467 * Temporary Files:: 
468 * Disabling Command Line Argument Expansion:: 
469 * Mixed-Language Programming on Windows:: 
470 * Windows Specific Add-Ons:: 
472 Mixed-Language Programming on Windows
474 * Windows Calling Conventions:: 
475 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
476 * Using DLLs with GNAT:: 
477 * Building DLLs with GNAT Project files:: 
478 * Building DLLs with GNAT:: 
479 * Building DLLs with gnatdll:: 
480 * Ada DLLs and Finalization:: 
481 * Creating a Spec for Ada DLLs:: 
482 * GNAT and Windows Resources:: 
483 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
484 * Debugging a DLL:: 
485 * Setting Stack Size from gnatlink:: 
486 * Setting Heap Size from gnatlink:: 
488 Windows Calling Conventions
490 * C Calling Convention:: 
491 * Stdcall Calling Convention:: 
492 * Win32 Calling Convention:: 
493 * DLL Calling Convention:: 
495 Using DLLs with GNAT
497 * Creating an Ada Spec for the DLL Services:: 
498 * Creating an Import Library:: 
500 Building DLLs with gnatdll
502 * Limitations When Using Ada DLLs from Ada:: 
503 * Exporting Ada Entities:: 
504 * Ada DLLs and Elaboration:: 
506 Creating a Spec for Ada DLLs
508 * Creating the Definition File:: 
509 * Using gnatdll:: 
511 GNAT and Windows Resources
513 * Building Resources:: 
514 * Compiling Resources:: 
515 * Using Resources:: 
517 Debugging a DLL
519 * Program and DLL Both Built with GCC/GNAT:: 
520 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
522 Windows Specific Add-Ons
524 * Win32Ada:: 
525 * wPOSIX:: 
527 Mac OS Topics
529 * Codesigning the Debugger:: 
531 Elaboration Order Handling in GNAT
533 * Elaboration Code:: 
534 * Checking the Elaboration Order:: 
535 * Controlling the Elaboration Order:: 
536 * Controlling Elaboration in GNAT - Internal Calls:: 
537 * Controlling Elaboration in GNAT - External Calls:: 
538 * Default Behavior in GNAT - Ensuring Safety:: 
539 * Treatment of Pragma Elaborate:: 
540 * Elaboration Issues for Library Tasks:: 
541 * Mixing Elaboration Models:: 
542 * What to Do If the Default Elaboration Behavior Fails:: 
543 * Elaboration for Indirect Calls:: 
544 * Summary of Procedures for Elaboration Control:: 
545 * Other Elaboration Order Considerations:: 
546 * Determining the Chosen Elaboration Order:: 
548 Inline Assembler
550 * Basic Assembler Syntax:: 
551 * A Simple Example of Inline Assembler:: 
552 * Output Variables in Inline Assembler:: 
553 * Input Variables in Inline Assembler:: 
554 * Inlining Inline Assembler Code:: 
555 * Other Asm Functionality:: 
557 Other Asm Functionality
559 * The Clobber Parameter:: 
560 * The Volatile Parameter:: 
562 @end detailmenu
563 @end menu
565 @node About This Guide,Getting Started with GNAT,Top,Top
566 @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}
567 @chapter About This Guide
571 This guide describes the use of GNAT,
572 a compiler and software development
573 toolset for the full Ada programming language.
574 It documents the features of the compiler and tools, and explains
575 how to use them to build Ada applications.
577 GNAT implements Ada 95, Ada 2005 and Ada 2012, and it may also be
578 invoked in Ada 83 compatibility mode.
579 By default, GNAT assumes Ada 2012, but you can override with a
580 compiler switch (@ref{6,,Compiling Different Versions of Ada})
581 to explicitly specify the language version.
582 Throughout this manual, references to 'Ada' without a year suffix
583 apply to all Ada 95/2005/2012 versions of the language.
585 @menu
586 * What This Guide Contains:: 
587 * What You Should Know before Reading This Guide:: 
588 * Related Information:: 
589 * A Note to Readers of Previous Versions of the Manual:: 
590 * Conventions:: 
592 @end menu
594 @node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
595 @anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
596 @section What This Guide Contains
599 This guide contains the following chapters:
602 @itemize *
604 @item 
605 @ref{8,,Getting Started with GNAT} describes how to get started compiling
606 and running Ada programs with the GNAT Ada programming environment.
608 @item 
609 @ref{9,,The GNAT Compilation Model} describes the compilation model used
610 by GNAT.
612 @item 
613 @ref{a,,Building Executable Programs with GNAT} describes how to use the
614 main GNAT tools to build executable programs, and it also gives examples of
615 using the GNU make utility with GNAT.
617 @item 
618 @ref{b,,GNAT Utility Programs} explains the various utility programs that
619 are included in the GNAT environment
621 @item 
622 @ref{c,,GNAT and Program Execution} covers a number of topics related to
623 running, debugging, and tuning the performace of programs developed
624 with GNAT
625 @end itemize
627 Appendices cover several additional topics:
630 @itemize *
632 @item 
633 @ref{d,,Platform-Specific Information} describes the different run-time
634 library implementations and also presents information on how to use
635 GNAT on several specific platforms
637 @item 
638 @ref{e,,Example of Binder Output File} shows the source code for the binder
639 output file for a sample program.
641 @item 
642 @ref{f,,Elaboration Order Handling in GNAT} describes how GNAT helps
643 you deal with elaboration order issues.
645 @item 
646 @ref{10,,Inline Assembler} shows how to use the inline assembly facility
647 in an Ada program.
648 @end itemize
650 @node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
651 @anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{11}
652 @section What You Should Know before Reading This Guide
655 @geindex Ada 95 Language Reference Manual
657 @geindex Ada 2005 Language Reference Manual
659 This guide assumes a basic familiarity with the Ada 95 language, as
660 described in the International Standard ANSI/ISO/IEC-8652:1995, January
661 1995.
662 It does not require knowledge of the features introduced by Ada 2005
663 or Ada 2012.
664 Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
665 the GNAT documentation package.
667 @node Related Information,A Note to Readers of Previous Versions of the Manual,What You Should Know before Reading This Guide,About This Guide
668 @anchor{gnat_ugn/about_this_guide related-information}@anchor{12}
669 @section Related Information
672 For further information about Ada and related tools, please refer to the
673 following documents:
676 @itemize *
678 @item 
679 @cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
680 @cite{Ada 2012 Reference Manual}, which contain reference
681 material for the several revisions of the Ada language standard.
683 @item 
684 @cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
685 implementation of Ada.
687 @item 
688 @cite{Using the GNAT Programming Studio}, which describes the GPS
689 Integrated Development Environment.
691 @item 
692 @cite{GNAT Programming Studio Tutorial}, which introduces the
693 main GPS features through examples.
695 @item 
696 @cite{Debugging with GDB},
697 for all details on the use of the GNU source-level debugger.
699 @item 
700 @cite{GNU Emacs Manual},
701 for full information on the extensible editor and programming
702 environment Emacs.
703 @end itemize
705 @node A Note to Readers of Previous Versions of the Manual,Conventions,Related Information,About This Guide
706 @anchor{gnat_ugn/about_this_guide a-note-to-readers-of-previous-versions-of-the-manual}@anchor{13}
707 @section A Note to Readers of Previous Versions of the Manual
710 In early 2015 the GNAT manuals were transitioned to the
711 reStructuredText (rst) / Sphinx documentation generator technology.
712 During that process the @cite{GNAT User's Guide} was reorganized
713 so that related topics would be described together in the same chapter
714 or appendix.  Here's a summary of the major changes realized in
715 the new document structure.
718 @itemize *
720 @item 
721 @ref{9,,The GNAT Compilation Model} has been extended so that it now covers
722 the following material:
725 @itemize -
727 @item 
728 The @cite{gnatname}, @cite{gnatkr}, and @cite{gnatchop} tools
730 @item 
731 @ref{14,,Configuration Pragmas}
733 @item 
734 @ref{15,,GNAT and Libraries}
736 @item 
737 @ref{16,,Conditional Compilation} including @ref{17,,Preprocessing with gnatprep}
738 and @ref{18,,Integrated Preprocessing}
740 @item 
741 @ref{19,,Generating Ada Bindings for C and C++ headers}
743 @item 
744 @ref{1a,,Using GNAT Files with External Tools}
745 @end itemize
747 @item 
748 @ref{a,,Building Executable Programs with GNAT} is a new chapter consolidating
749 the following content:
752 @itemize -
754 @item 
755 @ref{1b,,Building with gnatmake}
757 @item 
758 @ref{1c,,Compiling with gcc}
760 @item 
761 @ref{1d,,Binding with gnatbind}
763 @item 
764 @ref{1e,,Linking with gnatlink}
766 @item 
767 @ref{1f,,Using the GNU make Utility}
768 @end itemize
770 @item 
771 @ref{b,,GNAT Utility Programs} is a new chapter consolidating the information about several
772 GNAT tools:
776 @itemize -
778 @item 
779 @ref{20,,The File Cleanup Utility gnatclean}
781 @item 
782 @ref{21,,The GNAT Library Browser gnatls}
784 @item 
785 @ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
787 @item 
788 @ref{23,,The Ada to HTML Converter gnathtml}
789 @end itemize
791 @item 
792 @ref{c,,GNAT and Program Execution} is a new chapter consolidating the following:
795 @itemize -
797 @item 
798 @ref{24,,Running and Debugging Ada Programs}
800 @item 
801 @ref{25,,Code Coverage and Profiling}
803 @item 
804 @ref{26,,Improving Performance}
806 @item 
807 @ref{27,,Overflow Check Handling in GNAT}
809 @item 
810 @ref{28,,Performing Dimensionality Analysis in GNAT}
812 @item 
813 @ref{29,,Stack Related Facilities}
815 @item 
816 @ref{2a,,Memory Management Issues}
817 @end itemize
819 @item 
820 @ref{d,,Platform-Specific Information} is a new appendix consolidating the following:
823 @itemize -
825 @item 
826 @ref{2b,,Run-Time Libraries}
828 @item 
829 @ref{2c,,Microsoft Windows Topics}
831 @item 
832 @ref{2d,,Mac OS Topics}
833 @end itemize
835 @item 
836 The @cite{Compatibility and Porting Guide} appendix has been moved to the
837 @cite{GNAT Reference Manual}. It now includes a section
838 @cite{Writing Portable Fixed-Point Declarations} which was previously
839 a separate chapter in the @cite{GNAT User's Guide}.
840 @end itemize
842 @node Conventions,,A Note to Readers of Previous Versions of the Manual,About This Guide
843 @anchor{gnat_ugn/about_this_guide conventions}@anchor{2e}
844 @section Conventions
847 @geindex Conventions
848 @geindex typographical
850 @geindex Typographical conventions
852 Following are examples of the typographical and graphic conventions used
853 in this guide:
856 @itemize *
858 @item 
859 @cite{Functions}, @cite{utility program names}, @cite{standard names},
860 and @cite{classes}.
862 @item 
863 @cite{Option flags}
865 @item 
866 @code{File names}
868 @item 
869 @cite{Variables}
871 @item 
872 @emph{Emphasis}
874 @item 
875 [optional information or parameters]
877 @item 
878 Examples are described by text
880 @example
881 and then shown this way.
882 @end example
884 @item 
885 Commands that are entered by the user are shown as preceded by a prompt string
886 comprising the @code{$} character followed by a space.
888 @item 
889 Full file names are shown with the '/' character
890 as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
891 If you are using GNAT on a Windows platform, please note that
892 the '\' character should be used instead.
893 @end itemize
895 @node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
896 @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}
897 @chapter Getting Started with GNAT
900 This chapter describes how to use GNAT's command line interface to build
901 executable Ada programs.
902 On most platforms a visually oriented Integrated Development Environment
903 is also available, the GNAT Programming Studio (GPS).
904 GPS offers a graphical "look and feel", support for development in
905 other programming languages, comprehensive browsing features, and
906 many other capabilities.
907 For information on GPS please refer to
908 @cite{Using the GNAT Programming Studio}.
910 @menu
911 * Running GNAT:: 
912 * Running a Simple Ada Program:: 
913 * Running a Program with Multiple Units:: 
914 * Using the gnatmake Utility:: 
916 @end menu
918 @node Running GNAT,Running a Simple Ada Program,,Getting Started with GNAT
919 @anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{31}@anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{32}
920 @section Running GNAT
923 Three steps are needed to create an executable file from an Ada source
924 file:
927 @itemize *
929 @item 
930 The source file(s) must be compiled.
932 @item 
933 The file(s) must be bound using the GNAT binder.
935 @item 
936 All appropriate object files must be linked to produce an executable.
937 @end itemize
939 All three steps are most commonly handled by using the @emph{gnatmake}
940 utility program that, given the name of the main program, automatically
941 performs the necessary compilation, binding and linking steps.
943 @node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
944 @anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{33}@anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{34}
945 @section Running a Simple Ada Program
948 Any text editor may be used to prepare an Ada program.
949 (If Emacs is used, the optional Ada mode may be helpful in laying out the
950 program.)
951 The program text is a normal text file. We will assume in our initial
952 example that you have used your editor to prepare the following
953 standard format text file:
955 @example
956 with Ada.Text_IO; use Ada.Text_IO;
957 procedure Hello is
958 begin
959    Put_Line ("Hello WORLD!");
960 end Hello;
961 @end example
963 This file should be named @code{hello.adb}.
964 With the normal default file naming conventions, GNAT requires
965 that each file
966 contain a single compilation unit whose file name is the
967 unit name,
968 with periods replaced by hyphens; the
969 extension is @code{ads} for a
970 spec and @code{adb} for a body.
971 You can override this default file naming convention by use of the
972 special pragma @cite{Source_File_Name} (for further information please
973 see @ref{35,,Using Other File Names}).
974 Alternatively, if you want to rename your files according to this default
975 convention, which is probably more convenient if you will be using GNAT
976 for all your compilations, then the @cite{gnatchop} utility
977 can be used to generate correctly-named source files
978 (see @ref{36,,Renaming Files with gnatchop}).
980 You can compile the program using the following command (@cite{$} is used
981 as the command prompt in the examples in this document):
983 @example
984 $ gcc -c hello.adb
985 @end example
987 @emph{gcc} is the command used to run the compiler. This compiler is
988 capable of compiling programs in several languages, including Ada and
989 C. It assumes that you have given it an Ada program if the file extension is
990 either @code{.ads} or @code{.adb}, and it will then call
991 the GNAT compiler to compile the specified file.
993 The @code{-c} switch is required. It tells @emph{gcc} to only do a
994 compilation. (For C programs, @emph{gcc} can also do linking, but this
995 capability is not used directly for Ada programs, so the @code{-c}
996 switch must always be present.)
998 This compile command generates a file
999 @code{hello.o}, which is the object
1000 file corresponding to your Ada program. It also generates
1001 an 'Ada Library Information' file @code{hello.ali},
1002 which contains additional information used to check
1003 that an Ada program is consistent.
1004 To build an executable file,
1005 use @cite{gnatbind} to bind the program
1006 and @emph{gnatlink} to link it. The
1007 argument to both @cite{gnatbind} and @emph{gnatlink} is the name of the
1008 @code{ALI} file, but the default extension of @code{.ali} can
1009 be omitted. This means that in the most common case, the argument
1010 is simply the name of the main program:
1012 @example
1013 $ gnatbind hello
1014 $ gnatlink hello
1015 @end example
1017 A simpler method of carrying out these steps is to use @emph{gnatmake},
1018 a master program that invokes all the required
1019 compilation, binding and linking tools in the correct order. In particular,
1020 @emph{gnatmake} automatically recompiles any sources that have been
1021 modified since they were last compiled, or sources that depend
1022 on such modified sources, so that 'version skew' is avoided.
1024 @geindex Version skew (avoided by *gnatmake*)
1026 @example
1027 $ gnatmake hello.adb
1028 @end example
1030 The result is an executable program called @code{hello}, which can be
1031 run by entering:
1033 @example
1034 $ hello
1035 @end example
1037 assuming that the current directory is on the search path
1038 for executable programs.
1040 and, if all has gone well, you will see:
1042 @example
1043 Hello WORLD!
1044 @end example
1046 appear in response to this command.
1048 @node Running a Program with Multiple Units,Using the gnatmake Utility,Running a Simple Ada Program,Getting Started with GNAT
1049 @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}
1050 @section Running a Program with Multiple Units
1053 Consider a slightly more complicated example that has three files: a
1054 main program, and the spec and body of a package:
1056 @example
1057 package Greetings is
1058    procedure Hello;
1059    procedure Goodbye;
1060 end Greetings;
1062 with Ada.Text_IO; use Ada.Text_IO;
1063 package body Greetings is
1064    procedure Hello is
1065    begin
1066       Put_Line ("Hello WORLD!");
1067    end Hello;
1069    procedure Goodbye is
1070    begin
1071       Put_Line ("Goodbye WORLD!");
1072    end Goodbye;
1073 end Greetings;
1075 with Greetings;
1076 procedure Gmain is
1077 begin
1078    Greetings.Hello;
1079    Greetings.Goodbye;
1080 end Gmain;
1081 @end example
1083 Following the one-unit-per-file rule, place this program in the
1084 following three separate files:
1087 @table @asis
1089 @item @emph{greetings.ads}
1091 spec of package @cite{Greetings}
1093 @item @emph{greetings.adb}
1095 body of package @cite{Greetings}
1097 @item @emph{gmain.adb}
1099 body of main program
1100 @end table
1102 To build an executable version of
1103 this program, we could use four separate steps to compile, bind, and link
1104 the program, as follows:
1106 @example
1107 $ gcc -c gmain.adb
1108 $ gcc -c greetings.adb
1109 $ gnatbind gmain
1110 $ gnatlink gmain
1111 @end example
1113 Note that there is no required order of compilation when using GNAT.
1114 In particular it is perfectly fine to compile the main program first.
1115 Also, it is not necessary to compile package specs in the case where
1116 there is an accompanying body; you only need to compile the body. If you want
1117 to submit these files to the compiler for semantic checking and not code
1118 generation, then use the @code{-gnatc} switch:
1120 @example
1121 $ gcc -c greetings.ads -gnatc
1122 @end example
1124 Although the compilation can be done in separate steps as in the
1125 above example, in practice it is almost always more convenient
1126 to use the @emph{gnatmake} tool. All you need to know in this case
1127 is the name of the main program's source file. The effect of the above four
1128 commands can be achieved with a single one:
1130 @example
1131 $ gnatmake gmain.adb
1132 @end example
1134 In the next section we discuss the advantages of using @emph{gnatmake} in
1135 more detail.
1137 @node Using the gnatmake Utility,,Running a Program with Multiple Units,Getting Started with GNAT
1138 @anchor{gnat_ugn/getting_started_with_gnat using-the-gnatmake-utility}@anchor{39}@anchor{gnat_ugn/getting_started_with_gnat id5}@anchor{3a}
1139 @section Using the @emph{gnatmake} Utility
1142 If you work on a program by compiling single components at a time using
1143 @emph{gcc}, you typically keep track of the units you modify. In order to
1144 build a consistent system, you compile not only these units, but also any
1145 units that depend on the units you have modified.
1146 For example, in the preceding case,
1147 if you edit @code{gmain.adb}, you only need to recompile that file. But if
1148 you edit @code{greetings.ads}, you must recompile both
1149 @code{greetings.adb} and @code{gmain.adb}, because both files contain
1150 units that depend on @code{greetings.ads}.
1152 @emph{gnatbind} will warn you if you forget one of these compilation
1153 steps, so that it is impossible to generate an inconsistent program as a
1154 result of forgetting to do a compilation. Nevertheless it is tedious and
1155 error-prone to keep track of dependencies among units.
1156 One approach to handle the dependency-bookkeeping is to use a
1157 makefile. However, makefiles present maintenance problems of their own:
1158 if the dependencies change as you change the program, you must make
1159 sure that the makefile is kept up-to-date manually, which is also an
1160 error-prone process.
1162 The @emph{gnatmake} utility takes care of these details automatically.
1163 Invoke it using either one of the following forms:
1165 @example
1166 $ gnatmake gmain.adb
1167 $ gnatmake gmain
1168 @end example
1170 The argument is the name of the file containing the main program;
1171 you may omit the extension. @emph{gnatmake}
1172 examines the environment, automatically recompiles any files that need
1173 recompiling, and binds and links the resulting set of object files,
1174 generating the executable file, @code{gmain}.
1175 In a large program, it
1176 can be extremely helpful to use @emph{gnatmake}, because working out by hand
1177 what needs to be recompiled can be difficult.
1179 Note that @emph{gnatmake} takes into account all the Ada rules that
1180 establish dependencies among units. These include dependencies that result
1181 from inlining subprogram bodies, and from
1182 generic instantiation. Unlike some other
1183 Ada make tools, @emph{gnatmake} does not rely on the dependencies that were
1184 found by the compiler on a previous compilation, which may possibly
1185 be wrong when sources change. @emph{gnatmake} determines the exact set of
1186 dependencies from scratch each time it is run.
1188 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
1190 @node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
1191 @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}
1192 @chapter The GNAT Compilation Model
1195 @geindex GNAT compilation model
1197 @geindex Compilation model
1199 This chapter describes the compilation model used by GNAT. Although
1200 similar to that used by other languages such as C and C++, this model
1201 is substantially different from the traditional Ada compilation models,
1202 which are based on a centralized program library. The chapter covers
1203 the following material:
1206 @itemize *
1208 @item 
1209 Topics related to source file makeup and naming
1212 @itemize *
1214 @item 
1215 @ref{3d,,Source Representation}
1217 @item 
1218 @ref{3e,,Foreign Language Representation}
1220 @item 
1221 @ref{3f,,File Naming Topics and Utilities}
1222 @end itemize
1224 @item 
1225 @ref{14,,Configuration Pragmas}
1227 @item 
1228 @ref{40,,Generating Object Files}
1230 @item 
1231 @ref{41,,Source Dependencies}
1233 @item 
1234 @ref{42,,The Ada Library Information Files}
1236 @item 
1237 @ref{43,,Binding an Ada Program}
1239 @item 
1240 @ref{15,,GNAT and Libraries}
1242 @item 
1243 @ref{16,,Conditional Compilation}
1245 @item 
1246 @ref{44,,Mixed Language Programming}
1248 @item 
1249 @ref{45,,GNAT and Other Compilation Models}
1251 @item 
1252 @ref{1a,,Using GNAT Files with External Tools}
1253 @end itemize
1255 @menu
1256 * Source Representation:: 
1257 * Foreign Language Representation:: 
1258 * File Naming Topics and Utilities:: 
1259 * Configuration Pragmas:: 
1260 * Generating Object Files:: 
1261 * Source Dependencies:: 
1262 * The Ada Library Information Files:: 
1263 * Binding an Ada Program:: 
1264 * GNAT and Libraries:: 
1265 * Conditional Compilation:: 
1266 * Mixed Language Programming:: 
1267 * GNAT and Other Compilation Models:: 
1268 * Using GNAT Files with External Tools:: 
1270 @end menu
1272 @node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1273 @anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{3d}@anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{46}
1274 @section Source Representation
1277 @geindex Latin-1
1279 @geindex VT
1280 @geindex HT
1281 @geindex CR
1282 @geindex LF
1283 @geindex FF
1285 Ada source programs are represented in standard text files, using
1286 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1287 7-bit ASCII set, plus additional characters used for
1288 representing foreign languages (see @ref{3e,,Foreign Language Representation}
1289 for support of non-USA character sets). The format effector characters
1290 are represented using their standard ASCII encodings, as follows:
1292 @quotation
1295 @multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxx} 
1296 @item
1298 Character
1300 @tab
1302 Effect
1304 @tab
1306 Code
1308 @item
1310 @code{VT}
1312 @tab
1314 Vertical tab
1316 @tab
1318 @cite{16#0B#}
1320 @item
1322 @code{HT}
1324 @tab
1326 Horizontal tab
1328 @tab
1330 @cite{16#09#}
1332 @item
1334 @code{CR}
1336 @tab
1338 Carriage return
1340 @tab
1342 @cite{16#0D#}
1344 @item
1346 @code{LF}
1348 @tab
1350 Line feed
1352 @tab
1354 @cite{16#0A#}
1356 @item
1358 @code{FF}
1360 @tab
1362 Form feed
1364 @tab
1366 @cite{16#0C#}
1368 @end multitable
1370 @end quotation
1372 Source files are in standard text file format. In addition, GNAT will
1373 recognize a wide variety of stream formats, in which the end of
1374 physical lines is marked by any of the following sequences:
1375 @cite{LF}, @cite{CR}, @cite{CR-LF}, or @cite{LF-CR}. This is useful
1376 in accommodating files that are imported from other operating systems.
1378 @geindex End of source file; Source file@comma{} end
1380 @geindex SUB (control character)
1382 The end of a source file is normally represented by the physical end of
1383 file. However, the control character @cite{16#1A#} (@code{SUB}) is also
1384 recognized as signalling the end of the source file. Again, this is
1385 provided for compatibility with other operating systems where this
1386 code is used to represent the end of file.
1388 @geindex spec (definition)
1389 @geindex compilation (definition)
1391 Each file contains a single Ada compilation unit, including any pragmas
1392 associated with the unit. For example, this means you must place a
1393 package declaration (a package @cite{spec}) and the corresponding body in
1394 separate files. An Ada @cite{compilation} (which is a sequence of
1395 compilation units) is represented using a sequence of files. Similarly,
1396 you will place each subunit or child unit in a separate file.
1398 @node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1399 @anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{3e}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{47}
1400 @section Foreign Language Representation
1403 GNAT supports the standard character sets defined in Ada as well as
1404 several other non-standard character sets for use in localized versions
1405 of the compiler (@ref{48,,Character Set Control}).
1407 @menu
1408 * Latin-1:: 
1409 * Other 8-Bit Codes:: 
1410 * Wide_Character Encodings:: 
1411 * Wide_Wide_Character Encodings:: 
1413 @end menu
1415 @node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1416 @anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{49}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{4a}
1417 @subsection Latin-1
1420 @geindex Latin-1
1422 The basic character set is Latin-1. This character set is defined by ISO
1423 standard 8859, part 1. The lower half (character codes @cite{16#00#}
1424 ... @cite{16#7F#)} is identical to standard ASCII coding, but the upper
1425 half is used to represent additional characters. These include extended letters
1426 used by European languages, such as French accents, the vowels with umlauts
1427 used in German, and the extra letter A-ring used in Swedish.
1429 @geindex Ada.Characters.Latin_1
1431 For a complete list of Latin-1 codes and their encodings, see the source
1432 file of library unit @cite{Ada.Characters.Latin_1} in file
1433 @code{a-chlat1.ads}.
1434 You may use any of these extended characters freely in character or
1435 string literals. In addition, the extended characters that represent
1436 letters can be used in identifiers.
1438 @node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1439 @anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{4b}@anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{4c}
1440 @subsection Other 8-Bit Codes
1443 GNAT also supports several other 8-bit coding schemes:
1445 @geindex Latin-2
1447 @geindex ISO 8859-2
1450 @table @asis
1452 @item @emph{ISO 8859-2 (Latin-2)}
1454 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1455 equivalence.
1456 @end table
1458 @geindex Latin-3
1460 @geindex ISO 8859-3
1463 @table @asis
1465 @item @emph{ISO 8859-3 (Latin-3)}
1467 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1468 equivalence.
1469 @end table
1471 @geindex Latin-4
1473 @geindex ISO 8859-4
1476 @table @asis
1478 @item @emph{ISO 8859-4 (Latin-4)}
1480 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1481 equivalence.
1482 @end table
1484 @geindex ISO 8859-5
1486 @geindex Cyrillic
1489 @table @asis
1491 @item @emph{ISO 8859-5 (Cyrillic)}
1493 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1494 lowercase equivalence.
1495 @end table
1497 @geindex ISO 8859-15
1499 @geindex Latin-9
1502 @table @asis
1504 @item @emph{ISO 8859-15 (Latin-9)}
1506 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1507 lowercase equivalence
1508 @end table
1510 @geindex code page 437 (IBM PC)
1513 @table @asis
1515 @item @emph{IBM PC (code page 437)}
1517 This code page is the normal default for PCs in the U.S. It corresponds
1518 to the original IBM PC character set. This set has some, but not all, of
1519 the extended Latin-1 letters, but these letters do not have the same
1520 encoding as Latin-1. In this mode, these letters are allowed in
1521 identifiers with uppercase and lowercase equivalence.
1522 @end table
1524 @geindex code page 850 (IBM PC)
1527 @table @asis
1529 @item @emph{IBM PC (code page 850)}
1531 This code page is a modification of 437 extended to include all the
1532 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1533 mode, all these letters are allowed in identifiers with uppercase and
1534 lowercase equivalence.
1536 @item @emph{Full Upper 8-bit}
1538 Any character in the range 80-FF allowed in identifiers, and all are
1539 considered distinct. In other words, there are no uppercase and lowercase
1540 equivalences in this range. This is useful in conjunction with
1541 certain encoding schemes used for some foreign character sets (e.g.,
1542 the typical method of representing Chinese characters on the PC).
1544 @item @emph{No Upper-Half}
1546 No upper-half characters in the range 80-FF are allowed in identifiers.
1547 This gives Ada 83 compatibility for identifier names.
1548 @end table
1550 For precise data on the encodings permitted, and the uppercase and lowercase
1551 equivalences that are recognized, see the file @code{csets.adb} in
1552 the GNAT compiler sources. You will need to obtain a full source release
1553 of GNAT to obtain this file.
1555 @node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1556 @anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{4d}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{4e}
1557 @subsection Wide_Character Encodings
1560 GNAT allows wide character codes to appear in character and string
1561 literals, and also optionally in identifiers, by means of the following
1562 possible encoding schemes:
1565 @table @asis
1567 @item @emph{Hex Coding}
1569 In this encoding, a wide character is represented by the following five
1570 character sequence:
1572 @example
1573 ESC a b c d
1574 @end example
1576 where @cite{a}, @cite{b}, @cite{c}, @cite{d} are the four hexadecimal
1577 characters (using uppercase letters) of the wide character code. For
1578 example, ESC A345 is used to represent the wide character with code
1579 @cite{16#A345#}.
1580 This scheme is compatible with use of the full Wide_Character set.
1582 @item @emph{Upper-Half Coding}
1584 @geindex Upper-Half Coding
1586 The wide character with encoding @cite{16#abcd#} where the upper bit is on
1587 (in other words, 'a' is in the range 8-F) is represented as two bytes,
1588 @cite{16#ab#} and @cite{16#cd#}. The second byte cannot be a format control
1589 character, but is not required to be in the upper half. This method can
1590 be also used for shift-JIS or EUC, where the internal coding matches the
1591 external coding.
1593 @item @emph{Shift JIS Coding}
1595 @geindex Shift JIS Coding
1597 A wide character is represented by a two-character sequence,
1598 @cite{16#ab#} and
1599 @cite{16#cd#}, with the restrictions described for upper-half encoding as
1600 described above. The internal character code is the corresponding JIS
1601 character according to the standard algorithm for Shift-JIS
1602 conversion. Only characters defined in the JIS code set table can be
1603 used with this encoding method.
1605 @item @emph{EUC Coding}
1607 @geindex EUC Coding
1609 A wide character is represented by a two-character sequence
1610 @cite{16#ab#} and
1611 @cite{16#cd#}, with both characters being in the upper half. The internal
1612 character code is the corresponding JIS character according to the EUC
1613 encoding algorithm. Only characters defined in the JIS code set table
1614 can be used with this encoding method.
1616 @item @emph{UTF-8 Coding}
1618 A wide character is represented using
1619 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1620 10646-1/Am.2. Depending on the character value, the representation
1621 is a one, two, or three byte sequence:
1623 @example
1624 16#0000#-16#007f#: 2#0`xxxxxxx`#
1625 16#0080#-16#07ff#: 2#110`xxxxx`# 2#10`xxxxxx`#
1626 16#0800#-16#ffff#: 2#1110`xxxx`# 2#10`xxxxxx`# 2#10`xxxxxx`#
1627 @end example
1629 where the @cite{xxx} bits correspond to the left-padded bits of the
1630 16-bit character value. Note that all lower half ASCII characters
1631 are represented as ASCII bytes and all upper half characters and
1632 other wide characters are represented as sequences of upper-half
1633 (The full UTF-8 scheme allows for encoding 31-bit characters as
1634 6-byte sequences, and in the following section on wide wide
1635 characters, the use of these sequences is documented).
1637 @item @emph{Brackets Coding}
1639 In this encoding, a wide character is represented by the following eight
1640 character sequence:
1642 @example
1643 [ " a b c d " ]
1644 @end example
1646 where @cite{a}, @cite{b}, @cite{c}, @cite{d} are the four hexadecimal
1647 characters (using uppercase letters) of the wide character code. For
1648 example, ['A345'] is used to represent the wide character with code
1649 @cite{16#A345#}. It is also possible (though not required) to use the
1650 Brackets coding for upper half characters. For example, the code
1651 @cite{16#A3#} can be represented as @cite{['A3']}.
1653 This scheme is compatible with use of the full Wide_Character set,
1654 and is also the method used for wide character encoding in some standard
1655 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1656 @end table
1658 @cartouche
1659 @quotation Note 
1660 Some of these coding schemes do not permit the full use of the
1661 Ada character set. For example, neither Shift JIS nor EUC allow the
1662 use of the upper half of the Latin-1 set.
1663 @end quotation
1664 @end cartouche
1666 @node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1667 @anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{4f}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{50}
1668 @subsection Wide_Wide_Character Encodings
1671 GNAT allows wide wide character codes to appear in character and string
1672 literals, and also optionally in identifiers, by means of the following
1673 possible encoding schemes:
1676 @table @asis
1678 @item @emph{UTF-8 Coding}
1680 A wide character is represented using
1681 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1682 10646-1/Am.2. Depending on the character value, the representation
1683 of character codes with values greater than 16#FFFF# is a
1684 is a four, five, or six byte sequence:
1686 @example
1687 16#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1688                              10xxxxxx
1689 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1690                              10xxxxxx 10xxxxxx
1691 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1692                              10xxxxxx 10xxxxxx 10xxxxxx
1693 @end example
1695 where the @cite{xxx} bits correspond to the left-padded bits of the
1696 32-bit character value.
1698 @item @emph{Brackets Coding}
1700 In this encoding, a wide wide character is represented by the following ten or
1701 twelve byte character sequence:
1703 @example
1704 [ " a b c d e f " ]
1705 [ " a b c d e f g h " ]
1706 @end example
1708 where @cite{a-h} are the six or eight hexadecimal
1709 characters (using uppercase letters) of the wide wide character code. For
1710 example, ["1F4567"] is used to represent the wide wide character with code
1711 @cite{16#001F_4567#}.
1713 This scheme is compatible with use of the full Wide_Wide_Character set,
1714 and is also the method used for wide wide character encoding in some standard
1715 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1716 @end table
1718 @node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1719 @anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{3f}
1720 @section File Naming Topics and Utilities
1723 GNAT has a default file naming scheme and also provides the user with
1724 a high degree of control over how the names and extensions of the
1725 source files correspond to the Ada compilation units that they contain.
1727 @menu
1728 * File Naming Rules:: 
1729 * Using Other File Names:: 
1730 * Alternative File Naming Schemes:: 
1731 * Handling Arbitrary File Naming Conventions with gnatname:: 
1732 * File Name Krunching with gnatkr:: 
1733 * Renaming Files with gnatchop:: 
1735 @end menu
1737 @node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1738 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{52}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{53}
1739 @subsection File Naming Rules
1742 The default file name is determined by the name of the unit that the
1743 file contains. The name is formed by taking the full expanded name of
1744 the unit and replacing the separating dots with hyphens and using
1745 lowercase for all letters.
1747 An exception arises if the file name generated by the above rules starts
1748 with one of the characters
1749 @cite{a}, @cite{g}, @cite{i}, or @cite{s}, and the second character is a
1750 minus. In this case, the character tilde is used in place
1751 of the minus. The reason for this special rule is to avoid clashes with
1752 the standard names for child units of the packages System, Ada,
1753 Interfaces, and GNAT, which use the prefixes
1754 @cite{s-}, @cite{a-}, @cite{i-}, and @cite{g-},
1755 respectively.
1757 The file extension is @code{.ads} for a spec and
1758 @code{.adb} for a body. The following table shows some
1759 examples of these rules.
1761 @quotation
1764 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
1765 @item
1767 Source File
1769 @tab
1771 Ada Compilation Unit
1773 @item
1775 @code{main.ads}
1777 @tab
1779 Main (spec)
1781 @item
1783 @code{main.adb}
1785 @tab
1787 Main (body)
1789 @item
1791 @code{arith_functions.ads}
1793 @tab
1795 Arith_Functions (package spec)
1797 @item
1799 @code{arith_functions.adb}
1801 @tab
1803 Arith_Functions (package body)
1805 @item
1807 @code{func-spec.ads}
1809 @tab
1811 Func.Spec (child package spec)
1813 @item
1815 @code{func-spec.adb}
1817 @tab
1819 Func.Spec (child package body)
1821 @item
1823 @code{main-sub.adb}
1825 @tab
1827 Sub (subunit of Main)
1829 @item
1831 @code{a~bad.adb}
1833 @tab
1835 A.Bad (child package body)
1837 @end multitable
1839 @end quotation
1841 Following these rules can result in excessively long
1842 file names if corresponding
1843 unit names are long (for example, if child units or subunits are
1844 heavily nested). An option is available to shorten such long file names
1845 (called file name 'krunching'). This may be particularly useful when
1846 programs being developed with GNAT are to be used on operating systems
1847 with limited file name lengths. @ref{54,,Using gnatkr}.
1849 Of course, no file shortening algorithm can guarantee uniqueness over
1850 all possible unit names; if file name krunching is used, it is your
1851 responsibility to ensure no name clashes occur. Alternatively you
1852 can specify the exact file names that you want used, as described
1853 in the next section. Finally, if your Ada programs are migrating from a
1854 compiler with a different naming convention, you can use the gnatchop
1855 utility to produce source files that follow the GNAT naming conventions.
1856 (For details see @ref{36,,Renaming Files with gnatchop}.)
1858 Note: in the case of Windows or Mac OS operating systems, case is not
1859 significant. So for example on @cite{Windows} if the canonical name is
1860 @cite{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1861 However, case is significant for other operating systems, so for example,
1862 if you want to use other than canonically cased file names on a Unix system,
1863 you need to follow the procedures described in the next section.
1865 @node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1866 @anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{55}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{35}
1867 @subsection Using Other File Names
1870 @geindex File names
1872 In the previous section, we have described the default rules used by
1873 GNAT to determine the file name in which a given unit resides. It is
1874 often convenient to follow these default rules, and if you follow them,
1875 the compiler knows without being explicitly told where to find all
1876 the files it needs.
1878 @geindex Source_File_Name pragma
1880 However, in some cases, particularly when a program is imported from
1881 another Ada compiler environment, it may be more convenient for the
1882 programmer to specify which file names contain which units. GNAT allows
1883 arbitrary file names to be used by means of the Source_File_Name pragma.
1884 The form of this pragma is as shown in the following examples:
1886 @example
1887 pragma Source_File_Name (My_Utilities.Stacks,
1888   Spec_File_Name => "myutilst_a.ada");
1889 pragma Source_File_name (My_Utilities.Stacks,
1890   Body_File_Name => "myutilst.ada");
1891 @end example
1893 As shown in this example, the first argument for the pragma is the unit
1894 name (in this example a child unit). The second argument has the form
1895 of a named association. The identifier
1896 indicates whether the file name is for a spec or a body;
1897 the file name itself is given by a string literal.
1899 The source file name pragma is a configuration pragma, which means that
1900 normally it will be placed in the @code{gnat.adc}
1901 file used to hold configuration
1902 pragmas that apply to a complete compilation environment.
1903 For more details on how the @code{gnat.adc} file is created and used
1904 see @ref{56,,Handling of Configuration Pragmas}.
1906 @geindex gnat.adc
1908 GNAT allows completely arbitrary file names to be specified using the
1909 source file name pragma. However, if the file name specified has an
1910 extension other than @code{.ads} or @code{.adb} it is necessary to use
1911 a special syntax when compiling the file. The name in this case must be
1912 preceded by the special sequence @emph{-x} followed by a space and the name
1913 of the language, here @cite{ada}, as in:
1915 @example
1916 $ gcc -c -x ada peculiar_file_name.sim
1917 @end example
1919 @cite{gnatmake} handles non-standard file names in the usual manner (the
1920 non-standard file name for the main program is simply used as the
1921 argument to gnatmake). Note that if the extension is also non-standard,
1922 then it must be included in the @cite{gnatmake} command, it may not
1923 be omitted.
1925 @node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
1926 @anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{57}@anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{58}
1927 @subsection Alternative File Naming Schemes
1930 @geindex File naming schemes
1931 @geindex alternative
1933 @geindex File names
1935 The previous section described the use of the @cite{Source_File_Name}
1936 pragma to allow arbitrary names to be assigned to individual source files.
1937 However, this approach requires one pragma for each file, and especially in
1938 large systems can result in very long @code{gnat.adc} files, and also create
1939 a maintenance problem.
1941 @geindex Source_File_Name pragma
1943 GNAT also provides a facility for specifying systematic file naming schemes
1944 other than the standard default naming scheme previously described. An
1945 alternative scheme for naming is specified by the use of
1946 @cite{Source_File_Name} pragmas having the following format:
1948 @example
1949 pragma Source_File_Name (
1950    Spec_File_Name  => FILE_NAME_PATTERN
1951  [ , Casing          => CASING_SPEC]
1952  [ , Dot_Replacement => STRING_LITERAL ] );
1954 pragma Source_File_Name (
1955    Body_File_Name  => FILE_NAME_PATTERN
1956  [ , Casing          => CASING_SPEC ]
1957  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1959 pragma Source_File_Name (
1960    Subunit_File_Name  => FILE_NAME_PATTERN
1961  [ , Casing          => CASING_SPEC ]
1962  [ , Dot_Replacement => STRING_LITERAL ] ) ;
1964 FILE_NAME_PATTERN ::= STRING_LITERAL
1965 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1966 @end example
1968 The @cite{FILE_NAME_PATTERN} string shows how the file name is constructed.
1969 It contains a single asterisk character, and the unit name is substituted
1970 systematically for this asterisk. The optional parameter
1971 @cite{Casing} indicates
1972 whether the unit name is to be all upper-case letters, all lower-case letters,
1973 or mixed-case. If no
1974 @cite{Casing} parameter is used, then the default is all
1975 lower-case.
1977 The optional @cite{Dot_Replacement} string is used to replace any periods
1978 that occur in subunit or child unit names. If no @cite{Dot_Replacement}
1979 argument is used then separating dots appear unchanged in the resulting
1980 file name.
1981 Although the above syntax indicates that the
1982 @cite{Casing} argument must appear
1983 before the @cite{Dot_Replacement} argument, but it
1984 is also permissible to write these arguments in the opposite order.
1986 As indicated, it is possible to specify different naming schemes for
1987 bodies, specs, and subunits. Quite often the rule for subunits is the
1988 same as the rule for bodies, in which case, there is no need to give
1989 a separate @cite{Subunit_File_Name} rule, and in this case the
1990 @cite{Body_File_name} rule is used for subunits as well.
1992 The separate rule for subunits can also be used to implement the rather
1993 unusual case of a compilation environment (e.g., a single directory) which
1994 contains a subunit and a child unit with the same unit name. Although
1995 both units cannot appear in the same partition, the Ada Reference Manual
1996 allows (but does not require) the possibility of the two units coexisting
1997 in the same environment.
1999 The file name translation works in the following steps:
2002 @itemize *
2004 @item 
2005 If there is a specific @cite{Source_File_Name} pragma for the given unit,
2006 then this is always used, and any general pattern rules are ignored.
2008 @item 
2009 If there is a pattern type @cite{Source_File_Name} pragma that applies to
2010 the unit, then the resulting file name will be used if the file exists. If
2011 more than one pattern matches, the latest one will be tried first, and the
2012 first attempt resulting in a reference to a file that exists will be used.
2014 @item 
2015 If no pattern type @cite{Source_File_Name} pragma that applies to the unit
2016 for which the corresponding file exists, then the standard GNAT default
2017 naming rules are used.
2018 @end itemize
2020 As an example of the use of this mechanism, consider a commonly used scheme
2021 in which file names are all lower case, with separating periods copied
2022 unchanged to the resulting file name, and specs end with @code{.1.ada}, and
2023 bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
2024 two pragmas appear:
2026 @example
2027 pragma Source_File_Name
2028   (Spec_File_Name => ".1.ada");
2029 pragma Source_File_Name
2030   (Body_File_Name => ".2.ada");
2031 @end example
2033 The default GNAT scheme is actually implemented by providing the following
2034 default pragmas internally:
2036 @example
2037 pragma Source_File_Name
2038   (Spec_File_Name => ".ads", Dot_Replacement => "-");
2039 pragma Source_File_Name
2040   (Body_File_Name => ".adb", Dot_Replacement => "-");
2041 @end example
2043 Our final example implements a scheme typically used with one of the
2044 Ada 83 compilers, where the separator character for subunits was '__'
2045 (two underscores), specs were identified by adding @code{_.ADA}, bodies
2046 by adding @code{.ADA}, and subunits by
2047 adding @code{.SEP}. All file names were
2048 upper case. Child units were not present of course since this was an
2049 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2050 the same double underscore separator for child units.
2052 @example
2053 pragma Source_File_Name
2054   (Spec_File_Name => "_.ADA",
2055    Dot_Replacement => "__",
2056    Casing = Uppercase);
2057 pragma Source_File_Name
2058   (Body_File_Name => ".ADA",
2059    Dot_Replacement => "__",
2060    Casing = Uppercase);
2061 pragma Source_File_Name
2062   (Subunit_File_Name => ".SEP",
2063    Dot_Replacement => "__",
2064    Casing = Uppercase);
2065 @end example
2067 @geindex gnatname
2069 @node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
2070 @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}
2071 @subsection Handling Arbitrary File Naming Conventions with @cite{gnatname}
2074 @geindex File Naming Conventions
2076 @menu
2077 * Arbitrary File Naming Conventions:: 
2078 * Running gnatname:: 
2079 * Switches for gnatname:: 
2080 * Examples of gnatname Usage:: 
2082 @end menu
2084 @node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
2085 @anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{5b}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{5c}
2086 @subsubsection Arbitrary File Naming Conventions
2089 The GNAT compiler must be able to know the source file name of a compilation
2090 unit.  When using the standard GNAT default file naming conventions
2091 (@cite{.ads} for specs, @cite{.adb} for bodies), the GNAT compiler
2092 does not need additional information.
2094 When the source file names do not follow the standard GNAT default file naming
2095 conventions, the GNAT compiler must be given additional information through
2096 a configuration pragmas file (@ref{14,,Configuration Pragmas})
2097 or a project file.
2098 When the non-standard file naming conventions are well-defined,
2099 a small number of pragmas @cite{Source_File_Name} specifying a naming pattern
2100 (@ref{58,,Alternative File Naming Schemes}) may be sufficient. However,
2101 if the file naming conventions are irregular or arbitrary, a number
2102 of pragma @cite{Source_File_Name} for individual compilation units
2103 must be defined.
2104 To help maintain the correspondence between compilation unit names and
2105 source file names within the compiler,
2106 GNAT provides a tool @cite{gnatname} to generate the required pragmas for a
2107 set of files.
2109 @node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
2110 @anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{5d}@anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{5e}
2111 @subsubsection Running @cite{gnatname}
2114 The usual form of the @cite{gnatname} command is:
2116 @example
2117 $ gnatname [`switches`] `naming_pattern` [`naming_patterns`]
2118     [--and [`switches`] `naming_pattern` [`naming_patterns`]]
2119 @end example
2121 All of the arguments are optional. If invoked without any argument,
2122 @cite{gnatname} will display its usage.
2124 When used with at least one naming pattern, @cite{gnatname} will attempt to
2125 find all the compilation units in files that follow at least one of the
2126 naming patterns. To find these compilation units,
2127 @cite{gnatname} will use the GNAT compiler in syntax-check-only mode on all
2128 regular files.
2130 One or several Naming Patterns may be given as arguments to @cite{gnatname}.
2131 Each Naming Pattern is enclosed between double quotes (or single
2132 quotes on Windows).
2133 A Naming Pattern is a regular expression similar to the wildcard patterns
2134 used in file names by the Unix shells or the DOS prompt.
2136 @cite{gnatname} may be called with several sections of directories/patterns.
2137 Sections are separated by switch @cite{--and}. In each section, there must be
2138 at least one pattern. If no directory is specified in a section, the current
2139 directory (or the project directory is @cite{-P} is used) is implied.
2140 The options other that the directory switches and the patterns apply globally
2141 even if they are in different sections.
2143 Examples of Naming Patterns are:
2145 @example
2146 "*.[12].ada"
2147 "*.ad[sb]*"
2148 "body_*"    "spec_*"
2149 @end example
2151 For a more complete description of the syntax of Naming Patterns,
2152 see the second kind of regular expressions described in @code{g-regexp.ads}
2153 (the 'Glob' regular expressions).
2155 When invoked with no switch @cite{-P}, @cite{gnatname} will create a
2156 configuration pragmas file @code{gnat.adc} in the current working directory,
2157 with pragmas @cite{Source_File_Name} for each file that contains a valid Ada
2158 unit.
2160 @node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
2161 @anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{5f}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{60}
2162 @subsubsection Switches for @cite{gnatname}
2165 Switches for @cite{gnatname} must precede any specified Naming Pattern.
2167 You may specify any of the following switches to @cite{gnatname}:
2169 @geindex --version (gnatname)
2172 @table @asis
2174 @item @code{--version}
2176 Display Copyright and version, then exit disregarding all other options.
2177 @end table
2179 @geindex --help (gnatname)
2182 @table @asis
2184 @item @code{--help}
2186 If @emph{--version} was not used, display usage, then exit disregarding
2187 all other options.
2189 @item @code{--subdirs=@emph{dir}}
2191 Real object, library or exec directories are subdirectories <dir> of the
2192 specified ones.
2194 @item @code{--no-backup}
2196 Do not create a backup copy of an existing project file.
2198 @item @code{--and}
2200 Start another section of directories/patterns.
2201 @end table
2203 @geindex -c (gnatname)
2206 @table @asis
2208 @item @code{-c@emph{filename}}
2210 Create a configuration pragmas file @code{filename} (instead of the default
2211 @code{gnat.adc}).
2212 There may be zero, one or more space between @emph{-c} and
2213 @code{filename}.
2214 @code{filename} may include directory information. @code{filename} must be
2215 writable. There may be only one switch @emph{-c}.
2216 When a switch @emph{-c} is
2217 specified, no switch @emph{-P} may be specified (see below).
2218 @end table
2220 @geindex -d (gnatname)
2223 @table @asis
2225 @item @code{-d@emph{dir}}
2227 Look for source files in directory @code{dir}. There may be zero, one or more
2228 spaces between @emph{-d} and @code{dir}.
2229 @code{dir} may end with @cite{/**}, that is it may be of the form
2230 @cite{root_dir/**}. In this case, the directory @cite{root_dir} and all of its
2231 subdirectories, recursively, have to be searched for sources.
2232 When a switch @emph{-d}
2233 is specified, the current working directory will not be searched for source
2234 files, unless it is explicitly specified with a @emph{-d}
2235 or @emph{-D} switch.
2236 Several switches @emph{-d} may be specified.
2237 If @code{dir} is a relative path, it is relative to the directory of
2238 the configuration pragmas file specified with switch
2239 @emph{-c},
2240 or to the directory of the project file specified with switch
2241 @emph{-P} or,
2242 if neither switch @emph{-c}
2243 nor switch @emph{-P} are specified, it is relative to the
2244 current working directory. The directory
2245 specified with switch @emph{-d} must exist and be readable.
2246 @end table
2248 @geindex -D (gnatname)
2251 @table @asis
2253 @item @code{-D@emph{filename}}
2255 Look for source files in all directories listed in text file @code{filename}.
2256 There may be zero, one or more spaces between @emph{-D}
2257 and @code{filename}.
2258 @code{filename} must be an existing, readable text file.
2259 Each nonempty line in @code{filename} must be a directory.
2260 Specifying switch @emph{-D} is equivalent to specifying as many
2261 switches @emph{-d} as there are nonempty lines in
2262 @code{file}.
2264 @item @code{-eL}
2266 Follow symbolic links when processing project files.
2268 @geindex -f (gnatname)
2270 @item @code{-f@emph{pattern}}
2272 Foreign patterns. Using this switch, it is possible to add sources of languages
2273 other than Ada to the list of sources of a project file.
2274 It is only useful if a -P switch is used.
2275 For example,
2277 @example
2278 gnatname -Pprj -f"*.c" "*.ada"
2279 @end example
2281 will look for Ada units in all files with the @code{.ada} extension,
2282 and will add to the list of file for project @code{prj.gpr} the C files
2283 with extension @code{.c}.
2285 @geindex -h (gnatname)
2287 @item @code{-h}
2289 Output usage (help) information. The output is written to @code{stdout}.
2291 @geindex -P (gnatname)
2293 @item @code{-P@emph{proj}}
2295 Create or update project file @code{proj}. There may be zero, one or more space
2296 between @emph{-P} and @code{proj}. @code{proj} may include directory
2297 information. @code{proj} must be writable.
2298 There may be only one switch @emph{-P}.
2299 When a switch @emph{-P} is specified,
2300 no switch @emph{-c} may be specified.
2301 On all platforms, except on VMS, when @cite{gnatname} is invoked for an
2302 existing project file <proj>.gpr, a backup copy of the project file is created
2303 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
2304 non negative number that makes this backup copy a new file.
2306 @geindex -v (gnatname)
2308 @item @code{-v}
2310 Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2311 This includes name of the file written, the name of the directories to search
2312 and, for each file in those directories whose name matches at least one of
2313 the Naming Patterns, an indication of whether the file contains a unit,
2314 and if so the name of the unit.
2315 @end table
2317 @geindex -v -v (gnatname)
2320 @table @asis
2322 @item @code{-v -v}
2324 Very Verbose mode. In addition to the output produced in verbose mode,
2325 for each file in the searched directories whose name matches none of
2326 the Naming Patterns, an indication is given that there is no match.
2328 @geindex -x (gnatname)
2330 @item @code{-x@emph{pattern}}
2332 Excluded patterns. Using this switch, it is possible to exclude some files
2333 that would match the name patterns. For example,
2335 @example
2336 gnatname -x "*_nt.ada" "*.ada"
2337 @end example
2339 will look for Ada units in all files with the @code{.ada} extension,
2340 except those whose names end with @code{_nt.ada}.
2341 @end table
2343 @node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2344 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{61}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{62}
2345 @subsubsection Examples of @cite{gnatname} Usage
2348 @example
2349 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2350 @end example
2352 In this example, the directory @code{/home/me} must already exist
2353 and be writable. In addition, the directory
2354 @code{/home/me/sources} (specified by
2355 @emph{-d sources}) must exist and be readable.
2357 Note the optional spaces after @emph{-c} and @emph{-d}.
2359 @example
2360 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
2361 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2362 @end example
2364 Note that several switches @emph{-d} may be used,
2365 even in conjunction with one or several switches
2366 @emph{-D}. Several Naming Patterns and one excluded pattern
2367 are used in this example.
2369 @node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2370 @anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{63}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{64}
2371 @subsection File Name Krunching with @cite{gnatkr}
2374 @geindex gnatkr
2376 This section discusses the method used by the compiler to shorten
2377 the default file names chosen for Ada units so that they do not
2378 exceed the maximum length permitted. It also describes the
2379 @cite{gnatkr} utility that can be used to determine the result of
2380 applying this shortening.
2382 @menu
2383 * About gnatkr:: 
2384 * Using gnatkr:: 
2385 * Krunching Method:: 
2386 * Examples of gnatkr Usage:: 
2388 @end menu
2390 @node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2391 @anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{66}
2392 @subsubsection About @cite{gnatkr}
2395 The default file naming rule in GNAT
2396 is that the file name must be derived from
2397 the unit name. The exact default rule is as follows:
2400 @itemize *
2402 @item 
2403 Take the unit name and replace all dots by hyphens.
2405 @item 
2406 If such a replacement occurs in the
2407 second character position of a name, and the first character is
2408 @code{a}, @code{g}, @code{s}, or @code{i},
2409 then replace the dot by the character
2410 @code{~} (tilde)
2411 instead of a minus.
2413 The reason for this exception is to avoid clashes
2414 with the standard names for children of System, Ada, Interfaces,
2415 and GNAT, which use the prefixes
2416 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
2417 respectively.
2418 @end itemize
2420 The @code{-gnatk@emph{nn}}
2421 switch of the compiler activates a 'krunching'
2422 circuit that limits file names to nn characters (where nn is a decimal
2423 integer).
2425 The @cite{gnatkr} utility can be used to determine the krunched name for
2426 a given file, when krunched to a specified maximum length.
2428 @node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2429 @anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{67}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{54}
2430 @subsubsection Using @cite{gnatkr}
2433 The @cite{gnatkr} command has the form:
2435 @example
2436 $ gnatkr `name` [`length`]
2437 @end example
2439 @cite{name} is the uncrunched file name, derived from the name of the unit
2440 in the standard manner described in the previous section (i.e., in particular
2441 all dots are replaced by hyphens). The file name may or may not have an
2442 extension (defined as a suffix of the form period followed by arbitrary
2443 characters other than period). If an extension is present then it will
2444 be preserved in the output. For example, when krunching @code{hellofile.ads}
2445 to eight characters, the result will be hellofil.ads.
2447 Note: for compatibility with previous versions of @cite{gnatkr} dots may
2448 appear in the name instead of hyphens, but the last dot will always be
2449 taken as the start of an extension. So if @cite{gnatkr} is given an argument
2450 such as @code{Hello.World.adb} it will be treated exactly as if the first
2451 period had been a hyphen, and for example krunching to eight characters
2452 gives the result @code{hellworl.adb}.
2454 Note that the result is always all lower case.
2455 Characters of the other case are folded as required.
2457 @cite{length} represents the length of the krunched name. The default
2458 when no argument is given is 8 characters. A length of zero stands for
2459 unlimited, in other words do not chop except for system files where the
2460 implied crunching length is always eight characters.
2462 The output is the krunched name. The output has an extension only if the
2463 original argument was a file name with an extension.
2465 @node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2466 @anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{68}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{69}
2467 @subsubsection Krunching Method
2470 The initial file name is determined by the name of the unit that the file
2471 contains. The name is formed by taking the full expanded name of the
2472 unit and replacing the separating dots with hyphens and
2473 using lowercase
2474 for all letters, except that a hyphen in the second character position is
2475 replaced by a tilde if the first character is
2476 @code{a}, @code{i}, @code{g}, or @code{s}.
2477 The extension is @cite{.ads} for a
2478 spec and @cite{.adb} for a body.
2479 Krunching does not affect the extension, but the file name is shortened to
2480 the specified length by following these rules:
2483 @itemize *
2485 @item 
2486 The name is divided into segments separated by hyphens, tildes or
2487 underscores and all hyphens, tildes, and underscores are
2488 eliminated. If this leaves the name short enough, we are done.
2490 @item 
2491 If the name is too long, the longest segment is located (left-most
2492 if there are two of equal length), and shortened by dropping
2493 its last character. This is repeated until the name is short enough.
2495 As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2496 to fit the name into 8 characters as required by some operating systems:
2498 @example
2499 our-strings-wide_fixed 22
2500 our strings wide fixed 19
2501 our string  wide fixed 18
2502 our strin   wide fixed 17
2503 our stri    wide fixed 16
2504 our stri    wide fixe  15
2505 our str     wide fixe  14
2506 our str     wid  fixe  13
2507 our str     wid  fix   12
2508 ou  str     wid  fix   11
2509 ou  st      wid  fix   10
2510 ou  st      wi   fix   9
2511 ou  st      wi   fi    8
2512 Final file name: oustwifi.adb
2513 @end example
2515 @item 
2516 The file names for all predefined units are always krunched to eight
2517 characters. The krunching of these predefined units uses the following
2518 special prefix replacements:
2521 @multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} 
2522 @item
2524 Prefix
2526 @tab
2528 Replacement
2530 @item
2532 @code{ada-}
2534 @tab
2536 @code{a-}
2538 @item
2540 @code{gnat-}
2542 @tab
2544 @code{g-}
2546 @item
2548 @code{interfac es-}
2550 @tab
2552 @code{i-}
2554 @item
2556 @code{system-}
2558 @tab
2560 @code{s-}
2562 @end multitable
2565 These system files have a hyphen in the second character position. That
2566 is why normal user files replace such a character with a
2567 tilde, to avoid confusion with system file names.
2569 As an example of this special rule, consider
2570 @code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2572 @example
2573 ada-strings-wide_fixed 22
2574 a-  strings wide fixed 18
2575 a-  string  wide fixed 17
2576 a-  strin   wide fixed 16
2577 a-  stri    wide fixed 15
2578 a-  stri    wide fixe  14
2579 a-  str     wide fixe  13
2580 a-  str     wid  fixe  12
2581 a-  str     wid  fix   11
2582 a-  st      wid  fix   10
2583 a-  st      wi   fix   9
2584 a-  st      wi   fi    8
2585 Final file name: a-stwifi.adb
2586 @end example
2587 @end itemize
2589 Of course no file shortening algorithm can guarantee uniqueness over all
2590 possible unit names, and if file name krunching is used then it is your
2591 responsibility to ensure that no name clashes occur. The utility
2592 program @cite{gnatkr} is supplied for conveniently determining the
2593 krunched name of a file.
2595 @node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2596 @anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{6a}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{6b}
2597 @subsubsection Examples of @cite{gnatkr} Usage
2600 @example
2601 $ gnatkr very_long_unit_name.ads      --> velounna.ads
2602 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
2603 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2604 $ gnatkr grandparent-parent-child     --> grparchi
2605 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2606 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2607 @end example
2609 @node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2610 @anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{36}
2611 @subsection Renaming Files with @cite{gnatchop}
2614 @geindex gnatchop
2616 This section discusses how to handle files with multiple units by using
2617 the @cite{gnatchop} utility. This utility is also useful in renaming
2618 files to meet the standard GNAT default file naming conventions.
2620 @menu
2621 * Handling Files with Multiple Units:: 
2622 * Operating gnatchop in Compilation Mode:: 
2623 * Command Line for gnatchop:: 
2624 * Switches for gnatchop:: 
2625 * Examples of gnatchop Usage:: 
2627 @end menu
2629 @node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2630 @anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{6d}@anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{6e}
2631 @subsubsection Handling Files with Multiple Units
2634 The basic compilation model of GNAT requires that a file submitted to the
2635 compiler have only one unit and there be a strict correspondence
2636 between the file name and the unit name.
2638 The @cite{gnatchop} utility allows both of these rules to be relaxed,
2639 allowing GNAT to process files which contain multiple compilation units
2640 and files with arbitrary file names. @cite{gnatchop}
2641 reads the specified file and generates one or more output files,
2642 containing one unit per file. The unit and the file name correspond,
2643 as required by GNAT.
2645 If you want to permanently restructure a set of 'foreign' files so that
2646 they match the GNAT rules, and do the remaining development using the
2647 GNAT structure, you can simply use @emph{gnatchop} once, generate the
2648 new set of files and work with them from that point on.
2650 Alternatively, if you want to keep your files in the 'foreign' format,
2651 perhaps to maintain compatibility with some other Ada compilation
2652 system, you can set up a procedure where you use @emph{gnatchop} each
2653 time you compile, regarding the source files that it writes as temporary
2654 files that you throw away.
2656 Note that if your file containing multiple units starts with a byte order
2657 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2658 will each start with a copy of this BOM, meaning that they can be compiled
2659 automatically in UTF-8 mode without needing to specify an explicit encoding.
2661 @node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2662 @anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{6f}@anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{70}
2663 @subsubsection Operating gnatchop in Compilation Mode
2666 The basic function of @cite{gnatchop} is to take a file with multiple units
2667 and split it into separate files. The boundary between files is reasonably
2668 clear, except for the issue of comments and pragmas. In default mode, the
2669 rule is that any pragmas between units belong to the previous unit, except
2670 that configuration pragmas always belong to the following unit. Any comments
2671 belong to the following unit. These rules
2672 almost always result in the right choice of
2673 the split point without needing to mark it explicitly and most users will
2674 find this default to be what they want. In this default mode it is incorrect to
2675 submit a file containing only configuration pragmas, or one that ends in
2676 configuration pragmas, to @cite{gnatchop}.
2678 However, using a special option to activate 'compilation mode',
2679 @cite{gnatchop}
2680 can perform another function, which is to provide exactly the semantics
2681 required by the RM for handling of configuration pragmas in a compilation.
2682 In the absence of configuration pragmas (at the main file level), this
2683 option has no effect, but it causes such configuration pragmas to be handled
2684 in a quite different manner.
2686 First, in compilation mode, if @cite{gnatchop} is given a file that consists of
2687 only configuration pragmas, then this file is appended to the
2688 @code{gnat.adc} file in the current directory. This behavior provides
2689 the required behavior described in the RM for the actions to be taken
2690 on submitting such a file to the compiler, namely that these pragmas
2691 should apply to all subsequent compilations in the same compilation
2692 environment. Using GNAT, the current directory, possibly containing a
2693 @code{gnat.adc} file is the representation
2694 of a compilation environment. For more information on the
2695 @code{gnat.adc} file, see @ref{56,,Handling of Configuration Pragmas}.
2697 Second, in compilation mode, if @cite{gnatchop}
2698 is given a file that starts with
2699 configuration pragmas, and contains one or more units, then these
2700 configuration pragmas are prepended to each of the chopped files. This
2701 behavior provides the required behavior described in the RM for the
2702 actions to be taken on compiling such a file, namely that the pragmas
2703 apply to all units in the compilation, but not to subsequently compiled
2704 units.
2706 Finally, if configuration pragmas appear between units, they are appended
2707 to the previous unit. This results in the previous unit being illegal,
2708 since the compiler does not accept configuration pragmas that follow
2709 a unit. This provides the required RM behavior that forbids configuration
2710 pragmas other than those preceding the first compilation unit of a
2711 compilation.
2713 For most purposes, @cite{gnatchop} will be used in default mode. The
2714 compilation mode described above is used only if you need exactly
2715 accurate behavior with respect to compilations, and you have files
2716 that contain multiple units and configuration pragmas. In this
2717 circumstance the use of @cite{gnatchop} with the compilation mode
2718 switch provides the required behavior, and is for example the mode
2719 in which GNAT processes the ACVC tests.
2721 @node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2722 @anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{72}
2723 @subsubsection Command Line for @cite{gnatchop}
2726 The @cite{gnatchop} command has the form:
2728 @example
2729 $ gnatchop switches file_name [file_name ...]
2730       [directory]
2731 @end example
2733 The only required argument is the file name of the file to be chopped.
2734 There are no restrictions on the form of this file name. The file itself
2735 contains one or more Ada units, in normal GNAT format, concatenated
2736 together. As shown, more than one file may be presented to be chopped.
2738 When run in default mode, @cite{gnatchop} generates one output file in
2739 the current directory for each unit in each of the files.
2741 @cite{directory}, if specified, gives the name of the directory to which
2742 the output files will be written. If it is not specified, all files are
2743 written to the current directory.
2745 For example, given a
2746 file called @code{hellofiles} containing
2748 @example
2749 procedure Hello;
2751 with Ada.Text_IO; use Ada.Text_IO;
2752 procedure Hello is
2753 begin
2754    Put_Line ("Hello");
2755 end Hello;
2756 @end example
2758 the command
2760 @example
2761 $ gnatchop hellofiles
2762 @end example
2764 generates two files in the current directory, one called
2765 @code{hello.ads} containing the single line that is the procedure spec,
2766 and the other called @code{hello.adb} containing the remaining text. The
2767 original file is not affected. The generated files can be compiled in
2768 the normal manner.
2770 When gnatchop is invoked on a file that is empty or that contains only empty
2771 lines and/or comments, gnatchop will not fail, but will not produce any
2772 new sources.
2774 For example, given a
2775 file called @code{toto.txt} containing
2777 @example
2778 --  Just a comment
2779 @end example
2781 the command
2783 @example
2784 $ gnatchop toto.txt
2785 @end example
2787 will not produce any new file and will result in the following warnings:
2789 @example
2790 toto.txt:1:01: warning: empty file, contains no compilation units
2791 no compilation units found
2792 no source files written
2793 @end example
2795 @node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2796 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{73}@anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{74}
2797 @subsubsection Switches for @cite{gnatchop}
2800 @emph{gnatchop} recognizes the following switches:
2802 @geindex --version (gnatchop)
2805 @table @asis
2807 @item @code{--version}
2809 Display Copyright and version, then exit disregarding all other options.
2810 @end table
2812 @geindex --help (gnatchop)
2815 @table @asis
2817 @item @code{--help}
2819 If @emph{--version} was not used, display usage, then exit disregarding
2820 all other options.
2821 @end table
2823 @geindex -c (gnatchop)
2826 @table @asis
2828 @item @code{-c}
2830 Causes @cite{gnatchop} to operate in compilation mode, in which
2831 configuration pragmas are handled according to strict RM rules. See
2832 previous section for a full description of this mode.
2834 @item @code{-gnat@emph{xxx}}
2836 This passes the given @emph{-gnat`xxx*` switch to `gnat` which is
2837 used to parse the given file. Not all `xxx` options make sense,
2838 but for example, the use of *-gnati2} allows @cite{gnatchop} to
2839 process a source file that uses Latin-2 coding for identifiers.
2841 @item @code{-h}
2843 Causes @cite{gnatchop} to generate a brief help summary to the standard
2844 output file showing usage information.
2845 @end table
2847 @geindex -k (gnatchop)
2850 @table @asis
2852 @item @code{-k@emph{mm}}
2854 Limit generated file names to the specified number @cite{mm}
2855 of characters.
2856 This is useful if the
2857 resulting set of files is required to be interoperable with systems
2858 which limit the length of file names.
2859 No space is allowed between the @emph{-k} and the numeric value. The numeric
2860 value may be omitted in which case a default of @emph{-k8},
2861 suitable for use
2862 with DOS-like file systems, is used. If no @emph{-k} switch
2863 is present then
2864 there is no limit on the length of file names.
2865 @end table
2867 @geindex -p (gnatchop)
2870 @table @asis
2872 @item @code{-p}
2874 Causes the file modification time stamp of the input file to be
2875 preserved and used for the time stamp of the output file(s). This may be
2876 useful for preserving coherency of time stamps in an environment where
2877 @cite{gnatchop} is used as part of a standard build process.
2878 @end table
2880 @geindex -q (gnatchop)
2883 @table @asis
2885 @item @code{-q}
2887 Causes output of informational messages indicating the set of generated
2888 files to be suppressed. Warnings and error messages are unaffected.
2889 @end table
2891 @geindex -r (gnatchop)
2893 @geindex Source_Reference pragmas
2896 @table @asis
2898 @item @code{-r}
2900 Generate @cite{Source_Reference} pragmas. Use this switch if the output
2901 files are regarded as temporary and development is to be done in terms
2902 of the original unchopped file. This switch causes
2903 @cite{Source_Reference} pragmas to be inserted into each of the
2904 generated files to refers back to the original file name and line number.
2905 The result is that all error messages refer back to the original
2906 unchopped file.
2907 In addition, the debugging information placed into the object file (when
2908 the @emph{-g} switch of @emph{gcc} or @emph{gnatmake} is
2909 specified)
2910 also refers back to this original file so that tools like profilers and
2911 debuggers will give information in terms of the original unchopped file.
2913 If the original file to be chopped itself contains
2914 a @cite{Source_Reference}
2915 pragma referencing a third file, then gnatchop respects
2916 this pragma, and the generated @cite{Source_Reference} pragmas
2917 in the chopped file refer to the original file, with appropriate
2918 line numbers. This is particularly useful when @cite{gnatchop}
2919 is used in conjunction with @cite{gnatprep} to compile files that
2920 contain preprocessing statements and multiple units.
2921 @end table
2923 @geindex -v (gnatchop)
2926 @table @asis
2928 @item @code{-v}
2930 Causes @cite{gnatchop} to operate in verbose mode. The version
2931 number and copyright notice are output, as well as exact copies of
2932 the gnat1 commands spawned to obtain the chop control information.
2933 @end table
2935 @geindex -w (gnatchop)
2938 @table @asis
2940 @item @code{-w}
2942 Overwrite existing file names. Normally @cite{gnatchop} regards it as a
2943 fatal error if there is already a file with the same name as a
2944 file it would otherwise output, in other words if the files to be
2945 chopped contain duplicated units. This switch bypasses this
2946 check, and causes all but the last instance of such duplicated
2947 units to be skipped.
2948 @end table
2950 @geindex --GCC= (gnatchop)
2953 @table @asis
2955 @item @code{--GCC=@emph{xxxx}}
2957 Specify the path of the GNAT parser to be used. When this switch is used,
2958 no attempt is made to add the prefix to the GNAT parser executable.
2959 @end table
2961 @node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
2962 @anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{75}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{76}
2963 @subsubsection Examples of @cite{gnatchop} Usage
2966 @example
2967 $ gnatchop -w hello_s.ada prerelease/files
2968 @end example
2970 Chops the source file @code{hello_s.ada}. The output files will be
2971 placed in the directory @code{prerelease/files},
2972 overwriting any
2973 files with matching names in that directory (no files in the current
2974 directory are modified).
2976 @example
2977 $ gnatchop archive
2978 @end example
2980 Chops the source file @code{archive}
2981 into the current directory. One
2982 useful application of @cite{gnatchop} is in sending sets of sources
2983 around, for example in email messages. The required sources are simply
2984 concatenated (for example, using a Unix @cite{cat}
2985 command), and then
2986 @emph{gnatchop} is used at the other end to reconstitute the original
2987 file names.
2989 @example
2990 $ gnatchop file1 file2 file3 direc
2991 @end example
2993 Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
2994 the resulting files in the directory @code{direc}. Note that if any units
2995 occur more than once anywhere within this set of files, an error message
2996 is generated, and no files are written. To override this check, use the
2997 @emph{-w} switch,
2998 in which case the last occurrence in the last file will
2999 be the one that is output, and earlier duplicate occurrences for a given
3000 unit will be skipped.
3002 @node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
3003 @anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{14}
3004 @section Configuration Pragmas
3007 @geindex Configuration pragmas
3009 @geindex Pragmas
3010 @geindex configuration
3012 Configuration pragmas include those pragmas described as
3013 such in the Ada Reference Manual, as well as
3014 implementation-dependent pragmas that are configuration pragmas.
3015 See the @cite{Implementation_Defined_Pragmas} chapter in the
3016 @cite{GNAT_Reference_Manual} for details on these
3017 additional GNAT-specific configuration pragmas.
3018 Most notably, the pragma @cite{Source_File_Name}, which allows
3019 specifying non-default names for source files, is a configuration
3020 pragma. The following is a complete list of configuration pragmas
3021 recognized by GNAT:
3023 @example
3024 Ada_83
3025 Ada_95
3026 Ada_05
3027 Ada_2005
3028 Ada_12
3029 Ada_2012
3030 Allow_Integer_Address
3031 Annotate
3032 Assertion_Policy
3033 Assume_No_Invalid_Values
3034 C_Pass_By_Copy
3035 Check_Name
3036 Check_Policy
3037 Compile_Time_Error
3038 Compile_Time_Warning
3039 Compiler_Unit
3040 Component_Alignment
3041 Convention_Identifier
3042 Debug_Policy
3043 Detect_Blocking
3044 Default_Storage_Pool
3045 Discard_Names
3046 Elaboration_Checks
3047 Eliminate
3048 Extend_System
3049 Extensions_Allowed
3050 External_Name_Casing
3051 Fast_Math
3052 Favor_Top_Level
3053 Float_Representation
3054 Implicit_Packing
3055 Initialize_Scalars
3056 Interrupt_State
3057 License
3058 Locking_Policy
3059 Long_Float
3060 No_Run_Time
3061 No_Strict_Aliasing
3062 Normalize_Scalars
3063 Optimize_Alignment
3064 Persistent_BSS
3065 Polling
3066 Priority_Specific_Dispatching
3067 Profile
3068 Profile_Warnings
3069 Propagate_Exceptions
3070 Queuing_Policy
3071 Ravenscar
3072 Rename_Pragma
3073 Restricted_Run_Time
3074 Restrictions
3075 Restrictions_Warnings
3076 Reviewable
3077 Short_Circuit_And_Or
3078 Source_File_Name
3079 Source_File_Name_Project
3080 SPARK_Mode
3081 Style_Checks
3082 Suppress
3083 Suppress_Exception_Locations
3084 Task_Dispatching_Policy
3085 Universal_Data
3086 Unsuppress
3087 Use_VADS_Size
3088 Validity_Checks
3089 Warnings
3090 Wide_Character_Encoding
3091 @end example
3093 @menu
3094 * Handling of Configuration Pragmas:: 
3095 * The Configuration Pragmas Files:: 
3097 @end menu
3099 @node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
3100 @anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{78}@anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{56}
3101 @subsection Handling of Configuration Pragmas
3104 Configuration pragmas may either appear at the start of a compilation
3105 unit, or they can appear in a configuration pragma file to apply to
3106 all compilations performed in a given compilation environment.
3108 GNAT also provides the @cite{gnatchop} utility to provide an automatic
3109 way to handle configuration pragmas following the semantics for
3110 compilations (that is, files with multiple units), described in the RM.
3111 See @ref{6f,,Operating gnatchop in Compilation Mode} for details.
3112 However, for most purposes, it will be more convenient to edit the
3113 @code{gnat.adc} file that contains configuration pragmas directly,
3114 as described in the following section.
3116 In the case of @cite{Restrictions} pragmas appearing as configuration
3117 pragmas in individual compilation units, the exact handling depends on
3118 the type of restriction.
3120 Restrictions that require partition-wide consistency (like
3121 @cite{No_Tasking}) are
3122 recognized wherever they appear
3123 and can be freely inherited, e.g. from a @emph{with}ed unit to the @emph{with}ing
3124 unit. This makes sense since the binder will in any case insist on seeing
3125 consistent use, so any unit not conforming to any restrictions that are
3126 anywhere in the partition will be rejected, and you might as well find
3127 that out at compile time rather than at bind time.
3129 For restrictions that do not require partition-wide consistency, e.g.
3130 SPARK or No_Implementation_Attributes, in general the restriction applies
3131 only to the unit in which the pragma appears, and not to any other units.
3133 The exception is No_Elaboration_Code which always applies to the entire
3134 object file from a compilation, i.e. to the body, spec, and all subunits.
3135 This restriction can be specified in a configuration pragma file, or it
3136 can be on the body and/or the spec (in eithe case it applies to all the
3137 relevant units). It can appear on a subunit only if it has previously
3138 appeared in the body of spec.
3140 @node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
3141 @anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{79}@anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{7a}
3142 @subsection The Configuration Pragmas Files
3145 @geindex gnat.adc
3147 In GNAT a compilation environment is defined by the current
3148 directory at the time that a compile command is given. This current
3149 directory is searched for a file whose name is @code{gnat.adc}. If
3150 this file is present, it is expected to contain one or more
3151 configuration pragmas that will be applied to the current compilation.
3152 However, if the switch @emph{-gnatA} is used, @code{gnat.adc} is not
3153 considered. When taken into account, @code{gnat.adc} is added to the
3154 dependencies, so that if @code{gnat.adc} is modified later, an invocation of
3155 @emph{gnatmake} will recompile the source.
3157 Configuration pragmas may be entered into the @code{gnat.adc} file
3158 either by running @cite{gnatchop} on a source file that consists only of
3159 configuration pragmas, or more conveniently by direct editing of the
3160 @code{gnat.adc} file, which is a standard format source file.
3162 Besides @code{gnat.adc}, additional files containing configuration
3163 pragmas may be applied to the current compilation using the switch
3164 @code{-gnatec=@emph{path}} where @cite{path} must designate an existing file that
3165 contains only configuration pragmas. These configuration pragmas are
3166 in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
3167 is present and switch @emph{-gnatA} is not used).
3169 It is allowable to specify several switches @emph{-gnatec=}, all of which
3170 will be taken into account.
3172 Files containing configuration pragmas specified with switches
3173 @emph{-gnatec=} are added to the dependencies, unless they are
3174 temporary files. A file is considered temporary if its name ends in
3175 @code{.tmp} or @code{.TMP}. Certain tools follow this naming
3176 convention because they pass information to @emph{gcc} via
3177 temporary files that are immediately deleted; it doesn't make sense to
3178 depend on a file that no longer exists. Such tools include
3179 @emph{gprbuild}, @emph{gnatmake}, and @emph{gnatcheck}.
3181 If you are using project file, a separate mechanism is provided using
3182 project attributes.
3184 @c --Comment:
3185 @c See :ref:`Specifying_Configuration_Pragmas` for more details.
3187 @node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
3188 @anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{7b}
3189 @section Generating Object Files
3192 An Ada program consists of a set of source files, and the first step in
3193 compiling the program is to generate the corresponding object files.
3194 These are generated by compiling a subset of these source files.
3195 The files you need to compile are the following:
3198 @itemize *
3200 @item 
3201 If a package spec has no body, compile the package spec to produce the
3202 object file for the package.
3204 @item 
3205 If a package has both a spec and a body, compile the body to produce the
3206 object file for the package. The source file for the package spec need
3207 not be compiled in this case because there is only one object file, which
3208 contains the code for both the spec and body of the package.
3210 @item 
3211 For a subprogram, compile the subprogram body to produce the object file
3212 for the subprogram. The spec, if one is present, is as usual in a
3213 separate file, and need not be compiled.
3214 @end itemize
3216 @geindex Subunits
3219 @itemize *
3221 @item 
3222 In the case of subunits, only compile the parent unit. A single object
3223 file is generated for the entire subunit tree, which includes all the
3224 subunits.
3226 @item 
3227 Compile child units independently of their parent units
3228 (though, of course, the spec of all the ancestor unit must be present in order
3229 to compile a child unit).
3231 @geindex Generics
3233 @item 
3234 Compile generic units in the same manner as any other units. The object
3235 files in this case are small dummy files that contain at most the
3236 flag used for elaboration checking. This is because GNAT always handles generic
3237 instantiation by means of macro expansion. However, it is still necessary to
3238 compile generic units, for dependency checking and elaboration purposes.
3239 @end itemize
3241 The preceding rules describe the set of files that must be compiled to
3242 generate the object files for a program. Each object file has the same
3243 name as the corresponding source file, except that the extension is
3244 @code{.o} as usual.
3246 You may wish to compile other files for the purpose of checking their
3247 syntactic and semantic correctness. For example, in the case where a
3248 package has a separate spec and body, you would not normally compile the
3249 spec. However, it is convenient in practice to compile the spec to make
3250 sure it is error-free before compiling clients of this spec, because such
3251 compilations will fail if there is an error in the spec.
3253 GNAT provides an option for compiling such files purely for the
3254 purposes of checking correctness; such compilations are not required as
3255 part of the process of building a program. To compile a file in this
3256 checking mode, use the @emph{-gnatc} switch.
3258 @node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3259 @anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{7c}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{41}
3260 @section Source Dependencies
3263 A given object file clearly depends on the source file which is compiled
3264 to produce it. Here we are using "depends" in the sense of a typical
3265 @cite{make} utility; in other words, an object file depends on a source
3266 file if changes to the source file require the object file to be
3267 recompiled.
3268 In addition to this basic dependency, a given object may depend on
3269 additional source files as follows:
3272 @itemize *
3274 @item 
3275 If a file being compiled @emph{with}s a unit @cite{X}, the object file
3276 depends on the file containing the spec of unit @cite{X}. This includes
3277 files that are @emph{with}ed implicitly either because they are parents
3278 of @emph{with}ed child units or they are run-time units required by the
3279 language constructs used in a particular unit.
3281 @item 
3282 If a file being compiled instantiates a library level generic unit, the
3283 object file depends on both the spec and body files for this generic
3284 unit.
3286 @item 
3287 If a file being compiled instantiates a generic unit defined within a
3288 package, the object file depends on the body file for the package as
3289 well as the spec file.
3290 @end itemize
3292 @geindex Inline
3294 @geindex -gnatn switch
3297 @itemize *
3299 @item 
3300 If a file being compiled contains a call to a subprogram for which
3301 pragma @cite{Inline} applies and inlining is activated with the
3302 @emph{-gnatn} switch, the object file depends on the file containing the
3303 body of this subprogram as well as on the file containing the spec. Note
3304 that for inlining to actually occur as a result of the use of this switch,
3305 it is necessary to compile in optimizing mode.
3307 @geindex -gnatN switch
3309 The use of @emph{-gnatN} activates  inlining optimization
3310 that is performed by the front end of the compiler. This inlining does
3311 not require that the code generation be optimized. Like @emph{-gnatn},
3312 the use of this switch generates additional dependencies.
3314 When using a gcc-based back end (in practice this means using any version
3315 of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of
3316 @emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
3317 Historically front end inlining was more extensive than the gcc back end
3318 inlining, but that is no longer the case.
3320 @item 
3321 If an object file @code{O} depends on the proper body of a subunit through
3322 inlining or instantiation, it depends on the parent unit of the subunit.
3323 This means that any modification of the parent unit or one of its subunits
3324 affects the compilation of @code{O}.
3326 @item 
3327 The object file for a parent unit depends on all its subunit body files.
3329 @item 
3330 The previous two rules meant that for purposes of computing dependencies and
3331 recompilation, a body and all its subunits are treated as an indivisible whole.
3333 These rules are applied transitively: if unit @cite{A} @emph{with}s
3334 unit @cite{B}, whose elaboration calls an inlined procedure in package
3335 @cite{C}, the object file for unit @cite{A} will depend on the body of
3336 @cite{C}, in file @code{c.adb}.
3338 The set of dependent files described by these rules includes all the
3339 files on which the unit is semantically dependent, as dictated by the
3340 Ada language standard. However, it is a superset of what the
3341 standard describes, because it includes generic, inline, and subunit
3342 dependencies.
3344 An object file must be recreated by recompiling the corresponding source
3345 file if any of the source files on which it depends are modified. For
3346 example, if the @cite{make} utility is used to control compilation,
3347 the rule for an Ada object file must mention all the source files on
3348 which the object file depends, according to the above definition.
3349 The determination of the necessary
3350 recompilations is done automatically when one uses @emph{gnatmake}.
3351 @end itemize
3353 @node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3354 @anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{7d}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{42}
3355 @section The Ada Library Information Files
3358 @geindex Ada Library Information files
3360 @geindex ALI files
3362 Each compilation actually generates two output files. The first of these
3363 is the normal object file that has a @code{.o} extension. The second is a
3364 text file containing full dependency information. It has the same
3365 name as the source file, but an @code{.ali} extension.
3366 This file is known as the Ada Library Information (@code{ALI}) file.
3367 The following information is contained in the @code{ALI} file.
3370 @itemize *
3372 @item 
3373 Version information (indicates which version of GNAT was used to compile
3374 the unit(s) in question)
3376 @item 
3377 Main program information (including priority and time slice settings,
3378 as well as the wide character encoding used during compilation).
3380 @item 
3381 List of arguments used in the @emph{gcc} command for the compilation
3383 @item 
3384 Attributes of the unit, including configuration pragmas used, an indication
3385 of whether the compilation was successful, exception model used etc.
3387 @item 
3388 A list of relevant restrictions applying to the unit (used for consistency)
3389 checking.
3391 @item 
3392 Categorization information (e.g., use of pragma @cite{Pure}).
3394 @item 
3395 Information on all @emph{with}ed units, including presence of
3396 Elaborate` or @cite{Elaborate_All} pragmas.
3398 @item 
3399 Information from any @cite{Linker_Options} pragmas used in the unit
3401 @item 
3402 Information on the use of @cite{Body_Version} or @cite{Version}
3403 attributes in the unit.
3405 @item 
3406 Dependency information. This is a list of files, together with
3407 time stamp and checksum information. These are files on which
3408 the unit depends in the sense that recompilation is required
3409 if any of these units are modified.
3411 @item 
3412 Cross-reference data. Contains information on all entities referenced
3413 in the unit. Used by tools like @cite{gnatxref} and @cite{gnatfind} to
3414 provide cross-reference information.
3415 @end itemize
3417 For a full detailed description of the format of the @code{ALI} file,
3418 see the source of the body of unit @cite{Lib.Writ}, contained in file
3419 @code{lib-writ.adb} in the GNAT compiler sources.
3421 @node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3422 @anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{7e}@anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{43}
3423 @section Binding an Ada Program
3426 When using languages such as C and C++, once the source files have been
3427 compiled the only remaining step in building an executable program
3428 is linking the object modules together. This means that it is possible to
3429 link an inconsistent version of a program, in which two units have
3430 included different versions of the same header.
3432 The rules of Ada do not permit such an inconsistent program to be built.
3433 For example, if two clients have different versions of the same package,
3434 it is illegal to build a program containing these two clients.
3435 These rules are enforced by the GNAT binder, which also determines an
3436 elaboration order consistent with the Ada rules.
3438 The GNAT binder is run after all the object files for a program have
3439 been created. It is given the name of the main program unit, and from
3440 this it determines the set of units required by the program, by reading the
3441 corresponding ALI files. It generates error messages if the program is
3442 inconsistent or if no valid order of elaboration exists.
3444 If no errors are detected, the binder produces a main program, in Ada by
3445 default, that contains calls to the elaboration procedures of those
3446 compilation unit that require them, followed by
3447 a call to the main program. This Ada program is compiled to generate the
3448 object file for the main program. The name of
3449 the Ada file is @code{b~xxx}.adb` (with the corresponding spec
3450 @code{b~xxx}.ads`) where @cite{xxx} is the name of the
3451 main program unit.
3453 Finally, the linker is used to build the resulting executable program,
3454 using the object from the main program from the bind step as well as the
3455 object files for the Ada units of the program.
3457 @node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3458 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{15}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{7f}
3459 @section GNAT and Libraries
3462 @geindex Library building and using
3464 This section describes how to build and use libraries with GNAT, and also shows
3465 how to recompile the GNAT run-time library. You should be familiar with the
3466 Project Manager facility (see the @emph{GNAT_Project_Manager} chapter of the
3467 @emph{GPRbuild User's Guide}) before reading this chapter.
3469 @menu
3470 * Introduction to Libraries in GNAT:: 
3471 * General Ada Libraries:: 
3472 * Stand-alone Ada Libraries:: 
3473 * Rebuilding the GNAT Run-Time Library:: 
3475 @end menu
3477 @node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3478 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{80}@anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{81}
3479 @subsection Introduction to Libraries in GNAT
3482 A library is, conceptually, a collection of objects which does not have its
3483 own main thread of execution, but rather provides certain services to the
3484 applications that use it. A library can be either statically linked with the
3485 application, in which case its code is directly included in the application,
3486 or, on platforms that support it, be dynamically linked, in which case
3487 its code is shared by all applications making use of this library.
3489 GNAT supports both types of libraries.
3490 In the static case, the compiled code can be provided in different ways. The
3491 simplest approach is to provide directly the set of objects resulting from
3492 compilation of the library source files. Alternatively, you can group the
3493 objects into an archive using whatever commands are provided by the operating
3494 system. For the latter case, the objects are grouped into a shared library.
3496 In the GNAT environment, a library has three types of components:
3499 @itemize *
3501 @item 
3502 Source files,
3504 @item 
3505 @code{ALI} files (see @ref{42,,The Ada Library Information Files}), and
3507 @item 
3508 Object files, an archive or a shared library.
3509 @end itemize
3511 A GNAT library may expose all its source files, which is useful for
3512 documentation purposes. Alternatively, it may expose only the units needed by
3513 an external user to make use of the library. That is to say, the specs
3514 reflecting the library services along with all the units needed to compile
3515 those specs, which can include generic bodies or any body implementing an
3516 inlined routine. In the case of @emph{stand-alone libraries} those exposed
3517 units are called @emph{interface units} (@ref{82,,Stand-alone Ada Libraries}).
3519 All compilation units comprising an application, including those in a library,
3520 need to be elaborated in an order partially defined by Ada's semantics. GNAT
3521 computes the elaboration order from the @code{ALI} files and this is why they
3522 constitute a mandatory part of GNAT libraries.
3523 @emph{Stand-alone libraries} are the exception to this rule because a specific
3524 library elaboration routine is produced independently of the application(s)
3525 using the library.
3527 @node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3528 @anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{83}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{84}
3529 @subsection General Ada Libraries
3532 @menu
3533 * Building a library:: 
3534 * Installing a library:: 
3535 * Using a library:: 
3537 @end menu
3539 @node Building a library,Installing a library,,General Ada Libraries
3540 @anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{85}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{86}
3541 @subsubsection Building a library
3544 The easiest way to build a library is to use the Project Manager,
3545 which supports a special type of project called a @emph{Library Project}
3546 (see the @emph{Library Projects} section in the @emph{GNAT Project Manager}
3547 chapter of the @emph{GPRbuild User's Guide}).
3549 A project is considered a library project, when two project-level attributes
3550 are defined in it: @cite{Library_Name} and @cite{Library_Dir}. In order to
3551 control different aspects of library configuration, additional optional
3552 project-level attributes can be specified:
3555 @itemize *
3557 @item 
3559 @table @asis
3561 @item @emph{Library_Kind}
3563 This attribute controls whether the library is to be static or dynamic
3564 @end table
3566 @item 
3568 @table @asis
3570 @item @emph{Library_Version}
3572 This attribute specifies the library version; this value is used
3573 during dynamic linking of shared libraries to determine if the currently
3574 installed versions of the binaries are compatible.
3575 @end table
3577 @item 
3578 @emph{Library_Options}
3580 @item 
3582 @table @asis
3584 @item @emph{Library_GCC}
3586 These attributes specify additional low-level options to be used during
3587 library generation, and redefine the actual application used to generate
3588 library.
3589 @end table
3590 @end itemize
3592 The GNAT Project Manager takes full care of the library maintenance task,
3593 including recompilation of the source files for which objects do not exist
3594 or are not up to date, assembly of the library archive, and installation of
3595 the library (i.e., copying associated source, object and @code{ALI} files
3596 to the specified location).
3598 Here is a simple library project file:
3600 @example
3601 project My_Lib is
3602   for Source_Dirs use ("src1", "src2");
3603   for Object_Dir use "obj";
3604   for Library_Name use "mylib";
3605   for Library_Dir use "lib";
3606   for Library_Kind use "dynamic";
3607 end My_lib;
3608 @end example
3610 and the compilation command to build and install the library:
3612 @example
3613 $ gnatmake -Pmy_lib
3614 @end example
3616 It is not entirely trivial to perform manually all the steps required to
3617 produce a library. We recommend that you use the GNAT Project Manager
3618 for this task. In special cases where this is not desired, the necessary
3619 steps are discussed below.
3621 There are various possibilities for compiling the units that make up the
3622 library: for example with a Makefile (@ref{1f,,Using the GNU make Utility}) or
3623 with a conventional script. For simple libraries, it is also possible to create
3624 a dummy main program which depends upon all the packages that comprise the
3625 interface of the library. This dummy main program can then be given to
3626 @emph{gnatmake}, which will ensure that all necessary objects are built.
3628 After this task is accomplished, you should follow the standard procedure
3629 of the underlying operating system to produce the static or shared library.
3631 Here is an example of such a dummy program:
3633 @example
3634 with My_Lib.Service1;
3635 with My_Lib.Service2;
3636 with My_Lib.Service3;
3637 procedure My_Lib_Dummy is
3638 begin
3639    null;
3640 end;
3641 @end example
3643 Here are the generic commands that will build an archive or a shared library.
3645 @example
3646 # compiling the library
3647 $ gnatmake -c my_lib_dummy.adb
3649 # we don't need the dummy object itself
3650 $ rm my_lib_dummy.o my_lib_dummy.ali
3652 # create an archive with the remaining objects
3653 $ ar rc libmy_lib.a *.o
3654 # some systems may require "ranlib" to be run as well
3656 # or create a shared library
3657 $ gcc -shared -o libmy_lib.so *.o
3658 # some systems may require the code to have been compiled with -fPIC
3660 # remove the object files that are now in the library
3661 $ rm *.o
3663 # Make the ALI files read-only so that gnatmake will not try to
3664 # regenerate the objects that are in the library
3665 $ chmod -w *.ali
3666 @end example
3668 Please note that the library must have a name of the form @code{lib@emph{xxx}.a}
3669 or @code{lib@emph{xxx}.so} (or @code{lib@emph{xxx}.dll} on Windows) in order to
3670 be accessed by the directive @code{-l@emph{xxx}} at link time.
3672 @node Installing a library,Using a library,Building a library,General Ada Libraries
3673 @anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{87}@anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{88}
3674 @subsubsection Installing a library
3677 @geindex ADA_PROJECT_PATH
3679 @geindex GPR_PROJECT_PATH
3681 If you use project files, library installation is part of the library build
3682 process (see the @emph{Installing a Library with Project Files} section of the
3683 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}).
3685 When project files are not an option, it is also possible, but not recommended,
3686 to install the library so that the sources needed to use the library are on the
3687 Ada source path and the ALI files & libraries be on the Ada Object path (see
3688 @ref{89,,Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
3689 administrator can place general-purpose libraries in the default compiler
3690 paths, by specifying the libraries' location in the configuration files
3691 @code{ada_source_path} and @code{ada_object_path}. These configuration files
3692 must be located in the GNAT installation tree at the same place as the gcc spec
3693 file. The location of the gcc spec file can be determined as follows:
3695 @example
3696 $ gcc -v
3697 @end example
3699 The configuration files mentioned above have a simple format: each line
3700 must contain one unique directory name.
3701 Those names are added to the corresponding path
3702 in their order of appearance in the file. The names can be either absolute
3703 or relative; in the latter case, they are relative to where theses files
3704 are located.
3706 The files @code{ada_source_path} and @code{ada_object_path} might not be
3707 present in a
3708 GNAT installation, in which case, GNAT will look for its run-time library in
3709 the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3710 objects and @code{ALI} files). When the files exist, the compiler does not
3711 look in @code{adainclude} and @code{adalib}, and thus the
3712 @code{ada_source_path} file
3713 must contain the location for the GNAT run-time sources (which can simply
3714 be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3715 contain the location for the GNAT run-time objects (which can simply
3716 be @code{adalib}).
3718 You can also specify a new default path to the run-time library at compilation
3719 time with the switch @emph{--RTS=rts-path}. You can thus choose / change
3720 the run-time library you want your program to be compiled with. This switch is
3721 recognized by @emph{gcc}, @emph{gnatmake}, @emph{gnatbind},
3722 @emph{gnatls}, @emph{gnatfind} and @emph{gnatxref}.
3724 It is possible to install a library before or after the standard GNAT
3725 library, by reordering the lines in the configuration files. In general, a
3726 library must be installed before the GNAT library if it redefines
3727 any part of it.
3729 @node Using a library,,Installing a library,General Ada Libraries
3730 @anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{8a}@anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{8b}
3731 @subsubsection Using a library
3734 Once again, the project facility greatly simplifies the use of
3735 libraries. In this context, using a library is just a matter of adding a
3736 @emph{with} clause in the user project. For instance, to make use of the
3737 library @cite{My_Lib} shown in examples in earlier sections, you can
3738 write:
3740 @example
3741 with "my_lib";
3742 project My_Proj is
3743   ...
3744 end My_Proj;
3745 @end example
3747 Even if you have a third-party, non-Ada library, you can still use GNAT's
3748 Project Manager facility to provide a wrapper for it. For example, the
3749 following project, when @emph{with}ed by your main project, will link with the
3750 third-party library @code{liba.a}:
3752 @example
3753 project Liba is
3754    for Externally_Built use "true";
3755    for Source_Files use ();
3756    for Library_Dir use "lib";
3757    for Library_Name use "a";
3758    for Library_Kind use "static";
3759 end Liba;
3760 @end example
3762 This is an alternative to the use of @cite{pragma Linker_Options}. It is
3763 especially interesting in the context of systems with several interdependent
3764 static libraries where finding a proper linker order is not easy and best be
3765 left to the tools having visibility over project dependence information.
3767 In order to use an Ada library manually, you need to make sure that this
3768 library is on both your source and object path
3769 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}
3770 and @ref{8c,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3771 in an archive or a shared library, you need to specify the desired
3772 library at link time.
3774 For example, you can use the library @code{mylib} installed in
3775 @code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3777 @example
3778 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3779   -largs -lmy_lib
3780 @end example
3782 This can be expressed more simply:
3784 @example
3785 $ gnatmake my_appl
3786 @end example
3788 when the following conditions are met:
3791 @itemize *
3793 @item 
3794 @code{/dir/my_lib_src} has been added by the user to the environment
3795 variable 
3796 @geindex ADA_INCLUDE_PATH
3797 @geindex environment variable; ADA_INCLUDE_PATH
3798 @code{ADA_INCLUDE_PATH}, or by the administrator to the file
3799 @code{ada_source_path}
3801 @item 
3802 @code{/dir/my_lib_obj} has been added by the user to the environment
3803 variable 
3804 @geindex ADA_OBJECTS_PATH
3805 @geindex environment variable; ADA_OBJECTS_PATH
3806 @code{ADA_OBJECTS_PATH}, or by the administrator to the file
3807 @code{ada_object_path}
3809 @item 
3810 a pragma @cite{Linker_Options} has been added to one of the sources.
3811 For example:
3813 @example
3814 pragma Linker_Options ("-lmy_lib");
3815 @end example
3816 @end itemize
3818 Note that you may also load a library dynamically at
3819 run time given its filename, as illustrated in the GNAT @code{plugins} example
3820 in the directory @code{share/examples/gnat/plugins} within the GNAT
3821 install area.
3823 @node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3824 @anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{82}@anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{8d}
3825 @subsection Stand-alone Ada Libraries
3828 @geindex Stand-alone libraries
3830 @menu
3831 * Introduction to Stand-alone Libraries:: 
3832 * Building a Stand-alone Library:: 
3833 * Creating a Stand-alone Library to be used in a non-Ada context:: 
3834 * Restrictions in Stand-alone Libraries:: 
3836 @end menu
3838 @node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3839 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{8e}@anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{8f}
3840 @subsubsection Introduction to Stand-alone Libraries
3843 A Stand-alone Library (abbreviated 'SAL') is a library that contains the
3844 necessary code to
3845 elaborate the Ada units that are included in the library. In contrast with
3846 an ordinary library, which consists of all sources, objects and @code{ALI}
3847 files of the
3848 library, a SAL may specify a restricted subset of compilation units
3849 to serve as a library interface. In this case, the fully
3850 self-sufficient set of files will normally consist of an objects
3851 archive, the sources of interface units' specs, and the @code{ALI}
3852 files of interface units.
3853 If an interface spec contains a generic unit or an inlined subprogram,
3854 the body's
3855 source must also be provided; if the units that must be provided in the source
3856 form depend on other units, the source and @code{ALI} files of those must
3857 also be provided.
3859 The main purpose of a SAL is to minimize the recompilation overhead of client
3860 applications when a new version of the library is installed. Specifically,
3861 if the interface sources have not changed, client applications do not need to
3862 be recompiled. If, furthermore, a SAL is provided in the shared form and its
3863 version, controlled by @cite{Library_Version} attribute, is not changed,
3864 then the clients do not need to be relinked.
3866 SALs also allow the library providers to minimize the amount of library source
3867 text exposed to the clients.  Such 'information hiding' might be useful or
3868 necessary for various reasons.
3870 Stand-alone libraries are also well suited to be used in an executable whose
3871 main routine is not written in Ada.
3873 @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
3874 @anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{90}@anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{91}
3875 @subsubsection Building a Stand-alone Library
3878 GNAT's Project facility provides a simple way of building and installing
3879 stand-alone libraries; see the @emph{Stand-alone Library Projects} section
3880 in the @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}.
3881 To be a Stand-alone Library Project, in addition to the two attributes
3882 that make a project a Library Project (@cite{Library_Name} and
3883 @cite{Library_Dir}; see the @emph{Library Projects} section in the
3884 @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}),
3885 the attribute @cite{Library_Interface} must be defined.  For example:
3887 @example
3888 for Library_Dir use "lib_dir";
3889 for Library_Name use "dummy";
3890 for Library_Interface use ("int1", "int1.child");
3891 @end example
3893 Attribute @cite{Library_Interface} has a non-empty string list value,
3894 each string in the list designating a unit contained in an immediate source
3895 of the project file.
3897 When a Stand-alone Library is built, first the binder is invoked to build
3898 a package whose name depends on the library name
3899 (@code{b~dummy.ads/b} in the example above).
3900 This binder-generated package includes initialization and
3901 finalization procedures whose
3902 names depend on the library name (@cite{dummyinit} and @cite{dummyfinal}
3903 in the example
3904 above). The object corresponding to this package is included in the library.
3906 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3907 calling of these procedures if a static SAL is built, or if a shared SAL
3908 is built
3909 with the project-level attribute @cite{Library_Auto_Init} set to
3910 @cite{"false"}.
3912 For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
3913 (those that are listed in attribute @cite{Library_Interface}) are copied to
3914 the Library Directory. As a consequence, only the Interface Units may be
3915 imported from Ada units outside of the library. If other units are imported,
3916 the binding phase will fail.
3918 It is also possible to build an encapsulated library where not only
3919 the code to elaborate and finalize the library is embedded but also
3920 ensuring that the library is linked only against static
3921 libraries. So an encapsulated library only depends on system
3922 libraries, all other code, including the GNAT runtime, is embedded. To
3923 build an encapsulated library the attribute
3924 @cite{Library_Standalone} must be set to @cite{encapsulated}:
3926 @example
3927 for Library_Dir use "lib_dir";
3928 for Library_Name use "dummy";
3929 for Library_Kind use "dynamic";
3930 for Library_Interface use ("int1", "int1.child");
3931 for Library_Standalone use "encapsulated";
3932 @end example
3934 The default value for this attribute is @cite{standard} in which case
3935 a stand-alone library is built.
3937 The attribute @cite{Library_Src_Dir} may be specified for a
3938 Stand-Alone Library. @cite{Library_Src_Dir} is a simple attribute that has a
3939 single string value. Its value must be the path (absolute or relative to the
3940 project directory) of an existing directory. This directory cannot be the
3941 object directory or one of the source directories, but it can be the same as
3942 the library directory. The sources of the Interface
3943 Units of the library that are needed by an Ada client of the library will be
3944 copied to the designated directory, called the Interface Copy directory.
3945 These sources include the specs of the Interface Units, but they may also
3946 include bodies and subunits, when pragmas @cite{Inline} or @cite{Inline_Always}
3947 are used, or when there is a generic unit in the spec. Before the sources
3948 are copied to the Interface Copy directory, an attempt is made to delete all
3949 files in the Interface Copy directory.
3951 Building stand-alone libraries by hand is somewhat tedious, but for those
3952 occasions when it is necessary here are the steps that you need to perform:
3955 @itemize *
3957 @item 
3958 Compile all library sources.
3960 @item 
3961 Invoke the binder with the switch @emph{-n} (No Ada main program),
3962 with all the @code{ALI} files of the interfaces, and
3963 with the switch @emph{-L} to give specific names to the @cite{init}
3964 and @cite{final} procedures.  For example:
3966 @example
3967 $ gnatbind -n int1.ali int2.ali -Lsal1
3968 @end example
3970 @item 
3971 Compile the binder generated file:
3973 @example
3974 $ gcc -c b~int2.adb
3975 @end example
3977 @item 
3978 Link the dynamic library with all the necessary object files,
3979 indicating to the linker the names of the @cite{init} (and possibly
3980 @cite{final}) procedures for automatic initialization (and finalization).
3981 The built library should be placed in a directory different from
3982 the object directory.
3984 @item 
3985 Copy the @cite{ALI} files of the interface to the library directory,
3986 add in this copy an indication that it is an interface to a SAL
3987 (i.e., add a word @emph{SL} on the line in the @code{ALI} file that starts
3988 with letter 'P') and make the modified copy of the @code{ALI} file
3989 read-only.
3990 @end itemize
3992 Using SALs is not different from using other libraries
3993 (see @ref{8a,,Using a library}).
3995 @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
3996 @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}
3997 @subsubsection Creating a Stand-alone Library to be used in a non-Ada context
4000 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
4001 a non-Ada context.
4003 The only extra step required is to ensure that library interface subprograms
4004 are compatible with the main program, by means of @cite{pragma Export}
4005 or @cite{pragma Convention}.
4007 Here is an example of simple library interface for use with C main program:
4009 @example
4010 package My_Package is
4012    procedure Do_Something;
4013    pragma Export (C, Do_Something, "do_something");
4015    procedure Do_Something_Else;
4016    pragma Export (C, Do_Something_Else, "do_something_else");
4018 end My_Package;
4019 @end example
4021 On the foreign language side, you must provide a 'foreign' view of the
4022 library interface; remember that it should contain elaboration routines in
4023 addition to interface subprograms.
4025 The example below shows the content of @cite{mylib_interface.h} (note
4026 that there is no rule for the naming of this file, any name can be used)
4028 @example
4029 /* the library elaboration procedure */
4030 extern void mylibinit (void);
4032 /* the library finalization procedure */
4033 extern void mylibfinal (void);
4035 /* the interface exported by the library */
4036 extern void do_something (void);
4037 extern void do_something_else (void);
4038 @end example
4040 Libraries built as explained above can be used from any program, provided
4041 that the elaboration procedures (named @cite{mylibinit} in the previous
4042 example) are called before the library services are used. Any number of
4043 libraries can be used simultaneously, as long as the elaboration
4044 procedure of each library is called.
4046 Below is an example of a C program that uses the @cite{mylib} library.
4048 @example
4049 #include "mylib_interface.h"
4052 main (void)
4054    /* First, elaborate the library before using it */
4055    mylibinit ();
4057    /* Main program, using the library exported entities */
4058    do_something ();
4059    do_something_else ();
4061    /* Library finalization at the end of the program */
4062    mylibfinal ();
4063    return 0;
4065 @end example
4067 Note that invoking any library finalization procedure generated by
4068 @cite{gnatbind} shuts down the Ada run-time environment.
4069 Consequently, the
4070 finalization of all Ada libraries must be performed at the end of the program.
4071 No call to these libraries or to the Ada run-time library should be made
4072 after the finalization phase.
4074 Note also that special care must be taken with multi-tasks
4075 applications. The initialization and finalization routines are not
4076 protected against concurrent access. If such requirement is needed it
4077 must be ensured at the application level using a specific operating
4078 system services like a mutex or a critical-section.
4080 @node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
4081 @anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{94}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{95}
4082 @subsubsection Restrictions in Stand-alone Libraries
4085 The pragmas listed below should be used with caution inside libraries,
4086 as they can create incompatibilities with other Ada libraries:
4089 @itemize *
4091 @item 
4092 pragma @cite{Locking_Policy}
4094 @item 
4095 pragma @cite{Partition_Elaboration_Policy}
4097 @item 
4098 pragma @cite{Queuing_Policy}
4100 @item 
4101 pragma @cite{Task_Dispatching_Policy}
4103 @item 
4104 pragma @cite{Unreserve_All_Interrupts}
4105 @end itemize
4107 When using a library that contains such pragmas, the user must make sure
4108 that all libraries use the same pragmas with the same values. Otherwise,
4109 @cite{Program_Error} will
4110 be raised during the elaboration of the conflicting
4111 libraries. The usage of these pragmas and its consequences for the user
4112 should therefore be well documented.
4114 Similarly, the traceback in the exception occurrence mechanism should be
4115 enabled or disabled in a consistent manner across all libraries.
4116 Otherwise, Program_Error will be raised during the elaboration of the
4117 conflicting libraries.
4119 If the @cite{Version} or @cite{Body_Version}
4120 attributes are used inside a library, then you need to
4121 perform a @cite{gnatbind} step that specifies all @code{ALI} files in all
4122 libraries, so that version identifiers can be properly computed.
4123 In practice these attributes are rarely used, so this is unlikely
4124 to be a consideration.
4126 @node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
4127 @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}
4128 @subsection Rebuilding the GNAT Run-Time Library
4131 @geindex GNAT Run-Time Library
4132 @geindex rebuilding
4134 @geindex Building the GNAT Run-Time Library
4136 @geindex Rebuilding the GNAT Run-Time Library
4138 @geindex Run-Time Library
4139 @geindex rebuilding
4141 It may be useful to recompile the GNAT library in various contexts, the
4142 most important one being the use of partition-wide configuration pragmas
4143 such as @cite{Normalize_Scalars}. A special Makefile called
4144 @cite{Makefile.adalib} is provided to that effect and can be found in
4145 the directory containing the GNAT library. The location of this
4146 directory depends on the way the GNAT environment has been installed and can
4147 be determined by means of the command:
4149 @example
4150 $ gnatls -v
4151 @end example
4153 The last entry in the object search path usually contains the
4154 gnat library. This Makefile contains its own documentation and in
4155 particular the set of instructions needed to rebuild a new library and
4156 to use it.
4158 @geindex Conditional compilation
4160 @node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
4161 @anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{98}@anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{16}
4162 @section Conditional Compilation
4165 This section presents some guidelines for modeling conditional compilation in Ada and describes the
4166 gnatprep preprocessor utility.
4168 @geindex Conditional compilation
4170 @menu
4171 * Modeling Conditional Compilation in Ada:: 
4172 * Preprocessing with gnatprep:: 
4173 * Integrated Preprocessing:: 
4175 @end menu
4177 @node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
4178 @anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{99}@anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{9a}
4179 @subsection Modeling Conditional Compilation in Ada
4182 It is often necessary to arrange for a single source program
4183 to serve multiple purposes, where it is compiled in different
4184 ways to achieve these different goals. Some examples of the
4185 need for this feature are
4188 @itemize *
4190 @item 
4191 Adapting a program to a different hardware environment
4193 @item 
4194 Adapting a program to a different target architecture
4196 @item 
4197 Turning debugging features on and off
4199 @item 
4200 Arranging for a program to compile with different compilers
4201 @end itemize
4203 In C, or C++, the typical approach would be to use the preprocessor
4204 that is defined as part of the language. The Ada language does not
4205 contain such a feature. This is not an oversight, but rather a very
4206 deliberate design decision, based on the experience that overuse of
4207 the preprocessing features in C and C++ can result in programs that
4208 are extremely difficult to maintain. For example, if we have ten
4209 switches that can be on or off, this means that there are a thousand
4210 separate programs, any one of which might not even be syntactically
4211 correct, and even if syntactically correct, the resulting program
4212 might not work correctly. Testing all combinations can quickly become
4213 impossible.
4215 Nevertheless, the need to tailor programs certainly exists, and in
4216 this section we will discuss how this can
4217 be achieved using Ada in general, and GNAT in particular.
4219 @menu
4220 * Use of Boolean Constants:: 
4221 * Debugging - A Special Case:: 
4222 * Conditionalizing Declarations:: 
4223 * Use of Alternative Implementations:: 
4224 * Preprocessing:: 
4226 @end menu
4228 @node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4229 @anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{9b}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{9c}
4230 @subsubsection Use of Boolean Constants
4233 In the case where the difference is simply which code
4234 sequence is executed, the cleanest solution is to use Boolean
4235 constants to control which code is executed.
4237 @example
4238 FP_Initialize_Required : constant Boolean := True;
4240 if FP_Initialize_Required then
4242 end if;
4243 @end example
4245 Not only will the code inside the @cite{if} statement not be executed if
4246 the constant Boolean is @cite{False}, but it will also be completely
4247 deleted from the program.
4248 However, the code is only deleted after the @cite{if} statement
4249 has been checked for syntactic and semantic correctness.
4250 (In contrast, with preprocessors the code is deleted before the
4251 compiler ever gets to see it, so it is not checked until the switch
4252 is turned on.)
4254 @geindex Preprocessors (contrasted with conditional compilation)
4256 Typically the Boolean constants will be in a separate package,
4257 something like:
4259 @example
4260 package Config is
4261    FP_Initialize_Required : constant Boolean := True;
4262    Reset_Available        : constant Boolean := False;
4263    ...
4264 end Config;
4265 @end example
4267 The @cite{Config} package exists in multiple forms for the various targets,
4268 with an appropriate script selecting the version of @cite{Config} needed.
4269 Then any other unit requiring conditional compilation can do a @emph{with}
4270 of @cite{Config} to make the constants visible.
4272 @node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4273 @anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{9d}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{9e}
4274 @subsubsection Debugging - A Special Case
4277 A common use of conditional code is to execute statements (for example
4278 dynamic checks, or output of intermediate results) under control of a
4279 debug switch, so that the debugging behavior can be turned on and off.
4280 This can be done using a Boolean constant to control whether the code
4281 is active:
4283 @example
4284 if Debugging then
4285    Put_Line ("got to the first stage!");
4286 end if;
4287 @end example
4291 @example
4292 if Debugging and then Temperature > 999.0 then
4293    raise Temperature_Crazy;
4294 end if;
4295 @end example
4297 @geindex pragma Assert
4299 Since this is a common case, there are special features to deal with
4300 this in a convenient manner. For the case of tests, Ada 2005 has added
4301 a pragma @cite{Assert} that can be used for such tests. This pragma is modeled
4302 on the @cite{Assert} pragma that has always been available in GNAT, so this
4303 feature may be used with GNAT even if you are not using Ada 2005 features.
4304 The use of pragma @cite{Assert} is described in the
4305 @cite{GNAT_Reference_Manual}, but as an
4306 example, the last test could be written:
4308 @example
4309 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4310 @end example
4312 or simply
4314 @example
4315 pragma Assert (Temperature <= 999.0);
4316 @end example
4318 In both cases, if assertions are active and the temperature is excessive,
4319 the exception @cite{Assert_Failure} will be raised, with the given string in
4320 the first case or a string indicating the location of the pragma in the second
4321 case used as the exception message.
4323 @geindex pragma Assertion_Policy
4325 You can turn assertions on and off by using the @cite{Assertion_Policy}
4326 pragma.
4328 @geindex -gnata switch
4330 This is an Ada 2005 pragma which is implemented in all modes by
4331 GNAT. Alternatively, you can use the @emph{-gnata} switch
4332 to enable assertions from the command line, which applies to
4333 all versions of Ada.
4335 @geindex pragma Debug
4337 For the example above with the @cite{Put_Line}, the GNAT-specific pragma
4338 @cite{Debug} can be used:
4340 @example
4341 pragma Debug (Put_Line ("got to the first stage!"));
4342 @end example
4344 If debug pragmas are enabled, the argument, which must be of the form of
4345 a procedure call, is executed (in this case, @cite{Put_Line} will be called).
4346 Only one call can be present, but of course a special debugging procedure
4347 containing any code you like can be included in the program and then
4348 called in a pragma @cite{Debug} argument as needed.
4350 One advantage of pragma @cite{Debug} over the @cite{if Debugging then}
4351 construct is that pragma @cite{Debug} can appear in declarative contexts,
4352 such as at the very beginning of a procedure, before local declarations have
4353 been elaborated.
4355 @geindex pragma Debug_Policy
4357 Debug pragmas are enabled using either the @emph{-gnata} switch that also
4358 controls assertions, or with a separate Debug_Policy pragma.
4360 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4361 in Ada 95 and Ada 83 programs as well), and is analogous to
4362 pragma @cite{Assertion_Policy} to control assertions.
4364 @cite{Assertion_Policy} and @cite{Debug_Policy} are configuration pragmas,
4365 and thus they can appear in @code{gnat.adc} if you are not using a
4366 project file, or in the file designated to contain configuration pragmas
4367 in a project file.
4368 They then apply to all subsequent compilations. In practice the use of
4369 the @emph{-gnata} switch is often the most convenient method of controlling
4370 the status of these pragmas.
4372 Note that a pragma is not a statement, so in contexts where a statement
4373 sequence is required, you can't just write a pragma on its own. You have
4374 to add a @cite{null} statement.
4376 @example
4377 if ... then
4378    ... -- some statements
4379 else
4380    pragma Assert (Num_Cases < 10);
4381    null;
4382 end if;
4383 @end example
4385 @node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4386 @anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{a0}
4387 @subsubsection Conditionalizing Declarations
4390 In some cases it may be necessary to conditionalize declarations to meet
4391 different requirements. For example we might want a bit string whose length
4392 is set to meet some hardware message requirement.
4394 This may be possible using declare blocks controlled
4395 by conditional constants:
4397 @example
4398 if Small_Machine then
4399    declare
4400       X : Bit_String (1 .. 10);
4401    begin
4402       ...
4403    end;
4404 else
4405    declare
4406       X : Large_Bit_String (1 .. 1000);
4407    begin
4408       ...
4409    end;
4410 end if;
4411 @end example
4413 Note that in this approach, both declarations are analyzed by the
4414 compiler so this can only be used where both declarations are legal,
4415 even though one of them will not be used.
4417 Another approach is to define integer constants, e.g., @cite{Bits_Per_Word},
4418 or Boolean constants, e.g., @cite{Little_Endian}, and then write declarations
4419 that are parameterized by these constants. For example
4421 @example
4422 for Rec use
4423   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4424 end record;
4425 @end example
4427 If @cite{Bits_Per_Word} is set to 32, this generates either
4429 @example
4430 for Rec use
4431   Field1 at 0 range 0 .. 32;
4432 end record;
4433 @end example
4435 for the big endian case, or
4437 @example
4438 for Rec use record
4439     Field1 at 0 range 10 .. 32;
4440 end record;
4441 @end example
4443 for the little endian case. Since a powerful subset of Ada expression
4444 notation is usable for creating static constants, clever use of this
4445 feature can often solve quite difficult problems in conditionalizing
4446 compilation (note incidentally that in Ada 95, the little endian
4447 constant was introduced as @cite{System.Default_Bit_Order}, so you do not
4448 need to define this one yourself).
4450 @node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4451 @anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{a2}
4452 @subsubsection Use of Alternative Implementations
4455 In some cases, none of the approaches described above are adequate. This
4456 can occur for example if the set of declarations required is radically
4457 different for two different configurations.
4459 In this situation, the official Ada way of dealing with conditionalizing
4460 such code is to write separate units for the different cases. As long as
4461 this does not result in excessive duplication of code, this can be done
4462 without creating maintenance problems. The approach is to share common
4463 code as far as possible, and then isolate the code and declarations
4464 that are different. Subunits are often a convenient method for breaking
4465 out a piece of a unit that is to be conditionalized, with separate files
4466 for different versions of the subunit for different targets, where the
4467 build script selects the right one to give to the compiler.
4469 @geindex Subunits (and conditional compilation)
4471 As an example, consider a situation where a new feature in Ada 2005
4472 allows something to be done in a really nice way. But your code must be able
4473 to compile with an Ada 95 compiler. Conceptually you want to say:
4475 @example
4476 if Ada_2005 then
4477    ... neat Ada 2005 code
4478 else
4479    ... not quite as neat Ada 95 code
4480 end if;
4481 @end example
4483 where @cite{Ada_2005} is a Boolean constant.
4485 But this won't work when @cite{Ada_2005} is set to @cite{False},
4486 since the @cite{then} clause will be illegal for an Ada 95 compiler.
4487 (Recall that although such unreachable code would eventually be deleted
4488 by the compiler, it still needs to be legal.  If it uses features
4489 introduced in Ada 2005, it will be illegal in Ada 95.)
4491 So instead we write
4493 @example
4494 procedure Insert is separate;
4495 @end example
4497 Then we have two files for the subunit @cite{Insert}, with the two sets of
4498 code.
4499 If the package containing this is called @cite{File_Queries}, then we might
4500 have two files
4503 @itemize *
4505 @item 
4506 @code{file_queries-insert-2005.adb}
4508 @item 
4509 @code{file_queries-insert-95.adb}
4510 @end itemize
4512 and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4514 This can also be done with project files' naming schemes. For example:
4516 @example
4517 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4518 @end example
4520 Note also that with project files it is desirable to use a different extension
4521 than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4522 conflict may arise through another commonly used feature: to declare as part
4523 of the project a set of directories containing all the sources obeying the
4524 default naming scheme.
4526 The use of alternative units is certainly feasible in all situations,
4527 and for example the Ada part of the GNAT run-time is conditionalized
4528 based on the target architecture using this approach. As a specific example,
4529 consider the implementation of the AST feature in VMS. There is one
4530 spec: @code{s-asthan.ads} which is the same for all architectures, and three
4531 bodies:
4534 @itemize *
4536 @item 
4538 @table @asis
4540 @item @code{s-asthan.adb}
4542 used for all non-VMS operating systems
4543 @end table
4545 @item 
4547 @table @asis
4549 @item @code{s-asthan-vms-alpha.adb}
4551 used for VMS on the Alpha
4552 @end table
4554 @item 
4556 @table @asis
4558 @item @code{s-asthan-vms-ia64.adb}
4560 used for VMS on the ia64
4561 @end table
4562 @end itemize
4564 The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4565 this operating system feature is not available, and the two remaining
4566 versions interface with the corresponding versions of VMS to provide
4567 VMS-compatible AST handling. The GNAT build script knows the architecture
4568 and operating system, and automatically selects the right version,
4569 renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4571 Another style for arranging alternative implementations is through Ada's
4572 access-to-subprogram facility.
4573 In case some functionality is to be conditionally included,
4574 you can declare an access-to-procedure variable @cite{Ref} that is initialized
4575 to designate a 'do nothing' procedure, and then invoke @cite{Ref.all}
4576 when appropriate.
4577 In some library package, set @cite{Ref} to @cite{Proc'Access} for some
4578 procedure @cite{Proc} that performs the relevant processing.
4579 The initialization only occurs if the library package is included in the
4580 program.
4581 The same idea can also be implemented using tagged types and dispatching
4582 calls.
4584 @node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4585 @anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{a4}
4586 @subsubsection Preprocessing
4589 @geindex Preprocessing
4591 Although it is quite possible to conditionalize code without the use of
4592 C-style preprocessing, as described earlier in this section, it is
4593 nevertheless convenient in some cases to use the C approach. Moreover,
4594 older Ada compilers have often provided some preprocessing capability,
4595 so legacy code may depend on this approach, even though it is not
4596 standard.
4598 To accommodate such use, GNAT provides a preprocessor (modeled to a large
4599 extent on the various preprocessors that have been used
4600 with legacy code on other compilers, to enable easier transition).
4602 @geindex gnatprep
4604 The preprocessor may be used in two separate modes. It can be used quite
4605 separately from the compiler, to generate a separate output source file
4606 that is then fed to the compiler as a separate step. This is the
4607 @cite{gnatprep} utility, whose use is fully described in
4608 @ref{17,,Preprocessing with gnatprep}.
4610 The preprocessing language allows such constructs as
4612 @example
4613 #if DEBUG or else (PRIORITY > 4) then
4614    bunch of declarations
4615 #else
4616    completely different bunch of declarations
4617 #end if;
4618 @end example
4620 The values of the symbols @cite{DEBUG} and @cite{PRIORITY} can be
4621 defined either on the command line or in a separate file.
4623 The other way of running the preprocessor is even closer to the C style and
4624 often more convenient. In this approach the preprocessing is integrated into
4625 the compilation process. The compiler is fed the preprocessor input which
4626 includes @cite{#if} lines etc, and then the compiler carries out the
4627 preprocessing internally and processes the resulting output.
4628 For more details on this approach, see @ref{18,,Integrated Preprocessing}.
4630 @node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4631 @anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{17}
4632 @subsection Preprocessing with @cite{gnatprep}
4635 @geindex gnatprep
4637 @geindex Preprocessing (gnatprep)
4639 This section discusses how to use GNAT's @cite{gnatprep} utility for simple
4640 preprocessing.
4641 Although designed for use with GNAT, @cite{gnatprep} does not depend on any
4642 special GNAT features.
4643 For further discussion of conditional compilation in general, see
4644 @ref{16,,Conditional Compilation}.
4646 @menu
4647 * Preprocessing Symbols:: 
4648 * Using gnatprep:: 
4649 * Switches for gnatprep:: 
4650 * Form of Definitions File:: 
4651 * Form of Input Text for gnatprep:: 
4653 @end menu
4655 @node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4656 @anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{a6}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{a7}
4657 @subsubsection Preprocessing Symbols
4660 Preprocessing symbols are defined in definition files and referred to in
4661 sources to be preprocessed. A Preprocessing symbol is an identifier, following
4662 normal Ada (case-insensitive) rules for its syntax, with the restriction that
4663 all characters need to be in the ASCII set (no accented letters).
4665 @node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4666 @anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{a8}@anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{a9}
4667 @subsubsection Using @cite{gnatprep}
4670 To call @cite{gnatprep} use:
4672 @example
4673 $ gnatprep [`switches`] `infile` `outfile` [`deffile`]
4674 @end example
4676 where
4679 @itemize *
4681 @item 
4683 @table @asis
4685 @item @emph{switches}
4687 is an optional sequence of switches as described in the next section.
4688 @end table
4690 @item 
4692 @table @asis
4694 @item @emph{infile}
4696 is the full name of the input file, which is an Ada source
4697 file containing preprocessor directives.
4698 @end table
4700 @item 
4702 @table @asis
4704 @item @emph{outfile}
4706 is the full name of the output file, which is an Ada source
4707 in standard Ada form. When used with GNAT, this file name will
4708 normally have an ads or adb suffix.
4709 @end table
4711 @item 
4713 @table @asis
4715 @item @emph{deffile}
4717 is the full name of a text file containing definitions of
4718 preprocessing symbols to be referenced by the preprocessor. This argument is
4719 optional, and can be replaced by the use of the @emph{-D} switch.
4720 @end table
4721 @end itemize
4723 @node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4724 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{aa}@anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{ab}
4725 @subsubsection Switches for @cite{gnatprep}
4728 @geindex --version (gnatprep)
4731 @table @asis
4733 @item @code{--version}
4735 Display Copyright and version, then exit disregarding all other options.
4736 @end table
4738 @geindex --help (gnatprep)
4741 @table @asis
4743 @item @code{--help}
4745 If @emph{--version} was not used, display usage, then exit disregarding
4746 all other options.
4747 @end table
4749 @geindex -b (gnatprep)
4752 @table @asis
4754 @item @code{-b}
4756 Causes both preprocessor lines and the lines deleted by
4757 preprocessing to be replaced by blank lines in the output source file,
4758 preserving line numbers in the output file.
4759 @end table
4761 @geindex -c (gnatprep)
4764 @table @asis
4766 @item @code{-c}
4768 Causes both preprocessor lines and the lines deleted
4769 by preprocessing to be retained in the output source as comments marked
4770 with the special string @cite{"--! "}. This option will result in line numbers
4771 being preserved in the output file.
4772 @end table
4774 @geindex -C (gnatprep)
4777 @table @asis
4779 @item @code{-C}
4781 Causes comments to be scanned. Normally comments are ignored by gnatprep.
4782 If this option is specified, then comments are scanned and any $symbol
4783 substitutions performed as in program text. This is particularly useful
4784 when structured comments are used (e.g., when writing programs in the
4785 SPARK dialect of Ada). Note that this switch is not available when
4786 doing integrated preprocessing (it would be useless in this context
4787 since comments are ignored by the compiler in any case).
4788 @end table
4790 @geindex -D (gnatprep)
4793 @table @asis
4795 @item @code{-D@emph{symbol}=@emph{value}}
4797 Defines a new preprocessing symbol, associated with value. If no value is given
4798 on the command line, then symbol is considered to be @cite{True}. This switch
4799 can be used in place of a definition file.
4800 @end table
4802 @geindex -r (gnatprep)
4805 @table @asis
4807 @item @code{-r}
4809 Causes a @cite{Source_Reference} pragma to be generated that
4810 references the original input file, so that error messages will use
4811 the file name of this original file. The use of this switch implies
4812 that preprocessor lines are not to be removed from the file, so its
4813 use will force @emph{-b} mode if @emph{-c}
4814 has not been specified explicitly.
4816 Note that if the file to be preprocessed contains multiple units, then
4817 it will be necessary to @cite{gnatchop} the output file from
4818 @cite{gnatprep}. If a @cite{Source_Reference} pragma is present
4819 in the preprocessed file, it will be respected by
4820 @cite{gnatchop -r}
4821 so that the final chopped files will correctly refer to the original
4822 input source file for @cite{gnatprep}.
4823 @end table
4825 @geindex -s (gnatprep)
4828 @table @asis
4830 @item @code{-s}
4832 Causes a sorted list of symbol names and values to be
4833 listed on the standard output file.
4834 @end table
4836 @geindex -T (gnatprep)
4839 @table @asis
4841 @item @code{-T}
4843 Use LF as line terminators when writing files. By default the line terminator
4844 of the host (LF under unix, CR/LF under Windows) is used.
4845 @end table
4847 @geindex -u (gnatprep)
4850 @table @asis
4852 @item @code{-u}
4854 Causes undefined symbols to be treated as having the value FALSE in the context
4855 of a preprocessor test. In the absence of this option, an undefined symbol in
4856 a @cite{#if} or @cite{#elsif} test will be treated as an error.
4857 @end table
4859 @geindex -v (gnatprep)
4862 @table @asis
4864 @item @code{-v}
4866 Verbose mode: generates more output about work done.
4867 @end table
4869 Note: if neither @emph{-b} nor @emph{-c} is present,
4870 then preprocessor lines and
4871 deleted lines are completely removed from the output, unless -r is
4872 specified, in which case -b is assumed.
4874 @node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4875 @anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{ad}
4876 @subsubsection Form of Definitions File
4879 The definitions file contains lines of the form:
4881 @example
4882 symbol := value
4883 @end example
4885 where @cite{symbol} is a preprocessing symbol, and @cite{value} is one of the following:
4888 @itemize *
4890 @item 
4891 Empty, corresponding to a null substitution,
4893 @item 
4894 A string literal using normal Ada syntax, or
4896 @item 
4897 Any sequence of characters from the set @{letters, digits, period, underline@}.
4898 @end itemize
4900 Comment lines may also appear in the definitions file, starting with
4901 the usual @code{--},
4902 and comments may be added to the definitions lines.
4904 @node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4905 @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}
4906 @subsubsection Form of Input Text for @cite{gnatprep}
4909 The input text may contain preprocessor conditional inclusion lines,
4910 as well as general symbol substitution sequences.
4912 The preprocessor conditional inclusion commands have the form:
4914 @example
4915 #if <expression> [then]
4916    lines
4917 #elsif <expression> [then]
4918    lines
4919 #elsif <expression> [then]
4920    lines
4922 #else
4923    lines
4924 #end if;
4925 @end example
4927 In this example, <expression> is defined by the following grammar:
4929 @example
4930 <expression> ::=  <symbol>
4931 <expression> ::=  <symbol> = "<value>"
4932 <expression> ::=  <symbol> = <symbol>
4933 <expression> ::=  <symbol> = <integer>
4934 <expression> ::=  <symbol> > <integer>
4935 <expression> ::=  <symbol> >= <integer>
4936 <expression> ::=  <symbol> < <integer>
4937 <expression> ::=  <symbol> <= <integer>
4938 <expression> ::=  <symbol> 'Defined
4939 <expression> ::=  not <expression>
4940 <expression> ::=  <expression> and <expression>
4941 <expression> ::=  <expression> or <expression>
4942 <expression> ::=  <expression> and then <expression>
4943 <expression> ::=  <expression> or else <expression>
4944 <expression> ::=  ( <expression> )
4945 @end example
4947 Note the following restriction: it is not allowed to have "and" or "or"
4948 following "not" in the same expression without parentheses. For example, this
4949 is not allowed:
4951 @example
4952 not X or Y
4953 @end example
4955 This can be expressed instead as one of the following forms:
4957 @example
4958 (not X) or Y
4959 not (X or Y)
4960 @end example
4962 For the first test (<expression> ::= <symbol>) the symbol must have
4963 either the value true or false, that is to say the right-hand of the
4964 symbol definition must be one of the (case-insensitive) literals
4965 @cite{True} or @cite{False}. If the value is true, then the
4966 corresponding lines are included, and if the value is false, they are
4967 excluded.
4969 When comparing a symbol to an integer, the integer is any non negative
4970 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
4971 2#11#. The symbol value must also be a non negative integer. Integer values
4972 in the range 0 .. 2**31-1 are supported.
4974 The test (<expression> ::= <symbol>'Defined) is true only if
4975 the symbol has been defined in the definition file or by a @emph{-D}
4976 switch on the command line. Otherwise, the test is false.
4978 The equality tests are case insensitive, as are all the preprocessor lines.
4980 If the symbol referenced is not defined in the symbol definitions file,
4981 then the effect depends on whether or not switch @emph{-u}
4982 is specified. If so, then the symbol is treated as if it had the value
4983 false and the test fails. If this switch is not specified, then
4984 it is an error to reference an undefined symbol. It is also an error to
4985 reference a symbol that is defined with a value other than @cite{True}
4986 or @cite{False}.
4988 The use of the @cite{not} operator inverts the sense of this logical test.
4989 The @cite{not} operator cannot be combined with the @cite{or} or @cite{and}
4990 operators, without parentheses. For example, "if not X or Y then" is not
4991 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
4993 The @cite{then} keyword is optional as shown
4995 The @cite{#} must be the first non-blank character on a line, but
4996 otherwise the format is free form. Spaces or tabs may appear between
4997 the @cite{#} and the keyword. The keywords and the symbols are case
4998 insensitive as in normal Ada code. Comments may be used on a
4999 preprocessor line, but other than that, no other tokens may appear on a
5000 preprocessor line. Any number of @cite{elsif} clauses can be present,
5001 including none at all. The @cite{else} is optional, as in Ada.
5003 The @cite{#} marking the start of a preprocessor line must be the first
5004 non-blank character on the line, i.e., it must be preceded only by
5005 spaces or horizontal tabs.
5007 Symbol substitution outside of preprocessor lines is obtained by using
5008 the sequence:
5010 @example
5011 $symbol
5012 @end example
5014 anywhere within a source line, except in a comment or within a
5015 string literal. The identifier
5016 following the @cite{$} must match one of the symbols defined in the symbol
5017 definition file, and the result is to substitute the value of the
5018 symbol in place of @cite{$symbol} in the output file.
5020 Note that although the substitution of strings within a string literal
5021 is not possible, it is possible to have a symbol whose defined value is
5022 a string literal. So instead of setting XYZ to @cite{hello} and writing:
5024 @example
5025 Header : String := "$XYZ";
5026 @end example
5028 you should set XYZ to @cite{"hello"} and write:
5030 @example
5031 Header : String := $XYZ;
5032 @end example
5034 and then the substitution will occur as desired.
5036 @node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
5037 @anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{18}
5038 @subsection Integrated Preprocessing
5041 GNAT sources may be preprocessed immediately before compilation.
5042 In this case, the actual
5043 text of the source is not the text of the source file, but is derived from it
5044 through a process called preprocessing. Integrated preprocessing is specified
5045 through switches @emph{-gnatep} and/or @emph{-gnateD}. @emph{-gnatep}
5046 indicates, through a text file, the preprocessing data to be used.
5047 @code{-gnateD} specifies or modifies the values of preprocessing symbol.
5048 Note that integrated preprocessing applies only to Ada source files, it is
5049 not available for configuration pragma files.
5051 Note that when integrated preprocessing is used, the output from the
5052 preprocessor is not written to any external file. Instead it is passed
5053 internally to the compiler. If you need to preserve the result of
5054 preprocessing in a file, then you should use @emph{gnatprep}
5055 to perform the desired preprocessing in stand-alone mode.
5057 It is recommended that @emph{gnatmake} switch -s should be
5058 used when Integrated Preprocessing is used. The reason is that preprocessing
5059 with another Preprocessing Data file without changing the sources will
5060 not trigger recompilation without this switch.
5062 Note that @emph{gnatmake} switch -m will almost
5063 always trigger recompilation for sources that are preprocessed,
5064 because @emph{gnatmake} cannot compute the checksum of the source after
5065 preprocessing.
5067 The actual preprocessing function is described in detail in section
5068 @ref{17,,Preprocessing with gnatprep}. This section only describes how integrated
5069 preprocessing is triggered and parameterized.
5071 @geindex -gnatep (gcc)
5074 @table @asis
5076 @item @code{-gnatep=@emph{file}}
5078 This switch indicates to the compiler the file name (without directory
5079 information) of the preprocessor data file to use. The preprocessor data file
5080 should be found in the source directories. Alternatively when using project
5081 files, you can reference to the project file's directory via the
5082 @code{project name'Project_Dir} project attribute, e.g:
5084 @example
5085 project Prj is
5086    package Compiler is
5087       for Switches ("Ada") use
5088         ("-gnatep=" & Prj'Project_Dir & "prep.def");
5089    end Compiler;
5090 end Prj;
5091 @end example
5093 A preprocessing data file is a text file with significant lines indicating
5094 how should be preprocessed either a specific source or all sources not
5095 mentioned in other lines. A significant line is a nonempty, non-comment line.
5096 Comments are similar to Ada comments.
5098 Each significant line starts with either a literal string or the character '*'.
5099 A literal string is the file name (without directory information) of the source
5100 to preprocess. A character '*' indicates the preprocessing for all the sources
5101 that are not specified explicitly on other lines (order of the lines is not
5102 significant). It is an error to have two lines with the same file name or two
5103 lines starting with the character '*'.
5105 After the file name or the character '*', another optional literal string
5106 indicating the file name of the definition file to be used for preprocessing
5107 (@ref{ac,,Form of Definitions File}). The definition files are found by the
5108 compiler in one of the source directories. In some cases, when compiling
5109 a source in a directory other than the current directory, if the definition
5110 file is in the current directory, it may be necessary to add the current
5111 directory as a source directory through switch -I., otherwise
5112 the compiler would not find the definition file.
5114 Then, optionally, switches similar to those of @cite{gnatprep} may
5115 be found. Those switches are:
5118 @table @asis
5120 @item @code{-b}
5122 Causes both preprocessor lines and the lines deleted by
5123 preprocessing to be replaced by blank lines, preserving the line number.
5124 This switch is always implied; however, if specified after @emph{-c}
5125 it cancels the effect of @emph{-c}.
5127 @item @code{-c}
5129 Causes both preprocessor lines and the lines deleted
5130 by preprocessing to be retained as comments marked
5131 with the special string '@cite{--!}'.
5133 @item @code{-Dsymbol=@emph{value}}
5135 Define or redefine a symbol, associated with value. A symbol is an Ada
5136 identifier, or an Ada reserved word, with the exception of @cite{if},
5137 @cite{else}, @cite{elsif}, @cite{end}, @cite{and}, @cite{or} and @cite{then}.
5138 @cite{value} is either a literal string, an Ada identifier or any Ada reserved
5139 word. A symbol declared with this switch replaces a symbol with the
5140 same name defined in a definition file.
5142 @item @code{-s}
5144 Causes a sorted list of symbol names and values to be
5145 listed on the standard output file.
5147 @item @code{-u}
5149 Causes undefined symbols to be treated as having the value @cite{FALSE}
5150 in the context
5151 of a preprocessor test. In the absence of this option, an undefined symbol in
5152 a @cite{#if} or @cite{#elsif} test will be treated as an error.
5153 @end table
5155 Examples of valid lines in a preprocessor data file:
5157 @example
5158 "toto.adb"  "prep.def" -u
5159 --  preprocess "toto.adb", using definition file "prep.def",
5160 --  undefined symbol are False.
5162 * -c -DVERSION=V101
5163 --  preprocess all other sources without a definition file;
5164 --  suppressed lined are commented; symbol VERSION has the value V101.
5166 "titi.adb" "prep2.def" -s
5167 --  preprocess "titi.adb", using definition file "prep2.def";
5168 --  list all symbols with their values.
5169 @end example
5170 @end table
5172 @geindex -gnateD (gcc)
5175 @table @asis
5177 @item @code{-gnateDsymbol[=value]}
5179 Define or redefine a preprocessing symbol, associated with value. If no value
5180 is given on the command line, then the value of the symbol is @cite{True}.
5181 A symbol is an identifier, following normal Ada (case-insensitive)
5182 rules for its syntax, and value is either an arbitrary string between double
5183 quotes or any sequence (including an empty sequence) of characters from the
5184 set (letters, digits, period, underline).
5185 Ada reserved words may be used as symbols, with the exceptions of @cite{if},
5186 @cite{else}, @cite{elsif}, @cite{end}, @cite{and}, @cite{or} and @cite{then}.
5188 Examples:
5190 @example
5191 -gnateDToto=Titi
5192 -gnateDFoo
5193 -gnateDFoo=\"Foo-Bar\"
5194 @end example
5196 A symbol declared with this switch on the command line replaces a
5197 symbol with the same name either in a definition file or specified with a
5198 switch -D in the preprocessor data file.
5200 This switch is similar to switch @emph{-D} of @cite{gnatprep}.
5202 @item @code{-gnateG}
5204 When integrated preprocessing is performed and the preprocessor modifies
5205 the source text, write the result of this preprocessing into a file
5206 <source>.prep.
5207 @end table
5209 @node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5210 @anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{44}@anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{b1}
5211 @section Mixed Language Programming
5214 @geindex Mixed Language Programming
5216 This section describes how to develop a mixed-language program,
5217 with a focus on combining Ada with C or C++.
5219 @menu
5220 * Interfacing to C:: 
5221 * Calling Conventions:: 
5222 * Building Mixed Ada and C++ Programs:: 
5223 * Generating Ada Bindings for C and C++ headers:: 
5224 * Generating C Headers for Ada Specifications:: 
5226 @end menu
5228 @node Interfacing to C,Calling Conventions,,Mixed Language Programming
5229 @anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{b2}@anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{b3}
5230 @subsection Interfacing to C
5233 Interfacing Ada with a foreign language such as C involves using
5234 compiler directives to import and/or export entity definitions in each
5235 language -- using @cite{extern} statements in C, for instance, and the
5236 @cite{Import}, @cite{Export}, and @cite{Convention} pragmas in Ada.
5237 A full treatment of these topics is provided in Appendix B, section 1
5238 of the Ada Reference Manual.
5240 There are two ways to build a program using GNAT that contains some Ada
5241 sources and some foreign language sources, depending on whether or not
5242 the main subprogram is written in Ada.  Here is a source example with
5243 the main subprogram in Ada:
5245 @example
5246 /* file1.c */
5247 #include <stdio.h>
5249 void print_num (int num)
5251   printf ("num is %d.\\n", num);
5252   return;
5254 @end example
5256 @example
5257 /* file2.c */
5259 /* num_from_Ada is declared in my_main.adb */
5260 extern int num_from_Ada;
5262 int get_num (void)
5264   return num_from_Ada;
5266 @end example
5268 @example
5269 --  my_main.adb
5270 procedure My_Main is
5272    --  Declare then export an Integer entity called num_from_Ada
5273    My_Num : Integer := 10;
5274    pragma Export (C, My_Num, "num_from_Ada");
5276    --  Declare an Ada function spec for Get_Num, then use
5277    --  C function get_num for the implementation.
5278    function Get_Num return Integer;
5279    pragma Import (C, Get_Num, "get_num");
5281    --  Declare an Ada procedure spec for Print_Num, then use
5282    --  C function print_num for the implementation.
5283    procedure Print_Num (Num : Integer);
5284    pragma Import (C, Print_Num, "print_num";
5286 begin
5287    Print_Num (Get_Num);
5288 end My_Main;
5289 @end example
5291 To build this example:
5294 @itemize *
5296 @item 
5297 First compile the foreign language files to
5298 generate object files:
5300 @example
5301 $ gcc -c file1.c
5302 $ gcc -c file2.c
5303 @end example
5305 @item 
5306 Then, compile the Ada units to produce a set of object files and ALI
5307 files:
5309 @example
5310 $ gnatmake -c my_main.adb
5311 @end example
5313 @item 
5314 Run the Ada binder on the Ada main program:
5316 @example
5317 $ gnatbind my_main.ali
5318 @end example
5320 @item 
5321 Link the Ada main program, the Ada objects and the other language
5322 objects:
5324 @example
5325 $ gnatlink my_main.ali file1.o file2.o
5326 @end example
5327 @end itemize
5329 The last three steps can be grouped in a single command:
5331 @example
5332 $ gnatmake my_main.adb -largs file1.o file2.o
5333 @end example
5335 @geindex Binder output file
5337 If the main program is in a language other than Ada, then you may have
5338 more than one entry point into the Ada subsystem. You must use a special
5339 binder option to generate callable routines that initialize and
5340 finalize the Ada units (@ref{b4,,Binding with Non-Ada Main Programs}).
5341 Calls to the initialization and finalization routines must be inserted
5342 in the main program, or some other appropriate point in the code. The
5343 call to initialize the Ada units must occur before the first Ada
5344 subprogram is called, and the call to finalize the Ada units must occur
5345 after the last Ada subprogram returns. The binder will place the
5346 initialization and finalization subprograms into the
5347 @code{b~xxx.adb} file where they can be accessed by your C
5348 sources.  To illustrate, we have the following example:
5350 @example
5351 /* main.c */
5352 extern void adainit (void);
5353 extern void adafinal (void);
5354 extern int add (int, int);
5355 extern int sub (int, int);
5357 int main (int argc, char *argv[])
5359    int a = 21, b = 7;
5361    adainit();
5363    /* Should print "21 + 7 = 28" */
5364    printf ("%d + %d = %d\\n", a, b, add (a, b));
5366    /* Should print "21 - 7 = 14" */
5367    printf ("%d - %d = %d\\n", a, b, sub (a, b));
5369    adafinal();
5371 @end example
5373 @example
5374 --  unit1.ads
5375 package Unit1 is
5376    function Add (A, B : Integer) return Integer;
5377    pragma Export (C, Add, "add");
5378 end Unit1;
5379 @end example
5381 @example
5382 --  unit1.adb
5383 package body Unit1 is
5384    function Add (A, B : Integer) return Integer is
5385    begin
5386       return A + B;
5387    end Add;
5388 end Unit1;
5389 @end example
5391 @example
5392 --  unit2.ads
5393 package Unit2 is
5394    function Sub (A, B : Integer) return Integer;
5395    pragma Export (C, Sub, "sub");
5396 end Unit2;
5397 @end example
5399 @example
5400 --  unit2.adb
5401 package body Unit2 is
5402    function Sub (A, B : Integer) return Integer is
5403    begin
5404       return A - B;
5405    end Sub;
5406 end Unit2;
5407 @end example
5409 The build procedure for this application is similar to the last
5410 example's:
5413 @itemize *
5415 @item 
5416 First, compile the foreign language files to generate object files:
5418 @example
5419 $ gcc -c main.c
5420 @end example
5422 @item 
5423 Next, compile the Ada units to produce a set of object files and ALI
5424 files:
5426 @example
5427 $ gnatmake -c unit1.adb
5428 $ gnatmake -c unit2.adb
5429 @end example
5431 @item 
5432 Run the Ada binder on every generated ALI file.  Make sure to use the
5433 @code{-n} option to specify a foreign main program:
5435 @example
5436 $ gnatbind -n unit1.ali unit2.ali
5437 @end example
5439 @item 
5440 Link the Ada main program, the Ada objects and the foreign language
5441 objects. You need only list the last ALI file here:
5443 @example
5444 $ gnatlink unit2.ali main.o -o exec_file
5445 @end example
5447 This procedure yields a binary executable called @code{exec_file}.
5448 @end itemize
5450 Depending on the circumstances (for example when your non-Ada main object
5451 does not provide symbol @cite{main}), you may also need to instruct the
5452 GNAT linker not to include the standard startup objects by passing the
5453 @code{-nostartfiles} switch to @cite{gnatlink}.
5455 @node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5456 @anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{b5}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{b6}
5457 @subsection Calling Conventions
5460 @geindex Foreign Languages
5462 @geindex Calling Conventions
5464 GNAT follows standard calling sequence conventions and will thus interface
5465 to any other language that also follows these conventions. The following
5466 Convention identifiers are recognized by GNAT:
5468 @geindex Interfacing to Ada
5470 @geindex Other Ada compilers
5472 @geindex Convention Ada
5475 @table @asis
5477 @item @emph{Ada}
5479 This indicates that the standard Ada calling sequence will be
5480 used and all Ada data items may be passed without any limitations in the
5481 case where GNAT is used to generate both the caller and callee. It is also
5482 possible to mix GNAT generated code and code generated by another Ada
5483 compiler. In this case, the data types should be restricted to simple
5484 cases, including primitive types. Whether complex data types can be passed
5485 depends on the situation. Probably it is safe to pass simple arrays, such
5486 as arrays of integers or floats. Records may or may not work, depending
5487 on whether both compilers lay them out identically. Complex structures
5488 involving variant records, access parameters, tasks, or protected types,
5489 are unlikely to be able to be passed.
5491 Note that in the case of GNAT running
5492 on a platform that supports HP Ada 83, a higher degree of compatibility
5493 can be guaranteed, and in particular records are laid out in an identical
5494 manner in the two compilers. Note also that if output from two different
5495 compilers is mixed, the program is responsible for dealing with elaboration
5496 issues. Probably the safest approach is to write the main program in the
5497 version of Ada other than GNAT, so that it takes care of its own elaboration
5498 requirements, and then call the GNAT-generated adainit procedure to ensure
5499 elaboration of the GNAT components. Consult the documentation of the other
5500 Ada compiler for further details on elaboration.
5502 However, it is not possible to mix the tasking run time of GNAT and
5503 HP Ada 83, All the tasking operations must either be entirely within
5504 GNAT compiled sections of the program, or entirely within HP Ada 83
5505 compiled sections of the program.
5506 @end table
5508 @geindex Interfacing to Assembly
5510 @geindex Convention Assembler
5513 @table @asis
5515 @item @emph{Assembler}
5517 Specifies assembler as the convention. In practice this has the
5518 same effect as convention Ada (but is not equivalent in the sense of being
5519 considered the same convention).
5520 @end table
5522 @geindex Convention Asm
5524 @geindex Asm
5527 @table @asis
5529 @item @emph{Asm}
5531 Equivalent to Assembler.
5533 @geindex Interfacing to COBOL
5535 @geindex Convention COBOL
5536 @end table
5538 @geindex COBOL
5541 @table @asis
5543 @item @emph{COBOL}
5545 Data will be passed according to the conventions described
5546 in section B.4 of the Ada Reference Manual.
5547 @end table
5549 @geindex C
5551 @geindex Interfacing to C
5553 @geindex Convention C
5556 @table @asis
5558 @item @emph{C}
5560 Data will be passed according to the conventions described
5561 in section B.3 of the Ada Reference Manual.
5563 A note on interfacing to a C 'varargs' function:
5565 @quotation
5567 @geindex C varargs function
5569 @geindex Interfacing to C varargs function
5571 @geindex varargs function interfaces
5573 In C, @cite{varargs} allows a function to take a variable number of
5574 arguments. There is no direct equivalent in this to Ada. One
5575 approach that can be used is to create a C wrapper for each
5576 different profile and then interface to this C wrapper. For
5577 example, to print an @cite{int} value using @cite{printf},
5578 create a C function @cite{printfi} that takes two arguments, a
5579 pointer to a string and an int, and calls @cite{printf}.
5580 Then in the Ada program, use pragma @cite{Import} to
5581 interface to @cite{printfi}.
5583 It may work on some platforms to directly interface to
5584 a @cite{varargs} function by providing a specific Ada profile
5585 for a particular call. However, this does not work on
5586 all platforms, since there is no guarantee that the
5587 calling sequence for a two argument normal C function
5588 is the same as for calling a @cite{varargs} C function with
5589 the same two arguments.
5590 @end quotation
5591 @end table
5593 @geindex Convention Default
5595 @geindex Default
5598 @table @asis
5600 @item @emph{Default}
5602 Equivalent to C.
5603 @end table
5605 @geindex Convention External
5607 @geindex External
5610 @table @asis
5612 @item @emph{External}
5614 Equivalent to C.
5615 @end table
5617 @geindex C++
5619 @geindex Interfacing to C++
5621 @geindex Convention C++
5624 @table @asis
5626 @item @emph{C_Plus_Plus (or CPP)}
5628 This stands for C++. For most purposes this is identical to C.
5629 See the separate description of the specialized GNAT pragmas relating to
5630 C++ interfacing for further details.
5631 @end table
5633 @geindex Fortran
5635 @geindex Interfacing to Fortran
5637 @geindex Convention Fortran
5640 @table @asis
5642 @item @emph{Fortran}
5644 Data will be passed according to the conventions described
5645 in section B.5 of the Ada Reference Manual.
5647 @item @emph{Intrinsic}
5649 This applies to an intrinsic operation, as defined in the Ada
5650 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5651 this means that the body of the subprogram is provided by the compiler itself,
5652 usually by means of an efficient code sequence, and that the user does not
5653 supply an explicit body for it. In an application program, the pragma may
5654 be applied to the following sets of names:
5657 @itemize *
5659 @item 
5660 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5661 The corresponding subprogram declaration must have
5662 two formal parameters. The
5663 first one must be a signed integer type or a modular type with a binary
5664 modulus, and the second parameter must be of type Natural.
5665 The return type must be the same as the type of the first argument. The size
5666 of this type can only be 8, 16, 32, or 64.
5668 @item 
5669 Binary arithmetic operators: '+', '-', '*', '/'.
5670 The corresponding operator declaration must have parameters and result type
5671 that have the same root numeric type (for example, all three are long_float
5672 types). This simplifies the definition of operations that use type checking
5673 to perform dimensional checks:
5674 @end itemize
5676 @example
5677   type Distance is new Long_Float;
5678   type Time     is new Long_Float;
5679   type Velocity is new Long_Float;
5680   function "/" (D : Distance; T : Time)
5681     return Velocity;
5682   pragma Import (Intrinsic, "/");
5684 This common idiom is often programmed with a generic definition and an
5685 explicit body. The pragma makes it simpler to introduce such declarations.
5686 It incurs no overhead in compilation time or code size, because it is
5687 implemented as a single machine instruction.
5688 @end example
5691 @itemize *
5693 @item 
5694 General subprogram entities. This is used  to bind an Ada subprogram
5695 declaration to
5696 a compiler builtin by name with back-ends where such interfaces are
5697 available. A typical example is the set of @cite{__builtin} functions
5698 exposed by the GCC back-end, as in the following example:
5700 @example
5701 function builtin_sqrt (F : Float) return Float;
5702 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5703 @end example
5705 Most of the GCC builtins are accessible this way, and as for other
5706 import conventions (e.g. C), it is the user's responsibility to ensure
5707 that the Ada subprogram profile matches the underlying builtin
5708 expectations.
5709 @end itemize
5710 @end table
5712 @geindex Stdcall
5714 @geindex Convention Stdcall
5717 @table @asis
5719 @item @emph{Stdcall}
5721 This is relevant only to Windows implementations of GNAT,
5722 and specifies that the @cite{Stdcall} calling sequence will be used,
5723 as defined by the NT API. Nevertheless, to ease building
5724 cross-platform bindings this convention will be handled as a @cite{C} calling
5725 convention on non-Windows platforms.
5726 @end table
5728 @geindex DLL
5730 @geindex Convention DLL
5733 @table @asis
5735 @item @emph{DLL}
5737 This is equivalent to @cite{Stdcall}.
5738 @end table
5740 @geindex Win32
5742 @geindex Convention Win32
5745 @table @asis
5747 @item @emph{Win32}
5749 This is equivalent to @cite{Stdcall}.
5750 @end table
5752 @geindex Stubbed
5754 @geindex Convention Stubbed
5757 @table @asis
5759 @item @emph{Stubbed}
5761 This is a special convention that indicates that the compiler
5762 should provide a stub body that raises @cite{Program_Error}.
5763 @end table
5765 GNAT additionally provides a useful pragma @cite{Convention_Identifier}
5766 that can be used to parameterize conventions and allow additional synonyms
5767 to be specified. For example if you have legacy code in which the convention
5768 identifier Fortran77 was used for Fortran, you can use the configuration
5769 pragma:
5771 @example
5772 pragma Convention_Identifier (Fortran77, Fortran);
5773 @end example
5775 And from now on the identifier Fortran77 may be used as a convention
5776 identifier (for example in an @cite{Import} pragma) with the same
5777 meaning as Fortran.
5779 @node Building Mixed Ada and C++ Programs,Generating Ada Bindings for C and C++ headers,Calling Conventions,Mixed Language Programming
5780 @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}
5781 @subsection Building Mixed Ada and C++ Programs
5784 A programmer inexperienced with mixed-language development may find that
5785 building an application containing both Ada and C++ code can be a
5786 challenge.  This section gives a few hints that should make this task easier.
5788 @menu
5789 * Interfacing to C++:: 
5790 * Linking a Mixed C++ & Ada Program:: 
5791 * A Simple Example:: 
5792 * Interfacing with C++ constructors:: 
5793 * Interfacing with C++ at the Class Level:: 
5795 @end menu
5797 @node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5798 @anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{b9}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{ba}
5799 @subsubsection Interfacing to C++
5802 GNAT supports interfacing with the G++ compiler (or any C++ compiler
5803 generating code that is compatible with the G++ Application Binary
5804 Interface ---see @indicateurl{http://www.codesourcery.com/archives/cxx-abi}).
5806 Interfacing can be done at 3 levels: simple data, subprograms, and
5807 classes. In the first two cases, GNAT offers a specific @cite{Convention C_Plus_Plus}
5808 (or @cite{CPP}) that behaves exactly like @cite{Convention C}.
5809 Usually, C++ mangles the names of subprograms. To generate proper mangled
5810 names automatically, see @ref{19,,Generating Ada Bindings for C and C++ headers}).
5811 This problem can also be addressed manually in two ways:
5814 @itemize *
5816 @item 
5817 by modifying the C++ code in order to force a C convention using
5818 the @cite{extern "C"} syntax.
5820 @item 
5821 by figuring out the mangled name (using e.g. @emph{nm}) and using it as the
5822 Link_Name argument of the pragma import.
5823 @end itemize
5825 Interfacing at the class level can be achieved by using the GNAT specific
5826 pragmas such as @cite{CPP_Constructor}.  See the @cite{GNAT_Reference_Manual} for additional information.
5828 @node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5829 @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}
5830 @subsubsection Linking a Mixed C++ & Ada Program
5833 Usually the linker of the C++ development system must be used to link
5834 mixed applications because most C++ systems will resolve elaboration
5835 issues (such as calling constructors on global class instances)
5836 transparently during the link phase. GNAT has been adapted to ease the
5837 use of a foreign linker for the last phase. Three cases can be
5838 considered:
5841 @itemize *
5843 @item 
5844 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5845 The C++ linker can simply be called by using the C++ specific driver
5846 called @cite{g++}.
5848 Note that if the C++ code uses inline functions, you will need to
5849 compile your C++ code with the @cite{-fkeep-inline-functions} switch in
5850 order to provide an existing function implementation that the Ada code can
5851 link with.
5853 @example
5854 $ g++ -c -fkeep-inline-functions file1.C
5855 $ g++ -c -fkeep-inline-functions file2.C
5856 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5857 @end example
5859 @item 
5860 Using GNAT and G++ from two different GCC installations: If both
5861 compilers are on the :envvar`PATH`, the previous method may be used. It is
5862 important to note that environment variables such as
5863 @geindex C_INCLUDE_PATH
5864 @geindex environment variable; C_INCLUDE_PATH
5865 @code{C_INCLUDE_PATH}, 
5866 @geindex GCC_EXEC_PREFIX
5867 @geindex environment variable; GCC_EXEC_PREFIX
5868 @code{GCC_EXEC_PREFIX},
5869 @geindex BINUTILS_ROOT
5870 @geindex environment variable; BINUTILS_ROOT
5871 @code{BINUTILS_ROOT}, and
5872 @geindex GCC_ROOT
5873 @geindex environment variable; GCC_ROOT
5874 @code{GCC_ROOT} will affect both compilers
5875 at the same time and may make one of the two compilers operate
5876 improperly if set during invocation of the wrong compiler.  It is also
5877 very important that the linker uses the proper @code{libgcc.a} GCC
5878 library -- that is, the one from the C++ compiler installation. The
5879 implicit link command as suggested in the @cite{gnatmake} command
5880 from the former example can be replaced by an explicit link command with
5881 the full-verbosity option in order to verify which library is used:
5883 @example
5884 $ gnatbind ada_unit
5885 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5886 @end example
5888 If there is a problem due to interfering environment variables, it can
5889 be worked around by using an intermediate script. The following example
5890 shows the proper script to use when GNAT has not been installed at its
5891 default location and g++ has been installed at its default location:
5893 @example
5894 $ cat ./my_script
5895 #!/bin/sh
5896 unset BINUTILS_ROOT
5897 unset GCC_ROOT
5898 c++ $*
5899 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5900 @end example
5902 @item 
5903 Using a non-GNU C++ compiler: The commands previously described can be
5904 used to insure that the C++ linker is used. Nonetheless, you need to add
5905 a few more parameters to the link command line, depending on the exception
5906 mechanism used.
5908 If the @cite{setjmp/longjmp} exception mechanism is used, only the paths
5909 to the libgcc libraries are required:
5911 @example
5912 $ cat ./my_script
5913 #!/bin/sh
5914 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
5915 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5916 @end example
5918 where CC is the name of the non-GNU C++ compiler.
5920 If the @cite{zero cost} exception mechanism is used, and the platform
5921 supports automatic registration of exception tables (e.g., Solaris),
5922 paths to more objects are required:
5924 @example
5925 $ cat ./my_script
5926 #!/bin/sh
5927 CC `gcc -print-file-name=crtbegin.o` $* \\
5928 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \\
5929 `gcc -print-file-name=crtend.o`
5930 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5931 @end example
5933 If the "zero cost exception" mechanism is used, and the platform
5934 doesn't support automatic registration of exception tables (e.g., HP-UX
5935 or AIX), the simple approach described above will not work and
5936 a pre-linking phase using GNAT will be necessary.
5937 @end itemize
5939 Another alternative is to use the @code{gprbuild} multi-language builder
5940 which has a large knowledge base and knows how to link Ada and C++ code
5941 together automatically in most cases.
5943 @node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
5944 @anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{bd}@anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{be}
5945 @subsubsection A Simple Example
5948 The following example, provided as part of the GNAT examples, shows how
5949 to achieve procedural interfacing between Ada and C++ in both
5950 directions. The C++ class A has two methods. The first method is exported
5951 to Ada by the means of an extern C wrapper function. The second method
5952 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
5953 a limited record with a layout comparable to the C++ class. The Ada
5954 subprogram, in turn, calls the C++ method. So, starting from the C++
5955 main program, the process passes back and forth between the two
5956 languages.
5958 Here are the compilation commands:
5960 @example
5961 $ gnatmake -c simple_cpp_interface
5962 $ g++ -c cpp_main.C
5963 $ g++ -c ex7.C
5964 $ gnatbind -n simple_cpp_interface
5965 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
5966 @end example
5968 Here are the corresponding sources:
5970 @example
5971 //cpp_main.C
5973 #include "ex7.h"
5975 extern "C" @{
5976   void adainit (void);
5977   void adafinal (void);
5978   void method1 (A *t);
5981 void method1 (A *t)
5983   t->method1 ();
5986 int main ()
5988   A obj;
5989   adainit ();
5990   obj.method2 (3030);
5991   adafinal ();
5993 @end example
5995 @example
5996 //ex7.h
5998 class Origin @{
5999  public:
6000   int o_value;
6002 class A : public Origin @{
6003  public:
6004   void method1 (void);
6005   void method2 (int v);
6006   A();
6007   int   a_value;
6009 @end example
6011 @example
6012 //ex7.C
6014 #include "ex7.h"
6015 #include <stdio.h>
6017 extern "C" @{ void ada_method2 (A *t, int v);@}
6019 void A::method1 (void)
6021   a_value = 2020;
6022   printf ("in A::method1, a_value = %d \\n",a_value);
6025 void A::method2 (int v)
6027    ada_method2 (this, v);
6028    printf ("in A::method2, a_value = %d \\n",a_value);
6031 A::A(void)
6033    a_value = 1010;
6034   printf ("in A::A, a_value = %d \\n",a_value);
6036 @end example
6038 @example
6039 -- simple_cpp_interface.ads
6040 with System;
6041 package Simple_Cpp_Interface is
6042    type A is limited
6043       record
6044          Vptr    : System.Address;
6045          O_Value : Integer;
6046          A_Value : Integer;
6047       end record;
6048    pragma Convention (C, A);
6050    procedure Method1 (This : in out A);
6051    pragma Import (C, Method1);
6053    procedure Ada_Method2 (This : in out A; V : Integer);
6054    pragma Export (C, Ada_Method2);
6056 end Simple_Cpp_Interface;
6057 @end example
6059 @example
6060 -- simple_cpp_interface.adb
6061 package body Simple_Cpp_Interface is
6063    procedure Ada_Method2 (This : in out A; V : Integer) is
6064    begin
6065       Method1 (This);
6066       This.A_Value := V;
6067    end Ada_Method2;
6069 end Simple_Cpp_Interface;
6070 @end example
6072 @node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
6073 @anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{bf}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{c0}
6074 @subsubsection Interfacing with C++ constructors
6077 In order to interface with C++ constructors GNAT provides the
6078 @cite{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
6079 for additional information).
6080 In this section we present some common uses of C++ constructors
6081 in mixed-languages programs in GNAT.
6083 Let us assume that we need to interface with the following
6084 C++ class:
6086 @example
6087 class Root @{
6088 public:
6089   int  a_value;
6090   int  b_value;
6091   virtual int Get_Value ();
6092   Root();              // Default constructor
6093   Root(int v);         // 1st non-default constructor
6094   Root(int v, int w);  // 2nd non-default constructor
6096 @end example
6098 For this purpose we can write the following package spec (further
6099 information on how to build this spec is available in
6100 @ref{c1,,Interfacing with C++ at the Class Level} and
6101 @ref{19,,Generating Ada Bindings for C and C++ headers}).
6103 @example
6104 with Interfaces.C; use Interfaces.C;
6105 package Pkg_Root is
6106   type Root is tagged limited record
6107      A_Value : int;
6108      B_Value : int;
6109   end record;
6110   pragma Import (CPP, Root);
6112   function Get_Value (Obj : Root) return int;
6113   pragma Import (CPP, Get_Value);
6115   function Constructor return Root;
6116   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
6118   function Constructor (v : Integer) return Root;
6119   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
6121   function Constructor (v, w : Integer) return Root;
6122   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
6123 end Pkg_Root;
6124 @end example
6126 On the Ada side the constructor is represented by a function (whose
6127 name is arbitrary) that returns the classwide type corresponding to
6128 the imported C++ class. Although the constructor is described as a
6129 function, it is typically a procedure with an extra implicit argument
6130 (the object being initialized) at the implementation level. GNAT
6131 issues the appropriate call, whatever it is, to get the object
6132 properly initialized.
6134 Constructors can only appear in the following contexts:
6137 @itemize *
6139 @item 
6140 On the right side of an initialization of an object of type @cite{T}.
6142 @item 
6143 On the right side of an initialization of a record component of type @cite{T}.
6145 @item 
6146 In an Ada 2005 limited aggregate.
6148 @item 
6149 In an Ada 2005 nested limited aggregate.
6151 @item 
6152 In an Ada 2005 limited aggregate that initializes an object built in
6153 place by an extended return statement.
6154 @end itemize
6156 In a declaration of an object whose type is a class imported from C++,
6157 either the default C++ constructor is implicitly called by GNAT, or
6158 else the required C++ constructor must be explicitly called in the
6159 expression that initializes the object. For example:
6161 @example
6162 Obj1 : Root;
6163 Obj2 : Root := Constructor;
6164 Obj3 : Root := Constructor (v => 10);
6165 Obj4 : Root := Constructor (30, 40);
6166 @end example
6168 The first two declarations are equivalent: in both cases the default C++
6169 constructor is invoked (in the former case the call to the constructor is
6170 implicit, and in the latter case the call is explicit in the object
6171 declaration). @cite{Obj3} is initialized by the C++ non-default constructor
6172 that takes an integer argument, and @cite{Obj4} is initialized by the
6173 non-default C++ constructor that takes two integers.
6175 Let us derive the imported C++ class in the Ada side. For example:
6177 @example
6178 type DT is new Root with record
6179    C_Value : Natural := 2009;
6180 end record;
6181 @end example
6183 In this case the components DT inherited from the C++ side must be
6184 initialized by a C++ constructor, and the additional Ada components
6185 of type DT are initialized by GNAT. The initialization of such an
6186 object is done either by default, or by means of a function returning
6187 an aggregate of type DT, or by means of an extension aggregate.
6189 @example
6190 Obj5 : DT;
6191 Obj6 : DT := Function_Returning_DT (50);
6192 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6193 @end example
6195 The declaration of @cite{Obj5} invokes the default constructors: the
6196 C++ default constructor of the parent type takes care of the initialization
6197 of the components inherited from Root, and GNAT takes care of the default
6198 initialization of the additional Ada components of type DT (that is,
6199 @cite{C_Value} is initialized to value 2009). The order of invocation of
6200 the constructors is consistent with the order of elaboration required by
6201 Ada and C++. That is, the constructor of the parent type is always called
6202 before the constructor of the derived type.
6204 Let us now consider a record that has components whose type is imported
6205 from C++. For example:
6207 @example
6208 type Rec1 is limited record
6209    Data1 : Root := Constructor (10);
6210    Value : Natural := 1000;
6211 end record;
6213 type Rec2 (D : Integer := 20) is limited record
6214    Rec   : Rec1;
6215    Data2 : Root := Constructor (D, 30);
6216 end record;
6217 @end example
6219 The initialization of an object of type @cite{Rec2} will call the
6220 non-default C++ constructors specified for the imported components.
6221 For example:
6223 @example
6224 Obj8 : Rec2 (40);
6225 @end example
6227 Using Ada 2005 we can use limited aggregates to initialize an object
6228 invoking C++ constructors that differ from those specified in the type
6229 declarations. For example:
6231 @example
6232 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6233                         others => <>),
6234                 others => <>);
6235 @end example
6237 The above declaration uses an Ada 2005 limited aggregate to
6238 initialize @cite{Obj9}, and the C++ constructor that has two integer
6239 arguments is invoked to initialize the @cite{Data1} component instead
6240 of the constructor specified in the declaration of type @cite{Rec1}. In
6241 Ada 2005 the box in the aggregate indicates that unspecified components
6242 are initialized using the expression (if any) available in the component
6243 declaration. That is, in this case discriminant @cite{D} is initialized
6244 to value @cite{20}, @cite{Value} is initialized to value 1000, and the
6245 non-default C++ constructor that handles two integers takes care of
6246 initializing component @cite{Data2} with values @cite{20@comma{}30}.
6248 In Ada 2005 we can use the extended return statement to build the Ada
6249 equivalent to C++ non-default constructors. For example:
6251 @example
6252 function Constructor (V : Integer) return Rec2 is
6253 begin
6254    return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
6255                                  others => <>),
6256                          others => <>) do
6257       --  Further actions required for construction of
6258       --  objects of type Rec2
6259       ...
6260    end record;
6261 end Constructor;
6262 @end example
6264 In this example the extended return statement construct is used to
6265 build in place the returned object whose components are initialized
6266 by means of a limited aggregate. Any further action associated with
6267 the constructor can be placed inside the construct.
6269 @node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6270 @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}
6271 @subsubsection Interfacing with C++ at the Class Level
6274 In this section we demonstrate the GNAT features for interfacing with
6275 C++ by means of an example making use of Ada 2005 abstract interface
6276 types. This example consists of a classification of animals; classes
6277 have been used to model our main classification of animals, and
6278 interfaces provide support for the management of secondary
6279 classifications. We first demonstrate a case in which the types and
6280 constructors are defined on the C++ side and imported from the Ada
6281 side, and latter the reverse case.
6283 The root of our derivation will be the @cite{Animal} class, with a
6284 single private attribute (the @cite{Age} of the animal), a constructor,
6285 and two public primitives to set and get the value of this attribute.
6287 @example
6288 class Animal @{
6289  public:
6290    virtual void Set_Age (int New_Age);
6291    virtual int Age ();
6292    Animal() @{Age_Count = 0;@};
6293  private:
6294    int Age_Count;
6296 @end example
6298 Abstract interface types are defined in C++ by means of classes with pure
6299 virtual functions and no data members. In our example we will use two
6300 interfaces that provide support for the common management of @cite{Carnivore}
6301 and @cite{Domestic} animals:
6303 @example
6304 class Carnivore @{
6305 public:
6306    virtual int Number_Of_Teeth () = 0;
6309 class Domestic @{
6310 public:
6311    virtual void Set_Owner (char* Name) = 0;
6313 @end example
6315 Using these declarations, we can now say that a @cite{Dog} is an animal that is
6316 both Carnivore and Domestic, that is:
6318 @example
6319 class Dog : Animal, Carnivore, Domestic @{
6320  public:
6321    virtual int  Number_Of_Teeth ();
6322    virtual void Set_Owner (char* Name);
6324    Dog(); // Constructor
6325  private:
6326    int  Tooth_Count;
6327    char *Owner;
6329 @end example
6331 In the following examples we will assume that the previous declarations are
6332 located in a file named @cite{animals.h}. The following package demonstrates
6333 how to import these C++ declarations from the Ada side:
6335 @example
6336 with Interfaces.C.Strings; use Interfaces.C.Strings;
6337 package Animals is
6338   type Carnivore is limited interface;
6339   pragma Convention (C_Plus_Plus, Carnivore);
6340   function Number_Of_Teeth (X : Carnivore)
6341      return Natural is abstract;
6343   type Domestic is limited interface;
6344   pragma Convention (C_Plus_Plus, Domestic);
6345   procedure Set_Owner
6346     (X    : in out Domestic;
6347      Name : Chars_Ptr) is abstract;
6349   type Animal is tagged limited record
6350     Age : Natural;
6351   end record;
6352   pragma Import (C_Plus_Plus, Animal);
6354   procedure Set_Age (X : in out Animal; Age : Integer);
6355   pragma Import (C_Plus_Plus, Set_Age);
6357   function Age (X : Animal) return Integer;
6358   pragma Import (C_Plus_Plus, Age);
6360   function New_Animal return Animal;
6361   pragma CPP_Constructor (New_Animal);
6362   pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6364   type Dog is new Animal and Carnivore and Domestic with record
6365     Tooth_Count : Natural;
6366     Owner       : String (1 .. 30);
6367   end record;
6368   pragma Import (C_Plus_Plus, Dog);
6370   function Number_Of_Teeth (A : Dog) return Natural;
6371   pragma Import (C_Plus_Plus, Number_Of_Teeth);
6373   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6374   pragma Import (C_Plus_Plus, Set_Owner);
6376   function New_Dog return Dog;
6377   pragma CPP_Constructor (New_Dog);
6378   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6379 end Animals;
6380 @end example
6382 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6383 interfacing with these C++ classes is easy. The only requirement is that all
6384 the primitives and components must be declared exactly in the same order in
6385 the two languages.
6387 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6388 means of a @cite{pragma Convention (C_Plus_Plus)}, the convention used to pass
6389 the arguments to the called primitives will be the same as for C++. For the
6390 imported classes we use @cite{pragma Import} with convention @cite{C_Plus_Plus}
6391 to indicate that they have been defined on the C++ side; this is required
6392 because the dispatch table associated with these tagged types will be built
6393 in the C++ side and therefore will not contain the predefined Ada primitives
6394 which Ada would otherwise expect.
6396 As the reader can see there is no need to indicate the C++ mangled names
6397 associated with each subprogram because it is assumed that all the calls to
6398 these primitives will be dispatching calls. The only exception is the
6399 constructor, which must be registered with the compiler by means of
6400 @cite{pragma CPP_Constructor} and needs to provide its associated C++
6401 mangled name because the Ada compiler generates direct calls to it.
6403 With the above packages we can now declare objects of type Dog on the Ada side
6404 and dispatch calls to the corresponding subprograms on the C++ side. We can
6405 also extend the tagged type Dog with further fields and primitives, and
6406 override some of its C++ primitives on the Ada side. For example, here we have
6407 a type derivation defined on the Ada side that inherits all the dispatching
6408 primitives of the ancestor from the C++ side.
6410 @example
6411 with Animals; use Animals;
6412 package Vaccinated_Animals is
6413   type Vaccinated_Dog is new Dog with null record;
6414   function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6415 end Vaccinated_Animals;
6416 @end example
6418 It is important to note that, because of the ABI compatibility, the programmer
6419 does not need to add any further information to indicate either the object
6420 layout or the dispatch table entry associated with each dispatching operation.
6422 Now let us define all the types and constructors on the Ada side and export
6423 them to C++, using the same hierarchy of our previous example:
6425 @example
6426 with Interfaces.C.Strings;
6427 use Interfaces.C.Strings;
6428 package Animals is
6429   type Carnivore is limited interface;
6430   pragma Convention (C_Plus_Plus, Carnivore);
6431   function Number_Of_Teeth (X : Carnivore)
6432      return Natural is abstract;
6434   type Domestic is limited interface;
6435   pragma Convention (C_Plus_Plus, Domestic);
6436   procedure Set_Owner
6437     (X    : in out Domestic;
6438      Name : Chars_Ptr) is abstract;
6440   type Animal is tagged record
6441     Age : Natural;
6442   end record;
6443   pragma Convention (C_Plus_Plus, Animal);
6445   procedure Set_Age (X : in out Animal; Age : Integer);
6446   pragma Export (C_Plus_Plus, Set_Age);
6448   function Age (X : Animal) return Integer;
6449   pragma Export (C_Plus_Plus, Age);
6451   function New_Animal return Animal'Class;
6452   pragma Export (C_Plus_Plus, New_Animal);
6454   type Dog is new Animal and Carnivore and Domestic with record
6455     Tooth_Count : Natural;
6456     Owner       : String (1 .. 30);
6457   end record;
6458   pragma Convention (C_Plus_Plus, Dog);
6460   function Number_Of_Teeth (A : Dog) return Natural;
6461   pragma Export (C_Plus_Plus, Number_Of_Teeth);
6463   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6464   pragma Export (C_Plus_Plus, Set_Owner);
6466   function New_Dog return Dog'Class;
6467   pragma Export (C_Plus_Plus, New_Dog);
6468 end Animals;
6469 @end example
6471 Compared with our previous example the only differences are the use of
6472 @cite{pragma Convention} (instead of @cite{pragma Import}), and the use of
6473 @cite{pragma Export} to indicate to the GNAT compiler that the primitives will
6474 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6475 nothing else to be done; as explained above, the only requirement is that all
6476 the primitives and components are declared in exactly the same order.
6478 For completeness, let us see a brief C++ main program that uses the
6479 declarations available in @cite{animals.h} (presented in our first example) to
6480 import and use the declarations from the Ada side, properly initializing and
6481 finalizing the Ada run-time system along the way:
6483 @example
6484 #include "animals.h"
6485 #include <iostream>
6486 using namespace std;
6488 void Check_Carnivore (Carnivore *obj) @{...@}
6489 void Check_Domestic (Domestic *obj)   @{...@}
6490 void Check_Animal (Animal *obj)       @{...@}
6491 void Check_Dog (Dog *obj)             @{...@}
6493 extern "C" @{
6494   void adainit (void);
6495   void adafinal (void);
6496   Dog* new_dog ();
6499 void test ()
6501   Dog *obj = new_dog();  // Ada constructor
6502   Check_Carnivore (obj); // Check secondary DT
6503   Check_Domestic (obj);  // Check secondary DT
6504   Check_Animal (obj);    // Check primary DT
6505   Check_Dog (obj);       // Check primary DT
6508 int main ()
6510   adainit ();  test();  adafinal ();
6511   return 0;
6513 @end example
6515 @node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Building Mixed Ada and C++ Programs,Mixed Language Programming
6516 @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}
6517 @subsection Generating Ada Bindings for C and C++ headers
6520 @geindex Binding generation (for C and C++ headers)
6522 @geindex C headers (binding generation)
6524 @geindex C++ headers (binding generation)
6526 GNAT includes a binding generator for C and C++ headers which is
6527 intended to do 95% of the tedious work of generating Ada specs from C
6528 or C++ header files.
6530 Note that this capability is not intended to generate 100% correct Ada specs,
6531 and will is some cases require manual adjustments, although it can often
6532 be used out of the box in practice.
6534 Some of the known limitations include:
6537 @itemize *
6539 @item 
6540 only very simple character constant macros are translated into Ada
6541 constants. Function macros (macros with arguments) are partially translated
6542 as comments, to be completed manually if needed.
6544 @item 
6545 some extensions (e.g. vector types) are not supported
6547 @item 
6548 pointers to pointers or complex structures are mapped to System.Address
6550 @item 
6551 identifiers with identical name (except casing) will generate compilation
6552 errors (e.g. @cite{shm_get} vs @cite{SHM_GET}).
6553 @end itemize
6555 The code generated is using the Ada 2005 syntax, which makes it
6556 easier to interface with other languages than previous versions of Ada.
6558 @menu
6559 * Running the Binding Generator:: 
6560 * Generating Bindings for C++ Headers:: 
6561 * Switches:: 
6563 @end menu
6565 @node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6566 @anchor{gnat_ugn/the_gnat_compilation_model id71}@anchor{c4}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{c5}
6567 @subsubsection Running the Binding Generator
6570 The binding generator is part of the @emph{gcc} compiler and can be
6571 invoked via the @emph{-fdump-ada-spec} switch, which will generate Ada
6572 spec files for the header files specified on the command line, and all
6573 header files needed by these files transitively. For example:
6575 @example
6576 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
6577 $ gcc -c -gnat05 *.ads
6578 @end example
6580 will generate, under GNU/Linux, the following files: @code{time_h.ads},
6581 @code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6582 correspond to the files @code{/usr/include/time.h},
6583 @code{/usr/include/bits/time.h}, etc..., and will then compile in Ada 2005
6584 mode these Ada specs.
6586 The @cite{-C} switch tells @emph{gcc} to extract comments from headers,
6587 and will attempt to generate corresponding Ada comments.
6589 If you want to generate a single Ada file and not the transitive closure, you
6590 can use instead the @emph{-fdump-ada-spec-slim} switch.
6592 You can optionally specify a parent unit, of which all generated units will
6593 be children, using @cite{-fada-spec-parent=<unit>}.
6595 Note that we recommend when possible to use the @emph{g++} driver to
6596 generate bindings, even for most C headers, since this will in general
6597 generate better Ada specs. For generating bindings for C++ headers, it is
6598 mandatory to use the @emph{g++} command, or @emph{gcc -x c++} which
6599 is equivalent in this case. If @emph{g++} cannot work on your C headers
6600 because of incompatibilities between C and C++, then you can fallback to
6601 @emph{gcc} instead.
6603 For an example of better bindings generated from the C++ front-end,
6604 the name of the parameters (when available) are actually ignored by the C
6605 front-end. Consider the following C header:
6607 @example
6608 extern void foo (int variable);
6609 @end example
6611 with the C front-end, @cite{variable} is ignored, and the above is handled as:
6613 @example
6614 extern void foo (int);
6615 @end example
6617 generating a generic:
6619 @example
6620 procedure foo (param1 : int);
6621 @end example
6623 with the C++ front-end, the name is available, and we generate:
6625 @example
6626 procedure foo (variable : int);
6627 @end example
6629 In some cases, the generated bindings will be more complete or more meaningful
6630 when defining some macros, which you can do via the @emph{-D} switch. This
6631 is for example the case with @code{Xlib.h} under GNU/Linux:
6633 @example
6634 $ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6635 @end example
6637 The above will generate more complete bindings than a straight call without
6638 the @emph{-DXLIB_ILLEGAL_ACCESS} switch.
6640 In other cases, it is not possible to parse a header file in a stand-alone
6641 manner, because other include files need to be included first. In this
6642 case, the solution is to create a small header file including the needed
6643 @cite{#include} and possible @cite{#define} directives. For example, to
6644 generate Ada bindings for @code{readline/readline.h}, you need to first
6645 include @code{stdio.h}, so you can create a file with the following two
6646 lines in e.g. @code{readline1.h}:
6648 @example
6649 #include <stdio.h>
6650 #include <readline/readline.h>
6651 @end example
6653 and then generate Ada bindings from this file:
6655 @example
6656 $ g++ -c -fdump-ada-spec readline1.h
6657 @end example
6659 @node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6660 @anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{c6}@anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{c7}
6661 @subsubsection Generating Bindings for C++ Headers
6664 Generating bindings for C++ headers is done using the same options, always
6665 with the @emph{g++} compiler. Note that generating Ada spec from C++ headers is a
6666 much more complex job and support for C++ headers is much more limited that
6667 support for C headers. As a result, you will need to modify the resulting
6668 bindings by hand more extensively when using C++ headers.
6670 In this mode, C++ classes will be mapped to Ada tagged types, constructors
6671 will be mapped using the @cite{CPP_Constructor} pragma, and when possible,
6672 multiple inheritance of abstract classes will be mapped to Ada interfaces
6673 (see the @emph{Interfacing to C++} section in the @cite{GNAT Reference Manual}
6674 for additional information on interfacing to C++).
6676 For example, given the following C++ header file:
6678 @example
6679 class Carnivore @{
6680 public:
6681    virtual int Number_Of_Teeth () = 0;
6684 class Domestic @{
6685 public:
6686    virtual void Set_Owner (char* Name) = 0;
6689 class Animal @{
6690 public:
6691   int Age_Count;
6692   virtual void Set_Age (int New_Age);
6695 class Dog : Animal, Carnivore, Domestic @{
6696  public:
6697   int  Tooth_Count;
6698   char *Owner;
6700   virtual int  Number_Of_Teeth ();
6701   virtual void Set_Owner (char* Name);
6703   Dog();
6705 @end example
6707 The corresponding Ada code is generated:
6709 @example
6710 package Class_Carnivore is
6711   type Carnivore is limited interface;
6712   pragma Import (CPP, Carnivore);
6714   function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6715 end;
6716 use Class_Carnivore;
6718 package Class_Domestic is
6719   type Domestic is limited interface;
6720   pragma Import (CPP, Domestic);
6722   procedure Set_Owner
6723     (this : access Domestic;
6724      Name : Interfaces.C.Strings.chars_ptr) is abstract;
6725 end;
6726 use Class_Domestic;
6728 package Class_Animal is
6729   type Animal is tagged limited record
6730     Age_Count : aliased int;
6731   end record;
6732   pragma Import (CPP, Animal);
6734   procedure Set_Age (this : access Animal; New_Age : int);
6735   pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6736 end;
6737 use Class_Animal;
6739 package Class_Dog is
6740   type Dog is new Animal and Carnivore and Domestic with record
6741     Tooth_Count : aliased int;
6742     Owner : Interfaces.C.Strings.chars_ptr;
6743   end record;
6744   pragma Import (CPP, Dog);
6746   function Number_Of_Teeth (this : access Dog) return int;
6747   pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6749   procedure Set_Owner
6750     (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6751   pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6753   function New_Dog return Dog;
6754   pragma CPP_Constructor (New_Dog);
6755   pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6756 end;
6757 use Class_Dog;
6758 @end example
6760 @node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6761 @anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{c8}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{c9}
6762 @subsubsection Switches
6765 @geindex -fdump-ada-spec (gcc)
6768 @table @asis
6770 @item @code{-fdump-ada-spec}
6772 Generate Ada spec files for the given header files transitively (including
6773 all header files that these headers depend upon).
6774 @end table
6776 @geindex -fdump-ada-spec-slim (gcc)
6779 @table @asis
6781 @item @code{-fdump-ada-spec-slim}
6783 Generate Ada spec files for the header files specified on the command line
6784 only.
6785 @end table
6787 @geindex -fada-spec-parent (gcc)
6790 @table @asis
6792 @item @code{-fada-spec-parent=@emph{unit}}
6794 Specifies that all files generated by @emph{-fdump-ada-spec*} are
6795 to be child units of the specified parent unit.
6796 @end table
6798 @geindex -C (gcc)
6801 @table @asis
6803 @item @code{-C}
6805 Extract comments from headers and generate Ada comments in the Ada spec files.
6806 @end table
6808 @node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6809 @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}
6810 @subsection Generating C Headers for Ada Specifications
6813 @geindex Binding generation (for Ada specs)
6815 @geindex C headers (binding generation)
6817 GNAT includes a C header generator for Ada specifications which supports
6818 Ada types that have a direct mapping to C types. This includes in particular
6819 support for:
6822 @itemize *
6824 @item 
6825 Scalar types
6827 @item 
6828 Constrained arrays
6830 @item 
6831 Records (untagged)
6833 @item 
6834 Composition of the above types
6836 @item 
6837 Constant declarations
6839 @item 
6840 Object declarations
6842 @item 
6843 Subprogram declarations
6844 @end itemize
6846 @menu
6847 * Running the C Header Generator:: 
6849 @end menu
6851 @node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6852 @anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{cc}
6853 @subsubsection Running the C Header Generator
6856 The C header generator is part of the GNAT compiler and can be invoked via
6857 the @emph{-gnatceg} combination of switches, which will generate a @code{.h}
6858 file corresponding to the given input file (Ada spec or body). Note that
6859 only spec files are processed in any case, so giving a spec or a body file
6860 as input is equivalent. For example:
6862 @example
6863 $ gcc -c -gnatceg pack1.ads
6864 @end example
6866 will generate a self-contained file called @code{pack1.h} including
6867 common definitions from the Ada Standard package, followed by the
6868 definitions included in @code{pack1.ads}, as well as all the other units
6869 withed by this file.
6871 For instance, given the following Ada files:
6873 @example
6874 package Pack2 is
6875    type Int is range 1 .. 10;
6876 end Pack2;
6877 @end example
6879 @example
6880 with Pack2;
6882 package Pack1 is
6883    type Rec is record
6884       Field1, Field2 : Pack2.Int;
6885    end record;
6887    Global : Rec := (1, 2);
6889    procedure Proc1 (R : Rec);
6890    procedure Proc2 (R : in out Rec);
6891 end Pack1;
6892 @end example
6894 The above @cite{gcc} command will generate the following @code{pack1.h} file:
6896 @example
6897 /* Standard definitions skipped */
6898 #ifndef PACK2_ADS
6899 #define PACK2_ADS
6900 typedef short_short_integer pack2__TintB;
6901 typedef pack2__TintB pack2__int;
6902 #endif /* PACK2_ADS */
6904 #ifndef PACK1_ADS
6905 #define PACK1_ADS
6906 typedef struct _pack1__rec @{
6907   pack2__int field1;
6908   pack2__int field2;
6909 @} pack1__rec;
6910 extern pack1__rec pack1__global;
6911 extern void pack1__proc1(const pack1__rec r);
6912 extern void pack1__proc2(pack1__rec *r);
6913 #endif /* PACK1_ADS */
6914 @end example
6916 You can then @cite{include} @code{pack1.h} from a C source file and use the types,
6917 call subprograms, reference objects, and constants.
6919 @node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
6920 @anchor{gnat_ugn/the_gnat_compilation_model id74}@anchor{cd}@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{45}
6921 @section GNAT and Other Compilation Models
6924 This section compares the GNAT model with the approaches taken in
6925 other environents, first the C/C++ model and then the mechanism that
6926 has been used in other Ada systems, in particular those traditionally
6927 used for Ada 83.
6929 @menu
6930 * Comparison between GNAT and C/C++ Compilation Models:: 
6931 * Comparison between GNAT and Conventional Ada Library Models:: 
6933 @end menu
6935 @node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
6936 @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}
6937 @subsection Comparison between GNAT and C/C++ Compilation Models
6940 The GNAT model of compilation is close to the C and C++ models. You can
6941 think of Ada specs as corresponding to header files in C. As in C, you
6942 don't need to compile specs; they are compiled when they are used. The
6943 Ada @emph{with} is similar in effect to the @cite{#include} of a C
6944 header.
6946 One notable difference is that, in Ada, you may compile specs separately
6947 to check them for semantic and syntactic accuracy. This is not always
6948 possible with C headers because they are fragments of programs that have
6949 less specific syntactic or semantic rules.
6951 The other major difference is the requirement for running the binder,
6952 which performs two important functions. First, it checks for
6953 consistency. In C or C++, the only defense against assembling
6954 inconsistent programs lies outside the compiler, in a makefile, for
6955 example. The binder satisfies the Ada requirement that it be impossible
6956 to construct an inconsistent program when the compiler is used in normal
6957 mode.
6959 @geindex Elaboration order control
6961 The other important function of the binder is to deal with elaboration
6962 issues. There are also elaboration issues in C++ that are handled
6963 automatically. This automatic handling has the advantage of being
6964 simpler to use, but the C++ programmer has no control over elaboration.
6965 Where @cite{gnatbind} might complain there was no valid order of
6966 elaboration, a C++ compiler would simply construct a program that
6967 malfunctioned at run time.
6969 @node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
6970 @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}
6971 @subsection Comparison between GNAT and Conventional Ada Library Models
6974 This section is intended for Ada programmers who have
6975 used an Ada compiler implementing the traditional Ada library
6976 model, as described in the Ada Reference Manual.
6978 @geindex GNAT library
6980 In GNAT, there is no 'library' in the normal sense. Instead, the set of
6981 source files themselves acts as the library. Compiling Ada programs does
6982 not generate any centralized information, but rather an object file and
6983 a ALI file, which are of interest only to the binder and linker.
6984 In a traditional system, the compiler reads information not only from
6985 the source file being compiled, but also from the centralized library.
6986 This means that the effect of a compilation depends on what has been
6987 previously compiled. In particular:
6990 @itemize *
6992 @item 
6993 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
6994 to the version of the unit most recently compiled into the library.
6996 @item 
6997 Inlining is effective only if the necessary body has already been
6998 compiled into the library.
7000 @item 
7001 Compiling a unit may obsolete other units in the library.
7002 @end itemize
7004 In GNAT, compiling one unit never affects the compilation of any other
7005 units because the compiler reads only source files. Only changes to source
7006 files can affect the results of a compilation. In particular:
7009 @itemize *
7011 @item 
7012 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7013 to the source version of the unit that is currently accessible to the
7014 compiler.
7016 @geindex Inlining
7018 @item 
7019 Inlining requires the appropriate source files for the package or
7020 subprogram bodies to be available to the compiler. Inlining is always
7021 effective, independent of the order in which units are compiled.
7023 @item 
7024 Compiling a unit never affects any other compilations. The editing of
7025 sources may cause previous compilations to be out of date if they
7026 depended on the source file being modified.
7027 @end itemize
7029 The most important result of these differences is that order of compilation
7030 is never significant in GNAT. There is no situation in which one is
7031 required to do one compilation before another. What shows up as order of
7032 compilation requirements in the traditional Ada library becomes, in
7033 GNAT, simple source dependencies; in other words, there is only a set
7034 of rules saying what source files must be present when a file is
7035 compiled.
7037 @node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
7038 @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}
7039 @section Using GNAT Files with External Tools
7042 This section explains how files that are produced by GNAT may be
7043 used with tools designed for other languages.
7045 @menu
7046 * Using Other Utility Programs with GNAT:: 
7047 * The External Symbol Naming Scheme of GNAT:: 
7049 @end menu
7051 @node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
7052 @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}
7053 @subsection Using Other Utility Programs with GNAT
7056 The object files generated by GNAT are in standard system format and in
7057 particular the debugging information uses this format. This means
7058 programs generated by GNAT can be used with existing utilities that
7059 depend on these formats.
7061 In general, any utility program that works with C will also often work with
7062 Ada programs generated by GNAT. This includes software utilities such as
7063 gprof (a profiling program), gdb (the FSF debugger), and utilities such
7064 as Purify.
7066 @node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
7067 @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}
7068 @subsection The External Symbol Naming Scheme of GNAT
7071 In order to interpret the output from GNAT, when using tools that are
7072 originally intended for use with other languages, it is useful to
7073 understand the conventions used to generate link names from the Ada
7074 entity names.
7076 All link names are in all lowercase letters. With the exception of library
7077 procedure names, the mechanism used is simply to use the full expanded
7078 Ada name with dots replaced by double underscores. For example, suppose
7079 we have the following package spec:
7081 @example
7082 package QRS is
7083    MN : Integer;
7084 end QRS;
7085 @end example
7087 @geindex pragma Export
7089 The variable @cite{MN} has a full expanded Ada name of @cite{QRS.MN}, so
7090 the corresponding link name is @cite{qrs__mn}.
7091 Of course if a @cite{pragma Export} is used this may be overridden:
7093 @example
7094 package Exports is
7095    Var1 : Integer;
7096    pragma Export (Var1, C, External_Name => "var1_name");
7097    Var2 : Integer;
7098    pragma Export (Var2, C, Link_Name => "var2_link_name");
7099 end Exports;
7100 @end example
7102 In this case, the link name for @cite{Var1} is whatever link name the
7103 C compiler would assign for the C function @cite{var1_name}. This typically
7104 would be either @cite{var1_name} or @cite{_var1_name}, depending on operating
7105 system conventions, but other possibilities exist. The link name for
7106 @cite{Var2} is @cite{var2_link_name}, and this is not operating system
7107 dependent.
7109 One exception occurs for library level procedures. A potential ambiguity
7110 arises between the required name @cite{_main} for the C main program,
7111 and the name we would otherwise assign to an Ada library level procedure
7112 called @cite{Main} (which might well not be the main program).
7114 To avoid this ambiguity, we attach the prefix @cite{_ada_} to such
7115 names. So if we have a library level procedure such as:
7117 @example
7118 procedure Hello (S : String);
7119 @end example
7121 the external name of this procedure will be @cite{_ada_hello}.
7123 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7125 @node Building Executable Programs with GNAT,GNAT Utility Programs,The GNAT Compilation Model,Top
7126 @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}
7127 @chapter Building Executable Programs with GNAT
7130 This chapter describes first the gnatmake tool
7131 (@ref{1b,,Building with gnatmake}),
7132 which automatically determines the set of sources
7133 needed by an Ada compilation unit and executes the necessary
7134 (re)compilations, binding and linking.
7135 It also explains how to use each tool individually: the
7136 compiler (gcc, see @ref{1c,,Compiling with gcc}),
7137 binder (gnatbind, see @ref{1d,,Binding with gnatbind}),
7138 and linker (gnatlink, see @ref{1e,,Linking with gnatlink})
7139 to build executable programs.
7140 Finally, this chapter provides examples of
7141 how to make use of the general GNU make mechanism
7142 in a GNAT context (see @ref{1f,,Using the GNU make Utility}).
7145 @menu
7146 * Building with gnatmake:: 
7147 * Compiling with gcc:: 
7148 * Compiler Switches:: 
7149 * Linker Switches:: 
7150 * Binding with gnatbind:: 
7151 * Linking with gnatlink:: 
7152 * Using the GNU make Utility:: 
7154 @end menu
7156 @node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7157 @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}
7158 @section Building with @emph{gnatmake}
7161 @geindex gnatmake
7163 A typical development cycle when working on an Ada program consists of
7164 the following steps:
7167 @enumerate 
7169 @item 
7170 Edit some sources to fix bugs;
7172 @item 
7173 Add enhancements;
7175 @item 
7176 Compile all sources affected;
7178 @item 
7179 Rebind and relink; and
7181 @item 
7182 Test.
7183 @end enumerate
7185 @geindex Dependency rules (compilation)
7187 The third step in particular can be tricky, because not only do the modified
7188 files have to be compiled, but any files depending on these files must also be
7189 recompiled. The dependency rules in Ada can be quite complex, especially
7190 in the presence of overloading, @cite{use} clauses, generics and inlined
7191 subprograms.
7193 @emph{gnatmake} automatically takes care of the third and fourth steps
7194 of this process. It determines which sources need to be compiled,
7195 compiles them, and binds and links the resulting object files.
7197 Unlike some other Ada make programs, the dependencies are always
7198 accurately recomputed from the new sources. The source based approach of
7199 the GNAT compilation model makes this possible. This means that if
7200 changes to the source program cause corresponding changes in
7201 dependencies, they will always be tracked exactly correctly by
7202 @emph{gnatmake}.
7204 Note that for advanced forms of project structure, we recommend creating
7205 a project file as explained in the @emph{GNAT_Project_Manager} chapter in the
7206 @emph{GPRbuild User's Guide}, and using the
7207 @emph{gprbuild} tool which supports building with project files and works similarly
7208 to @emph{gnatmake}.
7210 @menu
7211 * Running gnatmake:: 
7212 * Switches for gnatmake:: 
7213 * Mode Switches for gnatmake:: 
7214 * Notes on the Command Line:: 
7215 * How gnatmake Works:: 
7216 * Examples of gnatmake Usage:: 
7218 @end menu
7220 @node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7221 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{da}@anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{db}
7222 @subsection Running @emph{gnatmake}
7225 The usual form of the @emph{gnatmake} command is
7227 @example
7228 $ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7229 @end example
7231 The only required argument is one @cite{file_name}, which specifies
7232 a compilation unit that is a main program. Several @cite{file_names} can be
7233 specified: this will result in several executables being built.
7234 If @cite{switches} are present, they can be placed before the first
7235 @cite{file_name}, between @cite{file_names} or after the last @cite{file_name}.
7236 If @cite{mode_switches} are present, they must always be placed after
7237 the last @cite{file_name} and all @cite{switches}.
7239 If you are using standard file extensions (@code{.adb} and
7240 @code{.ads}), then the
7241 extension may be omitted from the @cite{file_name} arguments. However, if
7242 you are using non-standard extensions, then it is required that the
7243 extension be given. A relative or absolute directory path can be
7244 specified in a @cite{file_name}, in which case, the input source file will
7245 be searched for in the specified directory only. Otherwise, the input
7246 source file will first be searched in the directory where
7247 @emph{gnatmake} was invoked and if it is not found, it will be search on
7248 the source path of the compiler as described in
7249 @ref{89,,Search Paths and the Run-Time Library (RTL)}.
7251 All @emph{gnatmake} output (except when you specify @emph{-M}) is sent to
7252 @code{stderr}. The output produced by the
7253 @emph{-M} switch is sent to @code{stdout}.
7255 @node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7256 @anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{dc}@anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{dd}
7257 @subsection Switches for @emph{gnatmake}
7260 You may specify any of the following switches to @emph{gnatmake}:
7262 @geindex --version (gnatmake)
7265 @table @asis
7267 @item @code{--version}
7269 Display Copyright and version, then exit disregarding all other options.
7270 @end table
7272 @geindex --help (gnatmake)
7275 @table @asis
7277 @item @code{--help}
7279 If @code{--version} was not used, display usage, then exit disregarding
7280 all other options.
7281 @end table
7283 @geindex --GCC=compiler_name (gnatmake)
7286 @table @asis
7288 @item @code{--GCC=@emph{compiler_name}}
7290 Program used for compiling. The default is @code{gcc}. You need to use
7291 quotes around @cite{compiler_name} if @cite{compiler_name} contains
7292 spaces or other separator characters.
7293 As an example @code{--GCC="foo -x  -y"}
7294 will instruct @emph{gnatmake} to use @code{foo -x -y} as your
7295 compiler. A limitation of this syntax is that the name and path name of
7296 the executable itself must not include any embedded spaces. Note that
7297 switch @code{-c} is always inserted after your command name. Thus in the
7298 above example the compiler command that will be used by @emph{gnatmake}
7299 will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7300 used, only the last @cite{compiler_name} is taken into account. However,
7301 all the additional switches are also taken into account. Thus,
7302 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7303 @code{--GCC="bar -x -y -z -t"}.
7304 @end table
7306 @geindex --GNATBIND=binder_name (gnatmake)
7309 @table @asis
7311 @item @code{--GNATBIND=@emph{binder_name}}
7313 Program used for binding. The default is @code{gnatbind}. You need to
7314 use quotes around @cite{binder_name} if @cite{binder_name} contains spaces
7315 or other separator characters.
7316 As an example @code{--GNATBIND="bar -x  -y"}
7317 will instruct @emph{gnatmake} to use @cite{bar -x -y} as your
7318 binder. Binder switches that are normally appended by @emph{gnatmake}
7319 to @code{gnatbind} are now appended to the end of @cite{bar -x -y}.
7320 A limitation of this syntax is that the name and path name of the executable
7321 itself must not include any embedded spaces.
7322 @end table
7324 @geindex --GNATLINK=linker_name (gnatmake)
7327 @table @asis
7329 @item @code{--GNATLINK=@emph{linker_name}}
7331 Program used for linking. The default is @code{gnatlink}. You need to
7332 use quotes around @cite{linker_name} if @cite{linker_name} contains spaces
7333 or other separator characters.
7334 As an example @code{--GNATLINK="lan -x  -y"}
7335 will instruct @emph{gnatmake} to use @code{lan -x -y} as your
7336 linker. Linker switches that are normally appended by @code{gnatmake} to
7337 @code{gnatlink} are now appended to the end of @code{lan -x -y}.
7338 A limitation of this syntax is that the name and path name of the executable
7339 itself must not include any embedded spaces.
7341 @item @code{--create-map-file}
7343 When linking an executable, create a map file. The name of the map file
7344 has the same name as the executable with extension ".map".
7346 @item @code{--create-map-file=@emph{mapfile}}
7348 When linking an executable, create a map file with the specified name.
7349 @end table
7351 @geindex --create-missing-dirs (gnatmake)
7354 @table @asis
7356 @item @code{--create-missing-dirs}
7358 When using project files (@code{-P@emph{project}}), automatically create
7359 missing object directories, library directories and exec
7360 directories.
7362 @item @code{--single-compile-per-obj-dir}
7364 Disallow simultaneous compilations in the same object directory when
7365 project files are used.
7367 @item @code{--subdirs=@emph{subdir}}
7369 Actual object directory of each project file is the subdirectory subdir of the
7370 object directory specified or defaulted in the project file.
7372 @item @code{--unchecked-shared-lib-imports}
7374 By default, shared library projects are not allowed to import static library
7375 projects. When this switch is used on the command line, this restriction is
7376 relaxed.
7378 @item @code{--source-info=@emph{source info file}}
7380 Specify a source info file. This switch is active only when project files
7381 are used. If the source info file is specified as a relative path, then it is
7382 relative to the object directory of the main project. If the source info file
7383 does not exist, then after the Project Manager has successfully parsed and
7384 processed the project files and found the sources, it creates the source info
7385 file. If the source info file already exists and can be read successfully,
7386 then the Project Manager will get all the needed information about the sources
7387 from the source info file and will not look for them. This reduces the time
7388 to process the project files, especially when looking for sources that take a
7389 long time. If the source info file exists but cannot be parsed successfully,
7390 the Project Manager will attempt to recreate it. If the Project Manager fails
7391 to create the source info file, a message is issued, but gnatmake does not
7392 fail. @emph{gnatmake} "trusts" the source info file. This means that
7393 if the source files have changed (addition, deletion, moving to a different
7394 source directory), then the source info file need to be deleted and recreated.
7395 @end table
7397 @geindex -a (gnatmake)
7400 @table @asis
7402 @item @code{-a}
7404 Consider all files in the make process, even the GNAT internal system
7405 files (for example, the predefined Ada library files), as well as any
7406 locked files. Locked files are files whose ALI file is write-protected.
7407 By default,
7408 @emph{gnatmake} does not check these files,
7409 because the assumption is that the GNAT internal files are properly up
7410 to date, and also that any write protected ALI files have been properly
7411 installed. Note that if there is an installation problem, such that one
7412 of these files is not up to date, it will be properly caught by the
7413 binder.
7414 You may have to specify this switch if you are working on GNAT
7415 itself. The switch @code{-a} is also useful
7416 in conjunction with @code{-f}
7417 if you need to recompile an entire application,
7418 including run-time files, using special configuration pragmas,
7419 such as a @cite{Normalize_Scalars} pragma.
7421 By default
7422 @code{gnatmake -a} compiles all GNAT
7423 internal files with
7424 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7425 @end table
7427 @geindex -b (gnatmake)
7430 @table @asis
7432 @item @code{-b}
7434 Bind only. Can be combined with @emph{-c} to do
7435 compilation and binding, but no link.
7436 Can be combined with @emph{-l}
7437 to do binding and linking. When not combined with
7438 @emph{-c}
7439 all the units in the closure of the main program must have been previously
7440 compiled and must be up to date. The root unit specified by @cite{file_name}
7441 may be given without extension, with the source extension or, if no GNAT
7442 Project File is specified, with the ALI file extension.
7443 @end table
7445 @geindex -c (gnatmake)
7448 @table @asis
7450 @item @code{-c}
7452 Compile only. Do not perform binding, except when @emph{-b}
7453 is also specified. Do not perform linking, except if both
7454 @emph{-b} and
7455 @emph{-l} are also specified.
7456 If the root unit specified by @cite{file_name} is not a main unit, this is the
7457 default. Otherwise @emph{gnatmake} will attempt binding and linking
7458 unless all objects are up to date and the executable is more recent than
7459 the objects.
7460 @end table
7462 @geindex -C (gnatmake)
7465 @table @asis
7467 @item @code{-C}
7469 Use a temporary mapping file. A mapping file is a way to communicate
7470 to the compiler two mappings: from unit names to file names (without
7471 any directory information) and from file names to path names (with
7472 full directory information). A mapping file can make the compiler's
7473 file searches faster, especially if there are many source directories,
7474 or the sources are read over a slow network connection. If
7475 @emph{-P} is used, a mapping file is always used, so
7476 @emph{-C} is unnecessary; in this case the mapping file
7477 is initially populated based on the project file. If
7478 @emph{-C} is used without
7479 @emph{-P},
7480 the mapping file is initially empty. Each invocation of the compiler
7481 will add any newly accessed sources to the mapping file.
7482 @end table
7484 @geindex -C= (gnatmake)
7487 @table @asis
7489 @item @code{-C=@emph{file}}
7491 Use a specific mapping file. The file, specified as a path name (absolute or
7492 relative) by this switch, should already exist, otherwise the switch is
7493 ineffective. The specified mapping file will be communicated to the compiler.
7494 This switch is not compatible with a project file
7495 (-P`file`) or with multiple compiling processes
7496 (-jnnn, when nnn is greater than 1).
7497 @end table
7499 @geindex -d (gnatmake)
7502 @table @asis
7504 @item @code{-d}
7506 Display progress for each source, up to date or not, as a single line:
7508 @example
7509 completed x out of y (zz%)
7510 @end example
7512 If the file needs to be compiled this is displayed after the invocation of
7513 the compiler. These lines are displayed even in quiet output mode.
7514 @end table
7516 @geindex -D (gnatmake)
7519 @table @asis
7521 @item @code{-D @emph{dir}}
7523 Put all object files and ALI file in directory @cite{dir}.
7524 If the @emph{-D} switch is not used, all object files
7525 and ALI files go in the current working directory.
7527 This switch cannot be used when using a project file.
7528 @end table
7530 @geindex -eI (gnatmake)
7533 @table @asis
7535 @item @code{-eI@emph{nnn}}
7537 Indicates that the main source is a multi-unit source and the rank of the unit
7538 in the source file is nnn. nnn needs to be a positive number and a valid
7539 index in the source. This switch cannot be used when @emph{gnatmake} is
7540 invoked for several mains.
7541 @end table
7543 @geindex -eL (gnatmake)
7545 @geindex symbolic links
7548 @table @asis
7550 @item @code{-eL}
7552 Follow all symbolic links when processing project files.
7553 This should be used if your project uses symbolic links for files or
7554 directories, but is not needed in other cases.
7556 @geindex naming scheme
7558 This also assumes that no directory matches the naming scheme for files (for
7559 instance that you do not have a directory called "sources.ads" when using the
7560 default GNAT naming scheme).
7562 When you do not have to use this switch (i.e., by default), gnatmake is able to
7563 save a lot of system calls (several per source file and object file), which
7564 can result in a significant speed up to load and manipulate a project file,
7565 especially when using source files from a remote system.
7566 @end table
7568 @geindex -eS (gnatmake)
7571 @table @asis
7573 @item @code{-eS}
7575 Output the commands for the compiler, the binder and the linker
7576 on standard output,
7577 instead of standard error.
7578 @end table
7580 @geindex -f (gnatmake)
7583 @table @asis
7585 @item @code{-f}
7587 Force recompilations. Recompile all sources, even though some object
7588 files may be up to date, but don't recompile predefined or GNAT internal
7589 files or locked files (files with a write-protected ALI file),
7590 unless the @emph{-a} switch is also specified.
7591 @end table
7593 @geindex -F (gnatmake)
7596 @table @asis
7598 @item @code{-F}
7600 When using project files, if some errors or warnings are detected during
7601 parsing and verbose mode is not in effect (no use of switch
7602 -v), then error lines start with the full path name of the project
7603 file, rather than its simple file name.
7604 @end table
7606 @geindex -g (gnatmake)
7609 @table @asis
7611 @item @code{-g}
7613 Enable debugging. This switch is simply passed to the compiler and to the
7614 linker.
7615 @end table
7617 @geindex -i (gnatmake)
7620 @table @asis
7622 @item @code{-i}
7624 In normal mode, @emph{gnatmake} compiles all object files and ALI files
7625 into the current directory. If the @emph{-i} switch is used,
7626 then instead object files and ALI files that already exist are overwritten
7627 in place. This means that once a large project is organized into separate
7628 directories in the desired manner, then @emph{gnatmake} will automatically
7629 maintain and update this organization. If no ALI files are found on the
7630 Ada object path (see @ref{89,,Search Paths and the Run-Time Library (RTL)}),
7631 the new object and ALI files are created in the
7632 directory containing the source being compiled. If another organization
7633 is desired, where objects and sources are kept in different directories,
7634 a useful technique is to create dummy ALI files in the desired directories.
7635 When detecting such a dummy file, @emph{gnatmake} will be forced to
7636 recompile the corresponding source file, and it will be put the resulting
7637 object and ALI files in the directory where it found the dummy file.
7638 @end table
7640 @geindex -j (gnatmake)
7642 @geindex Parallel make
7645 @table @asis
7647 @item @code{-j@emph{n}}
7649 Use @cite{n} processes to carry out the (re)compilations. On a multiprocessor
7650 machine compilations will occur in parallel. If @cite{n} is 0, then the
7651 maximum number of parallel compilations is the number of core processors
7652 on the platform. In the event of compilation errors, messages from various
7653 compilations might get interspersed (but @emph{gnatmake} will give you the
7654 full ordered list of failing compiles at the end). If this is problematic,
7655 rerun the make process with n set to 1 to get a clean list of messages.
7656 @end table
7658 @geindex -k (gnatmake)
7661 @table @asis
7663 @item @code{-k}
7665 Keep going. Continue as much as possible after a compilation error. To
7666 ease the programmer's task in case of compilation errors, the list of
7667 sources for which the compile fails is given when @emph{gnatmake}
7668 terminates.
7670 If @emph{gnatmake} is invoked with several @code{file_names} and with this
7671 switch, if there are compilation errors when building an executable,
7672 @emph{gnatmake} will not attempt to build the following executables.
7673 @end table
7675 @geindex -l (gnatmake)
7678 @table @asis
7680 @item @code{-l}
7682 Link only. Can be combined with @emph{-b} to binding
7683 and linking. Linking will not be performed if combined with
7684 @emph{-c}
7685 but not with @emph{-b}.
7686 When not combined with @emph{-b}
7687 all the units in the closure of the main program must have been previously
7688 compiled and must be up to date, and the main program needs to have been bound.
7689 The root unit specified by @cite{file_name}
7690 may be given without extension, with the source extension or, if no GNAT
7691 Project File is specified, with the ALI file extension.
7692 @end table
7694 @geindex -m (gnatmake)
7697 @table @asis
7699 @item @code{-m}
7701 Specify that the minimum necessary amount of recompilations
7702 be performed. In this mode @emph{gnatmake} ignores time
7703 stamp differences when the only
7704 modifications to a source file consist in adding/removing comments,
7705 empty lines, spaces or tabs. This means that if you have changed the
7706 comments in a source file or have simply reformatted it, using this
7707 switch will tell @emph{gnatmake} not to recompile files that depend on it
7708 (provided other sources on which these files depend have undergone no
7709 semantic modifications). Note that the debugging information may be
7710 out of date with respect to the sources if the @emph{-m} switch causes
7711 a compilation to be switched, so the use of this switch represents a
7712 trade-off between compilation time and accurate debugging information.
7713 @end table
7715 @geindex Dependencies
7716 @geindex producing list
7718 @geindex -M (gnatmake)
7721 @table @asis
7723 @item @code{-M}
7725 Check if all objects are up to date. If they are, output the object
7726 dependences to @code{stdout} in a form that can be directly exploited in
7727 a @code{Makefile}. By default, each source file is prefixed with its
7728 (relative or absolute) directory name. This name is whatever you
7729 specified in the various @emph{-aI}
7730 and @emph{-I} switches. If you use
7731 @cite{gnatmake -M}  @emph{-q}
7732 (see below), only the source file names,
7733 without relative paths, are output. If you just specify the  @emph{-M}
7734 switch, dependencies of the GNAT internal system files are omitted. This
7735 is typically what you want. If you also specify
7736 the @emph{-a} switch,
7737 dependencies of the GNAT internal files are also listed. Note that
7738 dependencies of the objects in external Ada libraries (see
7739 switch  @code{-aL@emph{dir}} in the following list)
7740 are never reported.
7741 @end table
7743 @geindex -n (gnatmake)
7746 @table @asis
7748 @item @code{-n}
7750 Don't compile, bind, or link. Checks if all objects are up to date.
7751 If they are not, the full name of the first file that needs to be
7752 recompiled is printed.
7753 Repeated use of this option, followed by compiling the indicated source
7754 file, will eventually result in recompiling all required units.
7755 @end table
7757 @geindex -o (gnatmake)
7760 @table @asis
7762 @item @code{-o @emph{exec_name}}
7764 Output executable name. The name of the final executable program will be
7765 @cite{exec_name}. If the @emph{-o} switch is omitted the default
7766 name for the executable will be the name of the input file in appropriate form
7767 for an executable file on the host system.
7769 This switch cannot be used when invoking @emph{gnatmake} with several
7770 @code{file_names}.
7771 @end table
7773 @geindex -p (gnatmake)
7776 @table @asis
7778 @item @code{-p}
7780 Same as @code{--create-missing-dirs}
7781 @end table
7783 @geindex -P (gnatmake)
7786 @table @asis
7788 @item @code{-P@emph{project}}
7790 Use project file @cite{project}. Only one such switch can be used.
7791 @end table
7793 @c -- Comment:
7794 @c :ref:`gnatmake_and_Project_Files`.
7796 @geindex -q (gnatmake)
7799 @table @asis
7801 @item @code{-q}
7803 Quiet. When this flag is not set, the commands carried out by
7804 @emph{gnatmake} are displayed.
7805 @end table
7807 @geindex -s (gnatmake)
7810 @table @asis
7812 @item @code{-s}
7814 Recompile if compiler switches have changed since last compilation.
7815 All compiler switches but -I and -o are taken into account in the
7816 following way:
7817 orders between different 'first letter' switches are ignored, but
7818 orders between same switches are taken into account. For example,
7819 @emph{-O -O2} is different than @emph{-O2 -O}, but @emph{-g -O}
7820 is equivalent to @emph{-O -g}.
7822 This switch is recommended when Integrated Preprocessing is used.
7823 @end table
7825 @geindex -u (gnatmake)
7828 @table @asis
7830 @item @code{-u}
7832 Unique. Recompile at most the main files. It implies -c. Combined with
7833 -f, it is equivalent to calling the compiler directly. Note that using
7834 -u with a project file and no main has a special meaning.
7835 @end table
7837 @c --Comment:
7838 @c (See :ref:`Project_Files_and_Main_Subprograms`.)
7840 @geindex -U (gnatmake)
7843 @table @asis
7845 @item @code{-U}
7847 When used without a project file or with one or several mains on the command
7848 line, is equivalent to -u. When used with a project file and no main
7849 on the command line, all sources of all project files are checked and compiled
7850 if not up to date, and libraries are rebuilt, if necessary.
7851 @end table
7853 @geindex -v (gnatmake)
7856 @table @asis
7858 @item @code{-v}
7860 Verbose. Display the reason for all recompilations @emph{gnatmake}
7861 decides are necessary, with the highest verbosity level.
7862 @end table
7864 @geindex -vl (gnatmake)
7867 @table @asis
7869 @item @code{-vl}
7871 Verbosity level Low. Display fewer lines than in verbosity Medium.
7872 @end table
7874 @geindex -vm (gnatmake)
7877 @table @asis
7879 @item @code{-vm}
7881 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7882 @end table
7884 @geindex -vm (gnatmake)
7887 @table @asis
7889 @item @code{-vh}
7891 Verbosity level High. Equivalent to -v.
7893 @item @code{-vP@emph{x}}
7895 Indicate the verbosity of the parsing of GNAT project files.
7896 See @ref{de,,Switches Related to Project Files}.
7897 @end table
7899 @geindex -x (gnatmake)
7902 @table @asis
7904 @item @code{-x}
7906 Indicate that sources that are not part of any Project File may be compiled.
7907 Normally, when using Project Files, only sources that are part of a Project
7908 File may be compile. When this switch is used, a source outside of all Project
7909 Files may be compiled. The ALI file and the object file will be put in the
7910 object directory of the main Project. The compilation switches used will only
7911 be those specified on the command line. Even when
7912 @emph{-x} is used, mains specified on the
7913 command line need to be sources of a project file.
7915 @item @code{-X@emph{name}=@emph{value}}
7917 Indicate that external variable @cite{name} has the value @cite{value}.
7918 The Project Manager will use this value for occurrences of
7919 @cite{external(name)} when parsing the project file.
7920 @ref{de,,Switches Related to Project Files}.
7921 @end table
7923 @geindex -z (gnatmake)
7926 @table @asis
7928 @item @code{-z}
7930 No main subprogram. Bind and link the program even if the unit name
7931 given on the command line is a package name. The resulting executable
7932 will execute the elaboration routines of the package and its closure,
7933 then the finalization routines.
7934 @end table
7936 @subsubheading GCC switches
7939 Any uppercase or multi-character switch that is not a @emph{gnatmake} switch
7940 is passed to @emph{gcc} (e.g., @emph{-O}, @emph{-gnato,} etc.)
7942 @subsubheading Source and library search path switches
7945 @geindex -aI (gnatmake)
7948 @table @asis
7950 @item @code{-aI@emph{dir}}
7952 When looking for source files also look in directory @cite{dir}.
7953 The order in which source files search is undertaken is
7954 described in @ref{89,,Search Paths and the Run-Time Library (RTL)}.
7955 @end table
7957 @geindex -aL (gnatmake)
7960 @table @asis
7962 @item @code{-aL@emph{dir}}
7964 Consider @cite{dir} as being an externally provided Ada library.
7965 Instructs @emph{gnatmake} to skip compilation units whose @code{.ALI}
7966 files have been located in directory @cite{dir}. This allows you to have
7967 missing bodies for the units in @cite{dir} and to ignore out of date bodies
7968 for the same units. You still need to specify
7969 the location of the specs for these units by using the switches
7970 @code{-aI@emph{dir}}  or @code{-I@emph{dir}}.
7971 Note: this switch is provided for compatibility with previous versions
7972 of @emph{gnatmake}. The easier method of causing standard libraries
7973 to be excluded from consideration is to write-protect the corresponding
7974 ALI files.
7975 @end table
7977 @geindex -aO (gnatmake)
7980 @table @asis
7982 @item @code{-aO@emph{dir}}
7984 When searching for library and object files, look in directory
7985 @cite{dir}. The order in which library files are searched is described in
7986 @ref{8c,,Search Paths for gnatbind}.
7987 @end table
7989 @geindex Search paths
7990 @geindex for gnatmake
7992 @geindex -A (gnatmake)
7995 @table @asis
7997 @item @code{-A@emph{dir}}
7999 Equivalent to @code{-aL@emph{dir}} @code{-aI@emph{dir}}.
8001 @geindex -I (gnatmake)
8003 @item @code{-I@emph{dir}}
8005 Equivalent to @code{-aO@emph{dir} -aI@emph{dir}}.
8006 @end table
8008 @geindex -I- (gnatmake)
8010 @geindex Source files
8011 @geindex suppressing search
8014 @table @asis
8016 @item @code{-I-}
8018 Do not look for source files in the directory containing the source
8019 file named in the command line.
8020 Do not look for ALI or object files in the directory
8021 where @emph{gnatmake} was invoked.
8022 @end table
8024 @geindex -L (gnatmake)
8026 @geindex Linker libraries
8029 @table @asis
8031 @item @code{-L@emph{dir}}
8033 Add directory @cite{dir} to the list of directories in which the linker
8034 will search for libraries. This is equivalent to
8035 @code{-largs} @code{-L@emph{dir}}.
8036 Furthermore, under Windows, the sources pointed to by the libraries path
8037 set in the registry are not searched for.
8038 @end table
8040 @geindex -nostdinc (gnatmake)
8043 @table @asis
8045 @item @code{-nostdinc}
8047 Do not look for source files in the system default directory.
8048 @end table
8050 @geindex -nostdlib (gnatmake)
8053 @table @asis
8055 @item @code{-nostdlib}
8057 Do not look for library files in the system default directory.
8058 @end table
8060 @geindex --RTS (gnatmake)
8063 @table @asis
8065 @item @code{--RTS=@emph{rts-path}}
8067 Specifies the default location of the runtime library. GNAT looks for the
8068 runtime
8069 in the following directories, and stops as soon as a valid runtime is found
8070 (@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
8071 @code{ada_object_path} present):
8074 @itemize *
8076 @item 
8077 @emph{<current directory>/$rts_path}
8079 @item 
8080 @emph{<default-search-dir>/$rts_path}
8082 @item 
8083 @emph{<default-search-dir>/rts-$rts_path}
8085 @item 
8086 The selected path is handled like a normal RTS path.
8087 @end itemize
8088 @end table
8090 @node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
8091 @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}
8092 @subsection Mode Switches for @emph{gnatmake}
8095 The mode switches (referred to as @cite{mode_switches}) allow the
8096 inclusion of switches that are to be passed to the compiler itself, the
8097 binder or the linker. The effect of a mode switch is to cause all
8098 subsequent switches up to the end of the switch list, or up to the next
8099 mode switch, to be interpreted as switches to be passed on to the
8100 designated component of GNAT.
8102 @geindex -cargs (gnatmake)
8105 @table @asis
8107 @item @code{-cargs @emph{switches}}
8109 Compiler switches. Here @cite{switches} is a list of switches
8110 that are valid switches for @emph{gcc}. They will be passed on to
8111 all compile steps performed by @emph{gnatmake}.
8112 @end table
8114 @geindex -bargs (gnatmake)
8117 @table @asis
8119 @item @code{-bargs @emph{switches}}
8121 Binder switches. Here @cite{switches} is a list of switches
8122 that are valid switches for @cite{gnatbind}. They will be passed on to
8123 all bind steps performed by @emph{gnatmake}.
8124 @end table
8126 @geindex -largs (gnatmake)
8129 @table @asis
8131 @item @code{-largs @emph{switches}}
8133 Linker switches. Here @cite{switches} is a list of switches
8134 that are valid switches for @emph{gnatlink}. They will be passed on to
8135 all link steps performed by @emph{gnatmake}.
8136 @end table
8138 @geindex -margs (gnatmake)
8141 @table @asis
8143 @item @code{-margs @emph{switches}}
8145 Make switches. The switches are directly interpreted by @emph{gnatmake},
8146 regardless of any previous occurrence of @emph{-cargs}, @emph{-bargs}
8147 or @emph{-largs}.
8148 @end table
8150 @node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8151 @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}
8152 @subsection Notes on the Command Line
8155 This section contains some additional useful notes on the operation
8156 of the @emph{gnatmake} command.
8158 @geindex Recompilation (by gnatmake)
8161 @itemize *
8163 @item 
8164 If @emph{gnatmake} finds no ALI files, it recompiles the main program
8165 and all other units required by the main program.
8166 This means that @emph{gnatmake}
8167 can be used for the initial compile, as well as during subsequent steps of
8168 the development cycle.
8170 @item 
8171 If you enter @code{gnatmake foo.adb}, where @code{foo}
8172 is a subunit or body of a generic unit, @emph{gnatmake} recompiles
8173 @code{foo.adb} (because it finds no ALI) and stops, issuing a
8174 warning.
8176 @item 
8177 In @emph{gnatmake} the switch @emph{-I}
8178 is used to specify both source and
8179 library file paths. Use @emph{-aI}
8180 instead if you just want to specify
8181 source paths only and @emph{-aO}
8182 if you want to specify library paths
8183 only.
8185 @item 
8186 @emph{gnatmake} will ignore any files whose ALI file is write-protected.
8187 This may conveniently be used to exclude standard libraries from
8188 consideration and in particular it means that the use of the
8189 @emph{-f} switch will not recompile these files
8190 unless @emph{-a} is also specified.
8192 @item 
8193 @emph{gnatmake} has been designed to make the use of Ada libraries
8194 particularly convenient. Assume you have an Ada library organized
8195 as follows: @emph{obj-dir} contains the objects and ALI files for
8196 of your Ada compilation units,
8197 whereas @emph{include-dir} contains the
8198 specs of these units, but no bodies. Then to compile a unit
8199 stored in @cite{main.adb}, which uses this Ada library you would just type:
8201 @example
8202 $ gnatmake -aI`include-dir`  -aL`obj-dir`  main
8203 @end example
8205 @item 
8206 Using @emph{gnatmake} along with the @emph{-m (minimal recompilation)}
8207 switch provides a mechanism for avoiding unnecessary recompilations. Using
8208 this switch,
8209 you can update the comments/format of your
8210 source files without having to recompile everything. Note, however, that
8211 adding or deleting lines in a source files may render its debugging
8212 info obsolete. If the file in question is a spec, the impact is rather
8213 limited, as that debugging info will only be useful during the
8214 elaboration phase of your program. For bodies the impact can be more
8215 significant. In all events, your debugger will warn you if a source file
8216 is more recent than the corresponding object, and alert you to the fact
8217 that the debugging information may be out of date.
8218 @end itemize
8220 @node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8221 @anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{e3}@anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{e4}
8222 @subsection How @emph{gnatmake} Works
8225 Generally @emph{gnatmake} automatically performs all necessary
8226 recompilations and you don't need to worry about how it works. However,
8227 it may be useful to have some basic understanding of the @emph{gnatmake}
8228 approach and in particular to understand how it uses the results of
8229 previous compilations without incorrectly depending on them.
8231 First a definition: an object file is considered @emph{up to date} if the
8232 corresponding ALI file exists and if all the source files listed in the
8233 dependency section of this ALI file have time stamps matching those in
8234 the ALI file. This means that neither the source file itself nor any
8235 files that it depends on have been modified, and hence there is no need
8236 to recompile this file.
8238 @emph{gnatmake} works by first checking if the specified main unit is up
8239 to date. If so, no compilations are required for the main unit. If not,
8240 @emph{gnatmake} compiles the main program to build a new ALI file that
8241 reflects the latest sources. Then the ALI file of the main unit is
8242 examined to find all the source files on which the main program depends,
8243 and @emph{gnatmake} recursively applies the above procedure on all these
8244 files.
8246 This process ensures that @emph{gnatmake} only trusts the dependencies
8247 in an existing ALI file if they are known to be correct. Otherwise it
8248 always recompiles to determine a new, guaranteed accurate set of
8249 dependencies. As a result the program is compiled 'upside down' from what may
8250 be more familiar as the required order of compilation in some other Ada
8251 systems. In particular, clients are compiled before the units on which
8252 they depend. The ability of GNAT to compile in any order is critical in
8253 allowing an order of compilation to be chosen that guarantees that
8254 @emph{gnatmake} will recompute a correct set of new dependencies if
8255 necessary.
8257 When invoking @emph{gnatmake} with several @cite{file_names}, if a unit is
8258 imported by several of the executables, it will be recompiled at most once.
8260 Note: when using non-standard naming conventions
8261 (@ref{35,,Using Other File Names}), changing through a configuration pragmas
8262 file the version of a source and invoking @emph{gnatmake} to recompile may
8263 have no effect, if the previous version of the source is still accessible
8264 by @emph{gnatmake}. It may be necessary to use the switch
8267 @node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8268 @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}
8269 @subsection Examples of @emph{gnatmake} Usage
8273 @table @asis
8275 @item @emph{gnatmake hello.adb}
8277 Compile all files necessary to bind and link the main program
8278 @code{hello.adb} (containing unit @cite{Hello}) and bind and link the
8279 resulting object files to generate an executable file @code{hello}.
8281 @item @emph{gnatmake main1 main2 main3}
8283 Compile all files necessary to bind and link the main programs
8284 @code{main1.adb} (containing unit @cite{Main1}), @code{main2.adb}
8285 (containing unit @cite{Main2}) and @code{main3.adb}
8286 (containing unit @cite{Main3}) and bind and link the resulting object files
8287 to generate three executable files @code{main1},
8288 @code{main2}  and @code{main3}.
8290 @item @emph{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8292 Compile all files necessary to bind and link the main program unit
8293 @cite{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8294 be done with optimization level 2 and the order of elaboration will be
8295 listed by the binder. @emph{gnatmake} will operate in quiet mode, not
8296 displaying commands it is executing.
8297 @end table
8299 @node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8300 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{1c}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{e7}
8301 @section Compiling with @emph{gcc}
8304 This section discusses how to compile Ada programs using the @emph{gcc}
8305 command. It also describes the set of switches
8306 that can be used to control the behavior of the compiler.
8308 @menu
8309 * Compiling Programs:: 
8310 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL. 
8311 * Order of Compilation Issues:: 
8312 * Examples:: 
8314 @end menu
8316 @node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8317 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{e8}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{e9}
8318 @subsection Compiling Programs
8321 The first step in creating an executable program is to compile the units
8322 of the program using the @emph{gcc} command. You must compile the
8323 following files:
8326 @itemize *
8328 @item 
8329 the body file (@code{.adb}) for a library level subprogram or generic
8330 subprogram
8332 @item 
8333 the spec file (@code{.ads}) for a library level package or generic
8334 package that has no body
8336 @item 
8337 the body file (@code{.adb}) for a library level package
8338 or generic package that has a body
8339 @end itemize
8341 You need @emph{not} compile the following files
8344 @itemize *
8346 @item 
8347 the spec of a library unit which has a body
8349 @item 
8350 subunits
8351 @end itemize
8353 because they are compiled as part of compiling related units. GNAT
8354 package specs
8355 when the corresponding body is compiled, and subunits when the parent is
8356 compiled.
8358 @geindex cannot generate code
8360 If you attempt to compile any of these files, you will get one of the
8361 following error messages (where @cite{fff} is the name of the file you
8362 compiled):
8364 @quotation
8366 @example
8367 cannot generate code for file `fff` (package spec)
8368 to check package spec, use -gnatc
8370 cannot generate code for file `fff` (missing subunits)
8371 to check parent unit, use -gnatc
8373 cannot generate code for file `fff` (subprogram spec)
8374 to check subprogram spec, use -gnatc
8376 cannot generate code for file `fff` (subunit)
8377 to check subunit, use -gnatc
8378 @end example
8379 @end quotation
8381 As indicated by the above error messages, if you want to submit
8382 one of these files to the compiler to check for correct semantics
8383 without generating code, then use the @emph{-gnatc} switch.
8385 The basic command for compiling a file containing an Ada unit is:
8387 @example
8388 $ gcc -c [switches] <file name>
8389 @end example
8391 where @cite{file name} is the name of the Ada file (usually
8392 having an extension @code{.ads} for a spec or @code{.adb} for a body).
8393 You specify the
8394 @code{-c} switch to tell @emph{gcc} to compile, but not link, the file.
8395 The result of a successful compilation is an object file, which has the
8396 same name as the source file but an extension of @code{.o} and an Ada
8397 Library Information (ALI) file, which also has the same name as the
8398 source file, but with @code{.ali} as the extension. GNAT creates these
8399 two output files in the current directory, but you may specify a source
8400 file in any directory using an absolute or relative path specification
8401 containing the directory information.
8403 @geindex gnat1
8405 @emph{gcc} is actually a driver program that looks at the extensions of
8406 the file arguments and loads the appropriate compiler. For example, the
8407 GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8408 These programs are in directories known to the driver program (in some
8409 configurations via environment variables you set), but need not be in
8410 your path. The @emph{gcc} driver also calls the assembler and any other
8411 utilities needed to complete the generation of the required object
8412 files.
8414 It is possible to supply several file names on the same @emph{gcc}
8415 command. This causes @emph{gcc} to call the appropriate compiler for
8416 each file. For example, the following command lists two separate
8417 files to be compiled:
8419 @example
8420 $ gcc -c x.adb y.adb
8421 @end example
8423 calls @cite{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8424 @code{y.adb}.
8425 The compiler generates two object files @code{x.o} and @code{y.o}
8426 and the two ALI files @code{x.ali} and @code{y.ali}.
8428 Any switches apply to all the files listed, see @ref{ea,,Compiler Switches} for a
8429 list of available @emph{gcc} switches.
8431 @node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8432 @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}
8433 @subsection Search Paths and the Run-Time Library (RTL)
8436 With the GNAT source-based library system, the compiler must be able to
8437 find source files for units that are needed by the unit being compiled.
8438 Search paths are used to guide this process.
8440 The compiler compiles one source file whose name must be given
8441 explicitly on the command line. In other words, no searching is done
8442 for this file. To find all other source files that are needed (the most
8443 common being the specs of units), the compiler examines the following
8444 directories, in the following order:
8447 @itemize *
8449 @item 
8450 The directory containing the source file of the main unit being compiled
8451 (the file name on the command line).
8453 @item 
8454 Each directory named by an @emph{-I} switch given on the @emph{gcc}
8455 command line, in the order given.
8457 @geindex ADA_PRJ_INCLUDE_FILE
8459 @item 
8460 Each of the directories listed in the text file whose name is given
8461 by the 
8462 @geindex ADA_PRJ_INCLUDE_FILE
8463 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8464 @code{ADA_PRJ_INCLUDE_FILE} environment variable.
8465 @geindex ADA_PRJ_INCLUDE_FILE
8466 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8467 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8468 driver when project files are used. It should not normally be set
8469 by other means.
8471 @geindex ADA_INCLUDE_PATH
8473 @item 
8474 Each of the directories listed in the value of the
8475 @geindex ADA_INCLUDE_PATH
8476 @geindex environment variable; ADA_INCLUDE_PATH
8477 @code{ADA_INCLUDE_PATH} environment variable.
8478 Construct this value
8479 exactly as the 
8480 @geindex PATH
8481 @geindex environment variable; PATH
8482 @code{PATH} environment variable: a list of directory
8483 names separated by colons (semicolons when working with the NT version).
8485 @item 
8486 The content of the @code{ada_source_path} file which is part of the GNAT
8487 installation tree and is used to store standard libraries such as the
8488 GNAT Run Time Library (RTL) source files.
8489 @ref{87,,Installing a library}
8490 @end itemize
8492 Specifying the switch @emph{-I-}
8493 inhibits the use of the directory
8494 containing the source file named in the command line. You can still
8495 have this directory on your search path, but in this case it must be
8496 explicitly requested with a @emph{-I} switch.
8498 Specifying the switch @emph{-nostdinc}
8499 inhibits the search of the default location for the GNAT Run Time
8500 Library (RTL) source files.
8502 The compiler outputs its object files and ALI files in the current
8503 working directory.
8504 Caution: The object file can be redirected with the @emph{-o} switch;
8505 however, @emph{gcc} and @cite{gnat1} have not been coordinated on this
8506 so the @code{ALI} file will not go to the right place. Therefore, you should
8507 avoid using the @emph{-o} switch.
8509 @geindex System.IO
8511 The packages @cite{Ada}, @cite{System}, and @cite{Interfaces} and their
8512 children make up the GNAT RTL, together with the simple @cite{System.IO}
8513 package used in the @cite{"Hello World"} example. The sources for these units
8514 are needed by the compiler and are kept together in one directory. Not
8515 all of the bodies are needed, but all of the sources are kept together
8516 anyway. In a normal installation, you need not specify these directory
8517 names when compiling or binding. Either the environment variables or
8518 the built-in defaults cause these files to be found.
8520 In addition to the language-defined hierarchies (@cite{System}, @cite{Ada} and
8521 @cite{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8522 consisting of child units of @cite{GNAT}. This is a collection of generally
8523 useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8524 for further details.
8526 Besides simplifying access to the RTL, a major use of search paths is
8527 in compiling sources from multiple directories. This can make
8528 development environments much more flexible.
8530 @node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8531 @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}
8532 @subsection Order of Compilation Issues
8535 If, in our earlier example, there was a spec for the @cite{hello}
8536 procedure, it would be contained in the file @code{hello.ads}; yet this
8537 file would not have to be explicitly compiled. This is the result of the
8538 model we chose to implement library management. Some of the consequences
8539 of this model are as follows:
8542 @itemize *
8544 @item 
8545 There is no point in compiling specs (except for package
8546 specs with no bodies) because these are compiled as needed by clients. If
8547 you attempt a useless compilation, you will receive an error message.
8548 It is also useless to compile subunits because they are compiled as needed
8549 by the parent.
8551 @item 
8552 There are no order of compilation requirements: performing a
8553 compilation never obsoletes anything. The only way you can obsolete
8554 something and require recompilations is to modify one of the
8555 source files on which it depends.
8557 @item 
8558 There is no library as such, apart from the ALI files
8559 (@ref{42,,The Ada Library Information Files}, for information on the format
8560 of these files). For now we find it convenient to create separate ALI files,
8561 but eventually the information therein may be incorporated into the object
8562 file directly.
8564 @item 
8565 When you compile a unit, the source files for the specs of all units
8566 that it @emph{with}s, all its subunits, and the bodies of any generics it
8567 instantiates must be available (reachable by the search-paths mechanism
8568 described above), or you will receive a fatal error message.
8569 @end itemize
8571 @node Examples,,Order of Compilation Issues,Compiling with gcc
8572 @anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{ee}@anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{ef}
8573 @subsection Examples
8576 The following are some typical Ada compilation command line examples:
8578 @example
8579 $ gcc -c xyz.adb
8580 @end example
8582 Compile body in file @code{xyz.adb} with all default options.
8584 @example
8585 $ gcc -c -O2 -gnata xyz-def.adb
8586 @end example
8588 Compile the child unit package in file @code{xyz-def.adb} with extensive
8589 optimizations, and pragma @cite{Assert}/@cite{Debug} statements
8590 enabled.
8592 @example
8593 $ gcc -c -gnatc abc-def.adb
8594 @end example
8596 Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8597 mode.
8599 @node Compiler Switches,Linker Switches,Compiling with gcc,Building Executable Programs with GNAT
8600 @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}
8601 @section Compiler Switches
8604 The @emph{gcc} command accepts switches that control the
8605 compilation process. These switches are fully described in this section:
8606 first an alphabetical listing of all switches with a brief description,
8607 and then functionally grouped sets of switches with more detailed
8608 information.
8610 More switches exist for GCC than those documented here, especially
8611 for specific targets. However, their use is not recommended as
8612 they may change code generation in ways that are incompatible with
8613 the Ada run-time library, or can cause inconsistencies between
8614 compilation units.
8616 @menu
8617 * Alphabetical List of All Switches:: 
8618 * Output and Error Message Control:: 
8619 * Warning Message Control:: 
8620 * Debugging and Assertion Control:: 
8621 * Validity Checking:: 
8622 * Style Checking:: 
8623 * Run-Time Checks:: 
8624 * Using gcc for Syntax Checking:: 
8625 * Using gcc for Semantic Checking:: 
8626 * Compiling Different Versions of Ada:: 
8627 * Character Set Control:: 
8628 * File Naming Control:: 
8629 * Subprogram Inlining Control:: 
8630 * Auxiliary Output Control:: 
8631 * Debugging Control:: 
8632 * Exception Handling Control:: 
8633 * Units to Sources Mapping Files:: 
8634 * Code Generation Control:: 
8636 @end menu
8638 @node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8639 @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}
8640 @subsection Alphabetical List of All Switches
8643 @geindex -b (gcc)
8646 @table @asis
8648 @item @code{-b @emph{target}}
8650 Compile your program to run on @cite{target}, which is the name of a
8651 system configuration. You must have a GNAT cross-compiler built if
8652 @cite{target} is not the same as your host system.
8653 @end table
8655 @geindex -B (gcc)
8658 @table @asis
8660 @item @code{-B@emph{dir}}
8662 Load compiler executables (for example, @cite{gnat1}, the Ada compiler)
8663 from @cite{dir} instead of the default location. Only use this switch
8664 when multiple versions of the GNAT compiler are available.
8665 See the "Options for Directory Search" section in the
8666 @cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8667 You would normally use the @emph{-b} or @emph{-V} switch instead.
8668 @end table
8670 @geindex -c (gcc)
8673 @table @asis
8675 @item @code{-c}
8677 Compile. Always use this switch when compiling Ada programs.
8679 Note: for some other languages when using @emph{gcc}, notably in
8680 the case of C and C++, it is possible to use
8681 use @emph{gcc} without a @emph{-c} switch to
8682 compile and link in one step. In the case of GNAT, you
8683 cannot use this approach, because the binder must be run
8684 and @emph{gcc} cannot be used to run the GNAT binder.
8685 @end table
8687 @geindex -fcallgraph-info (gcc)
8690 @table @asis
8692 @item @code{-fcallgraph-info[=su,da]}
8694 Makes the compiler output callgraph information for the program, on a
8695 per-file basis. The information is generated in the VCG format.  It can
8696 be decorated with additional, per-node and/or per-edge information, if a
8697 list of comma-separated markers is additionally specified. When the
8698 @cite{su} marker is specified, the callgraph is decorated with stack usage
8699 information; it is equivalent to @emph{-fstack-usage}. When the @cite{da}
8700 marker is specified, the callgraph is decorated with information about
8701 dynamically allocated objects.
8702 @end table
8704 @geindex -fdump-scos (gcc)
8707 @table @asis
8709 @item @code{-fdump-scos}
8711 Generates SCO (Source Coverage Obligation) information in the ALI file.
8712 This information is used by advanced coverage tools. See unit @code{SCOs}
8713 in the compiler sources for details in files @code{scos.ads} and
8714 @code{scos.adb}.
8715 @end table
8717 @geindex -fdump-xref (gcc)
8720 @table @asis
8722 @item @code{-fdump-xref}
8724 Generates cross reference information in GLI files for C and C++ sources.
8725 The GLI files have the same syntax as the ALI files for Ada, and can be used
8726 for source navigation in IDEs and on the command line using e.g. gnatxref
8727 and the @emph{--ext=gli} switch.
8728 @end table
8730 @geindex -flto (gcc)
8733 @table @asis
8735 @item @code{-flto[=@emph{n}]}
8737 Enables Link Time Optimization. This switch must be used in conjunction
8738 with the traditional @emph{-Ox} switches and instructs the compiler to
8739 defer most optimizations until the link stage. The advantage of this
8740 approach is that the compiler can do a whole-program analysis and choose
8741 the best interprocedural optimization strategy based on a complete view
8742 of the program, instead of a fragmentary view with the usual approach.
8743 This can also speed up the compilation of big programs and reduce the
8744 size of the executable, compared with a traditional per-unit compilation
8745 with inlining across modules enabled by the @emph{-gnatn} switch.
8746 The drawback of this approach is that it may require more memory and that
8747 the debugging information generated by -g with it might be hardly usable.
8748 The switch, as well as the accompanying @emph{-Ox} switches, must be
8749 specified both for the compilation and the link phases.
8750 If the @cite{n} parameter is specified, the optimization and final code
8751 generation at link time are executed using @cite{n} parallel jobs by
8752 means of an installed @emph{make} program.
8753 @end table
8755 @geindex -fno-inline (gcc)
8758 @table @asis
8760 @item @code{-fno-inline}
8762 Suppresses all inlining, unless requested with pragma @cite{Inline_Always}. The
8763 effect is enforced regardless of other optimization or inlining switches.
8764 Note that inlining can also be suppressed on a finer-grained basis with
8765 pragma @cite{No_Inline}.
8766 @end table
8768 @geindex -fno-inline-functions (gcc)
8771 @table @asis
8773 @item @code{-fno-inline-functions}
8775 Suppresses automatic inlining of subprograms, which is enabled
8776 if @emph{-O3} is used.
8777 @end table
8779 @geindex -fno-inline-small-functions (gcc)
8782 @table @asis
8784 @item @code{-fno-inline-small-functions}
8786 Suppresses automatic inlining of small subprograms, which is enabled
8787 if @emph{-O2} is used.
8788 @end table
8790 @geindex -fno-inline-functions-called-once (gcc)
8793 @table @asis
8795 @item @code{-fno-inline-functions-called-once}
8797 Suppresses inlining of subprograms local to the unit and called once
8798 from within it, which is enabled if @emph{-O1} is used.
8799 @end table
8801 @geindex -fno-ivopts (gcc)
8804 @table @asis
8806 @item @code{-fno-ivopts}
8808 Suppresses high-level loop induction variable optimizations, which are
8809 enabled if @emph{-O1} is used. These optimizations are generally
8810 profitable but, for some specific cases of loops with numerous uses
8811 of the iteration variable that follow a common pattern, they may end
8812 up destroying the regularity that could be exploited at a lower level
8813 and thus producing inferior code.
8814 @end table
8816 @geindex -fno-strict-aliasing (gcc)
8819 @table @asis
8821 @item @code{-fno-strict-aliasing}
8823 Causes the compiler to avoid assumptions regarding non-aliasing
8824 of objects of different types. See
8825 @ref{f3,,Optimization and Strict Aliasing} for details.
8826 @end table
8828 @geindex -fno-strict-overflow (gcc)
8831 @table @asis
8833 @item @code{-fno-strict-overflow}
8835 Causes the compiler to avoid assumptions regarding the rules of signed
8836 integer overflow. These rules specify that signed integer overflow will
8837 result in a Constraint_Error exception at run time and are enforced in
8838 default mode by the compiler, so this switch should not be necessary in
8839 normal operating mode. It might be useful in conjunction with @emph{-gnato0}
8840 for very peculiar cases of low-level programming.
8841 @end table
8843 @geindex -fstack-check (gcc)
8846 @table @asis
8848 @item @code{-fstack-check}
8850 Activates stack checking.
8851 See @ref{f4,,Stack Overflow Checking} for details.
8852 @end table
8854 @geindex -fstack-usage (gcc)
8857 @table @asis
8859 @item @code{-fstack-usage}
8861 Makes the compiler output stack usage information for the program, on a
8862 per-subprogram basis. See @ref{f5,,Static Stack Usage Analysis} for details.
8863 @end table
8865 @geindex -g (gcc)
8868 @table @asis
8870 @item @code{-g}
8872 Generate debugging information. This information is stored in the object
8873 file and copied from there to the final executable file by the linker,
8874 where it can be read by the debugger. You must use the
8875 @emph{-g} switch if you plan on using the debugger.
8876 @end table
8878 @geindex -gnat05 (gcc)
8881 @table @asis
8883 @item @code{-gnat05}
8885 Allow full Ada 2005 features.
8886 @end table
8888 @geindex -gnat12 (gcc)
8891 @table @asis
8893 @item @code{-gnat12}
8895 Allow full Ada 2012 features.
8896 @end table
8898 @geindex -gnat83 (gcc)
8900 @geindex -gnat2005 (gcc)
8903 @table @asis
8905 @item @code{-gnat2005}
8907 Allow full Ada 2005 features (same as @emph{-gnat05})
8908 @end table
8910 @geindex -gnat2012 (gcc)
8913 @table @asis
8915 @item @code{-gnat2012}
8917 Allow full Ada 2012 features (same as @emph{-gnat12})
8919 @item @code{-gnat83}
8921 Enforce Ada 83 restrictions.
8922 @end table
8924 @geindex -gnat95 (gcc)
8927 @table @asis
8929 @item @code{-gnat95}
8931 Enforce Ada 95 restrictions.
8933 Note: for compatibility with some Ada 95 compilers which support only
8934 the @cite{overriding} keyword of Ada 2005, the @emph{-gnatd.D} switch can
8935 be used along with @emph{-gnat95} to achieve a similar effect with GNAT.
8937 @emph{-gnatd.D} instructs GNAT to consider @cite{overriding} as a keyword
8938 and handle its associated semantic checks, even in Ada 95 mode.
8939 @end table
8941 @geindex -gnata (gcc)
8944 @table @asis
8946 @item @code{-gnata}
8948 Assertions enabled. @cite{Pragma Assert} and @cite{pragma Debug} to be
8949 activated. Note that these pragmas can also be controlled using the
8950 configuration pragmas @cite{Assertion_Policy} and @cite{Debug_Policy}.
8951 It also activates pragmas @cite{Check}, @cite{Precondition}, and
8952 @cite{Postcondition}. Note that these pragmas can also be controlled
8953 using the configuration pragma @cite{Check_Policy}. In Ada 2012, it
8954 also activates all assertions defined in the RM as aspects: preconditions,
8955 postconditions, type invariants and (sub)type predicates. In all Ada modes,
8956 corresponding pragmas for type invariants and (sub)type predicates are
8957 also activated. The default is that all these assertions are disabled,
8958 and have no effect, other than being checked for syntactic validity, and
8959 in the case of subtype predicates, constructions such as membership tests
8960 still test predicates even if assertions are turned off.
8961 @end table
8963 @geindex -gnatA (gcc)
8966 @table @asis
8968 @item @code{-gnatA}
8970 Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
8971 it will be ignored.
8972 @end table
8974 @geindex -gnatb (gcc)
8977 @table @asis
8979 @item @code{-gnatb}
8981 Generate brief messages to @code{stderr} even if verbose mode set.
8982 @end table
8984 @geindex -gnatB (gcc)
8987 @table @asis
8989 @item @code{-gnatB}
8991 Assume no invalid (bad) values except for 'Valid attribute use
8992 (@ref{f6,,Validity Checking}).
8993 @end table
8995 @geindex -gnatc (gcc)
8998 @table @asis
9000 @item @code{-gnatc}
9002 Check syntax and semantics only (no code generation attempted). When the
9003 compiler is invoked by @emph{gnatmake}, if the switch @emph{-gnatc} is
9004 only given to the compiler (after @emph{-cargs} or in package Compiler of
9005 the project file, @emph{gnatmake} will fail because it will not find the
9006 object file after compilation. If @emph{gnatmake} is called with
9007 @emph{-gnatc} as a builder switch (before @emph{-cargs} or in package
9008 Builder of the project file) then @emph{gnatmake} will not fail because
9009 it will not look for the object files after compilation, and it will not try
9010 to build and link.
9011 @end table
9013 @geindex -gnatC (gcc)
9016 @table @asis
9018 @item @code{-gnatC}
9020 Generate CodePeer intermediate format (no code generation attempted).
9021 This switch will generate an intermediate representation suitable for
9022 use by CodePeer (@code{.scil} files). This switch is not compatible with
9023 code generation (it will, among other things, disable some switches such
9024 as -gnatn, and enable others such as -gnata).
9025 @end table
9027 @geindex -gnatd (gcc)
9030 @table @asis
9032 @item @code{-gnatd}
9034 Specify debug options for the compiler. The string of characters after
9035 the @emph{-gnatd} specify the specific debug options. The possible
9036 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
9037 compiler source file @code{debug.adb} for details of the implemented
9038 debug options. Certain debug options are relevant to applications
9039 programmers, and these are documented at appropriate points in this
9040 users guide.
9041 @end table
9043 @geindex -gnatD[nn] (gcc)
9046 @table @asis
9048 @item @code{-gnatD}
9050 Create expanded source files for source level debugging. This switch
9051 also suppresses generation of cross-reference information
9052 (see @emph{-gnatx}). Note that this switch is not allowed if a previous
9053 -gnatR switch has been given, since these two switches are not compatible.
9054 @end table
9056 @geindex -gnateA (gcc)
9059 @table @asis
9061 @item @code{-gnateA}
9063 Check that the actual parameters of a subprogram call are not aliases of one
9064 another. To qualify as aliasing, the actuals must denote objects of a composite
9065 type, their memory locations must be identical or overlapping, and at least one
9066 of the corresponding formal parameters must be of mode OUT or IN OUT.
9068 @example
9069 type Rec_Typ is record
9070    Data : Integer := 0;
9071 end record;
9073 function Self (Val : Rec_Typ) return Rec_Typ is
9074 begin
9075    return Val;
9076 end Self;
9078 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
9079 begin
9080    null;
9081 end Detect_Aliasing;
9083 Obj : Rec_Typ;
9085 Detect_Aliasing (Obj, Obj);
9086 Detect_Aliasing (Obj, Self (Obj));
9087 @end example
9089 In the example above, the first call to @cite{Detect_Aliasing} fails with a
9090 @cite{Program_Error} at runtime because the actuals for @cite{Val_1} and
9091 @cite{Val_2} denote the same object. The second call executes without raising
9092 an exception because @cite{Self(Obj)} produces an anonymous object which does
9093 not share the memory location of @cite{Obj}.
9094 @end table
9096 @geindex -gnatec (gcc)
9099 @table @asis
9101 @item @code{-gnatec=@emph{path}}
9103 Specify a configuration pragma file
9104 (the equal sign is optional)
9105 (@ref{79,,The Configuration Pragmas Files}).
9106 @end table
9108 @geindex -gnateC (gcc)
9111 @table @asis
9113 @item @code{-gnateC}
9115 Generate CodePeer messages in a compiler-like format. This switch is only
9116 effective if @emph{-gnatcC} is also specified and requires an installation
9117 of CodePeer.
9118 @end table
9120 @geindex -gnated (gcc)
9123 @table @asis
9125 @item @code{-gnated}
9127 Disable atomic synchronization
9128 @end table
9130 @geindex -gnateD (gcc)
9133 @table @asis
9135 @item @code{-gnateDsymbol[=@emph{value}]}
9137 Defines a symbol, associated with @cite{value}, for preprocessing.
9138 (@ref{18,,Integrated Preprocessing}).
9139 @end table
9141 @geindex -gnateE (gcc)
9144 @table @asis
9146 @item @code{-gnateE}
9148 Generate extra information in exception messages. In particular, display
9149 extra column information and the value and range associated with index and
9150 range check failures, and extra column information for access checks.
9151 In cases where the compiler is able to determine at compile time that
9152 a check will fail, it gives a warning, and the extra information is not
9153 produced at run time.
9154 @end table
9156 @geindex -gnatef (gcc)
9159 @table @asis
9161 @item @code{-gnatef}
9163 Display full source path name in brief error messages.
9164 @end table
9166 @geindex -gnateF (gcc)
9169 @table @asis
9171 @item @code{-gnateF}
9173 Check for overflow on all floating-point operations, including those
9174 for unconstrained predefined types. See description of pragma
9175 @cite{Check_Float_Overflow} in GNAT RM.
9176 @end table
9178 @geindex -gnateg (gcc)
9180 @code{-gnateg}
9181 @code{-gnatceg}
9183 @quotation
9185 The @cite{-gnatc} switch must always be specified before this switch, e.g.
9186 @cite{-gnatceg}. Generate a C header from the Ada input file. See
9187 @ref{ca,,Generating C Headers for Ada Specifications} for more
9188 information.
9189 @end quotation
9191 @geindex -gnateG (gcc)
9194 @table @asis
9196 @item @code{-gnateG}
9198 Save result of preprocessing in a text file.
9199 @end table
9201 @geindex -gnatei (gcc)
9204 @table @asis
9206 @item @code{-gnatei@emph{nnn}}
9208 Set maximum number of instantiations during compilation of a single unit to
9209 @cite{nnn}. This may be useful in increasing the default maximum of 8000 for
9210 the rare case when a single unit legitimately exceeds this limit.
9211 @end table
9213 @geindex -gnateI (gcc)
9216 @table @asis
9218 @item @code{-gnateI@emph{nnn}}
9220 Indicates that the source is a multi-unit source and that the index of the
9221 unit to compile is @cite{nnn}. @cite{nnn} needs to be a positive number and need
9222 to be a valid index in the multi-unit source.
9223 @end table
9225 @geindex -gnatel (gcc)
9228 @table @asis
9230 @item @code{-gnatel}
9232 This switch can be used with the static elaboration model to issue info
9233 messages showing
9234 where implicit @cite{pragma Elaborate} and @cite{pragma Elaborate_All}
9235 are generated. This is useful in diagnosing elaboration circularities
9236 caused by these implicit pragmas when using the static elaboration
9237 model. See See the section in this guide on elaboration checking for
9238 further details. These messages are not generated by default, and are
9239 intended only for temporary use when debugging circularity problems.
9240 @end table
9242 @geindex -gnatel (gcc)
9245 @table @asis
9247 @item @code{-gnateL}
9249 This switch turns off the info messages about implicit elaboration pragmas.
9250 @end table
9252 @geindex -gnatem (gcc)
9255 @table @asis
9257 @item @code{-gnatem=@emph{path}}
9259 Specify a mapping file
9260 (the equal sign is optional)
9261 (@ref{f7,,Units to Sources Mapping Files}).
9262 @end table
9264 @geindex -gnatep (gcc)
9267 @table @asis
9269 @item @code{-gnatep=@emph{file}}
9271 Specify a preprocessing data file
9272 (the equal sign is optional)
9273 (@ref{18,,Integrated Preprocessing}).
9274 @end table
9276 @geindex -gnateP (gcc)
9279 @table @asis
9281 @item @code{-gnateP}
9283 Turn categorization dependency errors into warnings.
9284 Ada requires that units that WITH one another have compatible categories, for
9285 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9286 these errors become warnings (which can be ignored, or suppressed in the usual
9287 manner). This can be useful in some specialized circumstances such as the
9288 temporary use of special test software.
9289 @end table
9291 @geindex -gnateS (gcc)
9294 @table @asis
9296 @item @code{-gnateS}
9298 Synonym of @emph{-fdump-scos}, kept for backwards compatibility.
9299 @end table
9301 @geindex -gnatet=file (gcc)
9304 @table @asis
9306 @item @code{-gnatet=@emph{path}}
9308 Generate target dependent information. The format of the output file is
9309 described in the section about switch @emph{-gnateT}.
9310 @end table
9312 @geindex -gnateT (gcc)
9315 @table @asis
9317 @item @code{-gnateT=@emph{path}}
9319 Read target dependent information, such as endianness or sizes and alignments
9320 of base type. If this switch is passed, the default target dependent
9321 information of the compiler is replaced by the one read from the input file.
9322 This is used by tools other than the compiler, e.g. to do
9323 semantic analysis of programs that will run on some other target than
9324 the machine on which the tool is run.
9326 The following target dependent values should be defined,
9327 where @cite{Nat} denotes a natural integer value, @cite{Pos} denotes a
9328 positive integer value, and fields marked with a question mark are
9329 boolean fields, where a value of 0 is False, and a value of 1 is True:
9331 @example
9332 Bits_BE                    : Nat; -- Bits stored big-endian?
9333 Bits_Per_Unit              : Pos; -- Bits in a storage unit
9334 Bits_Per_Word              : Pos; -- Bits in a word
9335 Bytes_BE                   : Nat; -- Bytes stored big-endian?
9336 Char_Size                  : Pos; -- Standard.Character'Size
9337 Double_Float_Alignment     : Nat; -- Alignment of double float
9338 Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
9339 Double_Size                : Pos; -- Standard.Long_Float'Size
9340 Float_Size                 : Pos; -- Standard.Float'Size
9341 Float_Words_BE             : Nat; -- Float words stored big-endian?
9342 Int_Size                   : Pos; -- Standard.Integer'Size
9343 Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
9344 Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
9345 Long_Size                  : Pos; -- Standard.Long_Integer'Size
9346 Maximum_Alignment          : Pos; -- Maximum permitted alignment
9347 Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
9348 Pointer_Size               : Pos; -- System.Address'Size
9349 Short_Enums                : Nat; -- Short foreign convention enums?
9350 Short_Size                 : Pos; -- Standard.Short_Integer'Size
9351 Strict_Alignment           : Nat; -- Strict alignment?
9352 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9353 Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
9354 Words_BE                   : Nat; -- Words stored big-endian?
9355 @end example
9357 The format of the input file is as follows. First come the values of
9358 the variables defined above, with one line per value:
9360 @example
9361 name  value
9362 @end example
9364 where @cite{name} is the name of the parameter, spelled out in full,
9365 and cased as in the above list, and @cite{value} is an unsigned decimal
9366 integer. Two or more blanks separates the name from the value.
9368 All the variables must be present, in alphabetical order (i.e. the
9369 same order as the list above).
9371 Then there is a blank line to separate the two parts of the file. Then
9372 come the lines showing the floating-point types to be registered, with
9373 one line per registered mode:
9375 @example
9376 name  digs float_rep size alignment
9377 @end example
9379 where @cite{name} is the string name of the type (which can have
9380 single spaces embedded in the name (e.g. long double), @cite{digs} is
9381 the number of digits for the floating-point type, @cite{float_rep} is
9382 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
9383 AAMP), @cite{size} is the size in bits, @cite{alignment} is the
9384 alignment in bits. The name is followed by at least two blanks, fields
9385 are separated by at least one blank, and a LF character immediately
9386 follows the alignment field.
9388 Here is an example of a target parameterization file:
9390 @example
9391 Bits_BE                       0
9392 Bits_Per_Unit                 8
9393 Bits_Per_Word                64
9394 Bytes_BE                      0
9395 Char_Size                     8
9396 Double_Float_Alignment        0
9397 Double_Scalar_Alignment       0
9398 Double_Size                  64
9399 Float_Size                   32
9400 Float_Words_BE                0
9401 Int_Size                     64
9402 Long_Double_Size            128
9403 Long_Long_Size               64
9404 Long_Size                    64
9405 Maximum_Alignment            16
9406 Max_Unaligned_Field          64
9407 Pointer_Size                 64
9408 Short_Size                   16
9409 Strict_Alignment              0
9410 System_Allocator_Alignment   16
9411 Wchar_T_Size                 32
9412 Words_BE                      0
9414 float         15  I  64  64
9415 double        15  I  64  64
9416 long double   18  I  80 128
9417 TF            33  I 128 128
9418 @end example
9419 @end table
9421 @geindex -gnateu (gcc)
9424 @table @asis
9426 @item @code{-gnateu}
9428 Ignore unrecognized validity, warning, and style switches that
9429 appear after this switch is given. This may be useful when
9430 compiling sources developed on a later version of the compiler
9431 with an earlier version. Of course the earlier version must
9432 support this switch.
9433 @end table
9435 @geindex -gnateV (gcc)
9438 @table @asis
9440 @item @code{-gnateV}
9442 Check that all actual parameters of a subprogram call are valid according to
9443 the rules of validity checking (@ref{f6,,Validity Checking}).
9444 @end table
9446 @geindex -gnateY (gcc)
9449 @table @asis
9451 @item @code{-gnateY}
9453 Ignore all STYLE_CHECKS pragmas. Full legality checks
9454 are still carried out, but the pragmas have no effect
9455 on what style checks are active. This allows all style
9456 checking options to be controlled from the command line.
9457 @end table
9459 @geindex -gnatE (gcc)
9462 @table @asis
9464 @item @code{-gnatE}
9466 Full dynamic elaboration checks.
9467 @end table
9469 @geindex -gnatf (gcc)
9472 @table @asis
9474 @item @code{-gnatf}
9476 Full errors. Multiple errors per line, all undefined references, do not
9477 attempt to suppress cascaded errors.
9478 @end table
9480 @geindex -gnatF (gcc)
9483 @table @asis
9485 @item @code{-gnatF}
9487 Externals names are folded to all uppercase.
9488 @end table
9490 @geindex -gnatg (gcc)
9493 @table @asis
9495 @item @code{-gnatg}
9497 Internal GNAT implementation mode. This should not be used for
9498 applications programs, it is intended only for use by the compiler
9499 and its run-time library. For documentation, see the GNAT sources.
9500 Note that @emph{-gnatg} implies
9501 @emph{-gnatw.ge} and
9502 @emph{-gnatyg}
9503 so that all standard warnings and all standard style options are turned on.
9504 All warnings and style messages are treated as errors.
9505 @end table
9507 @geindex -gnatG[nn] (gcc)
9510 @table @asis
9512 @item @code{-gnatG=nn}
9514 List generated expanded code in source form.
9515 @end table
9517 @geindex -gnath (gcc)
9520 @table @asis
9522 @item @code{-gnath}
9524 Output usage information. The output is written to @code{stdout}.
9525 @end table
9527 @geindex -gnati (gcc)
9530 @table @asis
9532 @item @code{-gnati@emph{c}}
9534 Identifier character set (@cite{c} = 1/2/3/4/8/9/p/f/n/w).
9535 For details of the possible selections for @cite{c},
9536 see @ref{48,,Character Set Control}.
9537 @end table
9539 @geindex -gnatI (gcc)
9542 @table @asis
9544 @item @code{-gnatI}
9546 Ignore representation clauses. When this switch is used,
9547 representation clauses are treated as comments. This is useful
9548 when initially porting code where you want to ignore rep clause
9549 problems, and also for compiling foreign code (particularly
9550 for use with ASIS). The representation clauses that are ignored
9551 are: enumeration_representation_clause, record_representation_clause,
9552 and attribute_definition_clause for the following attributes:
9553 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9554 Object_Size, Size, Small, Stream_Size, and Value_Size.
9555 Note that this option should be used only for compiling -- the
9556 code is likely to malfunction at run time.
9558 Note that when @cite{-gnatct} is used to generate trees for input
9559 into @cite{ASIS} tools, these representation clauses are removed
9560 from the tree and ignored. This means that the tool will not see them.
9561 @end table
9563 @geindex -gnatjnn (gcc)
9566 @table @asis
9568 @item @code{-gnatj@emph{nn}}
9570 Reformat error messages to fit on @cite{nn} character lines
9571 @end table
9573 @geindex -gnatk (gcc)
9576 @table @asis
9578 @item @code{-gnatk=@emph{n}}
9580 Limit file names to @cite{n} (1-999) characters (@cite{k} = krunch).
9581 @end table
9583 @geindex -gnatl (gcc)
9586 @table @asis
9588 @item @code{-gnatl}
9590 Output full source listing with embedded error messages.
9591 @end table
9593 @geindex -gnatL (gcc)
9596 @table @asis
9598 @item @code{-gnatL}
9600 Used in conjunction with -gnatG or -gnatD to intersperse original
9601 source lines (as comment lines with line numbers) in the expanded
9602 source output.
9603 @end table
9605 @geindex -gnatm (gcc)
9608 @table @asis
9610 @item @code{-gnatm=@emph{n}}
9612 Limit number of detected error or warning messages to @cite{n}
9613 where @cite{n} is in the range 1..999999. The default setting if
9614 no switch is given is 9999. If the number of warnings reaches this
9615 limit, then a message is output and further warnings are suppressed,
9616 but the compilation is continued. If the number of error messages
9617 reaches this limit, then a message is output and the compilation
9618 is abandoned. The equal sign here is optional. A value of zero
9619 means that no limit applies.
9620 @end table
9622 @geindex -gnatn (gcc)
9625 @table @asis
9627 @item @code{-gnatn[12]}
9629 Activate inlining across modules for subprograms for which pragma @cite{Inline}
9630 is specified. This inlining is performed by the GCC back-end. An optional
9631 digit sets the inlining level: 1 for moderate inlining across modules
9632 or 2 for full inlining across modules. If no inlining level is specified,
9633 the compiler will pick it based on the optimization level.
9634 @end table
9636 @geindex -gnatN (gcc)
9639 @table @asis
9641 @item @code{-gnatN}
9643 Activate front end inlining for subprograms for which
9644 pragma @cite{Inline} is specified. This inlining is performed
9645 by the front end and will be visible in the
9646 @emph{-gnatG} output.
9648 When using a gcc-based back end (in practice this means using any version
9649 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
9650 @emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
9651 Historically front end inlining was more extensive than the gcc back end
9652 inlining, but that is no longer the case.
9653 @end table
9655 @geindex -gnato0 (gcc)
9658 @table @asis
9660 @item @code{-gnato0}
9662 Suppresses overflow checking. This causes the behavior of the compiler to
9663 match the default for older versions where overflow checking was suppressed
9664 by default. This is equivalent to having
9665 @cite{pragma Suppress (Overflow_Mode)} in a configuration pragma file.
9666 @end table
9668 @geindex -gnato?? (gcc)
9671 @table @asis
9673 @item @code{-gnato??}
9675 Set default mode for handling generation of code to avoid intermediate
9676 arithmetic overflow. Here @cite{??} is two digits, a
9677 single digit, or nothing. Each digit is one of the digits @cite{1}
9678 through @cite{3}:
9681 @multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
9682 @item
9684 Digit
9686 @tab
9688 Interpretation
9690 @item
9692 @emph{1}
9694 @tab
9696 All intermediate overflows checked against base type (@cite{STRICT})
9698 @item
9700 @emph{2}
9702 @tab
9704 Minimize intermediate overflows (@cite{MINIMIZED})
9706 @item
9708 @emph{3}
9710 @tab
9712 Eliminate intermediate overflows (@cite{ELIMINATED})
9714 @end multitable
9717 If only one digit appears, then it applies to all
9718 cases; if two digits are given, then the first applies outside
9719 assertions, pre/postconditions, and type invariants, and the second
9720 applies within assertions, pre/postconditions, and type invariants.
9722 If no digits follow the @emph{-gnato}, then it is equivalent to
9723 @emph{-gnato11},
9724 causing all intermediate overflows to be handled in strict
9725 mode.
9727 This switch also causes arithmetic overflow checking to be performed
9728 (as though @cite{pragma Unsuppress (Overflow_Mode)} had been specified).
9730 The default if no option @emph{-gnato} is given is that overflow handling
9731 is in @cite{STRICT} mode (computations done using the base type), and that
9732 overflow checking is enabled.
9734 Note that division by zero is a separate check that is not
9735 controlled by this switch (divide-by-zero checking is on by default).
9737 See also @ref{f8,,Specifying the Desired Mode}.
9738 @end table
9740 @geindex -gnatp (gcc)
9743 @table @asis
9745 @item @code{-gnatp}
9747 Suppress all checks. See @ref{f9,,Run-Time Checks} for details. This switch
9748 has no effect if cancelled by a subsequent @emph{-gnat-p} switch.
9749 @end table
9751 @geindex -gnat-p (gcc)
9754 @table @asis
9756 @item @code{-gnat-p}
9758 Cancel effect of previous @emph{-gnatp} switch.
9759 @end table
9761 @geindex -gnatP (gcc)
9764 @table @asis
9766 @item @code{-gnatP}
9768 Enable polling. This is required on some systems (notably Windows NT) to
9769 obtain asynchronous abort and asynchronous transfer of control capability.
9770 See @cite{Pragma_Polling} in the @cite{GNAT_Reference_Manual} for full
9771 details.
9772 @end table
9774 @geindex -gnatq (gcc)
9777 @table @asis
9779 @item @code{-gnatq}
9781 Don't quit. Try semantics, even if parse errors.
9782 @end table
9784 @geindex -gnatQ (gcc)
9787 @table @asis
9789 @item @code{-gnatQ}
9791 Don't quit. Generate @code{ALI} and tree files even if illegalities.
9792 Note that code generation is still suppressed in the presence of any
9793 errors, so even with @emph{-gnatQ} no object file is generated.
9794 @end table
9796 @geindex -gnatr (gcc)
9799 @table @asis
9801 @item @code{-gnatr}
9803 Treat pragma Restrictions as Restriction_Warnings.
9804 @end table
9806 @geindex -gnatR (gcc)
9809 @table @asis
9811 @item @code{-gnatR[0/1/2/3[s]]}
9813 Output representation information for declared types and objects.
9814 Note that this switch is not allowed if a previous @cite{-gnatD} switch has
9815 been given, since these two switches are not compatible.
9817 @item @code{-gnatRm[s]}
9819 Output convention and parameter passing mechanisms for all subprograms.
9820 @end table
9822 @geindex -gnats (gcc)
9825 @table @asis
9827 @item @code{-gnats}
9829 Syntax check only.
9830 @end table
9832 @geindex -gnatS (gcc)
9835 @table @asis
9837 @item @code{-gnatS}
9839 Print package Standard.
9840 @end table
9842 @geindex -gnatt (gcc)
9845 @table @asis
9847 @item @code{-gnatt}
9849 Generate tree output file.
9850 @end table
9852 @geindex -gnatT (gcc)
9855 @table @asis
9857 @item @code{-gnatT@emph{nnn}}
9859 All compiler tables start at @cite{nnn} times usual starting size.
9860 @end table
9862 @geindex -gnatu (gcc)
9865 @table @asis
9867 @item @code{-gnatu}
9869 List units for this compilation.
9870 @end table
9872 @geindex -gnatU (gcc)
9875 @table @asis
9877 @item @code{-gnatU}
9879 Tag all error messages with the unique string 'error:'
9880 @end table
9882 @geindex -gnatv (gcc)
9885 @table @asis
9887 @item @code{-gnatv}
9889 Verbose mode. Full error output with source lines to @code{stdout}.
9890 @end table
9892 @geindex -gnatV (gcc)
9895 @table @asis
9897 @item @code{-gnatV}
9899 Control level of validity checking (@ref{f6,,Validity Checking}).
9900 @end table
9902 @geindex -gnatw (gcc)
9905 @table @asis
9907 @item @code{-gnatw@emph{xxx}}
9909 Warning mode where
9910 @cite{xxx} is a string of option letters that denotes
9911 the exact warnings that
9912 are enabled or disabled (@ref{fa,,Warning Message Control}).
9913 @end table
9915 @geindex -gnatW (gcc)
9918 @table @asis
9920 @item @code{-gnatW@emph{e}}
9922 Wide character encoding method
9923 (@cite{e}=n/h/u/s/e/8).
9924 @end table
9926 @geindex -gnatx (gcc)
9929 @table @asis
9931 @item @code{-gnatx}
9933 Suppress generation of cross-reference information.
9934 @end table
9936 @geindex -gnatX (gcc)
9939 @table @asis
9941 @item @code{-gnatX}
9943 Enable GNAT implementation extensions and latest Ada version.
9944 @end table
9946 @geindex -gnaty (gcc)
9949 @table @asis
9951 @item @code{-gnaty}
9953 Enable built-in style checks (@ref{fb,,Style Checking}).
9954 @end table
9956 @geindex -gnatz (gcc)
9959 @table @asis
9961 @item @code{-gnatz@emph{m}}
9963 Distribution stub generation and compilation
9964 (@cite{m}=r/c for receiver/caller stubs).
9965 @end table
9967 @geindex -I (gcc)
9970 @table @asis
9972 @item @code{-I@emph{dir}}
9974 @geindex RTL
9976 Direct GNAT to search the @cite{dir} directory for source files needed by
9977 the current compilation
9978 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
9979 @end table
9981 @geindex -I- (gcc)
9984 @table @asis
9986 @item @code{-I-}
9988 @geindex RTL
9990 Except for the source file named in the command line, do not look for source
9991 files in the directory containing the source file named in the command line
9992 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
9993 @end table
9995 @geindex -o (gcc)
9998 @table @asis
10000 @item @code{-o @emph{file}}
10002 This switch is used in @emph{gcc} to redirect the generated object file
10003 and its associated ALI file. Beware of this switch with GNAT, because it may
10004 cause the object file and ALI file to have different names which in turn
10005 may confuse the binder and the linker.
10006 @end table
10008 @geindex -nostdinc (gcc)
10011 @table @asis
10013 @item @code{-nostdinc}
10015 Inhibit the search of the default location for the GNAT Run Time
10016 Library (RTL) source files.
10017 @end table
10019 @geindex -nostdlib (gcc)
10022 @table @asis
10024 @item @code{-nostdlib}
10026 Inhibit the search of the default location for the GNAT Run Time
10027 Library (RTL) ALI files.
10028 @end table
10030 @geindex -O (gcc)
10033 @table @asis
10035 @item @code{-O[@emph{n}]}
10037 @cite{n} controls the optimization level:
10040 @multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
10041 @item
10043 @emph{n}
10045 @tab
10047 Effect
10049 @item
10051 @emph{0}
10053 @tab
10055 No optimization, the default setting if no @emph{-O} appears
10057 @item
10059 @emph{1}
10061 @tab
10063 Normal optimization, the default if you specify @emph{-O} without an
10064 operand. A good compromise between code quality and compilation
10065 time.
10067 @item
10069 @emph{2}
10071 @tab
10073 Extensive optimization, may improve execution time, possibly at
10074 the cost of substantially increased compilation time.
10076 @item
10078 @emph{3}
10080 @tab
10082 Same as @emph{-O2}, and also includes inline expansion for small
10083 subprograms in the same unit.
10085 @item
10087 @emph{s}
10089 @tab
10091 Optimize space usage
10093 @end multitable
10096 See also @ref{fc,,Optimization Levels}.
10097 @end table
10099 @geindex -pass-exit-codes (gcc)
10102 @table @asis
10104 @item @code{-pass-exit-codes}
10106 Catch exit codes from the compiler and use the most meaningful as
10107 exit status.
10108 @end table
10110 @geindex --RTS (gcc)
10113 @table @asis
10115 @item @code{--RTS=@emph{rts-path}}
10117 Specifies the default location of the runtime library. Same meaning as the
10118 equivalent @emph{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
10119 @end table
10121 @geindex -S (gcc)
10124 @table @asis
10126 @item @code{-S}
10128 Used in place of @emph{-c} to
10129 cause the assembler source file to be
10130 generated, using @code{.s} as the extension,
10131 instead of the object file.
10132 This may be useful if you need to examine the generated assembly code.
10133 @end table
10135 @geindex -fverbose-asm (gcc)
10138 @table @asis
10140 @item @code{-fverbose-asm}
10142 Used in conjunction with @emph{-S}
10143 to cause the generated assembly code file to be annotated with variable
10144 names, making it significantly easier to follow.
10145 @end table
10147 @geindex -v (gcc)
10150 @table @asis
10152 @item @code{-v}
10154 Show commands generated by the @emph{gcc} driver. Normally used only for
10155 debugging purposes or if you need to be sure what version of the
10156 compiler you are executing.
10157 @end table
10159 @geindex -V (gcc)
10162 @table @asis
10164 @item @code{-V @emph{ver}}
10166 Execute @cite{ver} version of the compiler. This is the @emph{gcc}
10167 version, not the GNAT version.
10168 @end table
10170 @geindex -w (gcc)
10173 @table @asis
10175 @item @code{-w}
10177 Turn off warnings generated by the back end of the compiler. Use of
10178 this switch also causes the default for front end warnings to be set
10179 to suppress (as though @emph{-gnatws} had appeared at the start of
10180 the options).
10181 @end table
10183 @geindex Combining GNAT switches
10185 You may combine a sequence of GNAT switches into a single switch. For
10186 example, the combined switch
10188 @quotation
10190 @example
10191 -gnatofi3
10192 @end example
10193 @end quotation
10195 is equivalent to specifying the following sequence of switches:
10197 @quotation
10199 @example
10200 -gnato -gnatf -gnati3
10201 @end example
10202 @end quotation
10204 The following restrictions apply to the combination of switches
10205 in this manner:
10208 @itemize *
10210 @item 
10211 The switch @emph{-gnatc} if combined with other switches must come
10212 first in the string.
10214 @item 
10215 The switch @emph{-gnats} if combined with other switches must come
10216 first in the string.
10218 @item 
10219 The switches
10220 @emph{-gnatzc} and @emph{-gnatzr} may not be combined with any other
10221 switches, and only one of them may appear in the command line.
10223 @item 
10224 The switch @emph{-gnat-p} may not be combined with any other switch.
10226 @item 
10227 Once a 'y' appears in the string (that is a use of the @emph{-gnaty}
10228 switch), then all further characters in the switch are interpreted
10229 as style modifiers (see description of @emph{-gnaty}).
10231 @item 
10232 Once a 'd' appears in the string (that is a use of the @emph{-gnatd}
10233 switch), then all further characters in the switch are interpreted
10234 as debug flags (see description of @emph{-gnatd}).
10236 @item 
10237 Once a 'w' appears in the string (that is a use of the @emph{-gnatw}
10238 switch), then all further characters in the switch are interpreted
10239 as warning mode modifiers (see description of @emph{-gnatw}).
10241 @item 
10242 Once a 'V' appears in the string (that is a use of the @emph{-gnatV}
10243 switch), then all further characters in the switch are interpreted
10244 as validity checking options (@ref{f6,,Validity Checking}).
10246 @item 
10247 Option 'em', 'ec', 'ep', 'l=' and 'R' must be the last options in
10248 a combined list of options.
10249 @end itemize
10251 @node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10252 @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}
10253 @subsection Output and Error Message Control
10256 @geindex stderr
10258 The standard default format for error messages is called 'brief format'.
10259 Brief format messages are written to @code{stderr} (the standard error
10260 file) and have the following form:
10262 @example
10263 e.adb:3:04: Incorrect spelling of keyword "function"
10264 e.adb:4:20: ";" should be "is"
10265 @end example
10267 The first integer after the file name is the line number in the file,
10268 and the second integer is the column number within the line.
10269 @cite{GPS} can parse the error messages
10270 and point to the referenced character.
10271 The following switches provide control over the error message
10272 format:
10274 @geindex -gnatv (gcc)
10277 @table @asis
10279 @item @code{-gnatv}
10281 The @cite{v} stands for verbose.
10282 The effect of this setting is to write long-format error
10283 messages to @code{stdout} (the standard output file.
10284 The same program compiled with the
10285 @emph{-gnatv} switch would generate:
10287 @example
10288 3. funcion X (Q : Integer)
10289    |
10290 >>> Incorrect spelling of keyword "function"
10291 4. return Integer;
10292                  |
10293 >>> ";" should be "is"
10294 @end example
10296 The vertical bar indicates the location of the error, and the @code{>>>}
10297 prefix can be used to search for error messages. When this switch is
10298 used the only source lines output are those with errors.
10299 @end table
10301 @geindex -gnatl (gcc)
10304 @table @asis
10306 @item @code{-gnatl}
10308 The @cite{l} stands for list.
10309 This switch causes a full listing of
10310 the file to be generated. In the case where a body is
10311 compiled, the corresponding spec is also listed, along
10312 with any subunits. Typical output from compiling a package
10313 body @code{p.adb} might look like:
10315 @example
10316 Compiling: p.adb
10318      1. package body p is
10319      2.    procedure a;
10320      3.    procedure a is separate;
10321      4. begin
10322      5.    null
10323                |
10324         >>> missing ";"
10326      6. end;
10328 Compiling: p.ads
10330      1. package p is
10331      2.    pragma Elaborate_Body
10332                                 |
10333         >>> missing ";"
10335      3. end p;
10337 Compiling: p-a.adb
10339      1. separate p
10340                 |
10341         >>> missing "("
10343      2. procedure a is
10344      3. begin
10345      4.    null
10346                |
10347         >>> missing ";"
10349      5. end;
10350 @end example
10352 When you specify the @emph{-gnatv} or @emph{-gnatl} switches and
10353 standard output is redirected, a brief summary is written to
10354 @code{stderr} (standard error) giving the number of error messages and
10355 warning messages generated.
10356 @end table
10358 @geindex -gnatl=fname (gcc)
10361 @table @asis
10363 @item @code{-gnatl=@emph{fname}}
10365 This has the same effect as @emph{-gnatl} except that the output is
10366 written to a file instead of to standard output. If the given name
10367 @code{fname} does not start with a period, then it is the full name
10368 of the file to be written. If @code{fname} is an extension, it is
10369 appended to the name of the file being compiled. For example, if
10370 file @code{xyz.adb} is compiled with @emph{-gnatl=.lst},
10371 then the output is written to file xyz.adb.lst.
10372 @end table
10374 @geindex -gnatU (gcc)
10377 @table @asis
10379 @item @code{-gnatU}
10381 This switch forces all error messages to be preceded by the unique
10382 string 'error:'. This means that error messages take a few more
10383 characters in space, but allows easy searching for and identification
10384 of error messages.
10385 @end table
10387 @geindex -gnatb (gcc)
10390 @table @asis
10392 @item @code{-gnatb}
10394 The @cite{b} stands for brief.
10395 This switch causes GNAT to generate the
10396 brief format error messages to @code{stderr} (the standard error
10397 file) as well as the verbose
10398 format message or full listing (which as usual is written to
10399 @code{stdout} (the standard output file).
10400 @end table
10402 @geindex -gnatm (gcc)
10405 @table @asis
10407 @item @code{-gnatm=@emph{n}}
10409 The @cite{m} stands for maximum.
10410 @cite{n} is a decimal integer in the
10411 range of 1 to 999999 and limits the number of error or warning
10412 messages to be generated. For example, using
10413 @emph{-gnatm2} might yield
10415 @example
10416 e.adb:3:04: Incorrect spelling of keyword "function"
10417 e.adb:5:35: missing ".."
10418 fatal error: maximum number of errors detected
10419 compilation abandoned
10420 @end example
10422 The default setting if
10423 no switch is given is 9999. If the number of warnings reaches this
10424 limit, then a message is output and further warnings are suppressed,
10425 but the compilation is continued. If the number of error messages
10426 reaches this limit, then a message is output and the compilation
10427 is abandoned. A value of zero means that no limit applies.
10429 Note that the equal sign is optional, so the switches
10430 @emph{-gnatm2} and @emph{-gnatm=2} are equivalent.
10431 @end table
10433 @geindex -gnatf (gcc)
10436 @table @asis
10438 @item @code{-gnatf}
10440 @geindex Error messages
10441 @geindex suppressing
10443 The @cite{f} stands for full.
10444 Normally, the compiler suppresses error messages that are likely to be
10445 redundant. This switch causes all error
10446 messages to be generated. In particular, in the case of
10447 references to undefined variables. If a given variable is referenced
10448 several times, the normal format of messages is
10450 @example
10451 e.adb:7:07: "V" is undefined (more references follow)
10452 @end example
10454 where the parenthetical comment warns that there are additional
10455 references to the variable @cite{V}. Compiling the same program with the
10456 @emph{-gnatf} switch yields
10458 @example
10459 e.adb:7:07: "V" is undefined
10460 e.adb:8:07: "V" is undefined
10461 e.adb:8:12: "V" is undefined
10462 e.adb:8:16: "V" is undefined
10463 e.adb:9:07: "V" is undefined
10464 e.adb:9:12: "V" is undefined
10465 @end example
10467 The @emph{-gnatf} switch also generates additional information for
10468 some error messages.  Some examples are:
10471 @itemize *
10473 @item 
10474 Details on possibly non-portable unchecked conversion
10476 @item 
10477 List possible interpretations for ambiguous calls
10479 @item 
10480 Additional details on incorrect parameters
10481 @end itemize
10482 @end table
10484 @geindex -gnatjnn (gcc)
10487 @table @asis
10489 @item @code{-gnatjnn}
10491 In normal operation mode (or if @emph{-gnatj0} is used), then error messages
10492 with continuation lines are treated as though the continuation lines were
10493 separate messages (and so a warning with two continuation lines counts as
10494 three warnings, and is listed as three separate messages).
10496 If the @emph{-gnatjnn} switch is used with a positive value for nn, then
10497 messages are output in a different manner. A message and all its continuation
10498 lines are treated as a unit, and count as only one warning or message in the
10499 statistics totals. Furthermore, the message is reformatted so that no line
10500 is longer than nn characters.
10501 @end table
10503 @geindex -gnatq (gcc)
10506 @table @asis
10508 @item @code{-gnatq}
10510 The @cite{q} stands for quit (really 'don't quit').
10511 In normal operation mode, the compiler first parses the program and
10512 determines if there are any syntax errors. If there are, appropriate
10513 error messages are generated and compilation is immediately terminated.
10514 This switch tells
10515 GNAT to continue with semantic analysis even if syntax errors have been
10516 found. This may enable the detection of more errors in a single run. On
10517 the other hand, the semantic analyzer is more likely to encounter some
10518 internal fatal error when given a syntactically invalid tree.
10519 @end table
10521 @geindex -gnatQ (gcc)
10524 @table @asis
10526 @item @code{-gnatQ}
10528 In normal operation mode, the @code{ALI} file is not generated if any
10529 illegalities are detected in the program. The use of @emph{-gnatQ} forces
10530 generation of the @code{ALI} file. This file is marked as being in
10531 error, so it cannot be used for binding purposes, but it does contain
10532 reasonably complete cross-reference information, and thus may be useful
10533 for use by tools (e.g., semantic browsing tools or integrated development
10534 environments) that are driven from the @code{ALI} file. This switch
10535 implies @emph{-gnatq}, since the semantic phase must be run to get a
10536 meaningful ALI file.
10538 In addition, if @emph{-gnatt} is also specified, then the tree file is
10539 generated even if there are illegalities. It may be useful in this case
10540 to also specify @emph{-gnatq} to ensure that full semantic processing
10541 occurs. The resulting tree file can be processed by ASIS, for the purpose
10542 of providing partial information about illegal units, but if the error
10543 causes the tree to be badly malformed, then ASIS may crash during the
10544 analysis.
10546 When @emph{-gnatQ} is used and the generated @code{ALI} file is marked as
10547 being in error, @emph{gnatmake} will attempt to recompile the source when it
10548 finds such an @code{ALI} file, including with switch @emph{-gnatc}.
10550 Note that @emph{-gnatQ} has no effect if @emph{-gnats} is specified,
10551 since ALI files are never generated if @emph{-gnats} is set.
10552 @end table
10554 @node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10555 @anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{fa}@anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{ff}
10556 @subsection Warning Message Control
10559 @geindex Warning messages
10561 In addition to error messages, which correspond to illegalities as defined
10562 in the Ada Reference Manual, the compiler detects two kinds of warning
10563 situations.
10565 First, the compiler considers some constructs suspicious and generates a
10566 warning message to alert you to a possible error. Second, if the
10567 compiler detects a situation that is sure to raise an exception at
10568 run time, it generates a warning message. The following shows an example
10569 of warning messages:
10571 @example
10572 e.adb:4:24: warning: creation of object may raise Storage_Error
10573 e.adb:10:17: warning: static value out of range
10574 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10575 @end example
10577 GNAT considers a large number of situations as appropriate
10578 for the generation of warning messages. As always, warnings are not
10579 definite indications of errors. For example, if you do an out-of-range
10580 assignment with the deliberate intention of raising a
10581 @cite{Constraint_Error} exception, then the warning that may be
10582 issued does not indicate an error. Some of the situations for which GNAT
10583 issues warnings (at least some of the time) are given in the following
10584 list. This list is not complete, and new warnings are often added to
10585 subsequent versions of GNAT. The list is intended to give a general idea
10586 of the kinds of warnings that are generated.
10589 @itemize *
10591 @item 
10592 Possible infinitely recursive calls
10594 @item 
10595 Out-of-range values being assigned
10597 @item 
10598 Possible order of elaboration problems
10600 @item 
10601 Size not a multiple of alignment for a record type
10603 @item 
10604 Assertions (pragma Assert) that are sure to fail
10606 @item 
10607 Unreachable code
10609 @item 
10610 Address clauses with possibly unaligned values, or where an attempt is
10611 made to overlay a smaller variable with a larger one.
10613 @item 
10614 Fixed-point type declarations with a null range
10616 @item 
10617 Direct_IO or Sequential_IO instantiated with a type that has access values
10619 @item 
10620 Variables that are never assigned a value
10622 @item 
10623 Variables that are referenced before being initialized
10625 @item 
10626 Task entries with no corresponding @cite{accept} statement
10628 @item 
10629 Duplicate accepts for the same task entry in a @cite{select}
10631 @item 
10632 Objects that take too much storage
10634 @item 
10635 Unchecked conversion between types of differing sizes
10637 @item 
10638 Missing @cite{return} statement along some execution path in a function
10640 @item 
10641 Incorrect (unrecognized) pragmas
10643 @item 
10644 Incorrect external names
10646 @item 
10647 Allocation from empty storage pool
10649 @item 
10650 Potentially blocking operation in protected type
10652 @item 
10653 Suspicious parenthesization of expressions
10655 @item 
10656 Mismatching bounds in an aggregate
10658 @item 
10659 Attempt to return local value by reference
10661 @item 
10662 Premature instantiation of a generic body
10664 @item 
10665 Attempt to pack aliased components
10667 @item 
10668 Out of bounds array subscripts
10670 @item 
10671 Wrong length on string assignment
10673 @item 
10674 Violations of style rules if style checking is enabled
10676 @item 
10677 Unused @emph{with} clauses
10679 @item 
10680 @cite{Bit_Order} usage that does not have any effect
10682 @item 
10683 @cite{Standard.Duration} used to resolve universal fixed expression
10685 @item 
10686 Dereference of possibly null value
10688 @item 
10689 Declaration that is likely to cause storage error
10691 @item 
10692 Internal GNAT unit @emph{with}ed by application unit
10694 @item 
10695 Values known to be out of range at compile time
10697 @item 
10698 Unreferenced or unmodified variables. Note that a special
10699 exemption applies to variables which contain any of the substrings
10700 @cite{DISCARD@comma{} DUMMY@comma{} IGNORE@comma{} JUNK@comma{} UNUSED}, in any casing. Such variables
10701 are considered likely to be intentionally used in a situation where
10702 otherwise a warning would be given, so warnings of this kind are
10703 always suppressed for such variables.
10705 @item 
10706 Address overlays that could clobber memory
10708 @item 
10709 Unexpected initialization when address clause present
10711 @item 
10712 Bad alignment for address clause
10714 @item 
10715 Useless type conversions
10717 @item 
10718 Redundant assignment statements and other redundant constructs
10720 @item 
10721 Useless exception handlers
10723 @item 
10724 Accidental hiding of name by child unit
10726 @item 
10727 Access before elaboration detected at compile time
10729 @item 
10730 A range in a @cite{for} loop that is known to be null or might be null
10731 @end itemize
10733 The following section lists compiler switches that are available
10734 to control the handling of warning messages. It is also possible
10735 to exercise much finer control over what warnings are issued and
10736 suppressed using the GNAT pragma Warnings (see the description
10737 of the pragma in the @cite{GNAT_Reference_manual}).
10739 @geindex -gnatwa (gcc)
10742 @table @asis
10744 @item @code{-gnatwa}
10746 @emph{Activate most optional warnings.}
10748 This switch activates most optional warning messages.  See the remaining list
10749 in this section for details on optional warning messages that can be
10750 individually controlled.  The warnings that are not turned on by this
10751 switch are:
10754 @itemize *
10756 @item 
10757 @code{-gnatwd} (implicit dereferencing)
10759 @item 
10760 @code{-gnatw.d} (tag warnings with -gnatw switch)
10762 @item 
10763 @code{-gnatwh} (hiding)
10765 @item 
10766 @code{-gnatw.h} (holes in record layouts)
10768 @item 
10769 @code{-gnatw.k} (redefinition of names in standard)
10771 @item 
10772 @code{-gnatwl} (elaboration warnings)
10774 @item 
10775 @code{-gnatw.l} (inherited aspects)
10777 @item 
10778 @code{-gnatw.n} (atomic synchronization)
10780 @item 
10781 @code{-gnatwo} (address clause overlay)
10783 @item 
10784 @code{-gnatw.o} (values set by out parameters ignored)
10786 @item 
10787 @code{-gnatw.s} (overridden size clause)
10789 @item 
10790 @code{-gnatwt} (tracking of deleted conditional code)
10792 @item 
10793 @code{-gnatw.u} (unordered enumeration)
10795 @item 
10796 @code{-gnatw.w} (use of Warnings Off)
10798 @item 
10799 @code{-gnatw.y} (reasons for package needing body)
10800 @end itemize
10802 All other optional warnings are turned on.
10803 @end table
10805 @geindex -gnatwA (gcc)
10808 @table @asis
10810 @item @code{-gnatwA}
10812 @emph{Suppress all optional errors.}
10814 This switch suppresses all optional warning messages, see remaining list
10815 in this section for details on optional warning messages that can be
10816 individually controlled. Note that unlike switch @emph{-gnatws}, the
10817 use of switch @emph{-gnatwA} does not suppress warnings that are
10818 normally given unconditionally and cannot be individually controlled
10819 (for example, the warning about a missing exit path in a function).
10820 Also, again unlike switch @emph{-gnatws}, warnings suppressed by
10821 the use of switch @emph{-gnatwA} can be individually turned back
10822 on. For example the use of switch @emph{-gnatwA} followed by
10823 switch @emph{-gnatwd} will suppress all optional warnings except
10824 the warnings for implicit dereferencing.
10825 @end table
10827 @geindex -gnatw.a (gcc)
10830 @table @asis
10832 @item @code{-gnatw.a}
10834 @emph{Activate warnings on failing assertions.}
10836 @geindex Assert failures
10838 This switch activates warnings for assertions where the compiler can tell at
10839 compile time that the assertion will fail. Note that this warning is given
10840 even if assertions are disabled. The default is that such warnings are
10841 generated.
10842 @end table
10844 @geindex -gnatw.A (gcc)
10847 @table @asis
10849 @item @code{-gnatw.A}
10851 @emph{Suppress warnings on failing assertions.}
10853 @geindex Assert failures
10855 This switch suppresses warnings for assertions where the compiler can tell at
10856 compile time that the assertion will fail.
10857 @end table
10859 @geindex -gnatwb (gcc)
10862 @table @asis
10864 @item @code{-gnatwb}
10866 @emph{Activate warnings on bad fixed values.}
10868 @geindex Bad fixed values
10870 @geindex Fixed-point Small value
10872 @geindex Small value
10874 This switch activates warnings for static fixed-point expressions whose
10875 value is not an exact multiple of Small. Such values are implementation
10876 dependent, since an implementation is free to choose either of the multiples
10877 that surround the value. GNAT always chooses the closer one, but this is not
10878 required behavior, and it is better to specify a value that is an exact
10879 multiple, ensuring predictable execution. The default is that such warnings
10880 are not generated.
10881 @end table
10883 @geindex -gnatwB (gcc)
10886 @table @asis
10888 @item @code{-gnatwB}
10890 @emph{Suppress warnings on bad fixed values.}
10892 This switch suppresses warnings for static fixed-point expressions whose
10893 value is not an exact multiple of Small.
10894 @end table
10896 @geindex -gnatw.b (gcc)
10899 @table @asis
10901 @item @code{-gnatw.b}
10903 @emph{Activate warnings on biased representation.}
10905 @geindex Biased representation
10907 This switch activates warnings when a size clause, value size clause, component
10908 clause, or component size clause forces the use of biased representation for an
10909 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
10910 to represent 10/11). The default is that such warnings are generated.
10911 @end table
10913 @geindex -gnatwB (gcc)
10916 @table @asis
10918 @item @code{-gnatw.B}
10920 @emph{Suppress warnings on biased representation.}
10922 This switch suppresses warnings for representation clauses that force the use
10923 of biased representation.
10924 @end table
10926 @geindex -gnatwc (gcc)
10929 @table @asis
10931 @item @code{-gnatwc}
10933 @emph{Activate warnings on conditionals.}
10935 @geindex Conditionals
10936 @geindex constant
10938 This switch activates warnings for conditional expressions used in
10939 tests that are known to be True or False at compile time. The default
10940 is that such warnings are not generated.
10941 Note that this warning does
10942 not get issued for the use of boolean variables or constants whose
10943 values are known at compile time, since this is a standard technique
10944 for conditional compilation in Ada, and this would generate too many
10945 false positive warnings.
10947 This warning option also activates a special test for comparisons using
10948 the operators '>=' and' <='.
10949 If the compiler can tell that only the equality condition is possible,
10950 then it will warn that the '>' or '<' part of the test
10951 is useless and that the operator could be replaced by '='.
10952 An example would be comparing a @cite{Natural} variable <= 0.
10954 This warning option also generates warnings if
10955 one or both tests is optimized away in a membership test for integer
10956 values if the result can be determined at compile time. Range tests on
10957 enumeration types are not included, since it is common for such tests
10958 to include an end point.
10960 This warning can also be turned on using @emph{-gnatwa}.
10961 @end table
10963 @geindex -gnatwC (gcc)
10966 @table @asis
10968 @item @code{-gnatwC}
10970 @emph{Suppress warnings on conditionals.}
10972 This switch suppresses warnings for conditional expressions used in
10973 tests that are known to be True or False at compile time.
10974 @end table
10976 @geindex -gnatw.c (gcc)
10979 @table @asis
10981 @item @code{-gnatw.c}
10983 @emph{Activate warnings on missing component clauses.}
10985 @geindex Component clause
10986 @geindex missing
10988 This switch activates warnings for record components where a record
10989 representation clause is present and has component clauses for the
10990 majority, but not all, of the components. A warning is given for each
10991 component for which no component clause is present.
10992 @end table
10994 @geindex -gnatwC (gcc)
10997 @table @asis
10999 @item @code{-gnatw.C}
11001 @emph{Suppress warnings on missing component clauses.}
11003 This switch suppresses warnings for record components that are
11004 missing a component clause in the situation described above.
11005 @end table
11007 @geindex -gnatwd (gcc)
11010 @table @asis
11012 @item @code{-gnatwd}
11014 @emph{Activate warnings on implicit dereferencing.}
11016 If this switch is set, then the use of a prefix of an access type
11017 in an indexed component, slice, or selected component without an
11018 explicit @cite{.all} will generate a warning. With this warning
11019 enabled, access checks occur only at points where an explicit
11020 @cite{.all} appears in the source code (assuming no warnings are
11021 generated as a result of this switch). The default is that such
11022 warnings are not generated.
11023 @end table
11025 @geindex -gnatwD (gcc)
11028 @table @asis
11030 @item @code{-gnatwD}
11032 @emph{Suppress warnings on implicit dereferencing.}
11034 @geindex Implicit dereferencing
11036 @geindex Dereferencing
11037 @geindex implicit
11039 This switch suppresses warnings for implicit dereferences in
11040 indexed components, slices, and selected components.
11041 @end table
11043 @geindex -gnatw.d (gcc)
11046 @table @asis
11048 @item @code{-gnatw.d}
11050 @emph{Activate tagging of warning and info messages.}
11052 If this switch is set, then warning messages are tagged, with one of the
11053 following strings:
11055 @quotation
11058 @itemize -
11060 @item 
11061 @emph{[-gnatw?]}
11062 Used to tag warnings controlled by the switch @emph{-gnatwx} where x
11063 is a letter a-z.
11065 @item 
11066 @emph{[-gnatw.?]}
11067 Used to tag warnings controlled by the switch @emph{-gnatw.x} where x
11068 is a letter a-z.
11070 @item 
11071 @emph{[-gnatel]}
11072 Used to tag elaboration information (info) messages generated when the
11073 static model of elaboration is used and the @emph{-gnatel} switch is set.
11075 @item 
11076 @emph{[restriction warning]}
11077 Used to tag warning messages for restriction violations, activated by use
11078 of the pragma @emph{Restriction_Warnings}.
11080 @item 
11081 @emph{[warning-as-error]}
11082 Used to tag warning messages that have been converted to error messages by
11083 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11084 the string "error: " rather than "warning: ".
11086 @item 
11087 @emph{[enabled by default]}
11088 Used to tag all other warnings that are always given by default, unless
11089 warnings are completely suppressed using pragma @emph{Warnings(Off)} or
11090 the switch @emph{-gnatws}.
11091 @end itemize
11092 @end quotation
11093 @end table
11095 @geindex -gnatw.d (gcc)
11098 @table @asis
11100 @item @code{-gnatw.D}
11102 @emph{Deactivate tagging of warning and info messages messages.}
11104 If this switch is set, then warning messages return to the default
11105 mode in which warnings and info messages are not tagged as described above for
11106 @cite{-gnatw.d}.
11107 @end table
11109 @geindex -gnatwe (gcc)
11111 @geindex Warnings
11112 @geindex treat as error
11115 @table @asis
11117 @item @code{-gnatwe}
11119 @emph{Treat warnings and style checks as errors.}
11121 This switch causes warning messages and style check messages to be
11122 treated as errors.
11123 The warning string still appears, but the warning messages are counted
11124 as errors, and prevent the generation of an object file. Note that this
11125 is the only -gnatw switch that affects the handling of style check messages.
11126 Note also that this switch has no effect on info (information) messages, which
11127 are not treated as errors if this switch is present.
11128 @end table
11130 @geindex -gnatw.e (gcc)
11133 @table @asis
11135 @item @code{-gnatw.e}
11137 @emph{Activate every optional warning.}
11139 @geindex Warnings
11140 @geindex activate every optional warning
11142 This switch activates all optional warnings, including those which
11143 are not activated by @cite{-gnatwa}. The use of this switch is not
11144 recommended for normal use. If you turn this switch on, it is almost
11145 certain that you will get large numbers of useless warnings. The
11146 warnings that are excluded from @cite{-gnatwa} are typically highly
11147 specialized warnings that are suitable for use only in code that has
11148 been specifically designed according to specialized coding rules.
11149 @end table
11151 @geindex -gnatwf (gcc)
11154 @table @asis
11156 @item @code{-gnatwf}
11158 @emph{Activate warnings on unreferenced formals.}
11160 @geindex Formals
11161 @geindex unreferenced
11163 This switch causes a warning to be generated if a formal parameter
11164 is not referenced in the body of the subprogram. This warning can
11165 also be turned on using @emph{-gnatwu}. The
11166 default is that these warnings are not generated.
11167 @end table
11169 @geindex -gnatwF (gcc)
11172 @table @asis
11174 @item @code{-gnatwF}
11176 @emph{Suppress warnings on unreferenced formals.}
11178 This switch suppresses warnings for unreferenced formal
11179 parameters. Note that the
11180 combination @emph{-gnatwu} followed by @emph{-gnatwF} has the
11181 effect of warning on unreferenced entities other than subprogram
11182 formals.
11183 @end table
11185 @geindex -gnatwg (gcc)
11188 @table @asis
11190 @item @code{-gnatwg}
11192 @emph{Activate warnings on unrecognized pragmas.}
11194 @geindex Pragmas
11195 @geindex unrecognized
11197 This switch causes a warning to be generated if an unrecognized
11198 pragma is encountered. Apart from issuing this warning, the
11199 pragma is ignored and has no effect. The default
11200 is that such warnings are issued (satisfying the Ada Reference
11201 Manual requirement that such warnings appear).
11202 @end table
11204 @geindex -gnatwG (gcc)
11207 @table @asis
11209 @item @code{-gnatwG}
11211 @emph{Suppress warnings on unrecognized pragmas.}
11213 This switch suppresses warnings for unrecognized pragmas.
11214 @end table
11216 @geindex -gnatw.g (gcc)
11219 @table @asis
11221 @item @code{-gnatw.g}
11223 @emph{Warnings used for GNAT sources.}
11225 This switch sets the warning categories that are used by the standard
11226 GNAT style. Currently this is equivalent to
11227 @emph{-gnatwAao.sI.C.V.X}
11228 but more warnings may be added in the future without advanced notice.
11229 @end table
11231 @geindex -gnatwh (gcc)
11234 @table @asis
11236 @item @code{-gnatwh}
11238 @emph{Activate warnings on hiding.}
11240 @geindex Hiding of Declarations
11242 This switch activates warnings on hiding declarations that are considered
11243 potentially confusing. Not all cases of hiding cause warnings; for example an
11244 overriding declaration hides an implicit declaration, which is just normal
11245 code. The default is that warnings on hiding are not generated.
11246 @end table
11248 @geindex -gnatwH (gcc)
11251 @table @asis
11253 @item @code{-gnatwH}
11255 @emph{Suppress warnings on hiding.}
11257 This switch suppresses warnings on hiding declarations.
11258 @end table
11260 @geindex -gnatw.h (gcc)
11263 @table @asis
11265 @item @code{-gnatw.h}
11267 @emph{Activate warnings on holes/gaps in records.}
11269 @geindex Record Representation (gaps)
11271 This switch activates warnings on component clauses in record
11272 representation clauses that leave holes (gaps) in the record layout.
11273 If this warning option is active, then record representation clauses
11274 should specify a contiguous layout, adding unused fill fields if needed.
11275 @end table
11277 @geindex -gnatw.H (gcc)
11280 @table @asis
11282 @item @code{-gnatw.H}
11284 @emph{Suppress warnings on holes/gaps in records.}
11286 This switch suppresses warnings on component clauses in record
11287 representation clauses that leave holes (haps) in the record layout.
11288 @end table
11290 @geindex -gnatwi (gcc)
11293 @table @asis
11295 @item @code{-gnatwi}
11297 @emph{Activate warnings on implementation units.}
11299 This switch activates warnings for a @emph{with} of an internal GNAT
11300 implementation unit, defined as any unit from the @cite{Ada},
11301 @cite{Interfaces}, @cite{GNAT},
11302 or @cite{System}
11303 hierarchies that is not
11304 documented in either the Ada Reference Manual or the GNAT
11305 Programmer's Reference Manual. Such units are intended only
11306 for internal implementation purposes and should not be @emph{with}ed
11307 by user programs. The default is that such warnings are generated
11308 @end table
11310 @geindex -gnatwI (gcc)
11313 @table @asis
11315 @item @code{-gnatwI}
11317 @emph{Disable warnings on implementation units.}
11319 This switch disables warnings for a @emph{with} of an internal GNAT
11320 implementation unit.
11321 @end table
11323 @geindex -gnatw.i (gcc)
11326 @table @asis
11328 @item @code{-gnatw.i}
11330 @emph{Activate warnings on overlapping actuals.}
11332 This switch enables a warning on statically detectable overlapping actuals in
11333 a subprogram call, when one of the actuals is an in-out parameter, and the
11334 types of the actuals are not by-copy types. This warning is off by default.
11335 @end table
11337 @geindex -gnatw.I (gcc)
11340 @table @asis
11342 @item @code{-gnatw.I}
11344 @emph{Disable warnings on overlapping actuals.}
11346 This switch disables warnings on overlapping actuals in a call..
11347 @end table
11349 @geindex -gnatwj (gcc)
11352 @table @asis
11354 @item @code{-gnatwj}
11356 @emph{Activate warnings on obsolescent features (Annex J).}
11358 @geindex Features
11359 @geindex obsolescent
11361 @geindex Obsolescent features
11363 If this warning option is activated, then warnings are generated for
11364 calls to subprograms marked with @cite{pragma Obsolescent} and
11365 for use of features in Annex J of the Ada Reference Manual. In the
11366 case of Annex J, not all features are flagged. In particular use
11367 of the renamed packages (like @cite{Text_IO}) and use of package
11368 @cite{ASCII} are not flagged, since these are very common and
11369 would generate many annoying positive warnings. The default is that
11370 such warnings are not generated.
11372 In addition to the above cases, warnings are also generated for
11373 GNAT features that have been provided in past versions but which
11374 have been superseded (typically by features in the new Ada standard).
11375 For example, @cite{pragma Ravenscar} will be flagged since its
11376 function is replaced by @cite{pragma Profile(Ravenscar)}, and
11377 @cite{pragma Interface_Name} will be flagged since its function
11378 is replaced by @cite{pragma Import}.
11380 Note that this warning option functions differently from the
11381 restriction @cite{No_Obsolescent_Features} in two respects.
11382 First, the restriction applies only to annex J features.
11383 Second, the restriction does flag uses of package @cite{ASCII}.
11384 @end table
11386 @geindex -gnatwJ (gcc)
11389 @table @asis
11391 @item @code{-gnatwJ}
11393 @emph{Suppress warnings on obsolescent features (Annex J).}
11395 This switch disables warnings on use of obsolescent features.
11396 @end table
11398 @geindex -gnatwk (gcc)
11401 @table @asis
11403 @item @code{-gnatwk}
11405 @emph{Activate warnings on variables that could be constants.}
11407 This switch activates warnings for variables that are initialized but
11408 never modified, and then could be declared constants. The default is that
11409 such warnings are not given.
11410 @end table
11412 @geindex -gnatwK (gcc)
11415 @table @asis
11417 @item @code{-gnatwK}
11419 @emph{Suppress warnings on variables that could be constants.}
11421 This switch disables warnings on variables that could be declared constants.
11422 @end table
11424 @geindex -gnatw.k (gcc)
11427 @table @asis
11429 @item @code{-gnatw.k}
11431 @emph{Activate warnings on redefinition of names in standard.}
11433 This switch activates warnings for declarations that declare a name that
11434 is defined in package Standard. Such declarations can be confusing,
11435 especially since the names in package Standard continue to be directly
11436 visible, meaning that use visibiliy on such redeclared names does not
11437 work as expected. Names of discriminants and components in records are
11438 not included in this check.
11439 @end table
11441 @geindex -gnatwK (gcc)
11444 @table @asis
11446 @item @code{-gnatw.K}
11448 @emph{Suppress warnings on redefinition of names in standard.}
11450 This switch activates warnings for declarations that declare a name that
11451 is defined in package Standard.
11452 @end table
11454 @geindex -gnatwl (gcc)
11457 @table @asis
11459 @item @code{-gnatwl}
11461 @emph{Activate warnings for elaboration pragmas.}
11463 @geindex Elaboration
11464 @geindex warnings
11466 This switch activates warnings for possible elaboration problems,
11467 including suspicious use
11468 of @cite{Elaborate} pragmas, when using the static elaboration model, and
11469 possible situations that may raise @cite{Program_Error} when using the
11470 dynamic elaboration model.
11471 See the section in this guide on elaboration checking for further details.
11472 The default is that such warnings
11473 are not generated.
11474 @end table
11476 @geindex -gnatwL (gcc)
11479 @table @asis
11481 @item @code{-gnatwL}
11483 @emph{Suppress warnings for elaboration pragmas.}
11485 This switch suppresses warnings for possible elaboration problems.
11486 @end table
11488 @geindex -gnatw.l (gcc)
11491 @table @asis
11493 @item @code{-gnatw.l}
11495 @emph{List inherited aspects.}
11497 This switch causes the compiler to list inherited invariants,
11498 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
11499 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
11500 @end table
11502 @geindex -gnatw.L (gcc)
11505 @table @asis
11507 @item @code{-gnatw.L}
11509 @emph{Suppress listing of inherited aspects.}
11511 This switch suppresses listing of inherited aspects.
11512 @end table
11514 @geindex -gnatwm (gcc)
11517 @table @asis
11519 @item @code{-gnatwm}
11521 @emph{Activate warnings on modified but unreferenced variables.}
11523 This switch activates warnings for variables that are assigned (using
11524 an initialization value or with one or more assignment statements) but
11525 whose value is never read. The warning is suppressed for volatile
11526 variables and also for variables that are renamings of other variables
11527 or for which an address clause is given.
11528 The default is that these warnings are not given.
11529 @end table
11531 @geindex -gnatwM (gcc)
11534 @table @asis
11536 @item @code{-gnatwM}
11538 @emph{Disable warnings on modified but unreferenced variables.}
11540 This switch disables warnings for variables that are assigned or
11541 initialized, but never read.
11542 @end table
11544 @geindex -gnatw.m (gcc)
11547 @table @asis
11549 @item @code{-gnatw.m}
11551 @emph{Activate warnings on suspicious modulus values.}
11553 This switch activates warnings for modulus values that seem suspicious.
11554 The cases caught are where the size is the same as the modulus (e.g.
11555 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11556 with no size clause. The guess in both cases is that 2**x was intended
11557 rather than x. In addition expressions of the form 2*x for small x
11558 generate a warning (the almost certainly accurate guess being that
11559 2**x was intended). The default is that these warnings are given.
11560 @end table
11562 @geindex -gnatw.M (gcc)
11565 @table @asis
11567 @item @code{-gnatw.M}
11569 @emph{Disable warnings on suspicious modulus values.}
11571 This switch disables warnings for suspicious modulus values.
11572 @end table
11574 @geindex -gnatwn (gcc)
11577 @table @asis
11579 @item @code{-gnatwn}
11581 @emph{Set normal warnings mode.}
11583 This switch sets normal warning mode, in which enabled warnings are
11584 issued and treated as warnings rather than errors. This is the default
11585 mode. the switch @emph{-gnatwn} can be used to cancel the effect of
11586 an explicit @emph{-gnatws} or
11587 @emph{-gnatwe}. It also cancels the effect of the
11588 implicit @emph{-gnatwe} that is activated by the
11589 use of @emph{-gnatg}.
11590 @end table
11592 @geindex -gnatw.n (gcc)
11594 @geindex Atomic Synchronization
11595 @geindex warnings
11598 @table @asis
11600 @item @code{-gnatw.n}
11602 @emph{Activate warnings on atomic synchronization.}
11604 This switch actives warnings when an access to an atomic variable
11605 requires the generation of atomic synchronization code. These
11606 warnings are off by default.
11607 @end table
11609 @geindex -gnatw.N (gcc)
11612 @table @asis
11614 @item @code{-gnatw.N}
11616 @emph{Suppress warnings on atomic synchronization.}
11618 @geindex Atomic Synchronization
11619 @geindex warnings
11621 This switch suppresses warnings when an access to an atomic variable
11622 requires the generation of atomic synchronization code.
11623 @end table
11625 @geindex -gnatwo (gcc)
11627 @geindex Address Clauses
11628 @geindex warnings
11631 @table @asis
11633 @item @code{-gnatwo}
11635 @emph{Activate warnings on address clause overlays.}
11637 This switch activates warnings for possibly unintended initialization
11638 effects of defining address clauses that cause one variable to overlap
11639 another. The default is that such warnings are generated.
11640 @end table
11642 @geindex -gnatwO (gcc)
11645 @table @asis
11647 @item @code{-gnatwO}
11649 @emph{Suppress warnings on address clause overlays.}
11651 This switch suppresses warnings on possibly unintended initialization
11652 effects of defining address clauses that cause one variable to overlap
11653 another.
11654 @end table
11656 @geindex -gnatw.o (gcc)
11659 @table @asis
11661 @item @code{-gnatw.o}
11663 @emph{Activate warnings on modified but unreferenced out parameters.}
11665 This switch activates warnings for variables that are modified by using
11666 them as actuals for a call to a procedure with an out mode formal, where
11667 the resulting assigned value is never read. It is applicable in the case
11668 where there is more than one out mode formal. If there is only one out
11669 mode formal, the warning is issued by default (controlled by -gnatwu).
11670 The warning is suppressed for volatile
11671 variables and also for variables that are renamings of other variables
11672 or for which an address clause is given.
11673 The default is that these warnings are not given.
11674 @end table
11676 @geindex -gnatw.O (gcc)
11679 @table @asis
11681 @item @code{-gnatw.O}
11683 @emph{Disable warnings on modified but unreferenced out parameters.}
11685 This switch suppresses warnings for variables that are modified by using
11686 them as actuals for a call to a procedure with an out mode formal, where
11687 the resulting assigned value is never read.
11688 @end table
11690 @geindex -gnatwp (gcc)
11692 @geindex Inlining
11693 @geindex warnings
11696 @table @asis
11698 @item @code{-gnatwp}
11700 @emph{Activate warnings on ineffective pragma Inlines.}
11702 This switch activates warnings for failure of front end inlining
11703 (activated by @emph{-gnatN}) to inline a particular call. There are
11704 many reasons for not being able to inline a call, including most
11705 commonly that the call is too complex to inline. The default is
11706 that such warnings are not given.
11707 Warnings on ineffective inlining by the gcc back-end can be activated
11708 separately, using the gcc switch -Winline.
11709 @end table
11711 @geindex -gnatwP (gcc)
11714 @table @asis
11716 @item @code{-gnatwP}
11718 @emph{Suppress warnings on ineffective pragma Inlines.}
11720 This switch suppresses warnings on ineffective pragma Inlines. If the
11721 inlining mechanism cannot inline a call, it will simply ignore the
11722 request silently.
11723 @end table
11725 @geindex -gnatw.p (gcc)
11727 @geindex Parameter order
11728 @geindex warnings
11731 @table @asis
11733 @item @code{-gnatw.p}
11735 @emph{Activate warnings on parameter ordering.}
11737 This switch activates warnings for cases of suspicious parameter
11738 ordering when the list of arguments are all simple identifiers that
11739 match the names of the formals, but are in a different order. The
11740 warning is suppressed if any use of named parameter notation is used,
11741 so this is the appropriate way to suppress a false positive (and
11742 serves to emphasize that the "misordering" is deliberate). The
11743 default is that such warnings are not given.
11744 @end table
11746 @geindex -gnatw.P (gcc)
11749 @table @asis
11751 @item @code{-gnatw.P}
11753 @emph{Suppress warnings on parameter ordering.}
11755 This switch suppresses warnings on cases of suspicious parameter
11756 ordering.
11757 @end table
11759 @geindex -gnatwq (gcc)
11761 @geindex Parentheses
11762 @geindex warnings
11765 @table @asis
11767 @item @code{-gnatwq}
11769 @emph{Activate warnings on questionable missing parentheses.}
11771 This switch activates warnings for cases where parentheses are not used and
11772 the result is potential ambiguity from a readers point of view. For example
11773 (not a > b) when a and b are modular means ((not a) > b) and very likely the
11774 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11775 quite likely ((-x) mod 5) was intended. In such situations it seems best to
11776 follow the rule of always parenthesizing to make the association clear, and
11777 this warning switch warns if such parentheses are not present. The default
11778 is that these warnings are given.
11779 @end table
11781 @geindex -gnatwQ (gcc)
11784 @table @asis
11786 @item @code{-gnatwQ}
11788 @emph{Suppress warnings on questionable missing parentheses.}
11790 This switch suppresses warnings for cases where the association is not
11791 clear and the use of parentheses is preferred.
11792 @end table
11794 @geindex -gnatwr (gcc)
11797 @table @asis
11799 @item @code{-gnatwr}
11801 @emph{Activate warnings on redundant constructs.}
11803 This switch activates warnings for redundant constructs. The following
11804 is the current list of constructs regarded as redundant:
11807 @itemize *
11809 @item 
11810 Assignment of an item to itself.
11812 @item 
11813 Type conversion that converts an expression to its own type.
11815 @item 
11816 Use of the attribute @cite{Base} where @cite{typ'Base} is the same
11817 as @cite{typ}.
11819 @item 
11820 Use of pragma @cite{Pack} when all components are placed by a record
11821 representation clause.
11823 @item 
11824 Exception handler containing only a reraise statement (raise with no
11825 operand) which has no effect.
11827 @item 
11828 Use of the operator abs on an operand that is known at compile time
11829 to be non-negative
11831 @item 
11832 Comparison of boolean expressions to an explicit True value.
11833 @end itemize
11835 The default is that warnings for redundant constructs are not given.
11836 @end table
11838 @geindex -gnatwR (gcc)
11841 @table @asis
11843 @item @code{-gnatwR}
11845 @emph{Suppress warnings on redundant constructs.}
11847 This switch suppresses warnings for redundant constructs.
11848 @end table
11850 @geindex -gnatw.r (gcc)
11853 @table @asis
11855 @item @code{-gnatw.r}
11857 @emph{Activate warnings for object renaming function.}
11859 This switch activates warnings for an object renaming that renames a
11860 function call, which is equivalent to a constant declaration (as
11861 opposed to renaming the function itself).  The default is that these
11862 warnings are given.
11863 @end table
11865 @geindex -gnatwT (gcc)
11868 @table @asis
11870 @item @code{-gnatw.R}
11872 @emph{Suppress warnings for object renaming function.}
11874 This switch suppresses warnings for object renaming function.
11875 @end table
11877 @geindex -gnatws (gcc)
11880 @table @asis
11882 @item @code{-gnatws}
11884 @emph{Suppress all warnings.}
11886 This switch completely suppresses the
11887 output of all warning messages from the GNAT front end, including
11888 both warnings that can be controlled by switches described in this
11889 section, and those that are normally given unconditionally. The
11890 effect of this suppress action can only be cancelled by a subsequent
11891 use of the switch @emph{-gnatwn}.
11893 Note that switch @emph{-gnatws} does not suppress
11894 warnings from the @emph{gcc} back end.
11895 To suppress these back end warnings as well, use the switch @emph{-w}
11896 in addition to @emph{-gnatws}. Also this switch has no effect on the
11897 handling of style check messages.
11898 @end table
11900 @geindex -gnatw.s (gcc)
11902 @geindex Record Representation (component sizes)
11905 @table @asis
11907 @item @code{-gnatw.s}
11909 @emph{Activate warnings on overridden size clauses.}
11911 This switch activates warnings on component clauses in record
11912 representation clauses where the length given overrides that
11913 specified by an explicit size clause for the component type. A
11914 warning is similarly given in the array case if a specified
11915 component size overrides an explicit size clause for the array
11916 component type.
11917 @end table
11919 @geindex -gnatw.S (gcc)
11922 @table @asis
11924 @item @code{-gnatw.S}
11926 @emph{Suppress warnings on overridden size clauses.}
11928 This switch suppresses warnings on component clauses in record
11929 representation clauses that override size clauses, and similar
11930 warnings when an array component size overrides a size clause.
11931 @end table
11933 @geindex -gnatwt (gcc)
11935 @geindex Deactivated code
11936 @geindex warnings
11938 @geindex Deleted code
11939 @geindex warnings
11942 @table @asis
11944 @item @code{-gnatwt}
11946 @emph{Activate warnings for tracking of deleted conditional code.}
11948 This switch activates warnings for tracking of code in conditionals (IF and
11949 CASE statements) that is detected to be dead code which cannot be executed, and
11950 which is removed by the front end. This warning is off by default. This may be
11951 useful for detecting deactivated code in certified applications.
11952 @end table
11954 @geindex -gnatwT (gcc)
11957 @table @asis
11959 @item @code{-gnatwT}
11961 @emph{Suppress warnings for tracking of deleted conditional code.}
11963 This switch suppresses warnings for tracking of deleted conditional code.
11964 @end table
11966 @geindex -gnatw.t (gcc)
11969 @table @asis
11971 @item @code{-gnatw.t}
11973 @emph{Activate warnings on suspicious contracts.}
11975 This switch activates warnings on suspicious contracts. This includes
11976 warnings on suspicious postconditions (whether a pragma @cite{Postcondition} or a
11977 @cite{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
11978 @cite{Contract_Cases}). A function postcondition or contract case is suspicious
11979 when no postcondition or contract case for this function mentions the result
11980 of the function.  A procedure postcondition or contract case is suspicious
11981 when it only refers to the pre-state of the procedure, because in that case
11982 it should rather be expressed as a precondition. This switch also controls
11983 warnings on suspicious cases of expressions typically found in contracts like
11984 quantified expressions and uses of Update attribute. The default is that such
11985 warnings are generated.
11986 @end table
11988 @geindex -gnatw.T (gcc)
11991 @table @asis
11993 @item @code{-gnatw.T}
11995 @emph{Suppress warnings on suspicious contracts.}
11997 This switch suppresses warnings on suspicious contracts.
11998 @end table
12000 @geindex -gnatwu (gcc)
12003 @table @asis
12005 @item @code{-gnatwu}
12007 @emph{Activate warnings on unused entities.}
12009 This switch activates warnings to be generated for entities that
12010 are declared but not referenced, and for units that are @emph{with}ed
12011 and not
12012 referenced. In the case of packages, a warning is also generated if
12013 no entities in the package are referenced. This means that if a with'ed
12014 package is referenced but the only references are in @cite{use}
12015 clauses or @cite{renames}
12016 declarations, a warning is still generated. A warning is also generated
12017 for a generic package that is @emph{with}ed but never instantiated.
12018 In the case where a package or subprogram body is compiled, and there
12019 is a @emph{with} on the corresponding spec
12020 that is only referenced in the body,
12021 a warning is also generated, noting that the
12022 @emph{with} can be moved to the body. The default is that
12023 such warnings are not generated.
12024 This switch also activates warnings on unreferenced formals
12025 (it includes the effect of @emph{-gnatwf}).
12026 @end table
12028 @geindex -gnatwU (gcc)
12031 @table @asis
12033 @item @code{-gnatwU}
12035 @emph{Suppress warnings on unused entities.}
12037 This switch suppresses warnings for unused entities and packages.
12038 It also turns off warnings on unreferenced formals (and thus includes
12039 the effect of @emph{-gnatwF}).
12040 @end table
12042 @geindex -gnatw.u (gcc)
12045 @table @asis
12047 @item @code{-gnatw.u}
12049 @emph{Activate warnings on unordered enumeration types.}
12051 This switch causes enumeration types to be considered as conceptually
12052 unordered, unless an explicit pragma @cite{Ordered} is given for the type.
12053 The effect is to generate warnings in clients that use explicit comparisons
12054 or subranges, since these constructs both treat objects of the type as
12055 ordered. (A @emph{client} is defined as a unit that is other than the unit in
12056 which the type is declared, or its body or subunits.) Please refer to
12057 the description of pragma @cite{Ordered} in the
12058 @cite{GNAT Reference Manual} for further details.
12059 The default is that such warnings are not generated.
12060 @end table
12062 @geindex -gnatw.U (gcc)
12065 @table @asis
12067 @item @code{-gnatw.U}
12069 @emph{Deactivate warnings on unordered enumeration types.}
12071 This switch causes all enumeration types to be considered as ordered, so
12072 that no warnings are given for comparisons or subranges for any type.
12073 @end table
12075 @geindex -gnatwv (gcc)
12077 @geindex Unassigned variable warnings
12080 @table @asis
12082 @item @code{-gnatwv}
12084 @emph{Activate warnings on unassigned variables.}
12086 This switch activates warnings for access to variables which
12087 may not be properly initialized. The default is that
12088 such warnings are generated.
12089 @end table
12091 @geindex -gnatwV (gcc)
12094 @table @asis
12096 @item @code{-gnatwV}
12098 @emph{Suppress warnings on unassigned variables.}
12100 This switch suppresses warnings for access to variables which
12101 may not be properly initialized.
12102 For variables of a composite type, the warning can also be suppressed in
12103 Ada 2005 by using a default initialization with a box. For example, if
12104 Table is an array of records whose components are only partially uninitialized,
12105 then the following code:
12107 @example
12108 Tab : Table := (others => <>);
12109 @end example
12111 will suppress warnings on subsequent statements that access components
12112 of variable Tab.
12113 @end table
12115 @geindex -gnatw.v (gcc)
12117 @geindex bit order warnings
12120 @table @asis
12122 @item @code{-gnatw.v}
12124 @emph{Activate info messages for non-default bit order.}
12126 This switch activates messages (labeled "info", they are not warnings,
12127 just informational messages) about the effects of non-default bit-order
12128 on records to which a component clause is applied. The effect of specifying
12129 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12130 these messages, which are given by default, are useful in understanding the
12131 exact consequences of using this feature.
12132 @end table
12134 @geindex -gnatw.V (gcc)
12137 @table @asis
12139 @item @code{-gnatw.V}
12141 @emph{Suppress info messages for non-default bit order.}
12143 This switch suppresses information messages for the effects of specifying
12144 non-default bit order on record components with component clauses.
12145 @end table
12147 @geindex -gnatww (gcc)
12149 @geindex String indexing warnings
12152 @table @asis
12154 @item @code{-gnatww}
12156 @emph{Activate warnings on wrong low bound assumption.}
12158 This switch activates warnings for indexing an unconstrained string parameter
12159 with a literal or S'Length. This is a case where the code is assuming that the
12160 low bound is one, which is in general not true (for example when a slice is
12161 passed). The default is that such warnings are generated.
12162 @end table
12164 @geindex -gnatwW (gcc)
12167 @table @asis
12169 @item @code{-gnatwW}
12171 @emph{Suppress warnings on wrong low bound assumption.}
12173 This switch suppresses warnings for indexing an unconstrained string parameter
12174 with a literal or S'Length. Note that this warning can also be suppressed
12175 in a particular case by adding an assertion that the lower bound is 1,
12176 as shown in the following example:
12178 @example
12179 procedure K (S : String) is
12180    pragma Assert (S'First = 1);
12181    ...
12182 @end example
12183 @end table
12185 @geindex -gnatw.w (gcc)
12187 @geindex Warnings Off control
12190 @table @asis
12192 @item @code{-gnatw.w}
12194 @emph{Activate warnings on Warnings Off pragmas.}
12196 This switch activates warnings for use of @cite{pragma Warnings (Off@comma{} entity)}
12197 where either the pragma is entirely useless (because it suppresses no
12198 warnings), or it could be replaced by @cite{pragma Unreferenced} or
12199 @cite{pragma Unmodified}.
12200 Also activates warnings for the case of
12201 Warnings (Off, String), where either there is no matching
12202 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12203 The default is that these warnings are not given.
12204 @end table
12206 @geindex -gnatw.W (gcc)
12209 @table @asis
12211 @item @code{-gnatw.W}
12213 @emph{Suppress warnings on unnecessary Warnings Off pragmas.}
12215 This switch suppresses warnings for use of @cite{pragma Warnings (Off@comma{} ...)}.
12216 @end table
12218 @geindex -gnatwx (gcc)
12220 @geindex Export/Import pragma warnings
12223 @table @asis
12225 @item @code{-gnatwx}
12227 @emph{Activate warnings on Export/Import pragmas.}
12229 This switch activates warnings on Export/Import pragmas when
12230 the compiler detects a possible conflict between the Ada and
12231 foreign language calling sequences. For example, the use of
12232 default parameters in a convention C procedure is dubious
12233 because the C compiler cannot supply the proper default, so
12234 a warning is issued. The default is that such warnings are
12235 generated.
12236 @end table
12238 @geindex -gnatwX (gcc)
12241 @table @asis
12243 @item @code{-gnatwX}
12245 @emph{Suppress warnings on Export/Import pragmas.}
12247 This switch suppresses warnings on Export/Import pragmas.
12248 The sense of this is that you are telling the compiler that
12249 you know what you are doing in writing the pragma, and it
12250 should not complain at you.
12251 @end table
12253 @geindex -gnatwm (gcc)
12256 @table @asis
12258 @item @code{-gnatw.x}
12260 @emph{Activate warnings for No_Exception_Propagation mode.}
12262 This switch activates warnings for exception usage when pragma Restrictions
12263 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
12264 explicit exception raises which are not covered by a local handler, and for
12265 exception handlers which do not cover a local raise. The default is that these
12266 warnings are not given.
12268 @item @code{-gnatw.X}
12270 @emph{Disable warnings for No_Exception_Propagation mode.}
12272 This switch disables warnings for exception usage when pragma Restrictions
12273 (No_Exception_Propagation) is in effect.
12274 @end table
12276 @geindex -gnatwy (gcc)
12278 @geindex Ada compatibility issues warnings
12281 @table @asis
12283 @item @code{-gnatwy}
12285 @emph{Activate warnings for Ada compatibility issues.}
12287 For the most part, newer versions of Ada are upwards compatible
12288 with older versions. For example, Ada 2005 programs will almost
12289 always work when compiled as Ada 2012.
12290 However there are some exceptions (for example the fact that
12291 @cite{some} is now a reserved word in Ada 2012). This
12292 switch activates several warnings to help in identifying
12293 and correcting such incompatibilities. The default is that
12294 these warnings are generated. Note that at one point Ada 2005
12295 was called Ada 0Y, hence the choice of character.
12296 @end table
12298 @geindex -gnatwY (gcc)
12300 @geindex Ada compatibility issues warnings
12303 @table @asis
12305 @item @code{-gnatwY}
12307 @emph{Disable warnings for Ada compatibility issues.}
12309 This switch suppresses the warnings intended to help in identifying
12310 incompatibilities between Ada language versions.
12311 @end table
12313 @geindex -gnatw.y (gcc)
12315 @geindex Package spec needing body
12318 @table @asis
12320 @item @code{-gnatw.y}
12322 @emph{Activate information messages for why package spec needs body.}
12324 There are a number of cases in which a package spec needs a body.
12325 For example, the use of pragma Elaborate_Body, or the declaration
12326 of a procedure specification requiring a completion. This switch
12327 causes information messages to be output showing why a package
12328 specification requires a body. This can be useful in the case of
12329 a large package specification which is unexpectedly requiring a
12330 body. The default is that such information messages are not output.
12331 @end table
12333 @geindex -gnatw.Y (gcc)
12335 @geindex No information messages for why package spec needs body
12338 @table @asis
12340 @item @code{-gnatw.Y}
12342 @emph{Disable information messages for why package spec needs body.}
12344 This switch suppresses the output of information messages showing why
12345 a package specification needs a body.
12346 @end table
12348 @geindex -gnatwz (gcc)
12350 @geindex Unchecked_Conversion warnings
12353 @table @asis
12355 @item @code{-gnatwz}
12357 @emph{Activate warnings on unchecked conversions.}
12359 This switch activates warnings for unchecked conversions
12360 where the types are known at compile time to have different
12361 sizes. The default is that such warnings are generated. Warnings are also
12362 generated for subprogram pointers with different conventions.
12363 @end table
12365 @geindex -gnatwZ (gcc)
12368 @table @asis
12370 @item @code{-gnatwZ}
12372 @emph{Suppress warnings on unchecked conversions.}
12374 This switch suppresses warnings for unchecked conversions
12375 where the types are known at compile time to have different
12376 sizes or conventions.
12377 @end table
12379 @geindex -gnatw.z (gcc)
12381 @geindex Size/Alignment warnings
12384 @table @asis
12386 @item @code{-gnatw.z}
12388 @emph{Activate warnings for size not a multiple of alignment.}
12390 This switch activates warnings for cases of record types with
12391 specified @cite{Size} and @cite{Alignment} attributes where the
12392 size is not a multiple of the alignment, resulting in an object
12393 size that is greater than the specified size. The default
12394 is that such warnings are generated.
12395 @end table
12397 @geindex -gnatw.Z (gcc)
12399 @geindex Size/Alignment warnings
12402 @table @asis
12404 @item @code{-gnatw.Z}
12406 @emph{Suppress warnings for size not a multiple of alignment.}
12408 This switch suppresses warnings for cases of record types with
12409 specified @cite{Size} and @cite{Alignment} attributes where the
12410 size is not a multiple of the alignment, resulting in an object
12411 size that is greater than the specified size.
12412 The warning can also be
12413 suppressed by giving an explicit @cite{Object_Size} value.
12414 @end table
12416 @geindex -Wunused (gcc)
12419 @table @asis
12421 @item @code{-Wunused}
12423 The warnings controlled by the @emph{-gnatw} switch are generated by
12424 the front end of the compiler. The @emph{GCC} back end can provide
12425 additional warnings and they are controlled by the @emph{-W} switch.
12426 For example, @emph{-Wunused} activates back end
12427 warnings for entities that are declared but not referenced.
12428 @end table
12430 @geindex -Wuninitialized (gcc)
12433 @table @asis
12435 @item @code{-Wuninitialized}
12437 Similarly, @emph{-Wuninitialized} activates
12438 the back end warning for uninitialized variables. This switch must be
12439 used in conjunction with an optimization level greater than zero.
12440 @end table
12442 @geindex -Wstack-usage (gcc)
12445 @table @asis
12447 @item @code{-Wstack-usage=@emph{len}}
12449 Warn if the stack usage of a subprogram might be larger than @cite{len} bytes.
12450 See @ref{f5,,Static Stack Usage Analysis} for details.
12451 @end table
12453 @geindex -Wall (gcc)
12456 @table @asis
12458 @item @code{-Wall}
12460 This switch enables most warnings from the @emph{GCC} back end.
12461 The code generator detects a number of warning situations that are missed
12462 by the @emph{GNAT} front end, and this switch can be used to activate them.
12463 The use of this switch also sets the default front end warning mode to
12464 @emph{-gnatwa}, that is, most front end warnings activated as well.
12465 @end table
12467 @geindex -w (gcc)
12470 @table @asis
12472 @item @code{-w}
12474 Conversely, this switch suppresses warnings from the @emph{GCC} back end.
12475 The use of this switch also sets the default front end warning mode to
12476 @emph{-gnatws}, that is, front end warnings suppressed as well.
12477 @end table
12479 @geindex -Werror (gcc)
12482 @table @asis
12484 @item @code{-Werror}
12486 This switch causes warnings from the @emph{GCC} back end to be treated as
12487 errors.  The warning string still appears, but the warning messages are
12488 counted as errors, and prevent the generation of an object file.
12489 @end table
12491 A string of warning parameters can be used in the same parameter. For example:
12493 @example
12494 -gnatwaGe
12495 @end example
12497 will turn on all optional warnings except for unrecognized pragma warnings,
12498 and also specify that warnings should be treated as errors.
12500 When no switch @emph{-gnatw} is used, this is equivalent to:
12502 @quotation
12505 @itemize *
12507 @item 
12508 @code{-gnatw.a}
12510 @item 
12511 @code{-gnatwB}
12513 @item 
12514 @code{-gnatw.b}
12516 @item 
12517 @code{-gnatwC}
12519 @item 
12520 @code{-gnatw.C}
12522 @item 
12523 @code{-gnatwD}
12525 @item 
12526 @code{-gnatwF}
12528 @item 
12529 @code{-gnatwg}
12531 @item 
12532 @code{-gnatwH}
12534 @item 
12535 @code{-gnatwi}
12537 @item 
12538 @code{-gnatw.I}
12540 @item 
12541 @code{-gnatwJ}
12543 @item 
12544 @code{-gnatwK}
12546 @item 
12547 @code{-gnatwL}
12549 @item 
12550 @code{-gnatw.L}
12552 @item 
12553 @code{-gnatwM}
12555 @item 
12556 @code{-gnatw.m}
12558 @item 
12559 @code{-gnatwn}
12561 @item 
12562 @code{-gnatwo}
12564 @item 
12565 @code{-gnatw.O}
12567 @item 
12568 @code{-gnatwP}
12570 @item 
12571 @code{-gnatw.P}
12573 @item 
12574 @code{-gnatwq}
12576 @item 
12577 @code{-gnatwR}
12579 @item 
12580 @code{-gnatw.R}
12582 @item 
12583 @code{-gnatw.S}
12585 @item 
12586 @code{-gnatwT}
12588 @item 
12589 @code{-gnatw.T}
12591 @item 
12592 @code{-gnatwU}
12594 @item 
12595 @code{-gnatwv}
12597 @item 
12598 @code{-gnatww}
12600 @item 
12601 @code{-gnatw.W}
12603 @item 
12604 @code{-gnatwx}
12606 @item 
12607 @code{-gnatw.X}
12609 @item 
12610 @code{-gnatwy}
12612 @item 
12613 @code{-gnatwz}
12614 @end itemize
12615 @end quotation
12617 @node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12618 @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}
12619 @subsection Debugging and Assertion Control
12622 @geindex -gnata (gcc)
12625 @table @asis
12627 @item @code{-gnata}
12629 @geindex Assert
12631 @geindex Debug
12633 @geindex Assertions
12635 @geindex Precondition
12637 @geindex Postcondition
12639 @geindex Type invariants
12641 @geindex Subtype predicates
12643 The @cite{-gnata} option is equivalent to the following Assertion_Policy pragma:
12645 @example
12646 pragma Assertion_Policy (Check);
12647 @end example
12649 Which is a shorthand for:
12651 @example
12652 pragma Assertion_Policy
12653   (Assert               => Check,
12654    Static_Predicate     => Check,
12655    Dynamic_Predicate    => Check,
12656    Pre                  => Check,
12657    Pre'Class            => Check,
12658    Post                 => Check,
12659    Post'Class           => Check,
12660    Type_Invariant       => Check,
12661    Type_Invariant'Class => Check);
12662 @end example
12664 The pragmas @cite{Assert} and @cite{Debug} normally have no effect and
12665 are ignored. This switch, where @code{a} stands for assert, causes
12666 pragmas @cite{Assert} and @cite{Debug} to be activated. This switch also
12667 causes preconditions, postconditions, subtype predicates, and
12668 type invariants to be activated.
12670 The pragmas have the form:
12672 @example
12673 pragma Assert (<Boolean-expression> [, <static-string-expression>])
12674 pragma Debug (<procedure call>)
12675 pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
12676 pragma Predicate (<type-local-name>, <Boolean-expression>)
12677 pragma Precondition (<Boolean-expression>, <string-expression>)
12678 pragma Postcondition (<Boolean-expression>, <string-expression>)
12679 @end example
12681 The aspects have the form:
12683 @example
12684 with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
12685   => <Boolean-expression>;
12686 @end example
12688 The @cite{Assert} pragma causes @cite{Boolean-expression} to be tested.
12689 If the result is @cite{True}, the pragma has no effect (other than
12690 possible side effects from evaluating the expression). If the result is
12691 @cite{False}, the exception @cite{Assert_Failure} declared in the package
12692 @cite{System.Assertions} is raised (passing @cite{static-string-expression}, if
12693 present, as the message associated with the exception). If no string
12694 expression is given, the default is a string containing the file name and
12695 line number of the pragma.
12697 The @cite{Debug} pragma causes @cite{procedure} to be called. Note that
12698 @cite{pragma Debug} may appear within a declaration sequence, allowing
12699 debugging procedures to be called between declarations.
12701 For the aspect specification, the @cite{<Boolean-expression>} is evaluated.
12702 If the result is @cite{True}, the aspect has no effect. If the result
12703 is @cite{False}, the exception @cite{Assert_Failure} is raised.
12704 @end table
12706 @node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
12707 @anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{102}
12708 @subsection Validity Checking
12711 @geindex Validity Checking
12713 The Ada Reference Manual defines the concept of invalid values (see
12714 RM 13.9.1). The primary source of invalid values is uninitialized
12715 variables. A scalar variable that is left uninitialized may contain
12716 an invalid value; the concept of invalid does not apply to access or
12717 composite types.
12719 It is an error to read an invalid value, but the RM does not require
12720 run-time checks to detect such errors, except for some minimal
12721 checking to prevent erroneous execution (i.e. unpredictable
12722 behavior). This corresponds to the @emph{-gnatVd} switch below,
12723 which is the default. For example, by default, if the expression of a
12724 case statement is invalid, it will raise Constraint_Error rather than
12725 causing a wild jump, and if an array index on the left-hand side of an
12726 assignment is invalid, it will raise Constraint_Error rather than
12727 overwriting an arbitrary memory location.
12729 The @emph{-gnatVa} may be used to enable additional validity checks,
12730 which are not required by the RM. These checks are often very
12731 expensive (which is why the RM does not require them). These checks
12732 are useful in tracking down uninitialized variables, but they are
12733 not usually recommended for production builds, and in particular
12734 we do not recommend using these extra validity checking options in
12735 combination with optimization, since this can confuse the optimizer.
12736 If performance is a consideration, leading to the need to optimize,
12737 then the validity checking options should not be used.
12739 The other @emph{-gnatV}@code{x} switches below allow finer-grained
12740 control; you can enable whichever validity checks you desire. However,
12741 for most debugging purposes, @emph{-gnatVa} is sufficient, and the
12742 default @emph{-gnatVd} (i.e. standard Ada behavior) is usually
12743 sufficient for non-debugging use.
12745 The @emph{-gnatB} switch tells the compiler to assume that all
12746 values are valid (that is, within their declared subtype range)
12747 except in the context of a use of the Valid attribute. This means
12748 the compiler can generate more efficient code, since the range
12749 of values is better known at compile time. However, an uninitialized
12750 variable can cause wild jumps and memory corruption in this mode.
12752 The @emph{-gnatV}@code{x} switch allows control over the validity
12753 checking mode as described below.
12754 The @code{x} argument is a string of letters that
12755 indicate validity checks that are performed or not performed in addition
12756 to the default checks required by Ada as described above.
12758 @geindex -gnatVa (gcc)
12761 @table @asis
12763 @item @code{-gnatVa}
12765 @emph{All validity checks.}
12767 All validity checks are turned on.
12768 That is, @emph{-gnatVa} is
12769 equivalent to @emph{gnatVcdfimorst}.
12770 @end table
12772 @geindex -gnatVc (gcc)
12775 @table @asis
12777 @item @code{-gnatVc}
12779 @emph{Validity checks for copies.}
12781 The right hand side of assignments, and the initializing values of
12782 object declarations are validity checked.
12783 @end table
12785 @geindex -gnatVd (gcc)
12788 @table @asis
12790 @item @code{-gnatVd}
12792 @emph{Default (RM) validity checks.}
12794 Some validity checks are done by default following normal Ada semantics
12795 (RM 13.9.1 (9-11)).
12796 A check is done in case statements that the expression is within the range
12797 of the subtype. If it is not, Constraint_Error is raised.
12798 For assignments to array components, a check is done that the expression used
12799 as index is within the range. If it is not, Constraint_Error is raised.
12800 Both these validity checks may be turned off using switch @emph{-gnatVD}.
12801 They are turned on by default. If @emph{-gnatVD} is specified, a subsequent
12802 switch @emph{-gnatVd} will leave the checks turned on.
12803 Switch @emph{-gnatVD} should be used only if you are sure that all such
12804 expressions have valid values. If you use this switch and invalid values
12805 are present, then the program is erroneous, and wild jumps or memory
12806 overwriting may occur.
12807 @end table
12809 @geindex -gnatVe (gcc)
12812 @table @asis
12814 @item @code{-gnatVe}
12816 @emph{Validity checks for elementary components.}
12818 In the absence of this switch, assignments to record or array components are
12819 not validity checked, even if validity checks for assignments generally
12820 (@emph{-gnatVc}) are turned on. In Ada, assignment of composite values do not
12821 require valid data, but assignment of individual components does. So for
12822 example, there is a difference between copying the elements of an array with a
12823 slice assignment, compared to assigning element by element in a loop. This
12824 switch allows you to turn off validity checking for components, even when they
12825 are assigned component by component.
12826 @end table
12828 @geindex -gnatVf (gcc)
12831 @table @asis
12833 @item @code{-gnatVf}
12835 @emph{Validity checks for floating-point values.}
12837 In the absence of this switch, validity checking occurs only for discrete
12838 values. If @emph{-gnatVf} is specified, then validity checking also applies
12839 for floating-point values, and NaNs and infinities are considered invalid,
12840 as well as out of range values for constrained types. Note that this means
12841 that standard IEEE infinity mode is not allowed. The exact contexts
12842 in which floating-point values are checked depends on the setting of other
12843 options. For example, @emph{-gnatVif} or @emph{-gnatVfi}
12844 (the order does not matter) specifies that floating-point parameters of mode
12845 @cite{in} should be validity checked.
12846 @end table
12848 @geindex -gnatVi (gcc)
12851 @table @asis
12853 @item @code{-gnatVi}
12855 @emph{Validity checks for `in` mode parameters.}
12857 Arguments for parameters of mode @cite{in} are validity checked in function
12858 and procedure calls at the point of call.
12859 @end table
12861 @geindex -gnatVm (gcc)
12864 @table @asis
12866 @item @code{-gnatVm}
12868 @emph{Validity checks for `in out` mode parameters.}
12870 Arguments for parameters of mode @cite{in out} are validity checked in
12871 procedure calls at the point of call. The @cite{'m'} here stands for
12872 modify, since this concerns parameters that can be modified by the call.
12873 Note that there is no specific option to test @cite{out} parameters,
12874 but any reference within the subprogram will be tested in the usual
12875 manner, and if an invalid value is copied back, any reference to it
12876 will be subject to validity checking.
12877 @end table
12879 @geindex -gnatVn (gcc)
12882 @table @asis
12884 @item @code{-gnatVn}
12886 @emph{No validity checks.}
12888 This switch turns off all validity checking, including the default checking
12889 for case statements and left hand side subscripts. Note that the use of
12890 the switch @emph{-gnatp} suppresses all run-time checks, including
12891 validity checks, and thus implies @emph{-gnatVn}. When this switch
12892 is used, it cancels any other @emph{-gnatV} previously issued.
12893 @end table
12895 @geindex -gnatVo (gcc)
12898 @table @asis
12900 @item @code{-gnatVo}
12902 @emph{Validity checks for operator and attribute operands.}
12904 Arguments for predefined operators and attributes are validity checked.
12905 This includes all operators in package @cite{Standard},
12906 the shift operators defined as intrinsic in package @cite{Interfaces}
12907 and operands for attributes such as @cite{Pos}. Checks are also made
12908 on individual component values for composite comparisons, and on the
12909 expressions in type conversions and qualified expressions. Checks are
12910 also made on explicit ranges using @code{..} (e.g., slices, loops etc).
12911 @end table
12913 @geindex -gnatVp (gcc)
12916 @table @asis
12918 @item @code{-gnatVp}
12920 @emph{Validity checks for parameters.}
12922 This controls the treatment of parameters within a subprogram (as opposed
12923 to @emph{-gnatVi} and @emph{-gnatVm} which control validity testing
12924 of parameters on a call. If either of these call options is used, then
12925 normally an assumption is made within a subprogram that the input arguments
12926 have been validity checking at the point of call, and do not need checking
12927 again within a subprogram). If @emph{-gnatVp} is set, then this assumption
12928 is not made, and parameters are not assumed to be valid, so their validity
12929 will be checked (or rechecked) within the subprogram.
12930 @end table
12932 @geindex -gnatVr (gcc)
12935 @table @asis
12937 @item @code{-gnatVr}
12939 @emph{Validity checks for function returns.}
12941 The expression in @cite{return} statements in functions is validity
12942 checked.
12943 @end table
12945 @geindex -gnatVs (gcc)
12948 @table @asis
12950 @item @code{-gnatVs}
12952 @emph{Validity checks for subscripts.}
12954 All subscripts expressions are checked for validity, whether they appear
12955 on the right side or left side (in default mode only left side subscripts
12956 are validity checked).
12957 @end table
12959 @geindex -gnatVt (gcc)
12962 @table @asis
12964 @item @code{-gnatVt}
12966 @emph{Validity checks for tests.}
12968 Expressions used as conditions in @cite{if}, @cite{while} or @cite{exit}
12969 statements are checked, as well as guard expressions in entry calls.
12970 @end table
12972 The @emph{-gnatV} switch may be followed by a string of letters
12973 to turn on a series of validity checking options.
12974 For example, @code{-gnatVcr}
12975 specifies that in addition to the default validity checking, copies and
12976 function return expressions are to be validity checked.
12977 In order to make it easier to specify the desired combination of effects,
12978 the upper case letters @cite{CDFIMORST} may
12979 be used to turn off the corresponding lower case option.
12980 Thus @code{-gnatVaM} turns on all validity checking options except for
12981 checking of @cite{**in out**} procedure arguments.
12983 The specification of additional validity checking generates extra code (and
12984 in the case of @emph{-gnatVa} the code expansion can be substantial).
12985 However, these additional checks can be very useful in detecting
12986 uninitialized variables, incorrect use of unchecked conversion, and other
12987 errors leading to invalid values. The use of pragma @cite{Initialize_Scalars}
12988 is useful in conjunction with the extra validity checking, since this
12989 ensures that wherever possible uninitialized variables have invalid values.
12991 See also the pragma @cite{Validity_Checks} which allows modification of
12992 the validity checking mode at the program source level, and also allows for
12993 temporary disabling of validity checks.
12995 @node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
12996 @anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{103}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{fb}
12997 @subsection Style Checking
13000 @geindex Style checking
13002 @geindex -gnaty (gcc)
13004 The @emph{-gnatyx} switch causes the compiler to
13005 enforce specified style rules. A limited set of style rules has been used
13006 in writing the GNAT sources themselves. This switch allows user programs
13007 to activate all or some of these checks. If the source program fails a
13008 specified style check, an appropriate message is given, preceded by
13009 the character sequence '(style)'. This message does not prevent
13010 successful compilation (unless the @emph{-gnatwe} switch is used).
13012 Note that this is by no means intended to be a general facility for
13013 checking arbitrary coding standards. It is simply an embedding of the
13014 style rules we have chosen for the GNAT sources. If you are starting
13015 a project which does not have established style standards, you may
13016 find it useful to adopt the entire set of GNAT coding standards, or
13017 some subset of them.
13020 The string @cite{x} is a sequence of letters or digits
13021 indicating the particular style
13022 checks to be performed. The following checks are defined:
13024 @geindex -gnaty[0-9] (gcc)
13027 @table @asis
13029 @item @code{-gnaty0}
13031 @emph{Specify indentation level.}
13033 If a digit from 1-9 appears
13034 in the string after @emph{-gnaty}
13035 then proper indentation is checked, with the digit indicating the
13036 indentation level required. A value of zero turns off this style check.
13037 The general style of required indentation is as specified by
13038 the examples in the Ada Reference Manual. Full line comments must be
13039 aligned with the @cite{--} starting on a column that is a multiple of
13040 the alignment level, or they may be aligned the same way as the following
13041 non-blank line (this is useful when full line comments appear in the middle
13042 of a statement, or they may be aligned with the source line on the previous
13043 non-blank line.
13044 @end table
13046 @geindex -gnatya (gcc)
13049 @table @asis
13051 @item @code{-gnatya}
13053 @emph{Check attribute casing.}
13055 Attribute names, including the case of keywords such as @cite{digits}
13056 used as attributes names, must be written in mixed case, that is, the
13057 initial letter and any letter following an underscore must be uppercase.
13058 All other letters must be lowercase.
13059 @end table
13061 @geindex -gnatyA (gcc)
13064 @table @asis
13066 @item @code{-gnatyA}
13068 @emph{Use of array index numbers in array attributes.}
13070 When using the array attributes First, Last, Range,
13071 or Length, the index number must be omitted for one-dimensional arrays
13072 and is required for multi-dimensional arrays.
13073 @end table
13075 @geindex -gnatyb (gcc)
13078 @table @asis
13080 @item @code{-gnatyb}
13082 @emph{Blanks not allowed at statement end.}
13084 Trailing blanks are not allowed at the end of statements. The purpose of this
13085 rule, together with h (no horizontal tabs), is to enforce a canonical format
13086 for the use of blanks to separate source tokens.
13087 @end table
13089 @geindex -gnatyB (gcc)
13092 @table @asis
13094 @item @code{-gnatyB}
13096 @emph{Check Boolean operators.}
13098 The use of AND/OR operators is not permitted except in the cases of modular
13099 operands, array operands, and simple stand-alone boolean variables or
13100 boolean constants. In all other cases @cite{and then}/@cite{or else} are
13101 required.
13102 @end table
13104 @geindex -gnatyc (gcc)
13107 @table @asis
13109 @item @code{-gnatyc}
13111 @emph{Check comments, double space.}
13113 Comments must meet the following set of rules:
13116 @itemize *
13118 @item 
13119 The '@cite{--}' that starts the column must either start in column one,
13120 or else at least one blank must precede this sequence.
13122 @item 
13123 Comments that follow other tokens on a line must have at least one blank
13124 following the '@cite{--}' at the start of the comment.
13126 @item 
13127 Full line comments must have at least two blanks following the
13128 '@cite{--}' that starts the comment, with the following exceptions.
13130 @item 
13131 A line consisting only of the '@cite{--}' characters, possibly preceded
13132 by blanks is permitted.
13134 @item 
13135 A comment starting with '@cite{--x}' where @cite{x} is a special character
13136 is permitted.
13137 This allows proper processing of the output generated by specialized tools
13138 including @emph{gnatprep} (where '@cite{--!}' is used) and the SPARK
13139 annotation
13140 language (where '@cite{--#}' is used). For the purposes of this rule, a
13141 special character is defined as being in one of the ASCII ranges
13142 @cite{16#21#...16#2F#} or @cite{16#3A#...16#3F#}.
13143 Note that this usage is not permitted
13144 in GNAT implementation units (i.e., when @emph{-gnatg} is used).
13146 @item 
13147 A line consisting entirely of minus signs, possibly preceded by blanks, is
13148 permitted. This allows the construction of box comments where lines of minus
13149 signs are used to form the top and bottom of the box.
13151 @item 
13152 A comment that starts and ends with '@cite{--}' is permitted as long as at
13153 least one blank follows the initial '@cite{--}'. Together with the preceding
13154 rule, this allows the construction of box comments, as shown in the following
13155 example:
13157 @example
13158 ---------------------------
13159 -- This is a box comment --
13160 -- with two text lines.  --
13161 ---------------------------
13162 @end example
13163 @end itemize
13164 @end table
13166 @geindex -gnatyC (gcc)
13169 @table @asis
13171 @item @code{-gnatyC}
13173 @emph{Check comments, single space.}
13175 This is identical to @cite{c} except that only one space
13176 is required following the @cite{--} of a comment instead of two.
13177 @end table
13179 @geindex -gnatyd (gcc)
13182 @table @asis
13184 @item @code{-gnatyd}
13186 @emph{Check no DOS line terminators present.}
13188 All lines must be terminated by a single ASCII.LF
13189 character (in particular the DOS line terminator sequence CR/LF is not
13190 allowed).
13191 @end table
13193 @geindex -gnatye (gcc)
13196 @table @asis
13198 @item @code{-gnatye}
13200 @emph{Check end/exit labels.}
13202 Optional labels on @cite{end} statements ending subprograms and on
13203 @cite{exit} statements exiting named loops, are required to be present.
13204 @end table
13206 @geindex -gnatyf (gcc)
13209 @table @asis
13211 @item @code{-gnatyf}
13213 @emph{No form feeds or vertical tabs.}
13215 Neither form feeds nor vertical tab characters are permitted
13216 in the source text.
13217 @end table
13219 @geindex -gnatyg (gcc)
13222 @table @asis
13224 @item @code{-gnatyg}
13226 @emph{GNAT style mode.}
13228 The set of style check switches is set to match that used by the GNAT sources.
13229 This may be useful when developing code that is eventually intended to be
13230 incorporated into GNAT. Currently this is equivalent to @emph{-gnatwydISux})
13231 but additional style switches may be added to this set in the future without
13232 advance notice.
13233 @end table
13235 @geindex -gnatyh (gcc)
13238 @table @asis
13240 @item @code{-gnatyh}
13242 @emph{No horizontal tabs.}
13244 Horizontal tab characters are not permitted in the source text.
13245 Together with the b (no blanks at end of line) check, this
13246 enforces a canonical form for the use of blanks to separate
13247 source tokens.
13248 @end table
13250 @geindex -gnatyi (gcc)
13253 @table @asis
13255 @item @code{-gnatyi}
13257 @emph{Check if-then layout.}
13259 The keyword @cite{then} must appear either on the same
13260 line as corresponding @cite{if}, or on a line on its own, lined
13261 up under the @cite{if}.
13262 @end table
13264 @geindex -gnatyI (gcc)
13267 @table @asis
13269 @item @code{-gnatyI}
13271 @emph{check mode IN keywords.}
13273 Mode @cite{in} (the default mode) is not
13274 allowed to be given explicitly. @cite{in out} is fine,
13275 but not @cite{in} on its own.
13276 @end table
13278 @geindex -gnatyk (gcc)
13281 @table @asis
13283 @item @code{-gnatyk}
13285 @emph{Check keyword casing.}
13287 All keywords must be in lower case (with the exception of keywords
13288 such as @cite{digits} used as attribute names to which this check
13289 does not apply).
13290 @end table
13292 @geindex -gnatyl (gcc)
13295 @table @asis
13297 @item @code{-gnatyl}
13299 @emph{Check layout.}
13301 Layout of statement and declaration constructs must follow the
13302 recommendations in the Ada Reference Manual, as indicated by the
13303 form of the syntax rules. For example an @cite{else} keyword must
13304 be lined up with the corresponding @cite{if} keyword.
13306 There are two respects in which the style rule enforced by this check
13307 option are more liberal than those in the Ada Reference Manual. First
13308 in the case of record declarations, it is permissible to put the
13309 @cite{record} keyword on the same line as the @cite{type} keyword, and
13310 then the @cite{end} in @cite{end record} must line up under @cite{type}.
13311 This is also permitted when the type declaration is split on two lines.
13312 For example, any of the following three layouts is acceptable:
13314 @example
13315 type q is record
13316    a : integer;
13317    b : integer;
13318 end record;
13320 type q is
13321    record
13322       a : integer;
13323       b : integer;
13324    end record;
13326 type q is
13327    record
13328       a : integer;
13329       b : integer;
13330 end record;
13331 @end example
13333 Second, in the case of a block statement, a permitted alternative
13334 is to put the block label on the same line as the @cite{declare} or
13335 @cite{begin} keyword, and then line the @cite{end} keyword up under
13336 the block label. For example both the following are permitted:
13338 @example
13339 Block : declare
13340    A : Integer := 3;
13341 begin
13342    Proc (A, A);
13343 end Block;
13345 Block :
13346    declare
13347       A : Integer := 3;
13348    begin
13349       Proc (A, A);
13350    end Block;
13351 @end example
13353 The same alternative format is allowed for loops. For example, both of
13354 the following are permitted:
13356 @example
13357 Clear : while J < 10 loop
13358    A (J) := 0;
13359 end loop Clear;
13361 Clear :
13362    while J < 10 loop
13363       A (J) := 0;
13364    end loop Clear;
13365 @end example
13366 @end table
13368 @geindex -gnatyLnnn (gcc)
13371 @table @asis
13373 @item @code{-gnatyL}
13375 @emph{Set maximum nesting level.}
13377 The maximum level of nesting of constructs (including subprograms, loops,
13378 blocks, packages, and conditionals) may not exceed the given value
13379 @emph{nnn}. A value of zero disconnects this style check.
13380 @end table
13382 @geindex -gnatym (gcc)
13385 @table @asis
13387 @item @code{-gnatym}
13389 @emph{Check maximum line length.}
13391 The length of source lines must not exceed 79 characters, including
13392 any trailing blanks. The value of 79 allows convenient display on an
13393 80 character wide device or window, allowing for possible special
13394 treatment of 80 character lines. Note that this count is of
13395 characters in the source text. This means that a tab character counts
13396 as one character in this count and a wide character sequence counts as
13397 a single character (however many bytes are needed in the encoding).
13398 @end table
13400 @geindex -gnatyMnnn (gcc)
13403 @table @asis
13405 @item @code{-gnatyM}
13407 @emph{Set maximum line length.}
13409 The length of lines must not exceed the
13410 given value @emph{nnn}. The maximum value that can be specified is 32767.
13411 If neither style option for setting the line length is used, then the
13412 default is 255. This also controls the maximum length of lexical elements,
13413 where the only restriction is that they must fit on a single line.
13414 @end table
13416 @geindex -gnatyn (gcc)
13419 @table @asis
13421 @item @code{-gnatyn}
13423 @emph{Check casing of entities in Standard.}
13425 Any identifier from Standard must be cased
13426 to match the presentation in the Ada Reference Manual (for example,
13427 @cite{Integer} and @cite{ASCII.NUL}).
13428 @end table
13430 @geindex -gnatyN (gcc)
13433 @table @asis
13435 @item @code{-gnatyN}
13437 @emph{Turn off all style checks.}
13439 All style check options are turned off.
13440 @end table
13442 @geindex -gnatyo (gcc)
13445 @table @asis
13447 @item @code{-gnatyo}
13449 @emph{Check order of subprogram bodies.}
13451 All subprogram bodies in a given scope
13452 (e.g., a package body) must be in alphabetical order. The ordering
13453 rule uses normal Ada rules for comparing strings, ignoring casing
13454 of letters, except that if there is a trailing numeric suffix, then
13455 the value of this suffix is used in the ordering (e.g., Junk2 comes
13456 before Junk10).
13457 @end table
13459 @geindex -gnatyO (gcc)
13462 @table @asis
13464 @item @code{-gnatyO}
13466 @emph{Check that overriding subprograms are explicitly marked as such.}
13468 This applies to all subprograms of a derived type that override a primitive
13469 operation of the type, for both tagged and untagged types. In particular,
13470 the declaration of a primitive operation of a type extension that overrides
13471 an inherited operation must carry an overriding indicator. Another case is
13472 the declaration of a function that overrides a predefined operator (such
13473 as an equality operator).
13474 @end table
13476 @geindex -gnatyp (gcc)
13479 @table @asis
13481 @item @code{-gnatyp}
13483 @emph{Check pragma casing.}
13485 Pragma names must be written in mixed case, that is, the
13486 initial letter and any letter following an underscore must be uppercase.
13487 All other letters must be lowercase. An exception is that SPARK_Mode is
13488 allowed as an alternative for Spark_Mode.
13489 @end table
13491 @geindex -gnatyr (gcc)
13494 @table @asis
13496 @item @code{-gnatyr}
13498 @emph{Check references.}
13500 All identifier references must be cased in the same way as the
13501 corresponding declaration. No specific casing style is imposed on
13502 identifiers. The only requirement is for consistency of references
13503 with declarations.
13504 @end table
13506 @geindex -gnatys (gcc)
13509 @table @asis
13511 @item @code{-gnatys}
13513 @emph{Check separate specs.}
13515 Separate declarations ('specs') are required for subprograms (a
13516 body is not allowed to serve as its own declaration). The only
13517 exception is that parameterless library level procedures are
13518 not required to have a separate declaration. This exception covers
13519 the most frequent form of main program procedures.
13520 @end table
13522 @geindex -gnatyS (gcc)
13525 @table @asis
13527 @item @code{-gnatyS}
13529 @emph{Check no statements after then/else.}
13531 No statements are allowed
13532 on the same line as a @cite{then} or @cite{else} keyword following the
13533 keyword in an @cite{if} statement. @cite{or else} and @cite{and then} are not
13534 affected, and a special exception allows a pragma to appear after @cite{else}.
13535 @end table
13537 @geindex -gnatyt (gcc)
13540 @table @asis
13542 @item @code{-gnatyt}
13544 @emph{Check token spacing.}
13546 The following token spacing rules are enforced:
13549 @itemize *
13551 @item 
13552 The keywords @cite{abs} and @cite{not} must be followed by a space.
13554 @item 
13555 The token @cite{=>} must be surrounded by spaces.
13557 @item 
13558 The token @cite{<>} must be preceded by a space or a left parenthesis.
13560 @item 
13561 Binary operators other than @cite{**} must be surrounded by spaces.
13562 There is no restriction on the layout of the @cite{**} binary operator.
13564 @item 
13565 Colon must be surrounded by spaces.
13567 @item 
13568 Colon-equal (assignment, initialization) must be surrounded by spaces.
13570 @item 
13571 Comma must be the first non-blank character on the line, or be
13572 immediately preceded by a non-blank character, and must be followed
13573 by a space.
13575 @item 
13576 If the token preceding a left parenthesis ends with a letter or digit, then
13577 a space must separate the two tokens.
13579 @item 
13580 If the token following a right parenthesis starts with a letter or digit, then
13581 a space must separate the two tokens.
13583 @item 
13584 A right parenthesis must either be the first non-blank character on
13585 a line, or it must be preceded by a non-blank character.
13587 @item 
13588 A semicolon must not be preceded by a space, and must not be followed by
13589 a non-blank character.
13591 @item 
13592 A unary plus or minus may not be followed by a space.
13594 @item 
13595 A vertical bar must be surrounded by spaces.
13596 @end itemize
13598 Exactly one blank (and no other white space) must appear between
13599 a @cite{not} token and a following @cite{in} token.
13600 @end table
13602 @geindex -gnatyu (gcc)
13605 @table @asis
13607 @item @code{-gnatyu}
13609 @emph{Check unnecessary blank lines.}
13611 Unnecessary blank lines are not allowed. A blank line is considered
13612 unnecessary if it appears at the end of the file, or if more than
13613 one blank line occurs in sequence.
13614 @end table
13616 @geindex -gnatyx (gcc)
13619 @table @asis
13621 @item @code{-gnatyx}
13623 @emph{Check extra parentheses.}
13625 Unnecessary extra level of parentheses (C-style) are not allowed
13626 around conditions in @cite{if} statements, @cite{while} statements and
13627 @cite{exit} statements.
13628 @end table
13630 @geindex -gnatyy (gcc)
13633 @table @asis
13635 @item @code{-gnatyy}
13637 @emph{Set all standard style check options.}
13639 This is equivalent to @cite{gnaty3aAbcefhiklmnprst}, that is all checking
13640 options enabled with the exception of @emph{-gnatyB}, @emph{-gnatyd},
13641 @emph{-gnatyI}, @emph{-gnatyLnnn}, @emph{-gnatyo}, @emph{-gnatyO},
13642 @emph{-gnatyS}, @emph{-gnatyu}, and @emph{-gnatyx}.
13643 @end table
13645 @geindex -gnaty- (gcc)
13648 @table @asis
13650 @item @code{-gnaty-}
13652 @emph{Remove style check options.}
13654 This causes any subsequent options in the string to act as canceling the
13655 corresponding style check option. To cancel maximum nesting level control,
13656 use @emph{L} parameter witout any integer value after that, because any
13657 digit following @emph{-} in the parameter string of the @emph{-gnaty}
13658 option will be threated as canceling indentation check. The same is true
13659 for @emph{M} parameter. @emph{y} and @emph{N} parameters are not
13660 allowed after @emph{-}.
13661 @end table
13663 @geindex -gnaty+ (gcc)
13666 @table @asis
13668 @item @code{-gnaty+}
13670 @emph{Enable style check options.}
13672 This causes any subsequent options in the string to enable the corresponding
13673 style check option. That is, it cancels the effect of a previous -,
13674 if any.
13675 @end table
13677 @c end of switch description (leave this comment to ease automatic parsing for
13679 @c GPS
13681 In the above rules, appearing in column one is always permitted, that is,
13682 counts as meeting either a requirement for a required preceding space,
13683 or as meeting a requirement for no preceding space.
13685 Appearing at the end of a line is also always permitted, that is, counts
13686 as meeting either a requirement for a following space, or as meeting
13687 a requirement for no following space.
13689 If any of these style rules is violated, a message is generated giving
13690 details on the violation. The initial characters of such messages are
13691 always '@cite{(style)}'. Note that these messages are treated as warning
13692 messages, so they normally do not prevent the generation of an object
13693 file. The @emph{-gnatwe} switch can be used to treat warning messages,
13694 including style messages, as fatal errors.
13696 The switch @code{-gnaty} on its own (that is not
13697 followed by any letters or digits) is equivalent
13698 to the use of @emph{-gnatyy} as described above, that is all
13699 built-in standard style check options are enabled.
13701 The switch @code{-gnatyN} clears any previously set style checks.
13703 @node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
13704 @anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{f9}@anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{104}
13705 @subsection Run-Time Checks
13708 @geindex Division by zero
13710 @geindex Access before elaboration
13712 @geindex Checks
13713 @geindex division by zero
13715 @geindex Checks
13716 @geindex access before elaboration
13718 @geindex Checks
13719 @geindex stack overflow checking
13721 By default, the following checks are suppressed: stack overflow
13722 checks, and checks for access before elaboration on subprogram
13723 calls. All other checks, including overflow checks, range checks and
13724 array bounds checks, are turned on by default. The following @emph{gcc}
13725 switches refine this default behavior.
13727 @geindex -gnatp (gcc)
13730 @table @asis
13732 @item @code{-gnatp}
13734 @geindex Suppressing checks
13736 @geindex Checks
13737 @geindex suppressing
13739 This switch causes the unit to be compiled
13740 as though @cite{pragma Suppress (All_checks)}
13741 had been present in the source. Validity checks are also eliminated (in
13742 other words @emph{-gnatp} also implies @emph{-gnatVn}.
13743 Use this switch to improve the performance
13744 of the code at the expense of safety in the presence of invalid data or
13745 program bugs.
13747 Note that when checks are suppressed, the compiler is allowed, but not
13748 required, to omit the checking code. If the run-time cost of the
13749 checking code is zero or near-zero, the compiler will generate it even
13750 if checks are suppressed. In particular, if the compiler can prove
13751 that a certain check will necessarily fail, it will generate code to
13752 do an unconditional 'raise', even if checks are suppressed. The
13753 compiler warns in this case. Another case in which checks may not be
13754 eliminated is when they are embedded in certain run time routines such
13755 as math library routines.
13757 Of course, run-time checks are omitted whenever the compiler can prove
13758 that they will not fail, whether or not checks are suppressed.
13760 Note that if you suppress a check that would have failed, program
13761 execution is erroneous, which means the behavior is totally
13762 unpredictable. The program might crash, or print wrong answers, or
13763 do anything else. It might even do exactly what you wanted it to do
13764 (and then it might start failing mysteriously next week or next
13765 year). The compiler will generate code based on the assumption that
13766 the condition being checked is true, which can result in erroneous
13767 execution if that assumption is wrong.
13769 The checks subject to suppression include all the checks defined by the Ada
13770 standard, the additional implementation defined checks @cite{Alignment_Check},
13771 @cite{Duplicated_Tag_Check}, @cite{Predicate_Check}, Container_Checks, Tampering_Check,
13772 and @cite{Validity_Check}, as well as any checks introduced using @cite{pragma Check_Name}. Note that @cite{Atomic_Synchronization} is not automatically
13773 suppressed by use of this option.
13775 If the code depends on certain checks being active, you can use
13776 pragma @cite{Unsuppress} either as a configuration pragma or as
13777 a local pragma to make sure that a specified check is performed
13778 even if @emph{gnatp} is specified.
13780 The @emph{-gnatp} switch has no effect if a subsequent
13781 @emph{-gnat-p} switch appears.
13782 @end table
13784 @geindex -gnat-p (gcc)
13786 @geindex Suppressing checks
13788 @geindex Checks
13789 @geindex suppressing
13791 @geindex Suppress
13794 @table @asis
13796 @item @code{-gnat-p}
13798 This switch cancels the effect of a previous @emph{gnatp} switch.
13799 @end table
13801 @geindex -gnato?? (gcc)
13803 @geindex Overflow checks
13805 @geindex Overflow mode
13807 @geindex Check
13808 @geindex overflow
13811 @table @asis
13813 @item @code{-gnato??}
13815 This switch controls the mode used for computing intermediate
13816 arithmetic integer operations, and also enables overflow checking.
13817 For a full description of overflow mode and checking control, see
13818 the 'Overflow Check Handling in GNAT' appendix in this
13819 User's Guide.
13821 Overflow checks are always enabled by this switch. The argument
13822 controls the mode, using the codes
13825 @table @asis
13827 @item @emph{1 = STRICT}
13829 In STRICT mode, intermediate operations are always done using the
13830 base type, and overflow checking ensures that the result is within
13831 the base type range.
13833 @item @emph{2 = MINIMIZED}
13835 In MINIMIZED mode, overflows in intermediate operations are avoided
13836 where possible by using a larger integer type for the computation
13837 (typically @cite{Long_Long_Integer}). Overflow checking ensures that
13838 the result fits in this larger integer type.
13840 @item @emph{3 = ELIMINATED}
13842 In ELIMINATED mode, overflows in intermediate operations are avoided
13843 by using multi-precision arithmetic. In this case, overflow checking
13844 has no effect on intermediate operations (since overflow is impossible).
13845 @end table
13847 If two digits are present after @emph{-gnato} then the first digit
13848 sets the mode for expressions outside assertions, and the second digit
13849 sets the mode for expressions within assertions. Here assertions is used
13850 in the technical sense (which includes for example precondition and
13851 postcondition expressions).
13853 If one digit is present, the corresponding mode is applicable to both
13854 expressions within and outside assertion expressions.
13856 If no digits are present, the default is to enable overflow checks
13857 and set STRICT mode for both kinds of expressions. This is compatible
13858 with the use of @emph{-gnato} in previous versions of GNAT.
13860 @geindex Machine_Overflows
13862 Note that the @emph{-gnato??} switch does not affect the code generated
13863 for any floating-point operations; it applies only to integer semantics.
13864 For floating-point, GNAT has the @cite{Machine_Overflows}
13865 attribute set to @cite{False} and the normal mode of operation is to
13866 generate IEEE NaN and infinite values on overflow or invalid operations
13867 (such as dividing 0.0 by 0.0).
13869 The reason that we distinguish overflow checking from other kinds of
13870 range constraint checking is that a failure of an overflow check, unlike
13871 for example the failure of a range check, can result in an incorrect
13872 value, but cannot cause random memory destruction (like an out of range
13873 subscript), or a wild jump (from an out of range case value). Overflow
13874 checking is also quite expensive in time and space, since in general it
13875 requires the use of double length arithmetic.
13877 Note again that the default is @emph{-gnato11} (equivalent to @emph{-gnato1}),
13878 so overflow checking is performed in STRICT mode by default.
13879 @end table
13881 @geindex -gnatE (gcc)
13883 @geindex Elaboration checks
13885 @geindex Check
13886 @geindex elaboration
13889 @table @asis
13891 @item @code{-gnatE}
13893 Enables dynamic checks for access-before-elaboration
13894 on subprogram calls and generic instantiations.
13895 Note that @emph{-gnatE} is not necessary for safety, because in the
13896 default mode, GNAT ensures statically that the checks would not fail.
13897 For full details of the effect and use of this switch,
13898 @ref{1c,,Compiling with gcc}.
13899 @end table
13901 @geindex -fstack-check (gcc)
13903 @geindex Stack Overflow Checking
13905 @geindex Checks
13906 @geindex stack overflow checking
13909 @table @asis
13911 @item @code{-fstack-check}
13913 Activates stack overflow checking. For full details of the effect and use of
13914 this switch see @ref{f4,,Stack Overflow Checking}.
13915 @end table
13917 @geindex Unsuppress
13919 The setting of these switches only controls the default setting of the
13920 checks. You may modify them using either @cite{Suppress} (to remove
13921 checks) or @cite{Unsuppress} (to add back suppressed checks) pragmas in
13922 the program source.
13924 @node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
13925 @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}
13926 @subsection Using @emph{gcc} for Syntax Checking
13929 @geindex -gnats (gcc)
13932 @table @asis
13934 @item @code{-gnats}
13936 The @cite{s} stands for 'syntax'.
13938 Run GNAT in syntax checking only mode. For
13939 example, the command
13941 @example
13942 $ gcc -c -gnats x.adb
13943 @end example
13945 compiles file @code{x.adb} in syntax-check-only mode. You can check a
13946 series of files in a single command
13947 , and can use wild cards to specify such a group of files.
13948 Note that you must specify the @emph{-c} (compile
13949 only) flag in addition to the @emph{-gnats} flag.
13951 You may use other switches in conjunction with @emph{-gnats}. In
13952 particular, @emph{-gnatl} and @emph{-gnatv} are useful to control the
13953 format of any generated error messages.
13955 When the source file is empty or contains only empty lines and/or comments,
13956 the output is a warning:
13958 @example
13959 $ gcc -c -gnats -x ada toto.txt
13960 toto.txt:1:01: warning: empty file, contains no compilation units
13962 @end example
13964 Otherwise, the output is simply the error messages, if any. No object file or
13965 ALI file is generated by a syntax-only compilation. Also, no units other
13966 than the one specified are accessed. For example, if a unit @cite{X}
13967 @emph{with}s a unit @cite{Y}, compiling unit @cite{X} in syntax
13968 check only mode does not access the source file containing unit
13969 @cite{Y}.
13971 @geindex Multiple units
13972 @geindex syntax checking
13974 Normally, GNAT allows only a single unit in a source file. However, this
13975 restriction does not apply in syntax-check-only mode, and it is possible
13976 to check a file containing multiple compilation units concatenated
13977 together. This is primarily used by the @cite{gnatchop} utility
13978 (@ref{36,,Renaming Files with gnatchop}).
13979 @end table
13981 @node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
13982 @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}
13983 @subsection Using @emph{gcc} for Semantic Checking
13986 @geindex -gnatc (gcc)
13989 @table @asis
13991 @item @code{-gnatc}
13993 The @cite{c} stands for 'check'.
13994 Causes the compiler to operate in semantic check mode,
13995 with full checking for all illegalities specified in the
13996 Ada Reference Manual, but without generation of any object code
13997 (no object file is generated).
13999 Because dependent files must be accessed, you must follow the GNAT
14000 semantic restrictions on file structuring to operate in this mode:
14003 @itemize *
14005 @item 
14006 The needed source files must be accessible
14007 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
14009 @item 
14010 Each file must contain only one compilation unit.
14012 @item 
14013 The file name and unit name must match (@ref{52,,File Naming Rules}).
14014 @end itemize
14016 The output consists of error messages as appropriate. No object file is
14017 generated. An @code{ALI} file is generated for use in the context of
14018 cross-reference tools, but this file is marked as not being suitable
14019 for binding (since no object file is generated).
14020 The checking corresponds exactly to the notion of
14021 legality in the Ada Reference Manual.
14023 Any unit can be compiled in semantics-checking-only mode, including
14024 units that would not normally be compiled (subunits,
14025 and specifications where a separate body is present).
14026 @end table
14028 @node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14029 @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}
14030 @subsection Compiling Different Versions of Ada
14033 The switches described in this section allow you to explicitly specify
14034 the version of the Ada language that your programs are written in.
14035 The default mode is Ada 2012,
14036 but you can also specify Ada 95, Ada 2005 mode, or
14037 indicate Ada 83 compatibility mode.
14039 @geindex Compatibility with Ada 83
14041 @geindex -gnat83 (gcc)
14043 @geindex ACVC
14044 @geindex Ada 83 tests
14046 @geindex Ada 83 mode
14049 @table @asis
14051 @item @code{-gnat83} (Ada 83 Compatibility Mode)
14053 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14054 specifies that the program is to be compiled in Ada 83 mode. With
14055 @emph{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14056 semantics where this can be done easily.
14057 It is not possible to guarantee this switch does a perfect
14058 job; some subtle tests, such as are
14059 found in earlier ACVC tests (and that have been removed from the ACATS suite
14060 for Ada 95), might not compile correctly.
14061 Nevertheless, this switch may be useful in some circumstances, for example
14062 where, due to contractual reasons, existing code needs to be maintained
14063 using only Ada 83 features.
14065 With few exceptions (most notably the need to use @cite{<>} on
14066 unconstrained 
14067 @geindex Generic formal parameters
14068 generic formal parameters,
14069 the use of the new Ada 95 / Ada 2005
14070 reserved words, and the use of packages
14071 with optional bodies), it is not necessary to specify the
14072 @emph{-gnat83} switch when compiling Ada 83 programs, because, with rare
14073 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14074 a correct Ada 83 program is usually also a correct program
14075 in these later versions of the language standard. For further information
14076 please refer to the @cite{Compatibility_and_Porting_Guide} chapter in the
14077 @cite{GNAT Reference Manual}.
14078 @end table
14080 @geindex -gnat95 (gcc)
14082 @geindex Ada 95 mode
14085 @table @asis
14087 @item @code{-gnat95} (Ada 95 mode)
14089 This switch directs the compiler to implement the Ada 95 version of the
14090 language.
14091 Since Ada 95 is almost completely upwards
14092 compatible with Ada 83, Ada 83 programs may generally be compiled using
14093 this switch (see the description of the @emph{-gnat83} switch for further
14094 information about Ada 83 mode).
14095 If an Ada 2005 program is compiled in Ada 95 mode,
14096 uses of the new Ada 2005 features will cause error
14097 messages or warnings.
14099 This switch also can be used to cancel the effect of a previous
14100 @emph{-gnat83}, @emph{-gnat05/2005}, or @emph{-gnat12/2012}
14101 switch earlier in the command line.
14102 @end table
14104 @geindex -gnat05 (gcc)
14106 @geindex -gnat2005 (gcc)
14108 @geindex Ada 2005 mode
14111 @table @asis
14113 @item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14115 This switch directs the compiler to implement the Ada 2005 version of the
14116 language, as documented in the official Ada standards document.
14117 Since Ada 2005 is almost completely upwards
14118 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14119 may generally be compiled using this switch (see the description of the
14120 @emph{-gnat83} and @emph{-gnat95} switches for further
14121 information).
14122 @end table
14124 @geindex -gnat12 (gcc)
14126 @geindex -gnat2012 (gcc)
14128 @geindex Ada 2012 mode
14131 @table @asis
14133 @item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14135 This switch directs the compiler to implement the Ada 2012 version of the
14136 language (also the default).
14137 Since Ada 2012 is almost completely upwards
14138 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14139 Ada 83 and Ada 95 programs
14140 may generally be compiled using this switch (see the description of the
14141 @emph{-gnat83}, @emph{-gnat95}, and @emph{-gnat05/2005} switches
14142 for further information).
14143 @end table
14145 @geindex -gnatX (gcc)
14147 @geindex Ada language extensions
14149 @geindex GNAT extensions
14152 @table @asis
14154 @item @code{-gnatX} (Enable GNAT Extensions)
14156 This switch directs the compiler to implement the latest version of the
14157 language (currently Ada 2012) and also to enable certain GNAT implementation
14158 extensions that are not part of any Ada standard. For a full list of these
14159 extensions, see the GNAT reference manual.
14160 @end table
14162 @node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14163 @anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{48}
14164 @subsection Character Set Control
14167 @geindex -gnati (gcc)
14170 @table @asis
14172 @item @code{-gnati@emph{c}}
14174 Normally GNAT recognizes the Latin-1 character set in source program
14175 identifiers, as described in the Ada Reference Manual.
14176 This switch causes
14177 GNAT to recognize alternate character sets in identifiers. @cite{c} is a
14178 single character  indicating the character set, as follows:
14181 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14182 @item
14184 @emph{1}
14186 @tab
14188 ISO 8859-1 (Latin-1) identifiers
14190 @item
14192 @emph{2}
14194 @tab
14196 ISO 8859-2 (Latin-2) letters allowed in identifiers
14198 @item
14200 @emph{3}
14202 @tab
14204 ISO 8859-3 (Latin-3) letters allowed in identifiers
14206 @item
14208 @emph{4}
14210 @tab
14212 ISO 8859-4 (Latin-4) letters allowed in identifiers
14214 @item
14216 @emph{5}
14218 @tab
14220 ISO 8859-5 (Cyrillic) letters allowed in identifiers
14222 @item
14224 @emph{9}
14226 @tab
14228 ISO 8859-15 (Latin-9) letters allowed in identifiers
14230 @item
14232 @emph{p}
14234 @tab
14236 IBM PC letters (code page 437) allowed in identifiers
14238 @item
14240 @emph{8}
14242 @tab
14244 IBM PC letters (code page 850) allowed in identifiers
14246 @item
14248 @emph{f}
14250 @tab
14252 Full upper-half codes allowed in identifiers
14254 @item
14256 @emph{n}
14258 @tab
14260 No upper-half codes allowed in identifiers
14262 @item
14264 @emph{w}
14266 @tab
14268 Wide-character codes (that is, codes greater than 255)
14269 allowed in identifiers
14271 @end multitable
14274 See @ref{3e,,Foreign Language Representation} for full details on the
14275 implementation of these character sets.
14276 @end table
14278 @geindex -gnatW (gcc)
14281 @table @asis
14283 @item @code{-gnatW@emph{e}}
14285 Specify the method of encoding for wide characters.
14286 @cite{e} is one of the following:
14289 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14290 @item
14292 @emph{h}
14294 @tab
14296 Hex encoding (brackets coding also recognized)
14298 @item
14300 @emph{u}
14302 @tab
14304 Upper half encoding (brackets encoding also recognized)
14306 @item
14308 @emph{s}
14310 @tab
14312 Shift/JIS encoding (brackets encoding also recognized)
14314 @item
14316 @emph{e}
14318 @tab
14320 EUC encoding (brackets encoding also recognized)
14322 @item
14324 @emph{8}
14326 @tab
14328 UTF-8 encoding (brackets encoding also recognized)
14330 @item
14332 @emph{b}
14334 @tab
14336 Brackets encoding only (default value)
14338 @end multitable
14341 For full details on these encoding
14342 methods see @ref{4e,,Wide_Character Encodings}.
14343 Note that brackets coding is always accepted, even if one of the other
14344 options is specified, so for example @emph{-gnatW8} specifies that both
14345 brackets and UTF-8 encodings will be recognized. The units that are
14346 with'ed directly or indirectly will be scanned using the specified
14347 representation scheme, and so if one of the non-brackets scheme is
14348 used, it must be used consistently throughout the program. However,
14349 since brackets encoding is always recognized, it may be conveniently
14350 used in standard libraries, allowing these libraries to be used with
14351 any of the available coding schemes.
14353 Note that brackets encoding only applies to program text. Within comments,
14354 brackets are considered to be normal graphic characters, and bracket sequences
14355 are never recognized as wide characters.
14357 If no @emph{-gnatW?} parameter is present, then the default
14358 representation is normally Brackets encoding only. However, if the
14359 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14360 byte order mark or BOM for UTF-8), then these three characters are
14361 skipped and the default representation for the file is set to UTF-8.
14363 Note that the wide character representation that is specified (explicitly
14364 or by default) for the main program also acts as the default encoding used
14365 for Wide_Text_IO files if not specifically overridden by a WCEM form
14366 parameter.
14367 @end table
14369 When no @emph{-gnatW?} is specified, then characters (other than wide
14370 characters represented using brackets notation) are treated as 8-bit
14371 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14372 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14373 characters in the range 16#00#..16#1F# are not accepted in program text
14374 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14375 in program text, but allowed and ignored in comments. Note in particular
14376 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14377 as an end of line in this default mode. If your source program contains
14378 instances of the NEL character used as a line terminator,
14379 you must use UTF-8 encoding for the whole
14380 source program. In default mode, all lines must be ended by a standard
14381 end of line sequence (CR, CR/LF, or LF).
14383 Note that the convention of simply accepting all upper half characters in
14384 comments means that programs that use standard ASCII for program text, but
14385 UTF-8 encoding for comments are accepted in default mode, providing that the
14386 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14387 This is a common mode for many programs with foreign language comments.
14389 @node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14390 @anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{10b}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{10c}
14391 @subsection File Naming Control
14394 @geindex -gnatk (gcc)
14397 @table @asis
14399 @item @code{-gnatk@emph{n}}
14401 Activates file name 'krunching'. @cite{n}, a decimal integer in the range
14402 1-999, indicates the maximum allowable length of a file name (not
14403 including the @code{.ads} or @code{.adb} extension). The default is not
14404 to enable file name krunching.
14406 For the source file naming rules, @ref{52,,File Naming Rules}.
14407 @end table
14409 @node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14410 @anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{10d}@anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{10e}
14411 @subsection Subprogram Inlining Control
14414 @geindex -gnatn (gcc)
14417 @table @asis
14419 @item @code{-gnatn[12]}
14421 The @cite{n} here is intended to suggest the first syllable of the word 'inline'.
14422 GNAT recognizes and processes @cite{Inline} pragmas. However, for inlining to
14423 actually occur, optimization must be enabled and, by default, inlining of
14424 subprograms across modules is not performed. If you want to additionally
14425 enable inlining of subprograms specified by pragma @cite{Inline} across modules,
14426 you must also specify this switch.
14428 In the absence of this switch, GNAT does not attempt inlining across modules
14429 and does not access the bodies of subprograms for which @cite{pragma Inline} is
14430 specified if they are not in the current unit.
14432 You can optionally specify the inlining level: 1 for moderate inlining across
14433 modules, which is a good compromise between compilation times and performances
14434 at run time, or 2 for full inlining across modules, which may bring about
14435 longer compilation times. If no inlining level is specified, the compiler will
14436 pick it based on the optimization level: 1 for @emph{-O1}, @emph{-O2} or
14437 @emph{-Os} and 2 for @emph{-O3}.
14439 If you specify this switch the compiler will access these bodies,
14440 creating an extra source dependency for the resulting object file, and
14441 where possible, the call will be inlined.
14442 For further details on when inlining is possible
14443 see @ref{10f,,Inlining of Subprograms}.
14444 @end table
14446 @geindex -gnatN (gcc)
14449 @table @asis
14451 @item @code{-gnatN}
14453 This switch activates front-end inlining which also
14454 generates additional dependencies.
14456 When using a gcc-based back end (in practice this means using any version
14457 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
14458 @emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
14459 Historically front end inlining was more extensive than the gcc back end
14460 inlining, but that is no longer the case.
14461 @end table
14463 @node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14464 @anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{110}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{111}
14465 @subsection Auxiliary Output Control
14468 @geindex -gnatt (gcc)
14470 @geindex Writing internal trees
14472 @geindex Internal trees
14473 @geindex writing to file
14476 @table @asis
14478 @item @code{-gnatt}
14480 Causes GNAT to write the internal tree for a unit to a file (with the
14481 extension @code{.adt}.
14482 This not normally required, but is used by separate analysis tools.
14483 Typically
14484 these tools do the necessary compilations automatically, so you should
14485 not have to specify this switch in normal operation.
14486 Note that the combination of switches @emph{-gnatct}
14487 generates a tree in the form required by ASIS applications.
14488 @end table
14490 @geindex -gnatu (gcc)
14493 @table @asis
14495 @item @code{-gnatu}
14497 Print a list of units required by this compilation on @code{stdout}.
14498 The listing includes all units on which the unit being compiled depends
14499 either directly or indirectly.
14500 @end table
14502 @geindex -pass-exit-codes (gcc)
14505 @table @asis
14507 @item @code{-pass-exit-codes}
14509 If this switch is not used, the exit code returned by @emph{gcc} when
14510 compiling multiple files indicates whether all source files have
14511 been successfully used to generate object files or not.
14513 When @emph{-pass-exit-codes} is used, @emph{gcc} exits with an extended
14514 exit status and allows an integrated development environment to better
14515 react to a compilation failure. Those exit status are:
14518 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
14519 @item
14521 @emph{5}
14523 @tab
14525 There was an error in at least one source file.
14527 @item
14529 @emph{3}
14531 @tab
14533 At least one source file did not generate an object file.
14535 @item
14537 @emph{2}
14539 @tab
14541 The compiler died unexpectedly (internal error for example).
14543 @item
14545 @emph{0}
14547 @tab
14549 An object file has been generated for every source file.
14551 @end multitable
14553 @end table
14555 @node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
14556 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{112}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{113}
14557 @subsection Debugging Control
14560 @quotation
14562 @geindex Debugging options
14563 @end quotation
14565 @geindex -gnatd (gcc)
14568 @table @asis
14570 @item @code{-gnatd@emph{x}}
14572 Activate internal debugging switches. @cite{x} is a letter or digit, or
14573 string of letters or digits, which specifies the type of debugging
14574 outputs desired. Normally these are used only for internal development
14575 or system debugging purposes. You can find full documentation for these
14576 switches in the body of the @cite{Debug} unit in the compiler source
14577 file @code{debug.adb}.
14578 @end table
14580 @geindex -gnatG (gcc)
14583 @table @asis
14585 @item @code{-gnatG[=@emph{nn}]}
14587 This switch causes the compiler to generate auxiliary output containing
14588 a pseudo-source listing of the generated expanded code. Like most Ada
14589 compilers, GNAT works by first transforming the high level Ada code into
14590 lower level constructs. For example, tasking operations are transformed
14591 into calls to the tasking run-time routines. A unique capability of GNAT
14592 is to list this expanded code in a form very close to normal Ada source.
14593 This is very useful in understanding the implications of various Ada
14594 usage on the efficiency of the generated code. There are many cases in
14595 Ada (e.g., the use of controlled types), where simple Ada statements can
14596 generate a lot of run-time code. By using @emph{-gnatG} you can identify
14597 these cases, and consider whether it may be desirable to modify the coding
14598 approach to improve efficiency.
14600 The optional parameter @cite{nn} if present after -gnatG specifies an
14601 alternative maximum line length that overrides the normal default of 72.
14602 This value is in the range 40-999999, values less than 40 being silently
14603 reset to 40. The equal sign is optional.
14605 The format of the output is very similar to standard Ada source, and is
14606 easily understood by an Ada programmer. The following special syntactic
14607 additions correspond to low level features used in the generated code that
14608 do not have any exact analogies in pure Ada source form. The following
14609 is a partial list of these special constructions. See the spec
14610 of package @cite{Sprint} in file @code{sprint.ads} for a full list.
14612 @geindex -gnatL (gcc)
14614 If the switch @emph{-gnatL} is used in conjunction with
14615 @emph{-gnatG}, then the original source lines are interspersed
14616 in the expanded source (as comment lines with the original line number).
14619 @table @asis
14621 @item @code{new @emph{xxx} [storage_pool = @emph{yyy}]}
14623 Shows the storage pool being used for an allocator.
14625 @item @code{at end @emph{procedure-name};}
14627 Shows the finalization (cleanup) procedure for a scope.
14629 @item @code{(if @emph{expr} then @emph{expr} else @emph{expr})}
14631 Conditional expression equivalent to the @cite{x?y:z} construction in C.
14633 @item @code{@emph{target}^(@emph{source})}
14635 A conversion with floating-point truncation instead of rounding.
14637 @item @code{@emph{target}?(@emph{source})}
14639 A conversion that bypasses normal Ada semantic checking. In particular
14640 enumeration types and fixed-point types are treated simply as integers.
14642 @item @code{@emph{target}?^(@emph{source})}
14644 Combines the above two cases.
14645 @end table
14647 @code{@emph{x} #/ @emph{y}}
14649 @code{@emph{x} #mod @emph{y}}
14651 @code{@emph{x} # @emph{y}}
14654 @table @asis
14656 @item @code{@emph{x} #rem @emph{y}}
14658 A division or multiplication of fixed-point values which are treated as
14659 integers without any kind of scaling.
14661 @item @code{free @emph{expr} [storage_pool = @emph{xxx}]}
14663 Shows the storage pool associated with a @cite{free} statement.
14665 @item @code{[subtype or type declaration]}
14667 Used to list an equivalent declaration for an internally generated
14668 type that is referenced elsewhere in the listing.
14670 @item @code{freeze @emph{type-name} [@emph{actions}]}
14672 Shows the point at which @cite{type-name} is frozen, with possible
14673 associated actions to be performed at the freeze point.
14675 @item @code{reference @emph{itype}}
14677 Reference (and hence definition) to internal type @cite{itype}.
14679 @item @code{@emph{function-name}! (@emph{arg}, @emph{arg}, @emph{arg})}
14681 Intrinsic function call.
14683 @item @code{@emph{label-name} : label}
14685 Declaration of label @cite{labelname}.
14687 @item @code{#$ @emph{subprogram-name}}
14689 An implicit call to a run-time support routine
14690 (to meet the requirement of H.3.1(9) in a
14691 convenient manner).
14693 @item @code{@emph{expr} && @emph{expr} && @emph{expr} ... && @emph{expr}}
14695 A multiple concatenation (same effect as @cite{expr} & @cite{expr} &
14696 @cite{expr}, but handled more efficiently).
14698 @item @code{[constraint_error]}
14700 Raise the @cite{Constraint_Error} exception.
14702 @item @code{@emph{expression}'reference}
14704 A pointer to the result of evaluating @{expression@}.
14706 @item @code{@emph{target-type}!(@emph{source-expression})}
14708 An unchecked conversion of @cite{source-expression} to @cite{target-type}.
14710 @item @code{[@emph{numerator}/@emph{denominator}]}
14712 Used to represent internal real literals (that) have no exact
14713 representation in base 2-16 (for example, the result of compile time
14714 evaluation of the expression 1.0/27.0).
14715 @end table
14716 @end table
14718 @geindex -gnatD (gcc)
14721 @table @asis
14723 @item @code{-gnatD[=nn]}
14725 When used in conjunction with @emph{-gnatG}, this switch causes
14726 the expanded source, as described above for
14727 @emph{-gnatG} to be written to files with names
14728 @code{xxx.dg}, where @code{xxx} is the normal file name,
14729 instead of to the standard output file. For
14730 example, if the source file name is @code{hello.adb}, then a file
14731 @code{hello.adb.dg} will be written.  The debugging
14732 information generated by the @emph{gcc} @emph{-g} switch
14733 will refer to the generated @code{xxx.dg} file. This allows
14734 you to do source level debugging using the generated code which is
14735 sometimes useful for complex code, for example to find out exactly
14736 which part of a complex construction raised an exception. This switch
14737 also suppresses generation of cross-reference information (see
14738 @emph{-gnatx}) since otherwise the cross-reference information
14739 would refer to the @code{.dg} file, which would cause
14740 confusion since this is not the original source file.
14742 Note that @emph{-gnatD} actually implies @emph{-gnatG}
14743 automatically, so it is not necessary to give both options.
14744 In other words @emph{-gnatD} is equivalent to @emph{-gnatDG}).
14746 @geindex -gnatL (gcc)
14748 If the switch @emph{-gnatL} is used in conjunction with
14749 @emph{-gnatDG}, then the original source lines are interspersed
14750 in the expanded source (as comment lines with the original line number).
14752 The optional parameter @cite{nn} if present after -gnatD specifies an
14753 alternative maximum line length that overrides the normal default of 72.
14754 This value is in the range 40-999999, values less than 40 being silently
14755 reset to 40. The equal sign is optional.
14756 @end table
14758 @geindex -gnatr (gcc)
14760 @geindex pragma Restrictions
14763 @table @asis
14765 @item @code{-gnatr}
14767 This switch causes pragma Restrictions to be treated as Restriction_Warnings
14768 so that violation of restrictions causes warnings rather than illegalities.
14769 This is useful during the development process when new restrictions are added
14770 or investigated. The switch also causes pragma Profile to be treated as
14771 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
14772 restriction warnings rather than restrictions.
14773 @end table
14775 @geindex -gnatR (gcc)
14778 @table @asis
14780 @item @code{-gnatR[0|1|2|3[s]]}
14782 This switch controls output from the compiler of a listing showing
14783 representation information for declared types and objects. For
14784 @emph{-gnatR0}, no information is output (equivalent to omitting
14785 the @emph{-gnatR} switch). For @emph{-gnatR1} (which is the default,
14786 so @emph{-gnatR} with no parameter has the same effect), size and alignment
14787 information is listed for declared array and record types. For
14788 @emph{-gnatR2}, size and alignment information is listed for all
14789 declared types and objects. The @cite{Linker_Section} is also listed for any
14790 entity for which the @cite{Linker_Section} is set explicitly or implicitly (the
14791 latter case occurs for objects of a type for which a @cite{Linker_Section}
14792 is set).
14794 Finally @emph{-gnatR3} includes symbolic
14795 expressions for values that are computed at run time for
14796 variant records. These symbolic expressions have a mostly obvious
14797 format with #n being used to represent the value of the n'th
14798 discriminant. See source files @code{repinfo.ads/adb} in the
14799 @cite{GNAT} sources for full details on the format of @emph{-gnatR3}
14800 output. If the switch is followed by an s (e.g., @emph{-gnatR2s}), then
14801 the output is to a file with the name @code{file.rep} where
14802 file is the name of the corresponding source file.
14804 @item @code{-gnatRm[s]}
14806 This form of the switch controls output of subprogram conventions
14807 and parameter passing mechanisms for all subprograms. A following
14808 @cite{s} means output to a file as described above.
14810 Note that it is possible for record components to have zero size. In
14811 this case, the component clause uses an obvious extension of permitted
14812 Ada syntax, for example @cite{at 0 range 0 .. -1}.
14813 @end table
14815 @geindex -gnatS (gcc)
14818 @table @asis
14820 @item @code{-gnatS}
14822 The use of the switch @emph{-gnatS} for an
14823 Ada compilation will cause the compiler to output a
14824 representation of package Standard in a form very
14825 close to standard Ada. It is not quite possible to
14826 do this entirely in standard Ada (since new
14827 numeric base types cannot be created in standard
14828 Ada), but the output is easily
14829 readable to any Ada programmer, and is useful to
14830 determine the characteristics of target dependent
14831 types in package Standard.
14832 @end table
14834 @geindex -gnatx (gcc)
14837 @table @asis
14839 @item @code{-gnatx}
14841 Normally the compiler generates full cross-referencing information in
14842 the @code{ALI} file. This information is used by a number of tools,
14843 including @cite{gnatfind} and @cite{gnatxref}. The @emph{-gnatx} switch
14844 suppresses this information. This saves some space and may slightly
14845 speed up compilation, but means that these tools cannot be used.
14846 @end table
14848 @node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
14849 @anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{114}@anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{115}
14850 @subsection Exception Handling Control
14853 GNAT uses two methods for handling exceptions at run-time. The
14854 @cite{setjmp/longjmp} method saves the context when entering
14855 a frame with an exception handler. Then when an exception is
14856 raised, the context can be restored immediately, without the
14857 need for tracing stack frames. This method provides very fast
14858 exception propagation, but introduces significant overhead for
14859 the use of exception handlers, even if no exception is raised.
14861 The other approach is called 'zero cost' exception handling.
14862 With this method, the compiler builds static tables to describe
14863 the exception ranges. No dynamic code is required when entering
14864 a frame containing an exception handler. When an exception is
14865 raised, the tables are used to control a back trace of the
14866 subprogram invocation stack to locate the required exception
14867 handler. This method has considerably poorer performance for
14868 the propagation of exceptions, but there is no overhead for
14869 exception handlers if no exception is raised. Note that in this
14870 mode and in the context of mixed Ada and C/C++ programming,
14871 to propagate an exception through a C/C++ code, the C/C++ code
14872 must be compiled with the @emph{-funwind-tables} GCC's
14873 option.
14875 The following switches may be used to control which of the
14876 two exception handling methods is used.
14878 @geindex --RTS=sjlj (gnatmake)
14881 @table @asis
14883 @item @code{--RTS=sjlj}
14885 This switch causes the setjmp/longjmp run-time (when available) to be used
14886 for exception handling. If the default
14887 mechanism for the target is zero cost exceptions, then
14888 this switch can be used to modify this default, and must be
14889 used for all units in the partition.
14890 This option is rarely used. One case in which it may be
14891 advantageous is if you have an application where exception
14892 raising is common and the overall performance of the
14893 application is improved by favoring exception propagation.
14894 @end table
14896 @geindex --RTS=zcx (gnatmake)
14898 @geindex Zero Cost Exceptions
14901 @table @asis
14903 @item @code{--RTS=zcx}
14905 This switch causes the zero cost approach to be used
14906 for exception handling. If this is the default mechanism for the
14907 target (see below), then this switch is unneeded. If the default
14908 mechanism for the target is setjmp/longjmp exceptions, then
14909 this switch can be used to modify this default, and must be
14910 used for all units in the partition.
14911 This option can only be used if the zero cost approach
14912 is available for the target in use, otherwise it will generate an error.
14913 @end table
14915 The same option @emph{--RTS} must be used both for @emph{gcc}
14916 and @emph{gnatbind}. Passing this option to @emph{gnatmake}
14917 (@ref{dc,,Switches for gnatmake}) will ensure the required consistency
14918 through the compilation and binding steps.
14920 @node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
14921 @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}
14922 @subsection Units to Sources Mapping Files
14925 @geindex -gnatem (gcc)
14928 @table @asis
14930 @item @code{-gnatem=@emph{path}}
14932 A mapping file is a way to communicate to the compiler two mappings:
14933 from unit names to file names (without any directory information) and from
14934 file names to path names (with full directory information). These mappings
14935 are used by the compiler to short-circuit the path search.
14937 The use of mapping files is not required for correct operation of the
14938 compiler, but mapping files can improve efficiency, particularly when
14939 sources are read over a slow network connection. In normal operation,
14940 you need not be concerned with the format or use of mapping files,
14941 and the @emph{-gnatem} switch is not a switch that you would use
14942 explicitly. It is intended primarily for use by automatic tools such as
14943 @emph{gnatmake} running under the project file facility. The
14944 description here of the format of mapping files is provided
14945 for completeness and for possible use by other tools.
14947 A mapping file is a sequence of sets of three lines. In each set, the
14948 first line is the unit name, in lower case, with @cite{%s} appended
14949 for specs and @cite{%b} appended for bodies; the second line is the
14950 file name; and the third line is the path name.
14952 Example:
14954 @example
14955 main%b
14956 main.2.ada
14957 /gnat/project1/sources/main.2.ada
14958 @end example
14960 When the switch @emph{-gnatem} is specified, the compiler will
14961 create in memory the two mappings from the specified file. If there is
14962 any problem (nonexistent file, truncated file or duplicate entries),
14963 no mapping will be created.
14965 Several @emph{-gnatem} switches may be specified; however, only the
14966 last one on the command line will be taken into account.
14968 When using a project file, @emph{gnatmake} creates a temporary
14969 mapping file and communicates it to the compiler using this switch.
14970 @end table
14972 @node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
14973 @anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{117}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{118}
14974 @subsection Code Generation Control
14977 The GCC technology provides a wide range of target dependent
14978 @code{-m} switches for controlling
14979 details of code generation with respect to different versions of
14980 architectures. This includes variations in instruction sets (e.g.,
14981 different members of the power pc family), and different requirements
14982 for optimal arrangement of instructions (e.g., different members of
14983 the x86 family). The list of available @emph{-m} switches may be
14984 found in the GCC documentation.
14986 Use of these @emph{-m} switches may in some cases result in improved
14987 code performance.
14989 The GNAT technology is tested and qualified without any
14990 @code{-m} switches,
14991 so generally the most reliable approach is to avoid the use of these
14992 switches. However, we generally expect most of these switches to work
14993 successfully with GNAT, and many customers have reported successful
14994 use of these options.
14996 Our general advice is to avoid the use of @emph{-m} switches unless
14997 special needs lead to requirements in this area. In particular,
14998 there is no point in using @emph{-m} switches to improve performance
14999 unless you actually see a performance improvement.
15001 @node Linker Switches,Binding with gnatbind,Compiler Switches,Building Executable Programs with GNAT
15002 @anchor{gnat_ugn/building_executable_programs_with_gnat linker-switches}@anchor{119}@anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{11a}
15003 @section Linker Switches
15006 Linker switches can be specified after @code{-largs} builder switch.
15008 @geindex -fuse-ld=name
15011 @table @asis
15013 @item @code{-fuse-ld=@emph{name}}
15015 Linker to be used. The default is @code{bfd} for @code{ld.bfd},
15016 the alternative being @code{gold} for @code{ld.gold}. The later is
15017 a more recent and faster linker, but only available on GNU/Linux
15018 platforms.
15019 @end table
15021 @node Binding with gnatbind,Linking with gnatlink,Linker Switches,Building Executable Programs with GNAT
15022 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{1d}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{11b}
15023 @section Binding with @cite{gnatbind}
15026 @geindex gnatbind
15028 This chapter describes the GNAT binder, @cite{gnatbind}, which is used
15029 to bind compiled GNAT objects.
15031 Note: to invoke @cite{gnatbind} with a project file, use the @cite{gnat}
15032 driver (see @emph{The_GNAT_Driver_and_Project_Files}).
15034 The @cite{gnatbind} program performs four separate functions:
15037 @itemize *
15039 @item 
15040 Checks that a program is consistent, in accordance with the rules in
15041 Chapter 10 of the Ada Reference Manual. In particular, error
15042 messages are generated if a program uses inconsistent versions of a
15043 given unit.
15045 @item 
15046 Checks that an acceptable order of elaboration exists for the program
15047 and issues an error message if it cannot find an order of elaboration
15048 that satisfies the rules in Chapter 10 of the Ada Language Manual.
15050 @item 
15051 Generates a main program incorporating the given elaboration order.
15052 This program is a small Ada package (body and spec) that
15053 must be subsequently compiled
15054 using the GNAT compiler. The necessary compilation step is usually
15055 performed automatically by @emph{gnatlink}. The two most important
15056 functions of this program
15057 are to call the elaboration routines of units in an appropriate order
15058 and to call the main program.
15060 @item 
15061 Determines the set of object files required by the given main program.
15062 This information is output in the forms of comments in the generated program,
15063 to be read by the @emph{gnatlink} utility used to link the Ada application.
15064 @end itemize
15066 @menu
15067 * Running gnatbind:: 
15068 * Switches for gnatbind:: 
15069 * Command-Line Access:: 
15070 * Search Paths for gnatbind:: 
15071 * Examples of gnatbind Usage:: 
15073 @end menu
15075 @node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15076 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{11c}@anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{11d}
15077 @subsection Running @cite{gnatbind}
15080 The form of the @cite{gnatbind} command is
15082 @example
15083 $ gnatbind [`switches`] `mainprog`[.ali] [`switches`]
15084 @end example
15086 where @code{mainprog.adb} is the Ada file containing the main program
15087 unit body. @cite{gnatbind} constructs an Ada
15088 package in two files whose names are
15089 @code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15090 For example, if given the
15091 parameter @code{hello.ali}, for a main program contained in file
15092 @code{hello.adb}, the binder output files would be @code{b~hello.ads}
15093 and @code{b~hello.adb}.
15095 When doing consistency checking, the binder takes into consideration
15096 any source files it can locate. For example, if the binder determines
15097 that the given main program requires the package @cite{Pack}, whose
15098 @code{.ALI}
15099 file is @code{pack.ali} and whose corresponding source spec file is
15100 @code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15101 (using the same search path conventions as previously described for the
15102 @emph{gcc} command). If it can locate this source file, it checks that
15103 the time stamps
15104 or source checksums of the source and its references to in @code{ALI} files
15105 match. In other words, any @code{ALI} files that mentions this spec must have
15106 resulted from compiling this version of the source file (or in the case
15107 where the source checksums match, a version close enough that the
15108 difference does not matter).
15110 @geindex Source files
15111 @geindex use by binder
15113 The effect of this consistency checking, which includes source files, is
15114 that the binder ensures that the program is consistent with the latest
15115 version of the source files that can be located at bind time. Editing a
15116 source file without compiling files that depend on the source file cause
15117 error messages to be generated by the binder.
15119 For example, suppose you have a main program @code{hello.adb} and a
15120 package @cite{P}, from file @code{p.ads} and you perform the following
15121 steps:
15124 @itemize *
15126 @item 
15127 Enter @cite{gcc -c hello.adb} to compile the main program.
15129 @item 
15130 Enter @cite{gcc -c p.ads} to compile package @cite{P}.
15132 @item 
15133 Edit file @code{p.ads}.
15135 @item 
15136 Enter @cite{gnatbind hello}.
15137 @end itemize
15139 At this point, the file @code{p.ali} contains an out-of-date time stamp
15140 because the file @code{p.ads} has been edited. The attempt at binding
15141 fails, and the binder generates the following error messages:
15143 @example
15144 error: "hello.adb" must be recompiled ("p.ads" has been modified)
15145 error: "p.ads" has been modified and must be recompiled
15146 @end example
15148 Now both files must be recompiled as indicated, and then the bind can
15149 succeed, generating a main program. You need not normally be concerned
15150 with the contents of this file, but for reference purposes a sample
15151 binder output file is given in @ref{e,,Example of Binder Output File}.
15153 In most normal usage, the default mode of @emph{gnatbind} which is to
15154 generate the main package in Ada, as described in the previous section.
15155 In particular, this means that any Ada programmer can read and understand
15156 the generated main program. It can also be debugged just like any other
15157 Ada code provided the @emph{-g} switch is used for
15158 @emph{gnatbind} and @emph{gnatlink}.
15160 @node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15161 @anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{11e}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{11f}
15162 @subsection Switches for @emph{gnatbind}
15165 The following switches are available with @cite{gnatbind}; details will
15166 be presented in subsequent sections.
15168 @geindex --version (gnatbind)
15171 @table @asis
15173 @item @code{--version}
15175 Display Copyright and version, then exit disregarding all other options.
15176 @end table
15178 @geindex --help (gnatbind)
15181 @table @asis
15183 @item @code{--help}
15185 If @emph{--version} was not used, display usage, then exit disregarding
15186 all other options.
15187 @end table
15189 @geindex -a (gnatbind)
15192 @table @asis
15194 @item @code{-a}
15196 Indicates that, if supported by the platform, the adainit procedure should
15197 be treated as an initialisation routine by the linker (a constructor). This
15198 is intended to be used by the Project Manager to automatically initialize
15199 shared Stand-Alone Libraries.
15200 @end table
15202 @geindex -aO (gnatbind)
15205 @table @asis
15207 @item @code{-aO}
15209 Specify directory to be searched for ALI files.
15210 @end table
15212 @geindex -aI (gnatbind)
15215 @table @asis
15217 @item @code{-aI}
15219 Specify directory to be searched for source file.
15220 @end table
15222 @geindex -A (gnatbind)
15225 @table @asis
15227 @item @code{-A[=@emph{filename}]}
15229 Output ALI list (to standard output or to the named file).
15230 @end table
15232 @geindex -b (gnatbind)
15235 @table @asis
15237 @item @code{-b}
15239 Generate brief messages to @code{stderr} even if verbose mode set.
15240 @end table
15242 @geindex -c (gnatbind)
15245 @table @asis
15247 @item @code{-c}
15249 Check only, no generation of binder output file.
15250 @end table
15252 @geindex -dnn[k|m] (gnatbind)
15255 @table @asis
15257 @item @code{-d@emph{nn}[k|m]}
15259 This switch can be used to change the default task stack size value
15260 to a specified size @cite{nn}, which is expressed in bytes by default, or
15261 in kilobytes when suffixed with @cite{k} or in megabytes when suffixed
15262 with @cite{m}.
15263 In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15264 in effect, to completing all task specs with
15266 @example
15267 pragma Storage_Size (nn);
15268 @end example
15270 When they do not already have such a pragma.
15271 @end table
15273 @geindex -D (gnatbind)
15276 @table @asis
15278 @item @code{-D@emph{nn}[k|m]}
15280 This switch can be used to change the default secondary stack size value
15281 to a specified size @cite{nn}, which is expressed in bytes by default, or
15282 in kilobytes when suffixed with @cite{k} or in megabytes when suffixed
15283 with @cite{m}.
15285 The secondary stack is used to deal with functions that return a variable
15286 sized result, for example a function returning an unconstrained
15287 String. There are two ways in which this secondary stack is allocated.
15289 For most targets, the secondary stack is growing on demand and is allocated
15290 as a chain of blocks in the heap. The -D option is not very
15291 relevant. It only give some control over the size of the allocated
15292 blocks (whose size is the minimum of the default secondary stack size value,
15293 and the actual size needed for the current allocation request).
15295 For certain targets, notably VxWorks 653 and bare board targets,
15296 the secondary stack is allocated by carving off a chunk of the primary task
15297 stack. By default this is a fixed percentage of the primary task stack as
15298 defined by System.Parameter.Sec_Stack_Percentage. This can be overridden per
15299 task using the Secondary_Stack_Size pragma/aspect. The -D option is used to
15300 define the size of the environment task's secondary stack.
15301 @end table
15303 @geindex -e (gnatbind)
15306 @table @asis
15308 @item @code{-e}
15310 Output complete list of elaboration-order dependencies.
15311 @end table
15313 @geindex -Ea (gnatbind)
15316 @table @asis
15318 @item @code{-Ea}
15320 Store tracebacks in exception occurrences when the target supports it.
15321 The "a" is for "address"; tracebacks will contain hexadecimal addresses,
15322 unless symbolic tracebacks are enabled.
15324 See also the packages @cite{GNAT.Traceback} and
15325 @cite{GNAT.Traceback.Symbolic} for more information.
15326 Note that on x86 ports, you must not use @emph{-fomit-frame-pointer}
15327 @emph{gcc} option.
15328 @end table
15330 @geindex -Es (gnatbind)
15333 @table @asis
15335 @item @code{-Es}
15337 Store tracebacks in exception occurrences when the target supports it.
15338 The "s" is for "symbolic"; symbolic tracebacks are enabled.
15339 @end table
15341 @geindex -E (gnatbind)
15344 @table @asis
15346 @item @code{-E}
15348 Currently the same as @cite{-Ea}.
15349 @end table
15351 @geindex -f (gnatbind)
15354 @table @asis
15356 @item @code{-f@emph{elab-order}}
15358 Force elaboration order.
15359 @end table
15361 @geindex -F (gnatbind)
15364 @table @asis
15366 @item @code{-F}
15368 Force the checks of elaboration flags. @emph{gnatbind} does not normally
15369 generate checks of elaboration flags for the main executable, except when
15370 a Stand-Alone Library is used. However, there are cases when this cannot be
15371 detected by gnatbind. An example is importing an interface of a Stand-Alone
15372 Library through a pragma Import and only specifying through a linker switch
15373 this Stand-Alone Library. This switch is used to guarantee that elaboration
15374 flag checks are generated.
15375 @end table
15377 @geindex -h (gnatbind)
15380 @table @asis
15382 @item @code{-h}
15384 Output usage (help) information.
15386 @geindex -H32 (gnatbind)
15388 @item @code{-H32}
15390 Use 32-bit allocations for @cite{__gnat_malloc} (and thus for access types).
15391 For further details see @ref{120,,Dynamic Allocation Control}.
15393 @geindex -H64 (gnatbind)
15395 @geindex __gnat_malloc
15397 @item @code{-H64}
15399 Use 64-bit allocations for @cite{__gnat_malloc} (and thus for access types).
15400 For further details see @ref{120,,Dynamic Allocation Control}.
15402 @geindex -I (gnatbind)
15404 @item @code{-I}
15406 Specify directory to be searched for source and ALI files.
15408 @geindex -I- (gnatbind)
15410 @item @code{-I-}
15412 Do not look for sources in the current directory where @cite{gnatbind} was
15413 invoked, and do not look for ALI files in the directory containing the
15414 ALI file named in the @cite{gnatbind} command line.
15416 @geindex -l (gnatbind)
15418 @item @code{-l}
15420 Output chosen elaboration order.
15422 @geindex -L (gnatbind)
15424 @item @code{-L@emph{xxx}}
15426 Bind the units for library building. In this case the adainit and
15427 adafinal procedures (@ref{b4,,Binding with Non-Ada Main Programs})
15428 are renamed to @cite{xxx`init and `xxx`final. Implies -n. (:ref:`GNAT_and_Libraries}, for more details.)
15430 @geindex -M (gnatbind)
15432 @item @code{-M@emph{xyz}}
15434 Rename generated main program from main to xyz. This option is
15435 supported on cross environments only.
15437 @geindex -m (gnatbind)
15439 @item @code{-m@emph{n}}
15441 Limit number of detected errors or warnings to @cite{n}, where @cite{n} is
15442 in the range 1..999999. The default value if no switch is
15443 given is 9999. If the number of warnings reaches this limit, then a
15444 message is output and further warnings are suppressed, the bind
15445 continues in this case. If the number of errors reaches this
15446 limit, then a message is output and the bind is abandoned.
15447 A value of zero means that no limit is enforced. The equal
15448 sign is optional.
15450 @geindex -n (gnatbind)
15452 @item @code{-n}
15454 No main program.
15456 @geindex -nostdinc (gnatbind)
15458 @item @code{-nostdinc}
15460 Do not look for sources in the system default directory.
15462 @geindex -nostdlib (gnatbind)
15464 @item @code{-nostdlib}
15466 Do not look for library files in the system default directory.
15468 @geindex --RTS (gnatbind)
15470 @item @code{--RTS=@emph{rts-path}}
15472 Specifies the default location of the runtime library. Same meaning as the
15473 equivalent @emph{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
15475 @geindex -o (gnatbind)
15477 @item @code{-o @emph{file}}
15479 Name the output file @cite{file} (default is @code{b~`xxx}.adb`).
15480 Note that if this option is used, then linking must be done manually,
15481 gnatlink cannot be used.
15483 @geindex -O (gnatbind)
15485 @item @code{-O[=@emph{filename}]}
15487 Output object list (to standard output or to the named file).
15489 @geindex -p (gnatbind)
15491 @item @code{-p}
15493 Pessimistic (worst-case) elaboration order.
15495 @geindex -P (gnatbind)
15497 @item @code{-P}
15499 Generate binder file suitable for CodePeer.
15501 @geindex -R (gnatbind)
15503 @item @code{-R}
15505 Output closure source list, which includes all non-run-time units that are
15506 included in the bind.
15508 @geindex -Ra (gnatbind)
15510 @item @code{-Ra}
15512 Like @emph{-R} but the list includes run-time units.
15514 @geindex -s (gnatbind)
15516 @item @code{-s}
15518 Require all source files to be present.
15520 @geindex -S (gnatbind)
15522 @item @code{-S@emph{xxx}}
15524 Specifies the value to be used when detecting uninitialized scalar
15525 objects with pragma Initialize_Scalars.
15526 The @cite{xxx} string specified with the switch is one of:
15529 @itemize *
15531 @item 
15532 @code{in} for an invalid value.
15534 If zero is invalid for the discrete type in question,
15535 then the scalar value is set to all zero bits.
15536 For signed discrete types, the largest possible negative value of
15537 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15538 For unsigned discrete types, the underlying scalar value is set to all
15539 one bits. For floating-point types, a NaN value is set
15540 (see body of package System.Scalar_Values for exact values).
15542 @item 
15543 @code{lo} for low value.
15545 If zero is invalid for the discrete type in question,
15546 then the scalar value is set to all zero bits.
15547 For signed discrete types, the largest possible negative value of
15548 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15549 For unsigned discrete types, the underlying scalar value is set to all
15550 zero bits. For floating-point, a small value is set
15551 (see body of package System.Scalar_Values for exact values).
15553 @item 
15554 @code{hi} for high value.
15556 If zero is invalid for the discrete type in question,
15557 then the scalar value is set to all one bits.
15558 For signed discrete types, the largest possible positive value of
15559 the underlying scalar is set (i.e. a zero bit followed by all one bits).
15560 For unsigned discrete types, the underlying scalar value is set to all
15561 one bits. For floating-point, a large value is set
15562 (see body of package System.Scalar_Values for exact values).
15564 @item 
15565 @cite{xx} for hex value (two hex digits).
15567 The underlying scalar is set to a value consisting of repeated bytes, whose
15568 value corresponds to the given value. For example if @code{BF} is given,
15569 then a 32-bit scalar value will be set to the bit patterm @code{16#BFBFBFBF#}.
15570 @end itemize
15572 @geindex GNAT_INIT_SCALARS
15574 In addition, you can specify @emph{-Sev} to indicate that the value is
15575 to be set at run time. In this case, the program will look for an environment
15576 variable of the form @code{GNAT_INIT_SCALARS=@emph{yy}}, where @cite{yy} is one
15577 of @emph{in/lo/hi/`xx*` with the same meanings as above.
15578 If no environment variable is found, or if it does not have a valid value,
15579 then the default is *in} (invalid values).
15580 @end table
15582 @geindex -static (gnatbind)
15585 @table @asis
15587 @item @code{-static}
15589 Link against a static GNAT run time.
15591 @geindex -shared (gnatbind)
15593 @item @code{-shared}
15595 Link against a shared GNAT run time when available.
15597 @geindex -t (gnatbind)
15599 @item @code{-t}
15601 Tolerate time stamp and other consistency errors.
15603 @geindex -T (gnatbind)
15605 @item @code{-T@emph{n}}
15607 Set the time slice value to @cite{n} milliseconds. If the system supports
15608 the specification of a specific time slice value, then the indicated value
15609 is used. If the system does not support specific time slice values, but
15610 does support some general notion of round-robin scheduling, then any
15611 nonzero value will activate round-robin scheduling.
15613 A value of zero is treated specially. It turns off time
15614 slicing, and in addition, indicates to the tasking run time that the
15615 semantics should match as closely as possible the Annex D
15616 requirements of the Ada RM, and in particular sets the default
15617 scheduling policy to @cite{FIFO_Within_Priorities}.
15619 @geindex -u (gnatbind)
15621 @item @code{-u@emph{n}}
15623 Enable dynamic stack usage, with @cite{n} results stored and displayed
15624 at program termination. A result is generated when a task
15625 terminates. Results that can't be stored are displayed on the fly, at
15626 task termination. This option is currently not supported on Itanium
15627 platforms. (See @ref{121,,Dynamic Stack Usage Analysis} for details.)
15629 @geindex -v (gnatbind)
15631 @item @code{-v}
15633 Verbose mode. Write error messages, header, summary output to
15634 @code{stdout}.
15636 @geindex -V (gnatbind)
15638 @item @code{-V@emph{key}=@emph{value}}
15640 Store the given association of @cite{key} to @cite{value} in the bind environment.
15641 Values stored this way can be retrieved at run time using
15642 @cite{GNAT.Bind_Environment}.
15644 @geindex -w (gnatbind)
15646 @item @code{-w@emph{x}}
15648 Warning mode; @cite{x} = s/e for suppress/treat as error.
15650 @geindex -Wx (gnatbind)
15652 @item @code{-Wx@emph{e}}
15654 Override default wide character encoding for standard Text_IO files.
15656 @geindex -x (gnatbind)
15658 @item @code{-x}
15660 Exclude source files (check object consistency only).
15662 @geindex -Xnnn (gnatbind)
15664 @item @code{-X@emph{nnn}}
15666 Set default exit status value, normally 0 for POSIX compliance.
15668 @geindex -y (gnatbind)
15670 @item @code{-y}
15672 Enable leap seconds support in @cite{Ada.Calendar} and its children.
15674 @geindex -z (gnatbind)
15676 @item @code{-z}
15678 No main subprogram.
15679 @end table
15681 You may obtain this listing of switches by running @cite{gnatbind} with
15682 no arguments.
15684 @menu
15685 * Consistency-Checking Modes:: 
15686 * Binder Error Message Control:: 
15687 * Elaboration Control:: 
15688 * Output Control:: 
15689 * Dynamic Allocation Control:: 
15690 * Binding with Non-Ada Main Programs:: 
15691 * Binding Programs with No Main Subprogram:: 
15693 @end menu
15695 @node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
15696 @anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{122}@anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{123}
15697 @subsubsection Consistency-Checking Modes
15700 As described earlier, by default @cite{gnatbind} checks
15701 that object files are consistent with one another and are consistent
15702 with any source files it can locate. The following switches control binder
15703 access to sources.
15705 @quotation
15707 @geindex -s (gnatbind)
15708 @end quotation
15711 @table @asis
15713 @item @code{-s}
15715 Require source files to be present. In this mode, the binder must be
15716 able to locate all source files that are referenced, in order to check
15717 their consistency. In normal mode, if a source file cannot be located it
15718 is simply ignored. If you specify this switch, a missing source
15719 file is an error.
15721 @geindex -Wx (gnatbind)
15723 @item @code{-Wx@emph{e}}
15725 Override default wide character encoding for standard Text_IO files.
15726 Normally the default wide character encoding method used for standard
15727 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
15728 the main source input (see description of switch
15729 @emph{-gnatWx} for the compiler). The
15730 use of this switch for the binder (which has the same set of
15731 possible arguments) overrides this default as specified.
15733 @geindex -x (gnatbind)
15735 @item @code{-x}
15737 Exclude source files. In this mode, the binder only checks that ALI
15738 files are consistent with one another. Source files are not accessed.
15739 The binder runs faster in this mode, and there is still a guarantee that
15740 the resulting program is self-consistent.
15741 If a source file has been edited since it was last compiled, and you
15742 specify this switch, the binder will not detect that the object
15743 file is out of date with respect to the source file. Note that this is the
15744 mode that is automatically used by @emph{gnatmake} because in this
15745 case the checking against sources has already been performed by
15746 @emph{gnatmake} in the course of compilation (i.e., before binding).
15747 @end table
15749 @node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
15750 @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}
15751 @subsubsection Binder Error Message Control
15754 The following switches provide control over the generation of error
15755 messages from the binder:
15757 @quotation
15759 @geindex -v (gnatbind)
15760 @end quotation
15763 @table @asis
15765 @item @code{-v}
15767 Verbose mode. In the normal mode, brief error messages are generated to
15768 @code{stderr}. If this switch is present, a header is written
15769 to @code{stdout} and any error messages are directed to @code{stdout}.
15770 All that is written to @code{stderr} is a brief summary message.
15772 @geindex -b (gnatbind)
15774 @item @code{-b}
15776 Generate brief error messages to @code{stderr} even if verbose mode is
15777 specified. This is relevant only when used with the
15778 @emph{-v} switch.
15780 @geindex -m (gnatbind)
15782 @item @code{-m@emph{n}}
15784 Limits the number of error messages to @cite{n}, a decimal integer in the
15785 range 1-999. The binder terminates immediately if this limit is reached.
15787 @geindex -M (gnatbind)
15789 @item @code{-M@emph{xxx}}
15791 Renames the generated main program from @cite{main} to @cite{xxx}.
15792 This is useful in the case of some cross-building environments, where
15793 the actual main program is separate from the one generated
15794 by @cite{gnatbind}.
15796 @geindex -ws (gnatbind)
15798 @geindex Warnings
15800 @item @code{-ws}
15802 Suppress all warning messages.
15804 @geindex -we (gnatbind)
15806 @item @code{-we}
15808 Treat any warning messages as fatal errors.
15810 @geindex -t (gnatbind)
15812 @geindex Time stamp checks
15813 @geindex in binder
15815 @geindex Binder consistency checks
15817 @geindex Consistency checks
15818 @geindex in binder
15820 @item @code{-t}
15822 The binder performs a number of consistency checks including:
15825 @itemize *
15827 @item 
15828 Check that time stamps of a given source unit are consistent
15830 @item 
15831 Check that checksums of a given source unit are consistent
15833 @item 
15834 Check that consistent versions of @cite{GNAT} were used for compilation
15836 @item 
15837 Check consistency of configuration pragmas as required
15838 @end itemize
15840 Normally failure of such checks, in accordance with the consistency
15841 requirements of the Ada Reference Manual, causes error messages to be
15842 generated which abort the binder and prevent the output of a binder
15843 file and subsequent link to obtain an executable.
15845 The @emph{-t} switch converts these error messages
15846 into warnings, so that
15847 binding and linking can continue to completion even in the presence of such
15848 errors. The result may be a failed link (due to missing symbols), or a
15849 non-functional executable which has undefined semantics.
15851 @cartouche
15852 @quotation Note 
15853 This means that @emph{-t} should be used only in unusual situations,
15854 with extreme care.
15855 @end quotation
15856 @end cartouche
15857 @end table
15859 @node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
15860 @anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{126}@anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{127}
15861 @subsubsection Elaboration Control
15864 The following switches provide additional control over the elaboration
15865 order. For full details see @ref{f,,Elaboration Order Handling in GNAT}.
15867 @geindex -f (gnatbind)
15870 @table @asis
15872 @item @code{-f@emph{elab-order}}
15874 Force elaboration order.
15876 @cite{elab-order} should be the name of a "forced elaboration order file", that
15877 is, a text file containing library item names, one per line. A name of the
15878 form "some.unit%s" or "some.unit (spec)" denotes the spec of Some.Unit. A
15879 name of the form "some.unit%b" or "some.unit (body)" denotes the body of
15880 Some.Unit. Each pair of lines is taken to mean that there is an elaboration
15881 dependence of the second line on the first. For example, if the file
15882 contains:
15884 @example
15885 this (spec)
15886 this (body)
15887 that (spec)
15888 that (body)
15889 @end example
15891 then the spec of This will be elaborated before the body of This, and the
15892 body of This will be elaborated before the spec of That, and the spec of That
15893 will be elaborated before the body of That. The first and last of these three
15894 dependences are already required by Ada rules, so this file is really just
15895 forcing the body of This to be elaborated before the spec of That.
15897 The given order must be consistent with Ada rules, or else @cite{gnatbind} will
15898 give elaboration cycle errors. For example, if you say x (body) should be
15899 elaborated before x (spec), there will be a cycle, because Ada rules require
15900 x (spec) to be elaborated before x (body); you can't have the spec and body
15901 both elaborated before each other.
15903 If you later add "with That;" to the body of This, there will be a cycle, in
15904 which case you should erase either "this (body)" or "that (spec)" from the
15905 above forced elaboration order file.
15907 Blank lines and Ada-style comments are ignored. Unit names that do not exist
15908 in the program are ignored. Units in the GNAT predefined library are also
15909 ignored.
15911 @geindex -p (gnatbind)
15913 @item @code{-p}
15915 Normally the binder attempts to choose an elaboration order that is
15916 likely to minimize the likelihood of an elaboration order error resulting
15917 in raising a @cite{Program_Error} exception. This switch reverses the
15918 action of the binder, and requests that it deliberately choose an order
15919 that is likely to maximize the likelihood of an elaboration error.
15920 This is useful in ensuring portability and avoiding dependence on
15921 accidental fortuitous elaboration ordering.
15923 Normally it only makes sense to use the @emph{-p}
15924 switch if dynamic
15925 elaboration checking is used (@emph{-gnatE} switch used for compilation).
15926 This is because in the default static elaboration mode, all necessary
15927 @cite{Elaborate} and @cite{Elaborate_All} pragmas are implicitly inserted.
15928 These implicit pragmas are still respected by the binder in
15929 @emph{-p} mode, so a
15930 safe elaboration order is assured.
15932 Note that @emph{-p} is not intended for
15933 production use; it is more for debugging/experimental use.
15934 @end table
15936 @node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
15937 @anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{128}@anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{129}
15938 @subsubsection Output Control
15941 The following switches allow additional control over the output
15942 generated by the binder.
15944 @quotation
15946 @geindex -c (gnatbind)
15947 @end quotation
15950 @table @asis
15952 @item @code{-c}
15954 Check only. Do not generate the binder output file. In this mode the
15955 binder performs all error checks but does not generate an output file.
15957 @geindex -e (gnatbind)
15959 @item @code{-e}
15961 Output complete list of elaboration-order dependencies, showing the
15962 reason for each dependency. This output can be rather extensive but may
15963 be useful in diagnosing problems with elaboration order. The output is
15964 written to @code{stdout}.
15966 @geindex -h (gnatbind)
15968 @item @code{-h}
15970 Output usage information. The output is written to @code{stdout}.
15972 @geindex -K (gnatbind)
15974 @item @code{-K}
15976 Output linker options to @code{stdout}. Includes library search paths,
15977 contents of pragmas Ident and Linker_Options, and libraries added
15978 by @cite{gnatbind}.
15980 @geindex -l (gnatbind)
15982 @item @code{-l}
15984 Output chosen elaboration order. The output is written to @code{stdout}.
15986 @geindex -O (gnatbind)
15988 @item @code{-O}
15990 Output full names of all the object files that must be linked to provide
15991 the Ada component of the program. The output is written to @code{stdout}.
15992 This list includes the files explicitly supplied and referenced by the user
15993 as well as implicitly referenced run-time unit files. The latter are
15994 omitted if the corresponding units reside in shared libraries. The
15995 directory names for the run-time units depend on the system configuration.
15997 @geindex -o (gnatbind)
15999 @item @code{-o @emph{file}}
16001 Set name of output file to @cite{file} instead of the normal
16002 @code{b~`mainprog}.adb` default. Note that @cite{file} denote the Ada
16003 binder generated body filename.
16004 Note that if this option is used, then linking must be done manually.
16005 It is not possible to use gnatlink in this case, since it cannot locate
16006 the binder file.
16008 @geindex -r (gnatbind)
16010 @item @code{-r}
16012 Generate list of @cite{pragma Restrictions} that could be applied to
16013 the current unit. This is useful for code audit purposes, and also may
16014 be used to improve code generation in some cases.
16015 @end table
16017 @node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
16018 @anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{120}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{12a}
16019 @subsubsection Dynamic Allocation Control
16022 The heap control switches -- @emph{-H32} and @emph{-H64} --
16023 determine whether dynamic allocation uses 32-bit or 64-bit memory.
16024 They only affect compiler-generated allocations via @cite{__gnat_malloc};
16025 explicit calls to @cite{malloc} and related functions from the C
16026 run-time library are unaffected.
16029 @table @asis
16031 @item @code{-H32}
16033 Allocate memory on 32-bit heap
16035 @item @code{-H64}
16037 Allocate memory on 64-bit heap.  This is the default
16038 unless explicitly overridden by a @cite{'Size} clause on the access type.
16039 @end table
16041 These switches are only effective on VMS platforms.
16043 @node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
16044 @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}
16045 @subsubsection Binding with Non-Ada Main Programs
16048 The description so far has assumed that the main
16049 program is in Ada, and that the task of the binder is to generate a
16050 corresponding function @cite{main} that invokes this Ada main
16051 program. GNAT also supports the building of executable programs where
16052 the main program is not in Ada, but some of the called routines are
16053 written in Ada and compiled using GNAT (@ref{44,,Mixed Language Programming}).
16054 The following switch is used in this situation:
16056 @quotation
16058 @geindex -n (gnatbind)
16059 @end quotation
16062 @table @asis
16064 @item @code{-n}
16066 No main program. The main program is not in Ada.
16067 @end table
16069 In this case, most of the functions of the binder are still required,
16070 but instead of generating a main program, the binder generates a file
16071 containing the following callable routines:
16073 @quotation
16075 @geindex adainit
16078 @table @asis
16080 @item @emph{adainit}
16082 You must call this routine to initialize the Ada part of the program by
16083 calling the necessary elaboration routines. A call to @cite{adainit} is
16084 required before the first call to an Ada subprogram.
16086 Note that it is assumed that the basic execution environment must be setup
16087 to be appropriate for Ada execution at the point where the first Ada
16088 subprogram is called. In particular, if the Ada code will do any
16089 floating-point operations, then the FPU must be setup in an appropriate
16090 manner. For the case of the x86, for example, full precision mode is
16091 required. The procedure GNAT.Float_Control.Reset may be used to ensure
16092 that the FPU is in the right state.
16093 @end table
16095 @geindex adafinal
16098 @table @asis
16100 @item @emph{adafinal}
16102 You must call this routine to perform any library-level finalization
16103 required by the Ada subprograms. A call to @cite{adafinal} is required
16104 after the last call to an Ada subprogram, and before the program
16105 terminates.
16106 @end table
16107 @end quotation
16109 @geindex -n (gnatbind)
16111 @geindex Binder
16112 @geindex multiple input files
16114 If the @emph{-n} switch
16115 is given, more than one ALI file may appear on
16116 the command line for @cite{gnatbind}. The normal @emph{closure}
16117 calculation is performed for each of the specified units. Calculating
16118 the closure means finding out the set of units involved by tracing
16119 @emph{with} references. The reason it is necessary to be able to
16120 specify more than one ALI file is that a given program may invoke two or
16121 more quite separate groups of Ada units.
16123 The binder takes the name of its output file from the last specified ALI
16124 file, unless overridden by the use of the @emph{-o file}.
16126 @geindex -o (gnatbind)
16128 The output is an Ada unit in source form that can be compiled with GNAT.
16129 This compilation occurs automatically as part of the @emph{gnatlink}
16130 processing.
16132 Currently the GNAT run time requires a FPU using 80 bits mode
16133 precision. Under targets where this is not the default it is required to
16134 call GNAT.Float_Control.Reset before using floating point numbers (this
16135 include float computation, float input and output) in the Ada code. A
16136 side effect is that this could be the wrong mode for the foreign code
16137 where floating point computation could be broken after this call.
16139 @node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16140 @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}
16141 @subsubsection Binding Programs with No Main Subprogram
16144 It is possible to have an Ada program which does not have a main
16145 subprogram. This program will call the elaboration routines of all the
16146 packages, then the finalization routines.
16148 The following switch is used to bind programs organized in this manner:
16150 @quotation
16152 @geindex -z (gnatbind)
16153 @end quotation
16156 @table @asis
16158 @item @code{-z}
16160 Normally the binder checks that the unit name given on the command line
16161 corresponds to a suitable main subprogram. When this switch is used,
16162 a list of ALI files can be given, and the execution of the program
16163 consists of elaboration of these units in an appropriate order. Note
16164 that the default wide character encoding method for standard Text_IO
16165 files is always set to Brackets if this switch is set (you can use
16166 the binder switch
16167 @emph{-Wx} to override this default).
16168 @end table
16170 @node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16171 @anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{12e}@anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{12f}
16172 @subsection Command-Line Access
16175 The package @cite{Ada.Command_Line} provides access to the command-line
16176 arguments and program name. In order for this interface to operate
16177 correctly, the two variables
16179 @example
16180 int gnat_argc;
16181 char **gnat_argv;
16182 @end example
16184 @geindex gnat_argv
16186 @geindex gnat_argc
16188 are declared in one of the GNAT library routines. These variables must
16189 be set from the actual @cite{argc} and @cite{argv} values passed to the
16190 main program. With no @emph{n} present, @cite{gnatbind}
16191 generates the C main program to automatically set these variables.
16192 If the @emph{n} switch is used, there is no automatic way to
16193 set these variables. If they are not set, the procedures in
16194 @cite{Ada.Command_Line} will not be available, and any attempt to use
16195 them will raise @cite{Constraint_Error}. If command line access is
16196 required, your main program must set @cite{gnat_argc} and
16197 @cite{gnat_argv} from the @cite{argc} and @cite{argv} values passed to
16200 @node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16201 @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}
16202 @subsection Search Paths for @cite{gnatbind}
16205 The binder takes the name of an ALI file as its argument and needs to
16206 locate source files as well as other ALI files to verify object consistency.
16208 For source files, it follows exactly the same search rules as @emph{gcc}
16209 (see @ref{89,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16210 directories searched are:
16213 @itemize *
16215 @item 
16216 The directory containing the ALI file named in the command line, unless
16217 the switch @emph{-I-} is specified.
16219 @item 
16220 All directories specified by @emph{-I}
16221 switches on the @cite{gnatbind}
16222 command line, in the order given.
16224 @geindex ADA_PRJ_OBJECTS_FILE
16226 @item 
16227 Each of the directories listed in the text file whose name is given
16228 by the 
16229 @geindex ADA_PRJ_OBJECTS_FILE
16230 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16231 @code{ADA_PRJ_OBJECTS_FILE} environment variable.
16233 @geindex ADA_PRJ_OBJECTS_FILE
16234 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16235 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16236 driver when project files are used. It should not normally be set
16237 by other means.
16239 @geindex ADA_OBJECTS_PATH
16241 @item 
16242 Each of the directories listed in the value of the
16243 @geindex ADA_OBJECTS_PATH
16244 @geindex environment variable; ADA_OBJECTS_PATH
16245 @code{ADA_OBJECTS_PATH} environment variable.
16246 Construct this value
16247 exactly as the 
16248 @geindex PATH
16249 @geindex environment variable; PATH
16250 @code{PATH} environment variable: a list of directory
16251 names separated by colons (semicolons when working with the NT version
16252 of GNAT).
16254 @item 
16255 The content of the @code{ada_object_path} file which is part of the GNAT
16256 installation tree and is used to store standard libraries such as the
16257 GNAT Run Time Library (RTL) unless the switch @emph{-nostdlib} is
16258 specified. See @ref{87,,Installing a library}
16259 @end itemize
16261 @geindex -I (gnatbind)
16263 @geindex -aI (gnatbind)
16265 @geindex -aO (gnatbind)
16267 In the binder the switch @emph{-I}
16268 is used to specify both source and
16269 library file paths. Use @emph{-aI}
16270 instead if you want to specify
16271 source paths only, and @emph{-aO}
16272 if you want to specify library paths
16273 only. This means that for the binder
16274 @code{-I@emph{dir}} is equivalent to
16275 @code{-aI@emph{dir}}
16276 @code{-aO`@emph{dir}}.
16277 The binder generates the bind file (a C language source file) in the
16278 current working directory.
16280 @geindex Ada
16282 @geindex System
16284 @geindex Interfaces
16286 @geindex GNAT
16288 The packages @cite{Ada}, @cite{System}, and @cite{Interfaces} and their
16289 children make up the GNAT Run-Time Library, together with the package
16290 GNAT and its children, which contain a set of useful additional
16291 library functions provided by GNAT. The sources for these units are
16292 needed by the compiler and are kept together in one directory. The ALI
16293 files and object files generated by compiling the RTL are needed by the
16294 binder and the linker and are kept together in one directory, typically
16295 different from the directory containing the sources. In a normal
16296 installation, you need not specify these directory names when compiling
16297 or binding. Either the environment variables or the built-in defaults
16298 cause these files to be found.
16300 Besides simplifying access to the RTL, a major use of search paths is
16301 in compiling sources from multiple directories. This can make
16302 development environments much more flexible.
16304 @node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16305 @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}
16306 @subsection Examples of @cite{gnatbind} Usage
16309 Here are some examples of @cite{gnatbind} invovations:
16311 @quotation
16313 @example
16314 gnatbind hello
16315 @end example
16317 The main program @cite{Hello} (source program in @code{hello.adb}) is
16318 bound using the standard switch settings. The generated main program is
16319 @code{b~hello.adb}. This is the normal, default use of the binder.
16321 @example
16322 gnatbind hello -o mainprog.adb
16323 @end example
16325 The main program @cite{Hello} (source program in @code{hello.adb}) is
16326 bound using the standard switch settings. The generated main program is
16327 @code{mainprog.adb} with the associated spec in
16328 @code{mainprog.ads}. Note that you must specify the body here not the
16329 spec. Note that if this option is used, then linking must be done manually,
16330 since gnatlink will not be able to find the generated file.
16331 @end quotation
16333 @node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16334 @anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{133}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{1e}
16335 @section Linking with @emph{gnatlink}
16338 @geindex gnatlink
16340 This chapter discusses @emph{gnatlink}, a tool that links
16341 an Ada program and builds an executable file. This utility
16342 invokes the system linker (via the @emph{gcc} command)
16343 with a correct list of object files and library references.
16344 @emph{gnatlink} automatically determines the list of files and
16345 references for the Ada part of a program. It uses the binder file
16346 generated by the @emph{gnatbind} to determine this list.
16348 Note: to invoke @cite{gnatlink} with a project file, use the @cite{gnat}
16349 driver (see @emph{The_GNAT_Driver_and_Project_Files}).
16351 @menu
16352 * Running gnatlink:: 
16353 * Switches for gnatlink:: 
16355 @end menu
16357 @node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16358 @anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{134}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{135}
16359 @subsection Running @emph{gnatlink}
16362 The form of the @emph{gnatlink} command is
16364 @example
16365 $ gnatlink [`switches`] `mainprog`[.ali]
16366            [`non-Ada objects`] [`linker options`]
16367 @end example
16369 The arguments of @emph{gnatlink} (switches, main @code{ALI} file,
16370 non-Ada objects
16371 or linker options) may be in any order, provided that no non-Ada object may
16372 be mistaken for a main @code{ALI} file.
16373 Any file name @code{F} without the @code{.ali}
16374 extension will be taken as the main @code{ALI} file if a file exists
16375 whose name is the concatenation of @code{F} and @code{.ali}.
16377 @code{mainprog.ali} references the ALI file of the main program.
16378 The @code{.ali} extension of this file can be omitted. From this
16379 reference, @emph{gnatlink} locates the corresponding binder file
16380 @code{b~mainprog.adb} and, using the information in this file along
16381 with the list of non-Ada objects and linker options, constructs a
16382 linker command file to create the executable.
16384 The arguments other than the @emph{gnatlink} switches and the main
16385 @code{ALI} file are passed to the linker uninterpreted.
16386 They typically include the names of
16387 object files for units written in other languages than Ada and any library
16388 references required to resolve references in any of these foreign language
16389 units, or in @cite{Import} pragmas in any Ada units.
16391 @cite{linker options} is an optional list of linker specific
16392 switches.
16393 The default linker called by gnatlink is @emph{gcc} which in
16394 turn calls the appropriate system linker.
16396 One useful option for the linker is @emph{-s}: it reduces the size of the
16397 executable by removing all symbol table and relocation information from the
16398 executable.
16400 Standard options for the linker such as @emph{-lmy_lib} or
16401 @emph{-Ldir} can be added as is.
16402 For options that are not recognized by
16403 @emph{gcc} as linker options, use the @emph{gcc} switches
16404 @emph{-Xlinker} or @emph{-Wl,}.
16406 Refer to the GCC documentation for
16407 details.
16409 Here is an example showing how to generate a linker map:
16411 @example
16412 $ gnatlink my_prog -Wl,-Map,MAPFILE
16413 @end example
16415 Using @cite{linker options} it is possible to set the program stack and
16416 heap size.
16417 See @ref{136,,Setting Stack Size from gnatlink} and
16418 @ref{137,,Setting Heap Size from gnatlink}.
16420 @emph{gnatlink} determines the list of objects required by the Ada
16421 program and prepends them to the list of objects passed to the linker.
16422 @emph{gnatlink} also gathers any arguments set by the use of
16423 @cite{pragma Linker_Options} and adds them to the list of arguments
16424 presented to the linker.
16426 @node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
16427 @anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{138}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{139}
16428 @subsection Switches for @emph{gnatlink}
16431 The following switches are available with the @emph{gnatlink} utility:
16433 @geindex --version (gnatlink)
16436 @table @asis
16438 @item @code{--version}
16440 Display Copyright and version, then exit disregarding all other options.
16441 @end table
16443 @geindex --help (gnatlink)
16446 @table @asis
16448 @item @code{--help}
16450 If @emph{--version} was not used, display usage, then exit disregarding
16451 all other options.
16452 @end table
16454 @geindex Command line length
16456 @geindex -f (gnatlink)
16459 @table @asis
16461 @item @code{-f}
16463 On some targets, the command line length is limited, and @emph{gnatlink}
16464 will generate a separate file for the linker if the list of object files
16465 is too long.
16466 The @emph{-f} switch forces this file
16467 to be generated even if
16468 the limit is not exceeded. This is useful in some cases to deal with
16469 special situations where the command line length is exceeded.
16470 @end table
16472 @geindex Debugging information
16473 @geindex including
16475 @geindex -g (gnatlink)
16478 @table @asis
16480 @item @code{-g}
16482 The option to include debugging information causes the Ada bind file (in
16483 other words, @code{b~mainprog.adb}) to be compiled with @emph{-g}.
16484 In addition, the binder does not delete the @code{b~mainprog.adb},
16485 @code{b~mainprog.o} and @code{b~mainprog.ali} files.
16486 Without @emph{-g}, the binder removes these files by default.
16487 @end table
16489 @geindex -n (gnatlink)
16492 @table @asis
16494 @item @code{-n}
16496 Do not compile the file generated by the binder. This may be used when
16497 a link is rerun with different options, but there is no need to recompile
16498 the binder file.
16499 @end table
16501 @geindex -v (gnatlink)
16504 @table @asis
16506 @item @code{-v}
16508 Verbose mode. Causes additional information to be output, including a full
16509 list of the included object files.
16510 This switch option is most useful when you want
16511 to see what set of object files are being used in the link step.
16512 @end table
16514 @geindex -v -v (gnatlink)
16517 @table @asis
16519 @item @code{-v -v}
16521 Very verbose mode. Requests that the compiler operate in verbose mode when
16522 it compiles the binder file, and that the system linker run in verbose mode.
16523 @end table
16525 @geindex -o (gnatlink)
16528 @table @asis
16530 @item @code{-o @emph{exec-name}}
16532 @cite{exec-name} specifies an alternate name for the generated
16533 executable program. If this switch is omitted, the executable has the same
16534 name as the main unit. For example, @cite{gnatlink try.ali} creates
16535 an executable called @code{try}.
16536 @end table
16538 @geindex -b (gnatlink)
16541 @table @asis
16543 @item @code{-b @emph{target}}
16545 Compile your program to run on @cite{target}, which is the name of a
16546 system configuration. You must have a GNAT cross-compiler built if
16547 @cite{target} is not the same as your host system.
16548 @end table
16550 @geindex -B (gnatlink)
16553 @table @asis
16555 @item @code{-B@emph{dir}}
16557 Load compiler executables (for example, @cite{gnat1}, the Ada compiler)
16558 from @cite{dir} instead of the default location. Only use this switch
16559 when multiple versions of the GNAT compiler are available.
16560 See the @cite{Directory Options} section in @cite{The_GNU_Compiler_Collection}
16561 for further details. You would normally use the @emph{-b} or
16562 @emph{-V} switch instead.
16563 @end table
16565 @geindex -M (gnatlink)
16568 @table @asis
16570 @item @code{-M}
16572 When linking an executable, create a map file. The name of the map file
16573 has the same name as the executable with extension ".map".
16574 @end table
16576 @geindex -M= (gnatlink)
16579 @table @asis
16581 @item @code{-M=@emph{mapfile}}
16583 When linking an executable, create a map file. The name of the map file is
16584 @cite{mapfile}.
16585 @end table
16587 @geindex --GCC=compiler_name (gnatlink)
16590 @table @asis
16592 @item @code{--GCC=@emph{compiler_name}}
16594 Program used for compiling the binder file. The default is
16595 @code{gcc}. You need to use quotes around @cite{compiler_name} if
16596 @cite{compiler_name} contains spaces or other separator characters.
16597 As an example @code{--GCC="foo -x -y"} will instruct @emph{gnatlink} to
16598 use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
16599 inserted after your command name. Thus in the above example the compiler
16600 command that will be used by @emph{gnatlink} will be @code{foo -c -x -y}.
16601 A limitation of this syntax is that the name and path name of the executable
16602 itself must not include any embedded spaces. If the compiler executable is
16603 different from the default one (gcc or <prefix>-gcc), then the back-end
16604 switches in the ALI file are not used to compile the binder generated source.
16605 For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
16606 switches will be used for @code{--GCC="gcc -gnatv"}. If several
16607 @code{--GCC=compiler_name} are used, only the last @cite{compiler_name}
16608 is taken into account. However, all the additional switches are also taken
16609 into account. Thus,
16610 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
16611 @code{--GCC="bar -x -y -z -t"}.
16612 @end table
16614 @geindex --LINK= (gnatlink)
16617 @table @asis
16619 @item @code{--LINK=@emph{name}}
16621 @cite{name} is the name of the linker to be invoked. This is especially
16622 useful in mixed language programs since languages such as C++ require
16623 their own linker to be used. When this switch is omitted, the default
16624 name for the linker is @emph{gcc}. When this switch is used, the
16625 specified linker is called instead of @emph{gcc} with exactly the same
16626 parameters that would have been passed to @emph{gcc} so if the desired
16627 linker requires different parameters it is necessary to use a wrapper
16628 script that massages the parameters before invoking the real linker. It
16629 may be useful to control the exact invocation by using the verbose
16630 switch.
16631 @end table
16633 @node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
16634 @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}
16635 @section Using the GNU @cite{make} Utility
16638 @geindex make (GNU)
16639 @geindex GNU make
16641 This chapter offers some examples of makefiles that solve specific
16642 problems. It does not explain how to write a makefile, nor does it try to replace the
16643 @emph{gnatmake} utility (@ref{1b,,Building with gnatmake}).
16645 All the examples in this section are specific to the GNU version of
16646 make. Although @emph{make} is a standard utility, and the basic language
16647 is the same, these examples use some advanced features found only in
16648 @cite{GNU make}.
16650 @menu
16651 * Using gnatmake in a Makefile:: 
16652 * Automatically Creating a List of Directories:: 
16653 * Generating the Command Line Switches:: 
16654 * Overcoming Command Line Length Limits:: 
16656 @end menu
16658 @node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
16659 @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}
16660 @subsection Using gnatmake in a Makefile
16663 @c index makefile (GNU make)
16665 Complex project organizations can be handled in a very powerful way by
16666 using GNU make combined with gnatmake. For instance, here is a Makefile
16667 which allows you to build each subsystem of a big project into a separate
16668 shared library. Such a makefile allows you to significantly reduce the link
16669 time of very big applications while maintaining full coherence at
16670 each step of the build process.
16672 The list of dependencies are handled automatically by
16673 @emph{gnatmake}. The Makefile is simply used to call gnatmake in each of
16674 the appropriate directories.
16676 Note that you should also read the example on how to automatically
16677 create the list of directories
16678 (@ref{13d,,Automatically Creating a List of Directories})
16679 which might help you in case your project has a lot of subdirectories.
16681 @example
16682 ## This Makefile is intended to be used with the following directory
16683 ## configuration:
16684 ##  - The sources are split into a series of csc (computer software components)
16685 ##    Each of these csc is put in its own directory.
16686 ##    Their name are referenced by the directory names.
16687 ##    They will be compiled into shared library (although this would also work
16688 ##    with static libraries
16689 ##  - The main program (and possibly other packages that do not belong to any
16690 ##    csc is put in the top level directory (where the Makefile is).
16691 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16692 ##                    \\_ second_csc (sources) __ lib (will contain the library)
16693 ##                    \\_ ...
16694 ## Although this Makefile is build for shared library, it is easy to modify
16695 ## to build partial link objects instead (modify the lines with -shared and
16696 ## gnatlink below)
16698 ## With this makefile, you can change any file in the system or add any new
16699 ## file, and everything will be recompiled correctly (only the relevant shared
16700 ## objects will be recompiled, and the main program will be re-linked).
16702 # The list of computer software component for your project. This might be
16703 # generated automatically.
16704 CSC_LIST=aa bb cc
16706 # Name of the main program (no extension)
16707 MAIN=main
16709 # If we need to build objects with -fPIC, uncomment the following line
16710 #NEED_FPIC=-fPIC
16712 # The following variable should give the directory containing libgnat.so
16713 # You can get this directory through 'gnatls -v'. This is usually the last
16714 # directory in the Object_Path.
16715 GLIB=...
16717 # The directories for the libraries
16718 # (This macro expands the list of CSC to the list of shared libraries, you
16719 # could simply use the expanded form:
16720 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16721 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16723 $@{MAIN@}: objects $@{LIB_DIR@}
16724     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16725     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16727 objects::
16728     # recompile the sources
16729     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16731 # Note: In a future version of GNAT, the following commands will be simplified
16732 # by a new tool, gnatmlib
16733 $@{LIB_DIR@}:
16734     mkdir -p $@{dir $@@ @}
16735     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16736     cd $@{dir $@@ @} && cp -f ../*.ali .
16738 # The dependencies for the modules
16739 # Note that we have to force the expansion of *.o, since in some cases
16740 # make won't be able to do it itself.
16741 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16742 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16743 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16745 # Make sure all of the shared libraries are in the path before starting the
16746 # program
16747 run::
16748     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16750 clean::
16751     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16752     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16753     $@{RM@} $@{CSC_LIST:%=%/*.o@}
16754     $@{RM@} *.o *.ali $@{MAIN@}
16755 @end example
16757 @node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
16758 @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}
16759 @subsection Automatically Creating a List of Directories
16762 In most makefiles, you will have to specify a list of directories, and
16763 store it in a variable. For small projects, it is often easier to
16764 specify each of them by hand, since you then have full control over what
16765 is the proper order for these directories, which ones should be
16766 included.
16768 However, in larger projects, which might involve hundreds of
16769 subdirectories, it might be more convenient to generate this list
16770 automatically.
16772 The example below presents two methods. The first one, although less
16773 general, gives you more control over the list. It involves wildcard
16774 characters, that are automatically expanded by @emph{make}. Its
16775 shortcoming is that you need to explicitly specify some of the
16776 organization of your project, such as for instance the directory tree
16777 depth, whether some directories are found in a separate tree, etc.
16779 The second method is the most general one. It requires an external
16780 program, called @emph{find}, which is standard on all Unix systems. All
16781 the directories found under a given root directory will be added to the
16782 list.
16784 @example
16785 # The examples below are based on the following directory hierarchy:
16786 # All the directories can contain any number of files
16787 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
16788 #                       ->  ab
16789 #                       ->  ac
16790 #                ->  b  ->  ba  ->  baa
16791 #                       ->  bb
16792 #                       ->  bc
16793 # This Makefile creates a variable called DIRS, that can be reused any time
16794 # you need this list (see the other examples in this section)
16796 # The root of your project's directory hierarchy
16797 ROOT_DIRECTORY=.
16799 ####
16800 # First method: specify explicitly the list of directories
16801 # This allows you to specify any subset of all the directories you need.
16802 ####
16804 DIRS := a/aa/ a/ab/ b/ba/
16806 ####
16807 # Second method: use wildcards
16808 # Note that the argument(s) to wildcard below should end with a '/'.
16809 # Since wildcards also return file names, we have to filter them out
16810 # to avoid duplicate directory names.
16811 # We thus use make's `dir` and `sort` functions.
16812 # It sets DIRs to the following value (note that the directories aaa and baa
16813 # are not given, unless you change the arguments to wildcard).
16814 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16815 ####
16817 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16818                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16820 ####
16821 # Third method: use an external program
16822 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16823 # This is the most complete command: it sets DIRs to the following value:
16824 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16825 ####
16827 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16828 @end example
16830 @node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
16831 @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}
16832 @subsection Generating the Command Line Switches
16835 Once you have created the list of directories as explained in the
16836 previous section (@ref{13d,,Automatically Creating a List of Directories}),
16837 you can easily generate the command line arguments to pass to gnatmake.
16839 For the sake of completeness, this example assumes that the source path
16840 is not the same as the object path, and that you have two separate lists
16841 of directories.
16843 @example
16844 # see "Automatically creating a list of directories" to create
16845 # these variables
16846 SOURCE_DIRS=
16847 OBJECT_DIRS=
16849 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16850 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16852 all:
16853         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16854 @end example
16856 @node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
16857 @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}
16858 @subsection Overcoming Command Line Length Limits
16861 One problem that might be encountered on big projects is that many
16862 operating systems limit the length of the command line. It is thus hard to give
16863 gnatmake the list of source and object directories.
16865 This example shows how you can set up environment variables, which will
16866 make @emph{gnatmake} behave exactly as if the directories had been
16867 specified on the command line, but have a much higher length limit (or
16868 even none on most systems).
16870 It assumes that you have created a list of directories in your Makefile,
16871 using one of the methods presented in
16872 @ref{13d,,Automatically Creating a List of Directories}.
16873 For the sake of completeness, we assume that the object
16874 path (where the ALI files are found) is different from the sources patch.
16876 Note a small trick in the Makefile below: for efficiency reasons, we
16877 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16878 expanded immediately by @cite{make}. This way we overcome the standard
16879 make behavior which is to expand the variables only when they are
16880 actually used.
16882 On Windows, if you are using the standard Windows command shell, you must
16883 replace colons with semicolons in the assignments to these variables.
16885 @example
16886 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16887 # This is the same thing as putting the -I arguments on the command line.
16888 # (the equivalent of using -aI on the command line would be to define
16889 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16890 # You can of course have different values for these variables.
16892 # Note also that we need to keep the previous values of these variables, since
16893 # they might have been set before running 'make' to specify where the GNAT
16894 # library is installed.
16896 # see "Automatically creating a list of directories" to create these
16897 # variables
16898 SOURCE_DIRS=
16899 OBJECT_DIRS=
16901 empty:=
16902 space:=$@{empty@} $@{empty@}
16903 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16904 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16905 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16906 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16907 export ADA_INCLUDE_PATH
16908 export ADA_OBJECTS_PATH
16910 all:
16911         gnatmake main_unit
16912 @end example
16914 @node GNAT Utility Programs,GNAT and Program Execution,Building Executable Programs with GNAT,Top
16915 @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}
16916 @chapter GNAT Utility Programs
16919 This chapter describes a number of utility programs:
16923 @itemize *
16925 @item 
16926 @ref{20,,The File Cleanup Utility gnatclean}
16928 @item 
16929 @ref{21,,The GNAT Library Browser gnatls}
16931 @item 
16932 @ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
16934 @item 
16935 @ref{23,,The Ada to HTML Converter gnathtml}
16936 @end itemize
16938 Other GNAT utilities are described elsewhere in this manual:
16941 @itemize *
16943 @item 
16944 @ref{59,,Handling Arbitrary File Naming Conventions with gnatname}
16946 @item 
16947 @ref{63,,File Name Krunching with gnatkr}
16949 @item 
16950 @ref{36,,Renaming Files with gnatchop}
16952 @item 
16953 @ref{17,,Preprocessing with gnatprep}
16954 @end itemize
16956 @menu
16957 * The File Cleanup Utility gnatclean:: 
16958 * The GNAT Library Browser gnatls:: 
16959 * The Cross-Referencing Tools gnatxref and gnatfind:: 
16960 * The Ada to HTML Converter gnathtml:: 
16962 @end menu
16964 @node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
16965 @anchor{gnat_ugn/gnat_utility_programs id2}@anchor{145}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{20}
16966 @section The File Cleanup Utility @emph{gnatclean}
16969 @geindex File cleanup tool
16971 @geindex gnatclean
16973 @cite{gnatclean} is a tool that allows the deletion of files produced by the
16974 compiler, binder and linker, including ALI files, object files, tree files,
16975 expanded source files, library files, interface copy source files, binder
16976 generated files and executable files.
16978 @menu
16979 * Running gnatclean:: 
16980 * Switches for gnatclean:: 
16982 @end menu
16984 @node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
16985 @anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{146}@anchor{gnat_ugn/gnat_utility_programs id3}@anchor{147}
16986 @subsection Running @cite{gnatclean}
16989 The @cite{gnatclean} command has the form:
16991 @quotation
16993 @example
16994 $ gnatclean switches `names`
16995 @end example
16996 @end quotation
16998 where @cite{names} is a list of source file names. Suffixes @code{.ads} and
16999 @code{adb} may be omitted. If a project file is specified using switch
17000 @code{-P}, then @cite{names} may be completely omitted.
17002 In normal mode, @cite{gnatclean} delete the files produced by the compiler and,
17003 if switch @cite{-c} is not specified, by the binder and
17004 the linker. In informative-only mode, specified by switch
17005 @cite{-n}, the list of files that would have been deleted in
17006 normal mode is listed, but no file is actually deleted.
17008 @node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
17009 @anchor{gnat_ugn/gnat_utility_programs id4}@anchor{148}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{149}
17010 @subsection Switches for @cite{gnatclean}
17013 @cite{gnatclean} recognizes the following switches:
17015 @geindex --version (gnatclean)
17018 @table @asis
17020 @item @code{--version}
17022 Display Copyright and version, then exit disregarding all other options.
17023 @end table
17025 @geindex --help (gnatclean)
17028 @table @asis
17030 @item @code{--help}
17032 If @emph{--version} was not used, display usage, then exit disregarding
17033 all other options.
17035 @item @code{--subdirs=@emph{subdir}}
17037 Actual object directory of each project file is the subdirectory subdir of the
17038 object directory specified or defaulted in the project file.
17040 @item @code{--unchecked-shared-lib-imports}
17042 By default, shared library projects are not allowed to import static library
17043 projects. When this switch is used on the command line, this restriction is
17044 relaxed.
17045 @end table
17047 @geindex -c (gnatclean)
17050 @table @asis
17052 @item @code{-c}
17054 Only attempt to delete the files produced by the compiler, not those produced
17055 by the binder or the linker. The files that are not to be deleted are library
17056 files, interface copy files, binder generated files and executable files.
17057 @end table
17059 @geindex -D (gnatclean)
17062 @table @asis
17064 @item @code{-D @emph{dir}}
17066 Indicate that ALI and object files should normally be found in directory @cite{dir}.
17067 @end table
17069 @geindex -F (gnatclean)
17072 @table @asis
17074 @item @code{-F}
17076 When using project files, if some errors or warnings are detected during
17077 parsing and verbose mode is not in effect (no use of switch
17078 -v), then error lines start with the full path name of the project
17079 file, rather than its simple file name.
17080 @end table
17082 @geindex -h (gnatclean)
17085 @table @asis
17087 @item @code{-h}
17089 Output a message explaining the usage of @cite{gnatclean}.
17090 @end table
17092 @geindex -n (gnatclean)
17095 @table @asis
17097 @item @code{-n}
17099 Informative-only mode. Do not delete any files. Output the list of the files
17100 that would have been deleted if this switch was not specified.
17101 @end table
17103 @geindex -P (gnatclean)
17106 @table @asis
17108 @item @code{-P@emph{project}}
17110 Use project file @cite{project}. Only one such switch can be used.
17111 When cleaning a project file, the files produced by the compilation of the
17112 immediate sources or inherited sources of the project files are to be
17113 deleted. This is not depending on the presence or not of executable names
17114 on the command line.
17115 @end table
17117 @geindex -q (gnatclean)
17120 @table @asis
17122 @item @code{-q}
17124 Quiet output. If there are no errors, do not output anything, except in
17125 verbose mode (switch -v) or in informative-only mode
17126 (switch -n).
17127 @end table
17129 @geindex -r (gnatclean)
17132 @table @asis
17134 @item @code{-r}
17136 When a project file is specified (using switch -P),
17137 clean all imported and extended project files, recursively. If this switch
17138 is not specified, only the files related to the main project file are to be
17139 deleted. This switch has no effect if no project file is specified.
17140 @end table
17142 @geindex -v (gnatclean)
17145 @table @asis
17147 @item @code{-v}
17149 Verbose mode.
17150 @end table
17152 @geindex -vP (gnatclean)
17155 @table @asis
17157 @item @code{-vP@emph{x}}
17159 Indicates the verbosity of the parsing of GNAT project files.
17160 @ref{de,,Switches Related to Project Files}.
17161 @end table
17163 @geindex -X (gnatclean)
17166 @table @asis
17168 @item @code{-X@emph{name}=@emph{value}}
17170 Indicates that external variable @cite{name} has the value @cite{value}.
17171 The Project Manager will use this value for occurrences of
17172 @cite{external(name)} when parsing the project file.
17173 @ref{de,,Switches Related to Project Files}.
17174 @end table
17176 @geindex -aO (gnatclean)
17179 @table @asis
17181 @item @code{-aO@emph{dir}}
17183 When searching for ALI and object files, look in directory @cite{dir}.
17184 @end table
17186 @geindex -I (gnatclean)
17189 @table @asis
17191 @item @code{-I@emph{dir}}
17193 Equivalent to @code{-aO@emph{dir}}.
17194 @end table
17196 @geindex -I- (gnatclean)
17198 @geindex Source files
17199 @geindex suppressing search
17202 @table @asis
17204 @item @code{-I-}
17206 Do not look for ALI or object files in the directory
17207 where @cite{gnatclean} was invoked.
17208 @end table
17210 @node The GNAT Library Browser gnatls,The Cross-Referencing Tools gnatxref and gnatfind,The File Cleanup Utility gnatclean,GNAT Utility Programs
17211 @anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{21}@anchor{gnat_ugn/gnat_utility_programs id5}@anchor{14a}
17212 @section The GNAT Library Browser @cite{gnatls}
17215 @geindex Library browser
17217 @geindex gnatls
17219 @cite{gnatls} is a tool that outputs information about compiled
17220 units. It gives the relationship between objects, unit names and source
17221 files. It can also be used to check the source dependencies of a unit
17222 as well as various characteristics.
17224 Note: to invoke @cite{gnatls} with a project file, use the @cite{gnat}
17225 driver (see @emph{The_GNAT_Driver_and_Project_Files}).
17227 @menu
17228 * Running gnatls:: 
17229 * Switches for gnatls:: 
17230 * Example of gnatls Usage:: 
17232 @end menu
17234 @node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
17235 @anchor{gnat_ugn/gnat_utility_programs id6}@anchor{14b}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{14c}
17236 @subsection Running @cite{gnatls}
17239 The @cite{gnatls} command has the form
17241 @quotation
17243 @example
17244 $ gnatls switches `object_or_ali_file`
17245 @end example
17246 @end quotation
17248 The main argument is the list of object or @code{ali} files
17249 (see @ref{42,,The Ada Library Information Files})
17250 for which information is requested.
17252 In normal mode, without additional option, @cite{gnatls} produces a
17253 four-column listing. Each line represents information for a specific
17254 object. The first column gives the full path of the object, the second
17255 column gives the name of the principal unit in this object, the third
17256 column gives the status of the source and the fourth column gives the
17257 full path of the source representing this unit.
17258 Here is a simple example of use:
17260 @quotation
17262 @example
17263 $ gnatls *.o
17264 ./demo1.o            demo1            DIF demo1.adb
17265 ./demo2.o            demo2             OK demo2.adb
17266 ./hello.o            h1                OK hello.adb
17267 ./instr-child.o      instr.child      MOK instr-child.adb
17268 ./instr.o            instr             OK instr.adb
17269 ./tef.o              tef              DIF tef.adb
17270 ./text_io_example.o  text_io_example   OK text_io_example.adb
17271 ./tgef.o             tgef             DIF tgef.adb
17272 @end example
17273 @end quotation
17275 The first line can be interpreted as follows: the main unit which is
17276 contained in
17277 object file @code{demo1.o} is demo1, whose main source is in
17278 @code{demo1.adb}. Furthermore, the version of the source used for the
17279 compilation of demo1 has been modified (DIF). Each source file has a status
17280 qualifier which can be:
17283 @table @asis
17285 @item @emph{OK (unchanged)}
17287 The version of the source file used for the compilation of the
17288 specified unit corresponds exactly to the actual source file.
17290 @item @emph{MOK (slightly modified)}
17292 The version of the source file used for the compilation of the
17293 specified unit differs from the actual source file but not enough to
17294 require recompilation. If you use gnatmake with the qualifier
17295 @emph{-m (minimal recompilation)}, a file marked
17296 MOK will not be recompiled.
17298 @item @emph{DIF (modified)}
17300 No version of the source found on the path corresponds to the source
17301 used to build this object.
17303 @item @emph{??? (file not found)}
17305 No source file was found for this unit.
17307 @item @emph{HID (hidden,  unchanged version not first on PATH)}
17309 The version of the source that corresponds exactly to the source used
17310 for compilation has been found on the path but it is hidden by another
17311 version of the same source that has been modified.
17312 @end table
17314 @node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
17315 @anchor{gnat_ugn/gnat_utility_programs id7}@anchor{14d}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{14e}
17316 @subsection Switches for @cite{gnatls}
17319 @cite{gnatls} recognizes the following switches:
17321 @geindex --version (gnatls)
17324 @table @asis
17326 @item @code{--version}
17328 Display Copyright and version, then exit disregarding all other options.
17329 @end table
17331 @geindex --help (gnatls)
17334 @table @asis
17336 @item @code{*--help}
17338 If @emph{--version} was not used, display usage, then exit disregarding
17339 all other options.
17340 @end table
17342 @geindex -a (gnatls)
17345 @table @asis
17347 @item @code{-a}
17349 Consider all units, including those of the predefined Ada library.
17350 Especially useful with @emph{-d}.
17351 @end table
17353 @geindex -d (gnatls)
17356 @table @asis
17358 @item @code{-d}
17360 List sources from which specified units depend on.
17361 @end table
17363 @geindex -h (gnatls)
17366 @table @asis
17368 @item @code{-h}
17370 Output the list of options.
17371 @end table
17373 @geindex -o (gnatls)
17376 @table @asis
17378 @item @code{-o}
17380 Only output information about object files.
17381 @end table
17383 @geindex -s (gnatls)
17386 @table @asis
17388 @item @code{-s}
17390 Only output information about source files.
17391 @end table
17393 @geindex -u (gnatls)
17396 @table @asis
17398 @item @code{-u}
17400 Only output information about compilation units.
17401 @end table
17403 @geindex -files (gnatls)
17406 @table @asis
17408 @item @code{-files=@emph{file}}
17410 Take as arguments the files listed in text file @cite{file}.
17411 Text file @cite{file} may contain empty lines that are ignored.
17412 Each nonempty line should contain the name of an existing file.
17413 Several such switches may be specified simultaneously.
17414 @end table
17416 @geindex -aO (gnatls)
17418 @geindex -aI (gnatls)
17420 @geindex -I (gnatls)
17422 @geindex -I- (gnatls)
17425 @table @asis
17427 @item @code{-aO@emph{dir}}, @code{-aI@emph{dir}}, @code{-I@emph{dir}}, @code{-I-}, @code{-nostdinc}
17429 Source path manipulation. Same meaning as the equivalent @emph{gnatmake}
17430 flags (@ref{dc,,Switches for gnatmake}).
17431 @end table
17433 @geindex -aP (gnatls)
17436 @table @asis
17438 @item @code{-aP@emph{dir}}
17440 Add @cite{dir} at the beginning of the project search dir.
17441 @end table
17443 @geindex --RTS (gnatls)
17446 @table @asis
17448 @item @code{--RTS=@emph{rts-path}`}
17450 Specifies the default location of the runtime library. Same meaning as the
17451 equivalent @emph{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17452 @end table
17454 @geindex -v (gnatls)
17457 @table @asis
17459 @item @code{-v}
17461 Verbose mode. Output the complete source, object and project paths. Do not use
17462 the default column layout but instead use long format giving as much as
17463 information possible on each requested units, including special
17464 characteristics such as:
17467 @itemize *
17469 @item 
17470 @emph{Preelaborable}: The unit is preelaborable in the Ada sense.
17472 @item 
17473 @emph{No_Elab_Code}:  No elaboration code has been produced by the compiler for this unit.
17475 @item 
17476 @emph{Pure}: The unit is pure in the Ada sense.
17478 @item 
17479 @emph{Elaborate_Body}: The unit contains a pragma Elaborate_Body.
17481 @item 
17482 @emph{Remote_Types}: The unit contains a pragma Remote_Types.
17484 @item 
17485 @emph{Shared_Passive}: The unit contains a pragma Shared_Passive.
17487 @item 
17488 @emph{Predefined}: This unit is part of the predefined environment and cannot be modified
17489 by the user.
17491 @item 
17492 @emph{Remote_Call_Interface}: The unit contains a pragma Remote_Call_Interface.
17493 @end itemize
17494 @end table
17496 @node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
17497 @anchor{gnat_ugn/gnat_utility_programs id8}@anchor{14f}@anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{150}
17498 @subsection Example of @cite{gnatls} Usage
17501 Example of using the verbose switch. Note how the source and
17502 object paths are affected by the -I switch.
17504 @quotation
17506 @example
17507 $ gnatls -v -I.. demo1.o
17509 GNATLS 5.03w (20041123-34)
17510 Copyright 1997-2004 Free Software Foundation, Inc.
17512 Source Search Path:
17513    <Current_Directory>
17514    ../
17515    /home/comar/local/adainclude/
17517 Object Search Path:
17518    <Current_Directory>
17519    ../
17520    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17522 Project Search Path:
17523    <Current_Directory>
17524    /home/comar/local/lib/gnat/
17526 ./demo1.o
17527    Unit =>
17528      Name   => demo1
17529      Kind   => subprogram body
17530      Flags  => No_Elab_Code
17531      Source => demo1.adb    modified
17532 @end example
17533 @end quotation
17535 The following is an example of use of the dependency list.
17536 Note the use of the -s switch
17537 which gives a straight list of source files. This can be useful for
17538 building specialized scripts.
17540 @quotation
17542 @example
17543 $ gnatls -d demo2.o
17544 ./demo2.o   demo2        OK demo2.adb
17545                          OK gen_list.ads
17546                          OK gen_list.adb
17547                          OK instr.ads
17548                          OK instr-child.ads
17550 $ gnatls -d -s -a demo1.o
17551 demo1.adb
17552 /home/comar/local/adainclude/ada.ads
17553 /home/comar/local/adainclude/a-finali.ads
17554 /home/comar/local/adainclude/a-filico.ads
17555 /home/comar/local/adainclude/a-stream.ads
17556 /home/comar/local/adainclude/a-tags.ads
17557 gen_list.ads
17558 gen_list.adb
17559 /home/comar/local/adainclude/gnat.ads
17560 /home/comar/local/adainclude/g-io.ads
17561 instr.ads
17562 /home/comar/local/adainclude/system.ads
17563 /home/comar/local/adainclude/s-exctab.ads
17564 /home/comar/local/adainclude/s-finimp.ads
17565 /home/comar/local/adainclude/s-finroo.ads
17566 /home/comar/local/adainclude/s-secsta.ads
17567 /home/comar/local/adainclude/s-stalib.ads
17568 /home/comar/local/adainclude/s-stoele.ads
17569 /home/comar/local/adainclude/s-stratt.ads
17570 /home/comar/local/adainclude/s-tasoli.ads
17571 /home/comar/local/adainclude/s-unstyp.ads
17572 /home/comar/local/adainclude/unchconv.ads
17573 @end example
17574 @end quotation
17576 @node The Cross-Referencing Tools gnatxref and gnatfind,The Ada to HTML Converter gnathtml,The GNAT Library Browser gnatls,GNAT Utility Programs
17577 @anchor{gnat_ugn/gnat_utility_programs the-cross-referencing-tools-gnatxref-and-gnatfind}@anchor{22}@anchor{gnat_ugn/gnat_utility_programs id9}@anchor{151}
17578 @section The Cross-Referencing Tools @cite{gnatxref} and @cite{gnatfind}
17581 @geindex gnatxref
17583 @geindex gnatfind
17585 The compiler generates cross-referencing information (unless
17586 you set the @code{-gnatx} switch), which are saved in the @code{.ali} files.
17587 This information indicates where in the source each entity is declared and
17588 referenced. Note that entities in package Standard are not included, but
17589 entities in all other predefined units are included in the output.
17591 Before using any of these two tools, you need to compile successfully your
17592 application, so that GNAT gets a chance to generate the cross-referencing
17593 information.
17595 The two tools @cite{gnatxref} and @cite{gnatfind} take advantage of this
17596 information to provide the user with the capability to easily locate the
17597 declaration and references to an entity. These tools are quite similar,
17598 the difference being that @cite{gnatfind} is intended for locating
17599 definitions and/or references to a specified entity or entities, whereas
17600 @cite{gnatxref} is oriented to generating a full report of all
17601 cross-references.
17603 To use these tools, you must not compile your application using the
17604 @emph{-gnatx} switch on the @emph{gnatmake} command line
17605 (see @ref{1b,,Building with gnatmake}). Otherwise, cross-referencing
17606 information will not be generated.
17608 Note: to invoke @cite{gnatxref} or @cite{gnatfind} with a project file,
17609 use the @cite{gnat} driver (see @emph{The_GNAT_Driver_and_Project_Files}).
17611 @menu
17612 * gnatxref Switches:: 
17613 * gnatfind Switches:: 
17614 * Project Files for gnatxref and gnatfind:: 
17615 * Regular Expressions in gnatfind and gnatxref:: 
17616 * Examples of gnatxref Usage:: 
17617 * Examples of gnatfind Usage:: 
17619 @end menu
17621 @node gnatxref Switches,gnatfind Switches,,The Cross-Referencing Tools gnatxref and gnatfind
17622 @anchor{gnat_ugn/gnat_utility_programs id10}@anchor{152}@anchor{gnat_ugn/gnat_utility_programs gnatxref-switches}@anchor{153}
17623 @subsection @cite{gnatxref} Switches
17626 The command invocation for @cite{gnatxref} is:
17628 @quotation
17630 @example
17631 $ gnatxref [`switches`] `sourcefile1` [`sourcefile2` ...]
17632 @end example
17633 @end quotation
17635 where
17638 @table @asis
17640 @item @emph{sourcefile1} [, @emph{sourcefile2} ...]
17642 identify the source files for which a report is to be generated. The
17643 'with'ed units will be processed too. You must provide at least one file.
17645 These file names are considered to be regular expressions, so for instance
17646 specifying @code{source*.adb} is the same as giving every file in the current
17647 directory whose name starts with @code{source} and whose extension is
17648 @code{adb}.
17650 You shouldn't specify any directory name, just base names. @emph{gnatxref}
17651 and @emph{gnatfind} will be able to locate these files by themselves using
17652 the source path. If you specify directories, no result is produced.
17653 @end table
17655 The following switches are available for @emph{gnatxref}:
17657 @geindex --version (gnatxref)
17660 @table @asis
17662 @item @code{-version}
17664 Display Copyright and version, then exit disregarding all other options.
17665 @end table
17667 @geindex --help (gnatxref)
17670 @table @asis
17672 @item @code{-help}
17674 If @emph{--version} was not used, display usage, then exit disregarding
17675 all other options.
17676 @end table
17678 @geindex -a (gnatxref)
17681 @table @asis
17683 @item @code{a}
17685 If this switch is present, @cite{gnatfind} and @cite{gnatxref} will parse
17686 the read-only files found in the library search path. Otherwise, these files
17687 will be ignored. This option can be used to protect Gnat sources or your own
17688 libraries from being parsed, thus making @cite{gnatfind} and @cite{gnatxref}
17689 much faster, and their output much smaller. Read-only here refers to access
17690 or permissions status in the file system for the current user.
17691 @end table
17693 @geindex -aIDIR (gnatxref)
17696 @table @asis
17698 @item @code{aI@emph{DIR}}
17700 When looking for source files also look in directory DIR. The order in which
17701 source file search is undertaken is the same as for @emph{gnatmake}.
17702 @end table
17704 @geindex -aODIR (gnatxref)
17707 @table @asis
17709 @item @code{aO@emph{DIR}}
17711 When searching for library and object files, look in directory
17712 DIR. The order in which library files are searched is the same as for
17713 @emph{gnatmake}.
17714 @end table
17716 @geindex -nostdinc (gnatxref)
17719 @table @asis
17721 @item @code{nostdinc}
17723 Do not look for sources in the system default directory.
17724 @end table
17726 @geindex -nostdlib (gnatxref)
17729 @table @asis
17731 @item @code{nostdlib}
17733 Do not look for library files in the system default directory.
17734 @end table
17736 @geindex --ext (gnatxref)
17739 @table @asis
17741 @item @code{-ext=@emph{extension}}
17743 Specify an alternate ali file extension. The default is @cite{ali} and other
17744 extensions (e.g. @cite{gli} for C/C++ sources when using @emph{-fdump-xref})
17745 may be specified via this switch. Note that if this switch overrides the
17746 default, which means that only the new extension will be considered.
17747 @end table
17749 @geindex --RTS (gnatxref)
17752 @table @asis
17754 @item @code{-RTS=@emph{rts-path}}
17756 Specifies the default location of the runtime library. Same meaning as the
17757 equivalent @emph{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17758 @end table
17760 @geindex -d (gnatxref)
17763 @table @asis
17765 @item @code{d}
17767 If this switch is set @cite{gnatxref} will output the parent type
17768 reference for each matching derived types.
17769 @end table
17771 @geindex -f (gnatxref)
17774 @table @asis
17776 @item @code{f}
17778 If this switch is set, the output file names will be preceded by their
17779 directory (if the file was found in the search path). If this switch is
17780 not set, the directory will not be printed.
17781 @end table
17783 @geindex -g (gnatxref)
17786 @table @asis
17788 @item @code{g}
17790 If this switch is set, information is output only for library-level
17791 entities, ignoring local entities. The use of this switch may accelerate
17792 @cite{gnatfind} and @cite{gnatxref}.
17793 @end table
17795 @geindex -IDIR (gnatxref)
17798 @table @asis
17800 @item @code{I@emph{DIR}}
17802 Equivalent to @code{-aODIR -aIDIR}.
17803 @end table
17805 @geindex -pFILE (gnatxref)
17808 @table @asis
17810 @item @code{p@emph{FILE}}
17812 Specify a project file to use.
17814 By default, @cite{gnatxref} and @cite{gnatfind} will try to locate a
17815 project file in the current directory.
17817 If a project file is either specified or found by the tools, then the content
17818 of the source directory and object directory lines are added as if they
17819 had been specified respectively by @code{-aI}
17820 and @code{-aO}.
17822 @item @code{u}
17824 Output only unused symbols. This may be really useful if you give your
17825 main compilation unit on the command line, as @cite{gnatxref} will then
17826 display every unused entity and 'with'ed package.
17828 @item @code{v}
17830 Instead of producing the default output, @cite{gnatxref} will generate a
17831 @code{tags} file that can be used by vi. For examples how to use this
17832 feature, see @ref{154,,Examples of gnatxref Usage}. The tags file is output
17833 to the standard output, thus you will have to redirect it to a file.
17834 @end table
17836 All these switches may be in any order on the command line, and may even
17837 appear after the file names. They need not be separated by spaces, thus
17838 you can say @code{gnatxref -ag} instead of @code{gnatxref -a -g}.
17840 @node gnatfind Switches,Project Files for gnatxref and gnatfind,gnatxref Switches,The Cross-Referencing Tools gnatxref and gnatfind
17841 @anchor{gnat_ugn/gnat_utility_programs id11}@anchor{155}@anchor{gnat_ugn/gnat_utility_programs gnatfind-switches}@anchor{156}
17842 @subsection @cite{gnatfind} Switches
17845 The command invocation for @cite{gnatfind} is:
17847 @quotation
17849 @example
17850 $ gnatfind [`switches`] `pattern`[:`sourcefile`[:`line`[:`column`]]]
17851       [`file1` `file2` ...]
17852 @end example
17853 @end quotation
17855 with the following iterpretation of the command arguments:
17858 @table @asis
17860 @item @emph{pattern}
17862 An entity will be output only if it matches the regular expression found
17863 in @cite{pattern}, see @ref{157,,Regular Expressions in gnatfind and gnatxref}.
17865 Omitting the pattern is equivalent to specifying @code{*}, which
17866 will match any entity. Note that if you do not provide a pattern, you
17867 have to provide both a sourcefile and a line.
17869 Entity names are given in Latin-1, with uppercase/lowercase equivalence
17870 for matching purposes. At the current time there is no support for
17871 8-bit codes other than Latin-1, or for wide characters in identifiers.
17873 @item @emph{sourcefile}
17875 @cite{gnatfind} will look for references, bodies or declarations
17876 of symbols referenced in @code{sourcefile}, at line @cite{line}
17877 and column @cite{column}. See @ref{158,,Examples of gnatfind Usage}
17878 for syntax examples.
17880 @item @emph{line}
17882 A decimal integer identifying the line number containing
17883 the reference to the entity (or entities) to be located.
17885 @item @emph{column}
17887 A decimal integer identifying the exact location on the
17888 line of the first character of the identifier for the
17889 entity reference. Columns are numbered from 1.
17891 @item @emph{file1 file2 ...}
17893 The search will be restricted to these source files. If none are given, then
17894 the search will be conducted for every library file in the search path.
17895 These files must appear only after the pattern or sourcefile.
17897 These file names are considered to be regular expressions, so for instance
17898 specifying @code{source*.adb} is the same as giving every file in the current
17899 directory whose name starts with @code{source} and whose extension is
17900 @code{adb}.
17902 The location of the spec of the entity will always be displayed, even if it
17903 isn't in one of @code{file1}, @code{file2}, ... The
17904 occurrences of the entity in the separate units of the ones given on the
17905 command line will also be displayed.
17907 Note that if you specify at least one file in this part, @cite{gnatfind} may
17908 sometimes not be able to find the body of the subprograms.
17909 @end table
17911 At least one of 'sourcefile' or 'pattern' has to be present on
17912 the command line.
17914 The following switches are available:
17916 @geindex --version (gnatfind)
17919 @table @asis
17921 @item @code{--version}
17923 Display Copyright and version, then exit disregarding all other options.
17924 @end table
17926 @geindex --help (gnatfind)
17929 @table @asis
17931 @item @code{-help}
17933 If @emph{--version} was not used, display usage, then exit disregarding
17934 all other options.
17935 @end table
17937 @geindex -a (gnatfind)
17940 @table @asis
17942 @item @code{a}
17944 If this switch is present, @cite{gnatfind} and @cite{gnatxref} will parse
17945 the read-only files found in the library search path. Otherwise, these files
17946 will be ignored. This option can be used to protect Gnat sources or your own
17947 libraries from being parsed, thus making @cite{gnatfind} and @cite{gnatxref}
17948 much faster, and their output much smaller. Read-only here refers to access
17949 or permission status in the file system for the current user.
17950 @end table
17952 @geindex -aIDIR (gnatfind)
17955 @table @asis
17957 @item @code{aI@emph{DIR}}
17959 When looking for source files also look in directory DIR. The order in which
17960 source file search is undertaken is the same as for @emph{gnatmake}.
17961 @end table
17963 @geindex -aODIR (gnatfind)
17966 @table @asis
17968 @item @code{aO@emph{DIR}}
17970 When searching for library and object files, look in directory
17971 DIR. The order in which library files are searched is the same as for
17972 @emph{gnatmake}.
17973 @end table
17975 @geindex -nostdinc (gnatfind)
17978 @table @asis
17980 @item @code{nostdinc}
17982 Do not look for sources in the system default directory.
17983 @end table
17985 @geindex -nostdlib (gnatfind)
17988 @table @asis
17990 @item @code{nostdlib}
17992 Do not look for library files in the system default directory.
17993 @end table
17995 @geindex --ext (gnatfind)
17998 @table @asis
18000 @item @code{-ext=@emph{extension}}
18002 Specify an alternate ali file extension. The default is @cite{ali} and other
18003 extensions (e.g. @cite{gli} for C/C++ sources when using @emph{-fdump-xref})
18004 may be specified via this switch. Note that if this switch overrides the
18005 default, which means that only the new extension will be considered.
18006 @end table
18008 @geindex --RTS (gnatfind)
18011 @table @asis
18013 @item @code{-RTS=@emph{rts-path}}
18015 Specifies the default location of the runtime library. Same meaning as the
18016 equivalent @emph{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
18017 @end table
18019 @geindex -d (gnatfind)
18022 @table @asis
18024 @item @code{d}
18026 If this switch is set, then @cite{gnatfind} will output the parent type
18027 reference for each matching derived types.
18028 @end table
18030 @geindex -e (gnatfind)
18033 @table @asis
18035 @item @code{e}
18037 By default, @cite{gnatfind} accept the simple regular expression set for
18038 @cite{pattern}. If this switch is set, then the pattern will be
18039 considered as full Unix-style regular expression.
18040 @end table
18042 @geindex -f (gnatfind)
18045 @table @asis
18047 @item @code{f}
18049 If this switch is set, the output file names will be preceded by their
18050 directory (if the file was found in the search path). If this switch is
18051 not set, the directory will not be printed.
18052 @end table
18054 @geindex -g (gnatfind)
18057 @table @asis
18059 @item @code{g}
18061 If this switch is set, information is output only for library-level
18062 entities, ignoring local entities. The use of this switch may accelerate
18063 @cite{gnatfind} and @cite{gnatxref}.
18064 @end table
18066 @geindex -IDIR (gnatfind)
18069 @table @asis
18071 @item @code{I@emph{DIR}}
18073 Equivalent to @code{-aODIR -aIDIR}.
18074 @end table
18076 @geindex -pFILE (gnatfind)
18079 @table @asis
18081 @item @code{p@emph{FILE}}
18083 Specify a project file.
18084 By default, @cite{gnatxref} and @cite{gnatfind} will try to locate a
18085 project file in the current directory.
18087 If a project file is either specified or found by the tools, then the content
18088 of the source directory and object directory lines are added as if they
18089 had been specified respectively by @code{-aI} and
18090 @code{-aO}.
18091 @end table
18093 @geindex -r (gnatfind)
18096 @table @asis
18098 @item @code{r}
18100 By default, @cite{gnatfind} will output only the information about the
18101 declaration, body or type completion of the entities. If this switch is
18102 set, the @cite{gnatfind} will locate every reference to the entities in
18103 the files specified on the command line (or in every file in the search
18104 path if no file is given on the command line).
18105 @end table
18107 @geindex -s (gnatfind)
18110 @table @asis
18112 @item @code{s}
18114 If this switch is set, then @cite{gnatfind} will output the content
18115 of the Ada source file lines were the entity was found.
18116 @end table
18118 @geindex -t (gnatfind)
18121 @table @asis
18123 @item @code{t}
18125 If this switch is set, then @cite{gnatfind} will output the type hierarchy for
18126 the specified type. It act like -d option but recursively from parent
18127 type to parent type. When this switch is set it is not possible to
18128 specify more than one file.
18129 @end table
18131 All these switches may be in any order on the command line, and may even
18132 appear after the file names. They need not be separated by spaces, thus
18133 you can say @code{gnatxref -ag} instead of
18134 @code{gnatxref -a -g}.
18136 As stated previously, gnatfind will search in every directory in the
18137 search path. You can force it to look only in the current directory if
18138 you specify @cite{*} at the end of the command line.
18140 @node Project Files for gnatxref and gnatfind,Regular Expressions in gnatfind and gnatxref,gnatfind Switches,The Cross-Referencing Tools gnatxref and gnatfind
18141 @anchor{gnat_ugn/gnat_utility_programs project-files-for-gnatxref-and-gnatfind}@anchor{159}@anchor{gnat_ugn/gnat_utility_programs id12}@anchor{15a}
18142 @subsection Project Files for @emph{gnatxref} and @emph{gnatfind}
18145 Project files allow a programmer to specify how to compile its
18146 application, where to find sources, etc.  These files are used
18147 primarily by GPS, but they can also be used
18148 by the two tools @cite{gnatxref} and @cite{gnatfind}.
18150 A project file name must end with @code{.gpr}. If a single one is
18151 present in the current directory, then @cite{gnatxref} and @cite{gnatfind} will
18152 extract the information from it. If multiple project files are found, none of
18153 them is read, and you have to use the @code{-p} switch to specify the one
18154 you want to use.
18156 The following lines can be included, even though most of them have default
18157 values which can be used in most cases.
18158 The lines can be entered in any order in the file.
18159 Except for @code{src_dir} and @code{obj_dir}, you can only have one instance of
18160 each line. If you have multiple instances, only the last one is taken into
18161 account.
18164 @itemize *
18166 @item 
18168 @table @asis
18170 @item @emph{src_dir=DIR}
18172 [default: @cite{"./"}].
18173 Specifies a directory where to look for source files. Multiple @cite{src_dir}
18174 lines can be specified and they will be searched in the order they
18175 are specified.
18176 @end table
18178 @item 
18180 @table @asis
18182 @item @emph{obj_dir=DIR}
18184 [default: @cite{"./"}].
18185 Specifies a directory where to look for object and library files. Multiple
18186 @cite{obj_dir} lines can be specified, and they will be searched in the order
18187 they are specified
18188 @end table
18190 @item 
18192 @table @asis
18194 @item @emph{comp_opt=SWITCHES}
18196 [default: @cite{""}].
18197 Creates a variable which can be referred to subsequently by using
18198 the @cite{$@{comp_opt@}} notation. This is intended to store the default
18199 switches given to @emph{gnatmake} and @emph{gcc}.
18200 @end table
18202 @item 
18204 @table @asis
18206 @item @emph{bind_opt=SWITCHES}
18208 [default: @cite{""}].
18209 Creates a variable which can be referred to subsequently by using
18210 the @code{$@emph{bind_opt}} notation. This is intended to store the default
18211 switches given to @emph{gnatbind}.
18212 @end table
18214 @item 
18216 @table @asis
18218 @item @emph{link_opt=SWITCHES}
18220 [default: @cite{""}].
18221 Creates a variable which can be referred to subsequently by using
18222 the @code{$@emph{link_opt}} notation. This is intended to store the default
18223 switches given to @emph{gnatlink}.
18224 @end table
18226 @item 
18228 @table @asis
18230 @item @emph{main=EXECUTABLE}
18232 [default: @cite{""}].
18233 Specifies the name of the executable for the application. This variable can
18234 be referred to in the following lines by using the @code{@emph{$@{main}} notation.
18235 @end table
18237 @item 
18239 @table @asis
18241 @item @emph{comp_cmd=COMMAND}
18243 [default: @cite{"gcc -c -I$@{src_dir@} -g -gnatq"}].
18244 Specifies the command used to compile a single file in the application.
18245 @end table
18247 @item 
18249 @table @asis
18251 @item @emph{make_cmd=COMMAND}
18253 [default: @cite{"gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"}].
18254 Specifies the command used to recompile the whole application.
18255 @end table
18257 @item 
18259 @table @asis
18261 @item @emph{run_cmd=COMMAND}
18263 [default: @cite{"$@{main@}"}].
18264 Specifies the command used to run the application.
18265 @end table
18267 @item 
18269 @table @asis
18271 @item @emph{debug_cmd=COMMAND}
18273 [default: @cite{"gdb $@{main@}"}].
18274 Specifies the command used to debug the application
18275 @end table
18276 @end itemize
18278 @emph{gnatxref} and @emph{gnatfind} only take into account the
18279 @cite{src_dir} and @cite{obj_dir} lines, and ignore the others.
18281 @node Regular Expressions in gnatfind and gnatxref,Examples of gnatxref Usage,Project Files for gnatxref and gnatfind,The Cross-Referencing Tools gnatxref and gnatfind
18282 @anchor{gnat_ugn/gnat_utility_programs id13}@anchor{15b}@anchor{gnat_ugn/gnat_utility_programs regular-expressions-in-gnatfind-and-gnatxref}@anchor{157}
18283 @subsection Regular Expressions in @cite{gnatfind} and @cite{gnatxref}
18286 As specified in the section about @emph{gnatfind}, the pattern can be a
18287 regular expression. Two kinds of regular expressions
18288 are recognized:
18291 @itemize *
18293 @item 
18295 @table @asis
18297 @item @emph{Globbing pattern}
18299 These are the most common regular expression. They are the same as are
18300 generally used in a Unix shell command line, or in a DOS session.
18302 Here is a more formal grammar:
18304 @example
18305 regexp ::= term
18306 term   ::= elmt            -- matches elmt
18307 term   ::= elmt elmt       -- concatenation (elmt then elmt)
18308 term   ::= *               -- any string of 0 or more characters
18309 term   ::= ?               -- matches any character
18310 term   ::= [char @{char@}]   -- matches any character listed
18311 term   ::= [char - char]   -- matches any character in range
18312 @end example
18313 @end table
18315 @item 
18317 @table @asis
18319 @item @emph{Full regular expression}
18321 The second set of regular expressions is much more powerful. This is the
18322 type of regular expressions recognized by utilities such as @code{grep}.
18324 The following is the form of a regular expression, expressed in same BNF
18325 style as is found in the Ada Reference Manual:
18327 @example
18328 regexp ::= term @{| term@}   -- alternation (term or term ...)
18330 term ::= item @{item@}       -- concatenation (item then item)
18332 item ::= elmt              -- match elmt
18333 item ::= elmt *            -- zero or more elmt's
18334 item ::= elmt +            -- one or more elmt's
18335 item ::= elmt ?            -- matches elmt or nothing
18337 elmt ::= nschar            -- matches given character
18338 elmt ::= [nschar @{nschar@}]   -- matches any character listed
18339 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
18340 elmt ::= [char - char]     -- matches chars in given range
18341 elmt ::= \\ char            -- matches given character
18342 elmt ::= .                 -- matches any single character
18343 elmt ::= ( regexp )        -- parens used for grouping
18345 char ::= any character, including special characters
18346 nschar ::= any character except ()[].*+?^
18347 @end example
18349 Here are a few examples:
18351 @quotation
18354 @table @asis
18356 @item @code{abcde|fghi}
18358 will match any of the two strings @code{abcde} and @code{fghi},
18360 @item @code{abc*d}
18362 will match any string like @code{abd}, @code{abcd}, @code{abccd},
18363 @code{abcccd}, and so on,
18365 @item @code{[a-z]+}
18367 will match any string which has only lowercase characters in it (and at
18368 least one character.
18369 @end table
18370 @end quotation
18371 @end table
18372 @end itemize
18374 @node Examples of gnatxref Usage,Examples of gnatfind Usage,Regular Expressions in gnatfind and gnatxref,The Cross-Referencing Tools gnatxref and gnatfind
18375 @anchor{gnat_ugn/gnat_utility_programs examples-of-gnatxref-usage}@anchor{154}@anchor{gnat_ugn/gnat_utility_programs id14}@anchor{15c}
18376 @subsection Examples of @cite{gnatxref} Usage
18379 @menu
18380 * General Usage:: 
18381 * Using gnatxref with vi:: 
18383 @end menu
18385 @node General Usage,Using gnatxref with vi,,Examples of gnatxref Usage
18386 @anchor{gnat_ugn/gnat_utility_programs general-usage}@anchor{15d}
18387 @subsubsection General Usage
18390 For the following examples, we will consider the following units:
18392 @quotation
18394 @example
18395 main.ads:
18396 1: with Bar;
18397 2: package Main is
18398 3:     procedure Foo (B : in Integer);
18399 4:     C : Integer;
18400 5: private
18401 6:     D : Integer;
18402 7: end Main;
18404 main.adb:
18405 1: package body Main is
18406 2:     procedure Foo (B : in Integer) is
18407 3:     begin
18408 4:        C := B;
18409 5:        D := B;
18410 6:        Bar.Print (B);
18411 7:        Bar.Print (C);
18412 8:     end Foo;
18413 9: end Main;
18415 bar.ads:
18416 1: package Bar is
18417 2:     procedure Print (B : Integer);
18418 3: end bar;
18419 @end example
18420 @end quotation
18422 The first thing to do is to recompile your application (for instance, in
18423 that case just by doing a @code{gnatmake main}, so that GNAT generates
18424 the cross-referencing information.
18425 You can then issue any of the following commands:
18427 @quotation
18430 @itemize *
18432 @item 
18433 @code{gnatxref main.adb}
18434 @cite{gnatxref} generates cross-reference information for main.adb
18435 and every unit 'with'ed by main.adb.
18437 The output would be:
18439 @quotation
18441 @example
18442 B                                                      Type: Integer
18443   Decl: bar.ads           2:22
18444 B                                                      Type: Integer
18445   Decl: main.ads          3:20
18446   Body: main.adb          2:20
18447   Ref:  main.adb          4:13     5:13     6:19
18448 Bar                                                    Type: Unit
18449   Decl: bar.ads           1:9
18450   Ref:  main.adb          6:8      7:8
18451        main.ads           1:6
18452 C                                                      Type: Integer
18453   Decl: main.ads          4:5
18454   Modi: main.adb          4:8
18455   Ref:  main.adb          7:19
18456 D                                                      Type: Integer
18457   Decl: main.ads          6:5
18458   Modi: main.adb          5:8
18459 Foo                                                    Type: Unit
18460   Decl: main.ads          3:15
18461   Body: main.adb          2:15
18462 Main                                                    Type: Unit
18463   Decl: main.ads          2:9
18464   Body: main.adb          1:14
18465 Print                                                   Type: Unit
18466   Decl: bar.ads           2:15
18467   Ref:  main.adb          6:12     7:12
18468 @end example
18469 @end quotation
18471 This shows that the entity @cite{Main} is declared in main.ads, line 2, column 9,
18472 its body is in main.adb, line 1, column 14 and is not referenced any where.
18474 The entity @cite{Print} is declared in bar.ads, line 2, column 15 and it
18475 is referenced in main.adb, line 6 column 12 and line 7 column 12.
18477 @item 
18478 @code{gnatxref package1.adb package2.ads}
18479 @cite{gnatxref} will generates cross-reference information for
18480 package1.adb, package2.ads and any other package 'with'ed by any
18481 of these.
18482 @end itemize
18483 @end quotation
18485 @node Using gnatxref with vi,,General Usage,Examples of gnatxref Usage
18486 @anchor{gnat_ugn/gnat_utility_programs using-gnatxref-with-vi}@anchor{15e}
18487 @subsubsection Using gnatxref with vi
18490 @cite{gnatxref} can generate a tags file output, which can be used
18491 directly from @emph{vi}. Note that the standard version of @emph{vi}
18492 will not work properly with overloaded symbols. Consider using another
18493 free implementation of @emph{vi}, such as @emph{vim}.
18495 @quotation
18497 @example
18498 $ gnatxref -v gnatfind.adb > tags
18499 @end example
18500 @end quotation
18502 The following command will generate the tags file for @cite{gnatfind} itself
18503 (if the sources are in the search path!):
18505 @quotation
18507 @example
18508 $ gnatxref -v gnatfind.adb > tags
18509 @end example
18510 @end quotation
18512 From @emph{vi}, you can then use the command @code{:tag @emph{entity}}
18513 (replacing @cite{entity} by whatever you are looking for), and vi will
18514 display a new file with the corresponding declaration of entity.
18516 @node Examples of gnatfind Usage,,Examples of gnatxref Usage,The Cross-Referencing Tools gnatxref and gnatfind
18517 @anchor{gnat_ugn/gnat_utility_programs id15}@anchor{15f}@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatfind-usage}@anchor{158}
18518 @subsection Examples of @cite{gnatfind} Usage
18522 @itemize *
18524 @item 
18525 @code{gnatfind -f xyz:main.adb}
18526 Find declarations for all entities xyz referenced at least once in
18527 main.adb. The references are search in every library file in the search
18528 path.
18530 The directories will be printed as well (as the @code{-f}
18531 switch is set)
18533 The output will look like:
18535 @quotation
18537 @example
18538 directory/main.ads:106:14: xyz <= declaration
18539 directory/main.adb:24:10: xyz <= body
18540 directory/foo.ads:45:23: xyz <= declaration
18541 @end example
18542 @end quotation
18544 I.e., one of the entities xyz found in main.adb is declared at
18545 line 12 of main.ads (and its body is in main.adb), and another one is
18546 declared at line 45 of foo.ads
18548 @item 
18549 @code{gnatfind -fs xyz:main.adb}
18550 This is the same command as the previous one, but @cite{gnatfind} will
18551 display the content of the Ada source file lines.
18553 The output will look like:
18555 @example
18556 directory/main.ads:106:14: xyz <= declaration
18557    procedure xyz;
18558 directory/main.adb:24:10: xyz <= body
18559    procedure xyz is
18560 directory/foo.ads:45:23: xyz <= declaration
18561    xyz : Integer;
18562 @end example
18564 This can make it easier to find exactly the location your are looking
18565 for.
18567 @item 
18568 @code{gnatfind -r "*x*":main.ads:123 foo.adb}
18569 Find references to all entities containing an x that are
18570 referenced on line 123 of main.ads.
18571 The references will be searched only in main.ads and foo.adb.
18573 @item 
18574 @code{gnatfind main.ads:123}
18575 Find declarations and bodies for all entities that are referenced on
18576 line 123 of main.ads.
18578 This is the same as @code{gnatfind "*":main.adb:123`}
18580 @item 
18581 @code{gnatfind mydir/main.adb:123:45}
18582 Find the declaration for the entity referenced at column 45 in
18583 line 123 of file main.adb in directory mydir. Note that it
18584 is usual to omit the identifier name when the column is given,
18585 since the column position identifies a unique reference.
18587 The column has to be the beginning of the identifier, and should not
18588 point to any character in the middle of the identifier.
18589 @end itemize
18591 @node The Ada to HTML Converter gnathtml,,The Cross-Referencing Tools gnatxref and gnatfind,GNAT Utility Programs
18592 @anchor{gnat_ugn/gnat_utility_programs the-ada-to-html-converter-gnathtml}@anchor{23}@anchor{gnat_ugn/gnat_utility_programs id16}@anchor{160}
18593 @section The Ada to HTML Converter @cite{gnathtml}
18596 @geindex gnathtml
18598 @emph{gnathtml} is a Perl script that allows Ada source files to be browsed using
18599 standard Web browsers. For installation information, see @ref{161,,Installing gnathtml}.
18601 Ada reserved keywords are highlighted in a bold font and Ada comments in
18602 a blue font. Unless your program was compiled with the gcc @emph{-gnatx}
18603 switch to suppress the generation of cross-referencing information, user
18604 defined variables and types will appear in a different color; you will
18605 be able to click on any identifier and go to its declaration.
18607 @menu
18608 * Invoking gnathtml:: 
18609 * Installing gnathtml:: 
18611 @end menu
18613 @node Invoking gnathtml,Installing gnathtml,,The Ada to HTML Converter gnathtml
18614 @anchor{gnat_ugn/gnat_utility_programs invoking-gnathtml}@anchor{162}@anchor{gnat_ugn/gnat_utility_programs id17}@anchor{163}
18615 @subsection Invoking @emph{gnathtml}
18618 The command line is as follows:
18620 @quotation
18622 @example
18623 $ perl gnathtml.pl [`switches`] `ada-files`
18624 @end example
18625 @end quotation
18627 You can specify as many Ada files as you want. @cite{gnathtml} will generate
18628 an html file for every ada file, and a global file called @code{index.htm}.
18629 This file is an index of every identifier defined in the files.
18631 The following switches are available:
18633 @geindex -83 (gnathtml)
18636 @table @asis
18638 @item @code{83}
18640 Only the Ada 83 subset of keywords will be highlighted.
18641 @end table
18643 @geindex -cc (gnathtml)
18646 @table @asis
18648 @item @code{cc @emph{color}}
18650 This option allows you to change the color used for comments. The default
18651 value is green. The color argument can be any name accepted by html.
18652 @end table
18654 @geindex -d (gnathtml)
18657 @table @asis
18659 @item @code{d}
18661 If the Ada files depend on some other files (for instance through
18662 @cite{with} clauses, the latter files will also be converted to html.
18663 Only the files in the user project will be converted to html, not the files
18664 in the run-time library itself.
18665 @end table
18667 @geindex -D (gnathtml)
18670 @table @asis
18672 @item @code{D}
18674 This command is the same as @emph{-d} above, but @emph{gnathtml} will
18675 also look for files in the run-time library, and generate html files for them.
18676 @end table
18678 @geindex -ext (gnathtml)
18681 @table @asis
18683 @item @code{ext @emph{extension}}
18685 This option allows you to change the extension of the generated HTML files.
18686 If you do not specify an extension, it will default to @code{htm}.
18687 @end table
18689 @geindex -f (gnathtml)
18692 @table @asis
18694 @item @code{f}
18696 By default, gnathtml will generate html links only for global entities
18697 ('with'ed units, global variables and types,...).  If you specify
18698 @emph{-f} on the command line, then links will be generated for local
18699 entities too.
18700 @end table
18702 @geindex -l (gnathtml)
18705 @table @asis
18707 @item @code{l @emph{number}}
18709 If this switch is provided and @cite{number} is not 0, then
18710 @cite{gnathtml} will number the html files every @cite{number} line.
18711 @end table
18713 @geindex -I (gnathtml)
18716 @table @asis
18718 @item @code{I @emph{dir}}
18720 Specify a directory to search for library files (@code{.ALI} files) and
18721 source files. You can provide several -I switches on the command line,
18722 and the directories will be parsed in the order of the command line.
18723 @end table
18725 @geindex -o (gnathtml)
18728 @table @asis
18730 @item @code{o @emph{dir}}
18732 Specify the output directory for html files. By default, gnathtml will
18733 saved the generated html files in a subdirectory named @code{html/}.
18734 @end table
18736 @geindex -p (gnathtml)
18739 @table @asis
18741 @item @code{p @emph{file}}
18743 If you are using Emacs and the most recent Emacs Ada mode, which provides
18744 a full Integrated Development Environment for compiling, checking,
18745 running and debugging applications, you may use @code{.gpr} files
18746 to give the directories where Emacs can find sources and object files.
18748 Using this switch, you can tell gnathtml to use these files.
18749 This allows you to get an html version of your application, even if it
18750 is spread over multiple directories.
18751 @end table
18753 @geindex -sc (gnathtml)
18756 @table @asis
18758 @item @code{sc @emph{color}}
18760 This switch allows you to change the color used for symbol
18761 definitions.
18762 The default value is red. The color argument can be any name accepted by html.
18763 @end table
18765 @geindex -t (gnathtml)
18768 @table @asis
18770 @item @code{t @emph{file}}
18772 This switch provides the name of a file. This file contains a list of
18773 file names to be converted, and the effect is exactly as though they had
18774 appeared explicitly on the command line. This
18775 is the recommended way to work around the command line length limit on some
18776 systems.
18777 @end table
18779 @node Installing gnathtml,,Invoking gnathtml,The Ada to HTML Converter gnathtml
18780 @anchor{gnat_ugn/gnat_utility_programs installing-gnathtml}@anchor{161}@anchor{gnat_ugn/gnat_utility_programs id18}@anchor{164}
18781 @subsection Installing @cite{gnathtml}
18784 @cite{Perl} needs to be installed on your machine to run this script.
18785 @cite{Perl} is freely available for almost every architecture and
18786 operating system via the Internet.
18788 On Unix systems, you  may want to modify  the  first line of  the script
18789 @cite{gnathtml},  to explicitly  specify  where Perl
18790 is located. The syntax of this line is:
18792 @quotation
18794 @example
18795 #!full_path_name_to_perl
18796 @end example
18797 @end quotation
18799 Alternatively, you may run the script using the following command line:
18801 @quotation
18803 @example
18804 $ perl gnathtml.pl [`switches`] `files`
18805 @end example
18806 @end quotation
18808 @c -- +---------------------------------------------------------------------+
18810 @c -- | The following sections are present only in the PRO and GPL editions |
18812 @c -- +---------------------------------------------------------------------+
18821 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
18823 @node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
18824 @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}
18825 @chapter GNAT and Program Execution
18828 This chapter covers several topics:
18831 @itemize *
18833 @item 
18834 @ref{167,,Running and Debugging Ada Programs}
18836 @item 
18837 @ref{168,,Code Coverage and Profiling}
18839 @item 
18840 @ref{169,,Improving Performance}
18842 @item 
18843 @ref{16a,,Overflow Check Handling in GNAT}
18845 @item 
18846 @ref{16b,,Performing Dimensionality Analysis in GNAT}
18848 @item 
18849 @ref{16c,,Stack Related Facilities}
18851 @item 
18852 @ref{16d,,Memory Management Issues}
18853 @end itemize
18855 @menu
18856 * Running and Debugging Ada Programs:: 
18857 * Code Coverage and Profiling:: 
18858 * Improving Performance:: 
18859 * Overflow Check Handling in GNAT:: 
18860 * Performing Dimensionality Analysis in GNAT:: 
18861 * Stack Related Facilities:: 
18862 * Memory Management Issues:: 
18864 @end menu
18866 @node Running and Debugging Ada Programs,Code Coverage and Profiling,,GNAT and Program Execution
18867 @anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{167}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{24}
18868 @section Running and Debugging Ada Programs
18871 @geindex Debugging
18873 This section discusses how to debug Ada programs.
18875 An incorrect Ada program may be handled in three ways by the GNAT compiler:
18878 @itemize *
18880 @item 
18881 The illegality may be a violation of the static semantics of Ada. In
18882 that case GNAT diagnoses the constructs in the program that are illegal.
18883 It is then a straightforward matter for the user to modify those parts of
18884 the program.
18886 @item 
18887 The illegality may be a violation of the dynamic semantics of Ada. In
18888 that case the program compiles and executes, but may generate incorrect
18889 results, or may terminate abnormally with some exception.
18891 @item 
18892 When presented with a program that contains convoluted errors, GNAT
18893 itself may terminate abnormally without providing full diagnostics on
18894 the incorrect user program.
18895 @end itemize
18897 @geindex Debugger
18899 @geindex gdb
18901 @menu
18902 * The GNAT Debugger GDB:: 
18903 * Running GDB:: 
18904 * Introduction to GDB Commands:: 
18905 * Using Ada Expressions:: 
18906 * Calling User-Defined Subprograms:: 
18907 * Using the next Command in a Function:: 
18908 * Stopping When Ada Exceptions Are Raised:: 
18909 * Ada Tasks:: 
18910 * Debugging Generic Units:: 
18911 * Remote Debugging with gdbserver:: 
18912 * GNAT Abnormal Termination or Failure to Terminate:: 
18913 * Naming Conventions for GNAT Source Files:: 
18914 * Getting Internal Debugging Information:: 
18915 * Stack Traceback:: 
18917 @end menu
18919 @node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
18920 @anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{16e}@anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{16f}
18921 @subsection The GNAT Debugger GDB
18924 @cite{GDB} is a general purpose, platform-independent debugger that
18925 can be used to debug mixed-language programs compiled with @emph{gcc},
18926 and in particular is capable of debugging Ada programs compiled with
18927 GNAT. The latest versions of @cite{GDB} are Ada-aware and can handle
18928 complex Ada data structures.
18930 See @cite{Debugging with GDB},
18931 for full details on the usage of @cite{GDB}, including a section on
18932 its usage on programs. This manual should be consulted for full
18933 details. The section that follows is a brief introduction to the
18934 philosophy and use of @cite{GDB}.
18936 When GNAT programs are compiled, the compiler optionally writes debugging
18937 information into the generated object file, including information on
18938 line numbers, and on declared types and variables. This information is
18939 separate from the generated code. It makes the object files considerably
18940 larger, but it does not add to the size of the actual executable that
18941 will be loaded into memory, and has no impact on run-time performance. The
18942 generation of debug information is triggered by the use of the
18943 -g switch in the @emph{gcc} or @emph{gnatmake} command
18944 used to carry out the compilations. It is important to emphasize that
18945 the use of these options does not change the generated code.
18947 The debugging information is written in standard system formats that
18948 are used by many tools, including debuggers and profilers. The format
18949 of the information is typically designed to describe C types and
18950 semantics, but GNAT implements a translation scheme which allows full
18951 details about Ada types and variables to be encoded into these
18952 standard C formats. Details of this encoding scheme may be found in
18953 the file exp_dbug.ads in the GNAT source distribution. However, the
18954 details of this encoding are, in general, of no interest to a user,
18955 since @cite{GDB} automatically performs the necessary decoding.
18957 When a program is bound and linked, the debugging information is
18958 collected from the object files, and stored in the executable image of
18959 the program. Again, this process significantly increases the size of
18960 the generated executable file, but it does not increase the size of
18961 the executable program itself. Furthermore, if this program is run in
18962 the normal manner, it runs exactly as if the debug information were
18963 not present, and takes no more actual memory.
18965 However, if the program is run under control of @cite{GDB}, the
18966 debugger is activated.  The image of the program is loaded, at which
18967 point it is ready to run.  If a run command is given, then the program
18968 will run exactly as it would have if @cite{GDB} were not present. This
18969 is a crucial part of the @cite{GDB} design philosophy.  @cite{GDB} is
18970 entirely non-intrusive until a breakpoint is encountered.  If no
18971 breakpoint is ever hit, the program will run exactly as it would if no
18972 debugger were present. When a breakpoint is hit, @cite{GDB} accesses
18973 the debugging information and can respond to user commands to inspect
18974 variables, and more generally to report on the state of execution.
18976 @node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
18977 @anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{170}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{171}
18978 @subsection Running GDB
18981 This section describes how to initiate the debugger.
18983 The debugger can be launched from a @cite{GPS} menu or
18984 directly from the command line. The description below covers the latter use.
18985 All the commands shown can be used in the @cite{GPS} debug console window,
18986 but there are usually more GUI-based ways to achieve the same effect.
18988 The command to run @cite{GDB} is
18990 @quotation
18992 @example
18993 $ gdb program
18994 @end example
18995 @end quotation
18997 where @cite{program} is the name of the executable file. This
18998 activates the debugger and results in a prompt for debugger commands.
18999 The simplest command is simply @cite{run}, which causes the program to run
19000 exactly as if the debugger were not present. The following section
19001 describes some of the additional commands that can be given to @cite{GDB}.
19003 @node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
19004 @anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{172}@anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{173}
19005 @subsection Introduction to GDB Commands
19008 @cite{GDB} contains a large repertoire of commands.
19009 See @cite{Debugging with GDB} for extensive documentation on the use
19010 of these commands, together with examples of their use. Furthermore,
19011 the command @emph{help} invoked from within GDB activates a simple help
19012 facility which summarizes the available commands and their options.
19013 In this section we summarize a few of the most commonly
19014 used commands to give an idea of what @cite{GDB} is about. You should create
19015 a simple program with debugging information and experiment with the use of
19016 these @cite{GDB} commands on the program as you read through the
19017 following section.
19020 @itemize *
19022 @item 
19024 @table @asis
19026 @item @emph{set args `arguments`}
19028 The @cite{arguments} list above is a list of arguments to be passed to
19029 the program on a subsequent run command, just as though the arguments
19030 had been entered on a normal invocation of the program. The @cite{set args}
19031 command is not needed if the program does not require arguments.
19032 @end table
19034 @item 
19036 @table @asis
19038 @item @emph{run}
19040 The @cite{run} command causes execution of the program to start from
19041 the beginning. If the program is already running, that is to say if
19042 you are currently positioned at a breakpoint, then a prompt will ask
19043 for confirmation that you want to abandon the current execution and
19044 restart.
19045 @end table
19047 @item 
19049 @table @asis
19051 @item @emph{breakpoint `location`}
19053 The breakpoint command sets a breakpoint, that is to say a point at which
19054 execution will halt and @cite{GDB} will await further
19055 commands. @cite{location} is
19056 either a line number within a file, given in the format @cite{file:linenumber},
19057 or it is the name of a subprogram. If you request that a breakpoint be set on
19058 a subprogram that is overloaded, a prompt will ask you to specify on which of
19059 those subprograms you want to breakpoint. You can also
19060 specify that all of them should be breakpointed. If the program is run
19061 and execution encounters the breakpoint, then the program
19062 stops and @cite{GDB} signals that the breakpoint was encountered by
19063 printing the line of code before which the program is halted.
19064 @end table
19066 @item 
19068 @table @asis
19070 @item @emph{catch exception `name`}
19072 This command causes the program execution to stop whenever exception
19073 @cite{name} is raised.  If @cite{name} is omitted, then the execution is
19074 suspended when any exception is raised.
19075 @end table
19077 @item 
19079 @table @asis
19081 @item @emph{print `expression`}
19083 This will print the value of the given expression. Most simple
19084 Ada expression formats are properly handled by @cite{GDB}, so the expression
19085 can contain function calls, variables, operators, and attribute references.
19086 @end table
19088 @item 
19090 @table @asis
19092 @item @emph{continue}
19094 Continues execution following a breakpoint, until the next breakpoint or the
19095 termination of the program.
19096 @end table
19098 @item 
19100 @table @asis
19102 @item @emph{step}
19104 Executes a single line after a breakpoint. If the next statement
19105 is a subprogram call, execution continues into (the first statement of)
19106 the called subprogram.
19107 @end table
19109 @item 
19111 @table @asis
19113 @item @emph{next}
19115 Executes a single line. If this line is a subprogram call, executes and
19116 returns from the call.
19117 @end table
19119 @item 
19121 @table @asis
19123 @item @emph{list}
19125 Lists a few lines around the current source location. In practice, it
19126 is usually more convenient to have a separate edit window open with the
19127 relevant source file displayed. Successive applications of this command
19128 print subsequent lines. The command can be given an argument which is a
19129 line number, in which case it displays a few lines around the specified one.
19130 @end table
19132 @item 
19134 @table @asis
19136 @item @emph{backtrace}
19138 Displays a backtrace of the call chain. This command is typically
19139 used after a breakpoint has occurred, to examine the sequence of calls that
19140 leads to the current breakpoint. The display includes one line for each
19141 activation record (frame) corresponding to an active subprogram.
19142 @end table
19144 @item 
19146 @table @asis
19148 @item @emph{up}
19150 At a breakpoint, @cite{GDB} can display the values of variables local
19151 to the current frame. The command @cite{up} can be used to
19152 examine the contents of other active frames, by moving the focus up
19153 the stack, that is to say from callee to caller, one frame at a time.
19154 @end table
19156 @item 
19158 @table @asis
19160 @item @emph{down}
19162 Moves the focus of @cite{GDB} down from the frame currently being
19163 examined to the frame of its callee (the reverse of the previous command),
19164 @end table
19166 @item 
19168 @table @asis
19170 @item @emph{frame `n`}
19172 Inspect the frame with the given number. The value 0 denotes the frame
19173 of the current breakpoint, that is to say the top of the call stack.
19174 @end table
19176 @item 
19178 @table @asis
19180 @item @emph{kill}
19182 Kills the child process in which the program is running under GDB.
19183 This may be useful for several purposes:
19186 @itemize *
19188 @item 
19189 It allows you to recompile and relink your program, since on many systems
19190 you cannot regenerate an executable file while it is running in a process.
19192 @item 
19193 You can run your program outside the debugger, on systems that do not
19194 permit executing a program outside GDB while breakpoints are set
19195 within GDB.
19197 @item 
19198 It allows you to debug a core dump rather than a running process.
19199 @end itemize
19200 @end table
19201 @end itemize
19203 The above list is a very short introduction to the commands that
19204 @cite{GDB} provides. Important additional capabilities, including conditional
19205 breakpoints, the ability to execute command sequences on a breakpoint,
19206 the ability to debug at the machine instruction level and many other
19207 features are described in detail in @cite{Debugging with GDB}.
19208 Note that most commands can be abbreviated
19209 (for example, c for continue, bt for backtrace).
19211 @node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
19212 @anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{174}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{175}
19213 @subsection Using Ada Expressions
19216 @geindex Ada expressions (in gdb)
19218 @cite{GDB} supports a fairly large subset of Ada expression syntax, with some
19219 extensions. The philosophy behind the design of this subset is
19221 @quotation
19224 @itemize *
19226 @item 
19227 That @cite{GDB} should provide basic literals and access to operations for
19228 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19229 leaving more sophisticated computations to subprograms written into the
19230 program (which therefore may be called from @cite{GDB}).
19232 @item 
19233 That type safety and strict adherence to Ada language restrictions
19234 are not particularly relevant in a debugging context.
19236 @item 
19237 That brevity is important to the @cite{GDB} user.
19238 @end itemize
19239 @end quotation
19241 Thus, for brevity, the debugger acts as if there were
19242 implicit @cite{with} and @cite{use} clauses in effect for all user-written
19243 packages, thus making it unnecessary to fully qualify most names with
19244 their packages, regardless of context. Where this causes ambiguity,
19245 @cite{GDB} asks the user's intent.
19247 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19249 @node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
19250 @anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{176}@anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{177}
19251 @subsection Calling User-Defined Subprograms
19254 An important capability of @cite{GDB} is the ability to call user-defined
19255 subprograms while debugging. This is achieved simply by entering
19256 a subprogram call statement in the form:
19258 @quotation
19260 @example
19261 call subprogram-name (parameters)
19262 @end example
19263 @end quotation
19265 The keyword @cite{call} can be omitted in the normal case where the
19266 @cite{subprogram-name} does not coincide with any of the predefined
19267 @cite{GDB} commands.
19269 The effect is to invoke the given subprogram, passing it the
19270 list of parameters that is supplied. The parameters can be expressions and
19271 can include variables from the program being debugged. The
19272 subprogram must be defined
19273 at the library level within your program, and @cite{GDB} will call the
19274 subprogram within the environment of your program execution (which
19275 means that the subprogram is free to access or even modify variables
19276 within your program).
19278 The most important use of this facility is in allowing the inclusion of
19279 debugging routines that are tailored to particular data structures
19280 in your program. Such debugging routines can be written to provide a suitably
19281 high-level description of an abstract type, rather than a low-level dump
19282 of its physical layout. After all, the standard
19283 @cite{GDB print} command only knows the physical layout of your
19284 types, not their abstract meaning. Debugging routines can provide information
19285 at the desired semantic level and are thus enormously useful.
19287 For example, when debugging GNAT itself, it is crucial to have access to
19288 the contents of the tree nodes used to represent the program internally.
19289 But tree nodes are represented simply by an integer value (which in turn
19290 is an index into a table of nodes).
19291 Using the @cite{print} command on a tree node would simply print this integer
19292 value, which is not very useful. But the PN routine (defined in file
19293 treepr.adb in the GNAT sources) takes a tree node as input, and displays
19294 a useful high level representation of the tree node, which includes the
19295 syntactic category of the node, its position in the source, the integers
19296 that denote descendant nodes and parent node, as well as varied
19297 semantic information. To study this example in more detail, you might want to
19298 look at the body of the PN procedure in the stated file.
19300 Another useful application of this capability is to deal with situations of
19301 complex data which are not handled suitably by GDB. For example, if you specify
19302 Convention Fortran for a multi-dimensional array, GDB does not know that
19303 the ordering of array elements has been switched and will not properly
19304 address the array elements. In such a case, instead of trying to print the
19305 elements directly from GDB, you can write a callable procedure that prints
19306 the elements in the desired format.
19308 @node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
19309 @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}
19310 @subsection Using the @emph{next} Command in a Function
19313 When you use the @cite{next} command in a function, the current source
19314 location will advance to the next statement as usual. A special case
19315 arises in the case of a @cite{return} statement.
19317 Part of the code for a return statement is the 'epilogue' of the function.
19318 This is the code that returns to the caller. There is only one copy of
19319 this epilogue code, and it is typically associated with the last return
19320 statement in the function if there is more than one return. In some
19321 implementations, this epilogue is associated with the first statement
19322 of the function.
19324 The result is that if you use the @cite{next} command from a return
19325 statement that is not the last return statement of the function you
19326 may see a strange apparent jump to the last return statement or to
19327 the start of the function. You should simply ignore this odd jump.
19328 The value returned is always that from the first return statement
19329 that was stepped through.
19331 @node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
19332 @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}
19333 @subsection Stopping When Ada Exceptions Are Raised
19336 @geindex Exceptions (in gdb)
19338 You can set catchpoints that stop the program execution when your program
19339 raises selected exceptions.
19342 @itemize *
19344 @item 
19346 @table @asis
19348 @item @emph{catch exception}
19350 Set a catchpoint that stops execution whenever (any task in the) program
19351 raises any exception.
19352 @end table
19354 @item 
19356 @table @asis
19358 @item @emph{catch exception `name`}
19360 Set a catchpoint that stops execution whenever (any task in the) program
19361 raises the exception @cite{name}.
19362 @end table
19364 @item 
19366 @table @asis
19368 @item @emph{catch exception unhandled}
19370 Set a catchpoint that stops executing whenever (any task in the) program
19371 raises an exception for which there is no handler.
19372 @end table
19374 @item 
19376 @table @asis
19378 @item @emph{info exceptions}, @emph{info exceptions `regexp`}
19380 The @cite{info exceptions} command permits the user to examine all defined
19381 exceptions within Ada programs. With a regular expression, @cite{regexp}, as
19382 argument, prints out only those exceptions whose name matches @cite{regexp}.
19383 @end table
19384 @end itemize
19386 @geindex Tasks (in gdb)
19388 @node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
19389 @anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{17c}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{17d}
19390 @subsection Ada Tasks
19393 @cite{GDB} allows the following task-related commands:
19396 @itemize *
19398 @item 
19400 @table @asis
19402 @item @emph{info tasks}
19404 This command shows a list of current Ada tasks, as in the following example:
19406 @example
19407 (gdb) info tasks
19408   ID       TID P-ID   Thread Pri State                 Name
19409    1   8088000   0   807e000  15 Child Activation Wait main_task
19410    2   80a4000   1   80ae000  15 Accept/Select Wait    b
19411    3   809a800   1   80a4800  15 Child Activation Wait a
19412 *  4   80ae800   3   80b8000  15 Running               c
19413 @end example
19415 In this listing, the asterisk before the first task indicates it to be the
19416 currently running task. The first column lists the task ID that is used
19417 to refer to tasks in the following commands.
19418 @end table
19419 @end itemize
19421 @geindex Breakpoints and tasks
19424 @itemize *
19426 @item 
19427 @emph{break `linespec` task `taskid`}, @emph{break `linespec` task `taskid` if ...}
19429 @quotation
19431 These commands are like the @cite{break ... thread ...}.
19432 @cite{linespec} specifies source lines.
19434 Use the qualifier @code{task @emph{taskid}} with a breakpoint command
19435 to specify that you only want @cite{GDB} to stop the program when a
19436 particular Ada task reaches this breakpoint. @cite{taskid} is one of the
19437 numeric task identifiers assigned by @cite{GDB}, shown in the first
19438 column of the @code{info tasks} display.
19440 If you do not specify @code{task @emph{taskid}} when you set a
19441 breakpoint, the breakpoint applies to @emph{all} tasks of your
19442 program.
19444 You can use the @cite{task} qualifier on conditional breakpoints as
19445 well; in this case, place @code{task @emph{taskid}} before the
19446 breakpoint condition (before the @cite{if}).
19447 @end quotation
19448 @end itemize
19450 @geindex Task switching (in gdb)
19453 @itemize *
19455 @item 
19456 @emph{task `taskno`}
19458 @quotation
19460 This command allows switching to the task referred by @cite{taskno}. In
19461 particular, this allows browsing of the backtrace of the specified
19462 task. It is advisable to switch back to the original task before
19463 continuing execution otherwise the scheduling of the program may be
19464 perturbed.
19465 @end quotation
19466 @end itemize
19468 For more detailed information on the tasking support,
19469 see @cite{Debugging with GDB}.
19471 @geindex Debugging Generic Units
19473 @geindex Generics
19475 @node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
19476 @anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{17e}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{17f}
19477 @subsection Debugging Generic Units
19480 GNAT always uses code expansion for generic instantiation. This means that
19481 each time an instantiation occurs, a complete copy of the original code is
19482 made, with appropriate substitutions of formals by actuals.
19484 It is not possible to refer to the original generic entities in
19485 @cite{GDB}, but it is always possible to debug a particular instance of
19486 a generic, by using the appropriate expanded names. For example, if we have
19488 @quotation
19490 @example
19491 procedure g is
19493    generic package k is
19494       procedure kp (v1 : in out integer);
19495    end k;
19497    package body k is
19498       procedure kp (v1 : in out integer) is
19499       begin
19500          v1 := v1 + 1;
19501       end kp;
19502    end k;
19504    package k1 is new k;
19505    package k2 is new k;
19507    var : integer := 1;
19509 begin
19510    k1.kp (var);
19511    k2.kp (var);
19512    k1.kp (var);
19513    k2.kp (var);
19514 end;
19515 @end example
19516 @end quotation
19518 Then to break on a call to procedure kp in the k2 instance, simply
19519 use the command:
19521 @quotation
19523 @example
19524 (gdb) break g.k2.kp
19525 @end example
19526 @end quotation
19528 When the breakpoint occurs, you can step through the code of the
19529 instance in the normal manner and examine the values of local variables, as for
19530 other units.
19532 @geindex Remote Debugging with gdbserver
19534 @node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
19535 @anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{180}@anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{181}
19536 @subsection Remote Debugging with gdbserver
19539 On platforms where gdbserver is supported, it is possible to use this tool
19540 to debug your application remotely.  This can be useful in situations
19541 where the program needs to be run on a target host that is different
19542 from the host used for development, particularly when the target has
19543 a limited amount of resources (either CPU and/or memory).
19545 To do so, start your program using gdbserver on the target machine.
19546 gdbserver then automatically suspends the execution of your program
19547 at its entry point, waiting for a debugger to connect to it.  The
19548 following commands starts an application and tells gdbserver to
19549 wait for a connection with the debugger on localhost port 4444.
19551 @quotation
19553 @example
19554 $ gdbserver localhost:4444 program
19555 Process program created; pid = 5685
19556 Listening on port 4444
19557 @end example
19558 @end quotation
19560 Once gdbserver has started listening, we can tell the debugger to establish
19561 a connection with this gdbserver, and then start the same debugging session
19562 as if the program was being debugged on the same host, directly under
19563 the control of GDB.
19565 @quotation
19567 @example
19568 $ gdb program
19569 (gdb) target remote targethost:4444
19570 Remote debugging using targethost:4444
19571 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19572 (gdb) b foo.adb:3
19573 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19574 (gdb) continue
19575 Continuing.
19577 Breakpoint 1, foo () at foo.adb:4
19578 4       end foo;
19579 @end example
19580 @end quotation
19582 It is also possible to use gdbserver to attach to an already running
19583 program, in which case the execution of that program is simply suspended
19584 until the connection between the debugger and gdbserver is established.
19586 For more information on how to use gdbserver, see the @emph{Using the gdbserver Program}
19587 section in @cite{Debugging with GDB}.
19588 GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
19590 @geindex Abnormal Termination or Failure to Terminate
19592 @node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
19593 @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}
19594 @subsection GNAT Abnormal Termination or Failure to Terminate
19597 When presented with programs that contain serious errors in syntax
19598 or semantics,
19599 GNAT may on rare occasions  experience problems in operation, such
19600 as aborting with a
19601 segmentation fault or illegal memory access, raising an internal
19602 exception, terminating abnormally, or failing to terminate at all.
19603 In such cases, you can activate
19604 various features of GNAT that can help you pinpoint the construct in your
19605 program that is the likely source of the problem.
19607 The following strategies are presented in increasing order of
19608 difficulty, corresponding to your experience in using GNAT and your
19609 familiarity with compiler internals.
19612 @itemize *
19614 @item 
19615 Run @emph{gcc} with the @emph{-gnatf}. This first
19616 switch causes all errors on a given line to be reported. In its absence,
19617 only the first error on a line is displayed.
19619 The @emph{-gnatdO} switch causes errors to be displayed as soon as they
19620 are encountered, rather than after compilation is terminated. If GNAT
19621 terminates prematurely or goes into an infinite loop, the last error
19622 message displayed may help to pinpoint the culprit.
19624 @item 
19625 Run @emph{gcc} with the @emph{-v (verbose)} switch. In this
19626 mode, @emph{gcc} produces ongoing information about the progress of the
19627 compilation and provides the name of each procedure as code is
19628 generated. This switch allows you to find which Ada procedure was being
19629 compiled when it encountered a code generation problem.
19630 @end itemize
19632 @geindex -gnatdc switch
19635 @itemize *
19637 @item 
19638 Run @emph{gcc} with the @emph{-gnatdc} switch. This is a GNAT specific
19639 switch that does for the front-end what @emph{-v} does
19640 for the back end. The system prints the name of each unit,
19641 either a compilation unit or nested unit, as it is being analyzed.
19643 @item 
19644 Finally, you can start
19645 @cite{gdb} directly on the @cite{gnat1} executable. @cite{gnat1} is the
19646 front-end of GNAT, and can be run independently (normally it is just
19647 called from @emph{gcc}). You can use @cite{gdb} on @cite{gnat1} as you
19648 would on a C program (but @ref{16e,,The GNAT Debugger GDB} for caveats). The
19649 @cite{where} command is the first line of attack; the variable
19650 @cite{lineno} (seen by @cite{print lineno}), used by the second phase of
19651 @cite{gnat1} and by the @emph{gcc} backend, indicates the source line at
19652 which the execution stopped, and @cite{input_file name} indicates the name of
19653 the source file.
19654 @end itemize
19656 @node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
19657 @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}
19658 @subsection Naming Conventions for GNAT Source Files
19661 In order to examine the workings of the GNAT system, the following
19662 brief description of its organization may be helpful:
19665 @itemize *
19667 @item 
19668 Files with prefix @code{sc} contain the lexical scanner.
19670 @item 
19671 All files prefixed with @code{par} are components of the parser. The
19672 numbers correspond to chapters of the Ada Reference Manual. For example,
19673 parsing of select statements can be found in @code{par-ch9.adb}.
19675 @item 
19676 All files prefixed with @code{sem} perform semantic analysis. The
19677 numbers correspond to chapters of the Ada standard. For example, all
19678 issues involving context clauses can be found in @code{sem_ch10.adb}. In
19679 addition, some features of the language require sufficient special processing
19680 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19681 dynamic dispatching, etc.
19683 @item 
19684 All files prefixed with @code{exp} perform normalization and
19685 expansion of the intermediate representation (abstract syntax tree, or AST).
19686 these files use the same numbering scheme as the parser and semantics files.
19687 For example, the construction of record initialization procedures is done in
19688 @code{exp_ch3.adb}.
19690 @item 
19691 The files prefixed with @code{bind} implement the binder, which
19692 verifies the consistency of the compilation, determines an order of
19693 elaboration, and generates the bind file.
19695 @item 
19696 The files @code{atree.ads} and @code{atree.adb} detail the low-level
19697 data structures used by the front-end.
19699 @item 
19700 The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
19701 the abstract syntax tree as produced by the parser.
19703 @item 
19704 The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
19705 all entities, computed during semantic analysis.
19707 @item 
19708 Library management issues are dealt with in files with prefix
19709 @code{lib}.
19711 @geindex Annex A (in Ada Reference Manual)
19713 @item 
19714 Ada files with the prefix @code{a-} are children of @cite{Ada}, as
19715 defined in Annex A.
19717 @geindex Annex B (in Ada reference Manual)
19719 @item 
19720 Files with prefix @code{i-} are children of @cite{Interfaces}, as
19721 defined in Annex B.
19723 @geindex System (package in Ada Reference Manual)
19725 @item 
19726 Files with prefix @code{s-} are children of @cite{System}. This includes
19727 both language-defined children and GNAT run-time routines.
19729 @geindex GNAT (package)
19731 @item 
19732 Files with prefix @code{g-} are children of @cite{GNAT}. These are useful
19733 general-purpose packages, fully documented in their specs. All
19734 the other @code{.c} files are modifications of common @emph{gcc} files.
19735 @end itemize
19737 @node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
19738 @anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{186}@anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{187}
19739 @subsection Getting Internal Debugging Information
19742 Most compilers have internal debugging switches and modes. GNAT
19743 does also, except GNAT internal debugging switches and modes are not
19744 secret. A summary and full description of all the compiler and binder
19745 debug flags are in the file @code{debug.adb}. You must obtain the
19746 sources of the compiler to see the full detailed effects of these flags.
19748 The switches that print the source of the program (reconstructed from
19749 the internal tree) are of general interest for user programs, as are the
19750 options to print
19751 the full internal tree, and the entity table (the symbol table
19752 information). The reconstructed source provides a readable version of the
19753 program after the front-end has completed analysis and  expansion,
19754 and is useful when studying the performance of specific constructs.
19755 For example, constraint checks are indicated, complex aggregates
19756 are replaced with loops and assignments, and tasking primitives
19757 are replaced with run-time calls.
19759 @geindex traceback
19761 @geindex stack traceback
19763 @geindex stack unwinding
19765 @node Stack Traceback,,Getting Internal Debugging Information,Running and Debugging Ada Programs
19766 @anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{188}@anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{189}
19767 @subsection Stack Traceback
19770 Traceback is a mechanism to display the sequence of subprogram calls that
19771 leads to a specified execution point in a program. Often (but not always)
19772 the execution point is an instruction at which an exception has been raised.
19773 This mechanism is also known as @emph{stack unwinding} because it obtains
19774 its information by scanning the run-time stack and recovering the activation
19775 records of all active subprograms. Stack unwinding is one of the most
19776 important tools for program debugging.
19778 The first entry stored in traceback corresponds to the deepest calling level,
19779 that is to say the subprogram currently executing the instruction
19780 from which we want to obtain the traceback.
19782 Note that there is no runtime performance penalty when stack traceback
19783 is enabled, and no exception is raised during program execution.
19785 @geindex traceback
19786 @geindex non-symbolic
19788 @menu
19789 * Non-Symbolic Traceback:: 
19790 * Symbolic Traceback:: 
19792 @end menu
19794 @node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
19795 @anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{18a}@anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{18b}
19796 @subsubsection Non-Symbolic Traceback
19799 Note: this feature is not supported on all platforms. See
19800 @code{GNAT.Traceback} spec in @code{g-traceb.ads}
19801 for a complete list of supported platforms.
19803 @subsubheading Tracebacks From an Unhandled Exception
19806 A runtime non-symbolic traceback is a list of addresses of call instructions.
19807 To enable this feature you must use the @emph{-E}
19808 @cite{gnatbind}'s option. With this option a stack traceback is stored as part
19809 of exception information. You can retrieve this information using the
19810 @cite{addr2line} tool.
19812 Here is a simple example:
19814 @quotation
19816 @example
19817 procedure STB is
19819    procedure P1 is
19820    begin
19821       raise Constraint_Error;
19822    end P1;
19824    procedure P2 is
19825    begin
19826       P1;
19827    end P2;
19829 begin
19830    P2;
19831 end STB;
19832 @end example
19834 @example
19835 $ gnatmake stb -bargs -E
19836 $ stb
19838 Execution terminated by unhandled exception
19839 Exception name: CONSTRAINT_ERROR
19840 Message: stb.adb:5
19841 Call stack traceback locations:
19842 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19843 @end example
19844 @end quotation
19846 As we see the traceback lists a sequence of addresses for the unhandled
19847 exception @cite{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19848 guess that this exception come from procedure P1. To translate these
19849 addresses into the source lines where the calls appear, the
19850 @cite{addr2line} tool, described below, is invaluable. The use of this tool
19851 requires the program to be compiled with debug information.
19853 @quotation
19855 @example
19856 $ gnatmake -g stb -bargs -E
19857 $ stb
19859 Execution terminated by unhandled exception
19860 Exception name: CONSTRAINT_ERROR
19861 Message: stb.adb:5
19862 Call stack traceback locations:
19863 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19865 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19866    0x4011f1 0x77e892a4
19868 00401373 at d:/stb/stb.adb:5
19869 0040138B at d:/stb/stb.adb:10
19870 0040139C at d:/stb/stb.adb:14
19871 00401335 at d:/stb/b~stb.adb:104
19872 004011C4 at /build/.../crt1.c:200
19873 004011F1 at /build/.../crt1.c:222
19874 77E892A4 in ?? at ??:0
19875 @end example
19876 @end quotation
19878 The @cite{addr2line} tool has several other useful options:
19880 @quotation
19883 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
19884 @item
19886 @code{--functions}
19888 @tab
19890 to get the function name corresponding to any location
19892 @item
19894 @code{--demangle=gnat}
19896 @tab
19898 to use the gnat decoding mode for the function names.
19899 Note that for binutils version 2.9.x the option is
19900 simply @code{--demangle}.
19902 @end multitable
19905 @example
19906 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
19907    0x40139c 0x401335 0x4011c4 0x4011f1
19909 00401373 in stb.p1 at d:/stb/stb.adb:5
19910 0040138B in stb.p2 at d:/stb/stb.adb:10
19911 0040139C in stb at d:/stb/stb.adb:14
19912 00401335 in main at d:/stb/b~stb.adb:104
19913 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
19914 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
19915 @end example
19916 @end quotation
19918 From this traceback we can see that the exception was raised in
19919 @code{stb.adb} at line 5, which was reached from a procedure call in
19920 @code{stb.adb} at line 10, and so on. The @code{b~std.adb} is the binder file,
19921 which contains the call to the main program.
19922 @ref{11c,,Running gnatbind}. The remaining entries are assorted runtime routines,
19923 and the output will vary from platform to platform.
19925 It is also possible to use @cite{GDB} with these traceback addresses to debug
19926 the program. For example, we can break at a given code location, as reported
19927 in the stack traceback:
19929 @quotation
19931 @example
19932 $ gdb -nw stb
19933 @end example
19934 @end quotation
19936 Furthermore, this feature is not implemented inside Windows DLL. Only
19937 the non-symbolic traceback is reported in this case.
19939 @quotation
19941 @example
19942 (gdb) break *0x401373
19943 Breakpoint 1 at 0x401373: file stb.adb, line 5.
19944 @end example
19945 @end quotation
19947 It is important to note that the stack traceback addresses
19948 do not change when debug information is included. This is particularly useful
19949 because it makes it possible to release software without debug information (to
19950 minimize object size), get a field report that includes a stack traceback
19951 whenever an internal bug occurs, and then be able to retrieve the sequence
19952 of calls with the same program compiled with debug information.
19954 @subsubheading Tracebacks From Exception Occurrences
19957 Non-symbolic tracebacks are obtained by using the @emph{-E} binder argument.
19958 The stack traceback is attached to the exception information string, and can
19959 be retrieved in an exception handler within the Ada program, by means of the
19960 Ada facilities defined in @cite{Ada.Exceptions}. Here is a simple example:
19962 @quotation
19964 @example
19965 with Ada.Text_IO;
19966 with Ada.Exceptions;
19968 procedure STB is
19970    use Ada;
19971    use Ada.Exceptions;
19973    procedure P1 is
19974       K : Positive := 1;
19975    begin
19976       K := K - 1;
19977    exception
19978       when E : others =>
19979          Text_IO.Put_Line (Exception_Information (E));
19980    end P1;
19982    procedure P2 is
19983    begin
19984       P1;
19985    end P2;
19987 begin
19988    P2;
19989 end STB;
19990 @end example
19991 @end quotation
19993 This program will output:
19995 @quotation
19997 @example
19998 $ stb
20000 Exception name: CONSTRAINT_ERROR
20001 Message: stb.adb:12
20002 Call stack traceback locations:
20003 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20004 @end example
20005 @end quotation
20007 @subsubheading Tracebacks From Anywhere in a Program
20010 It is also possible to retrieve a stack traceback from anywhere in a
20011 program. For this you need to
20012 use the @cite{GNAT.Traceback} API. This package includes a procedure called
20013 @cite{Call_Chain} that computes a complete stack traceback, as well as useful
20014 display procedures described below. It is not necessary to use the
20015 @emph{-E gnatbind} option in this case, because the stack traceback mechanism
20016 is invoked explicitly.
20018 In the following example we compute a traceback at a specific location in
20019 the program, and we display it using @cite{GNAT.Debug_Utilities.Image} to
20020 convert addresses to strings:
20022 @quotation
20024 @example
20025 with Ada.Text_IO;
20026 with GNAT.Traceback;
20027 with GNAT.Debug_Utilities;
20029 procedure STB is
20031    use Ada;
20032    use GNAT;
20033    use GNAT.Traceback;
20035    procedure P1 is
20036       TB  : Tracebacks_Array (1 .. 10);
20037       --  We are asking for a maximum of 10 stack frames.
20038       Len : Natural;
20039       --  Len will receive the actual number of stack frames returned.
20040    begin
20041       Call_Chain (TB, Len);
20043       Text_IO.Put ("In STB.P1 : ");
20045       for K in 1 .. Len loop
20046          Text_IO.Put (Debug_Utilities.Image (TB (K)));
20047          Text_IO.Put (' ');
20048       end loop;
20050       Text_IO.New_Line;
20051    end P1;
20053    procedure P2 is
20054    begin
20055       P1;
20056    end P2;
20058 begin
20059    P2;
20060 end STB;
20061 @end example
20063 @example
20064 $ gnatmake -g stb
20065 $ stb
20067 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
20068 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20069 @end example
20070 @end quotation
20072 You can then get further information by invoking the @cite{addr2line}
20073 tool as described earlier (note that the hexadecimal addresses
20074 need to be specified in C format, with a leading '0x').
20076 @geindex traceback
20077 @geindex symbolic
20079 @node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
20080 @anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{18c}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{18d}
20081 @subsubsection Symbolic Traceback
20084 A symbolic traceback is a stack traceback in which procedure names are
20085 associated with each code location.
20087 Note that this feature is not supported on all platforms. See
20088 @code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
20089 list of currently supported platforms.
20091 Note that the symbolic traceback requires that the program be compiled
20092 with debug information. If it is not compiled with debug information
20093 only the non-symbolic information will be valid.
20095 @subsubheading Tracebacks From Exception Occurrences
20098 Here is an example:
20100 @quotation
20102 @example
20103 with Ada.Text_IO;
20104 with GNAT.Traceback.Symbolic;
20106 procedure STB is
20108    procedure P1 is
20109    begin
20110       raise Constraint_Error;
20111    end P1;
20113    procedure P2 is
20114    begin
20115       P1;
20116    end P2;
20118    procedure P3 is
20119    begin
20120       P2;
20121    end P3;
20123 begin
20124    P3;
20125 exception
20126    when E : others =>
20127       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20128 end STB;
20129 @end example
20131 @example
20132 $ gnatmake -g .\stb -bargs -E
20133 $ stb
20135 0040149F in stb.p1 at stb.adb:8
20136 004014B7 in stb.p2 at stb.adb:13
20137 004014CF in stb.p3 at stb.adb:18
20138 004015DD in ada.stb at stb.adb:22
20139 00401461 in main at b~stb.adb:168
20140 004011C4 in __mingw_CRTStartup at crt1.c:200
20141 004011F1 in mainCRTStartup at crt1.c:222
20142 77E892A4 in ?? at ??:0
20143 @end example
20144 @end quotation
20146 In the above example the @code{.\} syntax in the @emph{gnatmake} command
20147 is currently required by @emph{addr2line} for files that are in
20148 the current working directory.
20149 Moreover, the exact sequence of linker options may vary from platform
20150 to platform.
20151 The above @emph{-largs} section is for Windows platforms. By contrast,
20152 under Unix there is no need for the @emph{-largs} section.
20153 Differences across platforms are due to details of linker implementation.
20155 @subsubheading Tracebacks From Anywhere in a Program
20158 It is possible to get a symbolic stack traceback
20159 from anywhere in a program, just as for non-symbolic tracebacks.
20160 The first step is to obtain a non-symbolic
20161 traceback, and then call @cite{Symbolic_Traceback} to compute the symbolic
20162 information. Here is an example:
20164 @quotation
20166 @example
20167 with Ada.Text_IO;
20168 with GNAT.Traceback;
20169 with GNAT.Traceback.Symbolic;
20171 procedure STB is
20173    use Ada;
20174    use GNAT.Traceback;
20175    use GNAT.Traceback.Symbolic;
20177    procedure P1 is
20178       TB  : Tracebacks_Array (1 .. 10);
20179       --  We are asking for a maximum of 10 stack frames.
20180       Len : Natural;
20181       --  Len will receive the actual number of stack frames returned.
20182    begin
20183       Call_Chain (TB, Len);
20184       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20185    end P1;
20187    procedure P2 is
20188    begin
20189       P1;
20190    end P2;
20192 begin
20193    P2;
20194 end STB;
20195 @end example
20196 @end quotation
20198 @subsubheading Automatic Symbolic Tracebacks
20201 Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
20202 in @cite{gprbuild -g ... -bargs -Es}).
20203 This will cause the Exception_Information to contain a symbolic traceback,
20204 which will also be printed if an unhandled exception terminates the
20205 program.
20207 @geindex Code Coverage
20209 @geindex Profiling
20211 @node Code Coverage and Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
20212 @anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{168}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-and-profiling}@anchor{25}
20213 @section Code Coverage and Profiling
20216 This section describes how to use the @cite{gcov} coverage testing tool and
20217 the @cite{gprof} profiler tool on Ada programs.
20219 @geindex gcov
20221 @menu
20222 * Code Coverage of Ada Programs with gcov:: 
20223 * Profiling an Ada Program with gprof:: 
20225 @end menu
20227 @node Code Coverage of Ada Programs with gcov,Profiling an Ada Program with gprof,,Code Coverage and Profiling
20228 @anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{18e}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-of-ada-programs-with-gcov}@anchor{18f}
20229 @subsection Code Coverage of Ada Programs with gcov
20232 @cite{gcov} is a test coverage program: it analyzes the execution of a given
20233 program on selected tests, to help you determine the portions of the program
20234 that are still untested.
20236 @cite{gcov} is part of the GCC suite, and is described in detail in the GCC
20237 User's Guide. You can refer to this documentation for a more complete
20238 description.
20240 This chapter provides a quick startup guide, and
20241 details some GNAT-specific features.
20243 @menu
20244 * Quick startup guide:: 
20245 * GNAT specifics:: 
20247 @end menu
20249 @node Quick startup guide,GNAT specifics,,Code Coverage of Ada Programs with gcov
20250 @anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{190}@anchor{gnat_ugn/gnat_and_program_execution quick-startup-guide}@anchor{191}
20251 @subsubsection Quick startup guide
20254 In order to perform coverage analysis of a program using @cite{gcov}, several
20255 steps are needed:
20258 @enumerate 
20260 @item 
20261 Instrument the code during the compilation process,
20263 @item 
20264 Execute the instrumented program, and
20266 @item 
20267 Invoke the @cite{gcov} tool to generate the coverage results.
20268 @end enumerate
20270 @geindex -fprofile-arcs (gcc)
20272 @geindex -ftest-coverage (gcc
20274 @geindex -fprofile-arcs (gnatbind)
20276 The code instrumentation needed by gcov is created at the object level.
20277 The source code is not modified in any way, because the instrumentation code is
20278 inserted by gcc during the compilation process. To compile your code with code
20279 coverage activated, you need to recompile your whole project using the
20280 switches
20281 @cite{-fprofile-arcs} and @cite{-ftest-coverage}, and link it using
20282 @cite{-fprofile-arcs}.
20284 @quotation
20286 @example
20287 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \\
20288    -largs -fprofile-arcs
20289 @end example
20290 @end quotation
20292 This compilation process will create @code{.gcno} files together with
20293 the usual object files.
20295 Once the program is compiled with coverage instrumentation, you can
20296 run it as many times as needed -- on portions of a test suite for
20297 example. The first execution will produce @code{.gcda} files at the
20298 same location as the @code{.gcno} files.  Subsequent executions
20299 will update those files, so that a cumulative result of the covered
20300 portions of the program is generated.
20302 Finally, you need to call the @cite{gcov} tool. The different options of
20303 @cite{gcov} are described in the GCC User's Guide, section 'Invoking gcov'.
20305 This will create annotated source files with a @code{.gcov} extension:
20306 @code{my_main.adb} file will be analyzed in @code{my_main.adb.gcov}.
20308 @node GNAT specifics,,Quick startup guide,Code Coverage of Ada Programs with gcov
20309 @anchor{gnat_ugn/gnat_and_program_execution gnat-specifics}@anchor{192}@anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{193}
20310 @subsubsection GNAT specifics
20313 Because of Ada semantics, portions of the source code may be shared among
20314 several object files. This is the case for example when generics are
20315 involved, when inlining is active  or when declarations generate  initialisation
20316 calls. In order to take
20317 into account this shared code, you need to call @cite{gcov} on all
20318 source files of the tested program at once.
20320 The list of source files might exceed the system's maximum command line
20321 length. In order to bypass this limitation, a new mechanism has been
20322 implemented in @cite{gcov}: you can now list all your project's files into a
20323 text file, and provide this file to gcov as a parameter,  preceded by a @code{@@}
20324 (e.g. @code{gcov @@mysrclist.txt}).
20326 Note that on AIX compiling a static library with @cite{-fprofile-arcs} is
20327 not supported as there can be unresolved symbols during the final link.
20329 @geindex gprof
20331 @geindex Profiling
20333 @node Profiling an Ada Program with gprof,,Code Coverage of Ada Programs with gcov,Code Coverage and Profiling
20334 @anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{194}@anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{195}
20335 @subsection Profiling an Ada Program with gprof
20338 This section is not meant to be an exhaustive documentation of @cite{gprof}.
20339 Full documentation for it can be found in the @cite{GNU Profiler User's Guide}
20340 documentation that is part of this GNAT distribution.
20342 Profiling a program helps determine the parts of a program that are executed
20343 most often, and are therefore the most time-consuming.
20345 @cite{gprof} is the standard GNU profiling tool; it has been enhanced to
20346 better handle Ada programs and multitasking.
20347 It is currently supported on the following platforms
20350 @itemize *
20352 @item 
20353 linux x86/x86_64
20355 @item 
20356 solaris sparc/sparc64/x86
20358 @item 
20359 windows x86
20360 @end itemize
20362 In order to profile a program using @cite{gprof}, several steps are needed:
20365 @enumerate 
20367 @item 
20368 Instrument the code, which requires a full recompilation of the project with the
20369 proper switches.
20371 @item 
20372 Execute the program under the analysis conditions, i.e. with the desired
20373 input.
20375 @item 
20376 Analyze the results using the @cite{gprof} tool.
20377 @end enumerate
20379 The following sections detail the different steps, and indicate how
20380 to interpret the results.
20382 @menu
20383 * Compilation for profiling:: 
20384 * Program execution:: 
20385 * Running gprof:: 
20386 * Interpretation of profiling results:: 
20388 @end menu
20390 @node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
20391 @anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{196}@anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{197}
20392 @subsubsection Compilation for profiling
20395 @geindex -pg (gcc)
20396 @geindex for profiling
20398 @geindex -pg (gnatlink)
20399 @geindex for profiling
20401 In order to profile a program the first step is to tell the compiler
20402 to generate the necessary profiling information. The compiler switch to be used
20403 is @code{-pg}, which must be added to other compilation switches. This
20404 switch needs to be specified both during compilation and link stages, and can
20405 be specified once when using gnatmake:
20407 @quotation
20409 @example
20410 $ gnatmake -f -pg -P my_project
20411 @end example
20412 @end quotation
20414 Note that only the objects that were compiled with the @code{-pg} switch will
20415 be profiled; if you need to profile your whole project, use the @code{-f}
20416 gnatmake switch to force full recompilation.
20418 @node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
20419 @anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{198}@anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{199}
20420 @subsubsection Program execution
20423 Once the program has been compiled for profiling, you can run it as usual.
20425 The only constraint imposed by profiling is that the program must terminate
20426 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20427 properly analyzed.
20429 Once the program completes execution, a data file called @code{gmon.out} is
20430 generated in the directory where the program was launched from. If this file
20431 already exists, it will be overwritten.
20433 @node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
20434 @anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{19a}@anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{19b}
20435 @subsubsection Running gprof
20438 The @cite{gprof} tool is called as follow:
20440 @quotation
20442 @example
20443 $ gprof my_prog gmon.out
20444 @end example
20445 @end quotation
20447 or simply:
20449 @quotation
20451 @example
20452 $  gprof my_prog
20453 @end example
20454 @end quotation
20456 The complete form of the gprof command line is the following:
20458 @quotation
20460 @example
20461 $ gprof [switches] [executable [data-file]]
20462 @end example
20463 @end quotation
20465 @cite{gprof} supports numerous switches. The order of these
20466 switch does not matter. The full list of options can be found in
20467 the GNU Profiler User's Guide documentation that comes with this documentation.
20469 The following is the subset of those switches that is most relevant:
20471 @geindex --demangle (gprof)
20474 @table @asis
20476 @item @code{--demangle[=@emph{style}]}, @code{--no-demangle}
20478 These options control whether symbol names should be demangled when
20479 printing output.  The default is to demangle C++ symbols.  The
20480 @code{--no-demangle} option may be used to turn off demangling. Different
20481 compilers have different mangling styles.  The optional demangling style
20482 argument can be used to choose an appropriate demangling style for your
20483 compiler, in particular Ada symbols generated by GNAT can be demangled using
20484 @code{--demangle=gnat}.
20485 @end table
20487 @geindex -e (gprof)
20490 @table @asis
20492 @item @code{-e @emph{function_name}}
20494 The @code{-e @emph{function}} option tells @cite{gprof} not to print
20495 information about the function @cite{function_name} (and its
20496 children...) in the call graph.  The function will still be listed
20497 as a child of any functions that call it, but its index number will be
20498 shown as @code{[not printed]}.  More than one @code{-e} option may be
20499 given; only one @cite{function_name} may be indicated with each @code{-e}
20500 option.
20501 @end table
20503 @geindex -E (gprof)
20506 @table @asis
20508 @item @code{-E @emph{function_name}}
20510 The @code{-E @emph{function}} option works like the @code{-e} option, but
20511 execution time spent in the function (and children who were not called from
20512 anywhere else), will not be used to compute the percentages-of-time for
20513 the call graph.  More than one @code{-E} option may be given; only one
20514 @cite{function_name} may be indicated with each @code{-E} option.
20515 @end table
20517 @geindex -f (gprof)
20520 @table @asis
20522 @item @code{-f @emph{function_name}}
20524 The @code{-f @emph{function}} option causes @cite{gprof} to limit the
20525 call graph to the function @cite{function_name} and its children (and
20526 their children...).  More than one @code{-f} option may be given;
20527 only one @cite{function_name} may be indicated with each @code{-f}
20528 option.
20529 @end table
20531 @geindex -F (gprof)
20534 @table @asis
20536 @item @code{-F @emph{function_name}}
20538 The @code{-F @emph{function}} option works like the @code{-f} option, but
20539 only time spent in the function and its children (and their
20540 children...) will be used to determine total-time and
20541 percentages-of-time for the call graph.  More than one @code{-F} option
20542 may be given; only one @cite{function_name} may be indicated with each
20543 @code{-F} option.  The @code{-F} option overrides the @code{-E} option.
20544 @end table
20546 @node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
20547 @anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{19c}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{19d}
20548 @subsubsection Interpretation of profiling results
20551 The results of the profiling analysis are represented by two arrays: the
20552 'flat profile' and the 'call graph'. Full documentation of those outputs
20553 can be found in the GNU Profiler User's Guide.
20555 The flat profile shows the time spent in each function of the program, and how
20556 many time it has been called. This allows you to locate easily the most
20557 time-consuming functions.
20559 The call graph shows, for each subprogram, the subprograms that call it,
20560 and the subprograms that it calls. It also provides an estimate of the time
20561 spent in each of those callers/called subprograms.
20563 @node Improving Performance,Overflow Check Handling in GNAT,Code Coverage and Profiling,GNAT and Program Execution
20564 @anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{26}@anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{169}
20565 @section Improving Performance
20568 @geindex Improving performance
20570 This section presents several topics related to program performance.
20571 It first describes some of the tradeoffs that need to be considered
20572 and some of the techniques for making your program run faster.
20575 It then documents the unused subprogram/data elimination feature,
20576 which can reduce the size of program executables.
20578 @menu
20579 * Performance Considerations:: 
20580 * Text_IO Suggestions:: 
20581 * Reducing Size of Executables with Unused Subprogram/Data Elimination:: 
20583 @end menu
20585 @node Performance Considerations,Text_IO Suggestions,,Improving Performance
20586 @anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{19e}@anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{19f}
20587 @subsection Performance Considerations
20590 The GNAT system provides a number of options that allow a trade-off
20591 between
20594 @itemize *
20596 @item 
20597 performance of the generated code
20599 @item 
20600 speed of compilation
20602 @item 
20603 minimization of dependences and recompilation
20605 @item 
20606 the degree of run-time checking.
20607 @end itemize
20609 The defaults (if no options are selected) aim at improving the speed
20610 of compilation and minimizing dependences, at the expense of performance
20611 of the generated code:
20614 @itemize *
20616 @item 
20617 no optimization
20619 @item 
20620 no inlining of subprogram calls
20622 @item 
20623 all run-time checks enabled except overflow and elaboration checks
20624 @end itemize
20626 These options are suitable for most program development purposes. This
20627 section describes how you can modify these choices, and also provides
20628 some guidelines on debugging optimized code.
20630 @menu
20631 * Controlling Run-Time Checks:: 
20632 * Use of Restrictions:: 
20633 * Optimization Levels:: 
20634 * Debugging Optimized Code:: 
20635 * Inlining of Subprograms:: 
20636 * Floating_Point_Operations:: 
20637 * Vectorization of loops:: 
20638 * Other Optimization Switches:: 
20639 * Optimization and Strict Aliasing:: 
20640 * Aliased Variables and Optimization:: 
20641 * Atomic Variables and Optimization:: 
20642 * Passive Task Optimization:: 
20644 @end menu
20646 @node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
20647 @anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{1a0}@anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{1a1}
20648 @subsubsection Controlling Run-Time Checks
20651 By default, GNAT generates all run-time checks, except stack overflow
20652 checks, and checks for access before elaboration on subprogram
20653 calls. The latter are not required in default mode, because all
20654 necessary checking is done at compile time.
20656 @geindex -gnatp (gcc)
20658 @geindex -gnato (gcc)
20660 The gnat switch, @emph{-gnatp} allows this default to be modified. See
20661 @ref{f9,,Run-Time Checks}.
20663 Our experience is that the default is suitable for most development
20664 purposes.
20666 Elaboration checks are off by default, and also not needed by default, since
20667 GNAT uses a static elaboration analysis approach that avoids the need for
20668 run-time checking. This manual contains a full chapter discussing the issue
20669 of elaboration checks, and if the default is not satisfactory for your use,
20670 you should read this chapter.
20672 For validity checks, the minimal checks required by the Ada Reference
20673 Manual (for case statements and assignments to array elements) are on
20674 by default. These can be suppressed by use of the @emph{-gnatVn} switch.
20675 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20676 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20677 it may be reasonable to routinely use @emph{-gnatVn}. Validity checks
20678 are also suppressed entirely if @emph{-gnatp} is used.
20680 @geindex Overflow checks
20682 @geindex Checks
20683 @geindex overflow
20685 @geindex Suppress
20687 @geindex Unsuppress
20689 @geindex pragma Suppress
20691 @geindex pragma Unsuppress
20693 Note that the setting of the switches controls the default setting of
20694 the checks. They may be modified using either @cite{pragma Suppress} (to
20695 remove checks) or @cite{pragma Unsuppress} (to add back suppressed
20696 checks) in the program source.
20698 @node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
20699 @anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{1a2}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{1a3}
20700 @subsubsection Use of Restrictions
20703 The use of pragma Restrictions allows you to control which features are
20704 permitted in your program. Apart from the obvious point that if you avoid
20705 relatively expensive features like finalization (enforceable by the use
20706 of pragma Restrictions (No_Finalization), the use of this pragma does not
20707 affect the generated code in most cases.
20709 One notable exception to this rule is that the possibility of task abort
20710 results in some distributed overhead, particularly if finalization or
20711 exception handlers are used. The reason is that certain sections of code
20712 have to be marked as non-abortable.
20714 If you use neither the @cite{abort} statement, nor asynchronous transfer
20715 of control (@cite{select ... then abort}), then this distributed overhead
20716 is removed, which may have a general positive effect in improving
20717 overall performance.  Especially code involving frequent use of tasking
20718 constructs and controlled types will show much improved performance.
20719 The relevant restrictions pragmas are
20721 @quotation
20723 @example
20724 pragma Restrictions (No_Abort_Statements);
20725 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
20726 @end example
20727 @end quotation
20729 It is recommended that these restriction pragmas be used if possible. Note
20730 that this also means that you can write code without worrying about the
20731 possibility of an immediate abort at any point.
20733 @node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
20734 @anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{1a4}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{fc}
20735 @subsubsection Optimization Levels
20738 @geindex -O (gcc)
20740 Without any optimization option,
20741 the compiler's goal is to reduce the cost of
20742 compilation and to make debugging produce the expected results.
20743 Statements are independent: if you stop the program with a breakpoint between
20744 statements, you can then assign a new value to any variable or change
20745 the program counter to any other statement in the subprogram and get exactly
20746 the results you would expect from the source code.
20748 Turning on optimization makes the compiler attempt to improve the
20749 performance and/or code size at the expense of compilation time and
20750 possibly the ability to debug the program.
20752 If you use multiple
20753 -O options, with or without level numbers,
20754 the last such option is the one that is effective.
20756 The default is optimization off. This results in the fastest compile
20757 times, but GNAT makes absolutely no attempt to optimize, and the
20758 generated programs are considerably larger and slower than when
20759 optimization is enabled. You can use the
20760 @emph{-O} switch (the permitted forms are @emph{-O0}, @emph{-O1}
20761 @emph{-O2}, @emph{-O3}, and @emph{-Os})
20762 to @emph{gcc} to control the optimization level:
20765 @itemize *
20767 @item 
20769 @table @asis
20771 @item @emph{-O0}
20773 No optimization (the default);
20774 generates unoptimized code but has
20775 the fastest compilation time.
20777 Note that many other compilers do fairly extensive optimization
20778 even if 'no optimization' is specified. With gcc, it is
20779 very unusual to use -O0 for production if
20780 execution time is of any concern, since -O0
20781 really does mean no optimization at all. This difference between
20782 gcc and other compilers should be kept in mind when doing
20783 performance comparisons.
20784 @end table
20786 @item 
20788 @table @asis
20790 @item @emph{-O1}
20792 Moderate optimization;
20793 optimizes reasonably well but does not
20794 degrade compilation time significantly.
20795 @end table
20797 @item 
20799 @table @asis
20801 @item @emph{-O2}
20803 Full optimization;
20804 generates highly optimized code and has
20805 the slowest compilation time.
20806 @end table
20808 @item 
20810 @table @asis
20812 @item @emph{-O3}
20814 Full optimization as in @emph{-O2};
20815 also uses more aggressive automatic inlining of subprograms within a unit
20816 (@ref{10f,,Inlining of Subprograms}) and attempts to vectorize loops.
20817 @end table
20819 @item 
20821 @table @asis
20823 @item @emph{-Os}
20825 Optimize space usage (code and data) of resulting program.
20826 @end table
20827 @end itemize
20829 Higher optimization levels perform more global transformations on the
20830 program and apply more expensive analysis algorithms in order to generate
20831 faster and more compact code. The price in compilation time, and the
20832 resulting improvement in execution time,
20833 both depend on the particular application and the hardware environment.
20834 You should experiment to find the best level for your application.
20836 Since the precise set of optimizations done at each level will vary from
20837 release to release (and sometime from target to target), it is best to think
20838 of the optimization settings in general terms.
20839 See the @emph{Options That Control Optimization} section in
20840 @cite{Using the GNU Compiler Collection (GCC)}
20841 for details about
20842 the @emph{-O} settings and a number of @emph{-f} options that
20843 individually enable or disable specific optimizations.
20845 Unlike some other compilation systems, @emph{gcc} has
20846 been tested extensively at all optimization levels. There are some bugs
20847 which appear only with optimization turned on, but there have also been
20848 bugs which show up only in @emph{unoptimized} code. Selecting a lower
20849 level of optimization does not improve the reliability of the code
20850 generator, which in practice is highly reliable at all optimization
20851 levels.
20853 Note regarding the use of @emph{-O3}: The use of this optimization level
20854 is generally discouraged with GNAT, since it often results in larger
20855 executables which may run more slowly. See further discussion of this point
20856 in @ref{10f,,Inlining of Subprograms}.
20858 @node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
20859 @anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{1a5}@anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{1a6}
20860 @subsubsection Debugging Optimized Code
20863 @geindex Debugging optimized code
20865 @geindex Optimization and debugging
20867 Although it is possible to do a reasonable amount of debugging at
20868 nonzero optimization levels,
20869 the higher the level the more likely that
20870 source-level constructs will have been eliminated by optimization.
20871 For example, if a loop is strength-reduced, the loop
20872 control variable may be completely eliminated and thus cannot be
20873 displayed in the debugger.
20874 This can only happen at @emph{-O2} or @emph{-O3}.
20875 Explicit temporary variables that you code might be eliminated at
20876 level @emph{-O1} or higher.
20878 @geindex -g (gcc)
20880 The use of the @emph{-g} switch,
20881 which is needed for source-level debugging,
20882 affects the size of the program executable on disk,
20883 and indeed the debugging information can be quite large.
20884 However, it has no effect on the generated code (and thus does not
20885 degrade performance)
20887 Since the compiler generates debugging tables for a compilation unit before
20888 it performs optimizations, the optimizing transformations may invalidate some
20889 of the debugging data.  You therefore need to anticipate certain
20890 anomalous situations that may arise while debugging optimized code.
20891 These are the most common cases:
20894 @itemize *
20896 @item 
20897 @emph{The 'hopping Program Counter':}  Repeated @cite{step} or @cite{next}
20898 commands show
20899 the PC bouncing back and forth in the code.  This may result from any of
20900 the following optimizations:
20903 @itemize -
20905 @item 
20906 @emph{Common subexpression elimination:} using a single instance of code for a
20907 quantity that the source computes several times.  As a result you
20908 may not be able to stop on what looks like a statement.
20910 @item 
20911 @emph{Invariant code motion:} moving an expression that does not change within a
20912 loop, to the beginning of the loop.
20914 @item 
20915 @emph{Instruction scheduling:} moving instructions so as to
20916 overlap loads and stores (typically) with other code, or in
20917 general to move computations of values closer to their uses. Often
20918 this causes you to pass an assignment statement without the assignment
20919 happening and then later bounce back to the statement when the
20920 value is actually needed.  Placing a breakpoint on a line of code
20921 and then stepping over it may, therefore, not always cause all the
20922 expected side-effects.
20923 @end itemize
20925 @item 
20926 @emph{The 'big leap':} More commonly known as @emph{cross-jumping}, in which
20927 two identical pieces of code are merged and the program counter suddenly
20928 jumps to a statement that is not supposed to be executed, simply because
20929 it (and the code following) translates to the same thing as the code
20930 that @emph{was} supposed to be executed.  This effect is typically seen in
20931 sequences that end in a jump, such as a @cite{goto}, a @cite{return}, or
20932 a @cite{break} in a C @cite{switch} statement.
20934 @item 
20935 @emph{The 'roving variable':} The symptom is an unexpected value in a variable.
20936 There are various reasons for this effect:
20939 @itemize -
20941 @item 
20942 In a subprogram prologue, a parameter may not yet have been moved to its
20943 'home'.
20945 @item 
20946 A variable may be dead, and its register re-used.  This is
20947 probably the most common cause.
20949 @item 
20950 As mentioned above, the assignment of a value to a variable may
20951 have been moved.
20953 @item 
20954 A variable may be eliminated entirely by value propagation or
20955 other means.  In this case, GCC may incorrectly generate debugging
20956 information for the variable
20957 @end itemize
20959 In general, when an unexpected value appears for a local variable or parameter
20960 you should first ascertain if that value was actually computed by
20961 your program, as opposed to being incorrectly reported by the debugger.
20962 Record fields or
20963 array elements in an object designated by an access value
20964 are generally less of a problem, once you have ascertained that the access
20965 value is sensible.
20966 Typically, this means checking variables in the preceding code and in the
20967 calling subprogram to verify that the value observed is explainable from other
20968 values (one must apply the procedure recursively to those
20969 other values); or re-running the code and stopping a little earlier
20970 (perhaps before the call) and stepping to better see how the variable obtained
20971 the value in question; or continuing to step @emph{from} the point of the
20972 strange value to see if code motion had simply moved the variable's
20973 assignments later.
20974 @end itemize
20976 In light of such anomalies, a recommended technique is to use @emph{-O0}
20977 early in the software development cycle, when extensive debugging capabilities
20978 are most needed, and then move to @emph{-O1} and later @emph{-O2} as
20979 the debugger becomes less critical.
20980 Whether to use the @emph{-g} switch in the release version is
20981 a release management issue.
20982 Note that if you use @emph{-g} you can then use the @emph{strip} program
20983 on the resulting executable,
20984 which removes both debugging information and global symbols.
20986 @node Inlining of Subprograms,Floating_Point_Operations,Debugging Optimized Code,Performance Considerations
20987 @anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{1a7}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{10f}
20988 @subsubsection Inlining of Subprograms
20991 A call to a subprogram in the current unit is inlined if all the
20992 following conditions are met:
20995 @itemize *
20997 @item 
20998 The optimization level is at least @emph{-O1}.
21000 @item 
21001 The called subprogram is suitable for inlining: It must be small enough
21002 and not contain something that @emph{gcc} cannot support in inlined
21003 subprograms.
21005 @geindex pragma Inline
21007 @geindex Inline
21009 @item 
21010 Any one of the following applies: @cite{pragma Inline} is applied to the
21011 subprogram; the subprogram is local to the unit and called once from
21012 within it; the subprogram is small and optimization level @emph{-O2} is
21013 specified; optimization level @emph{-O3} is specified.
21014 @end itemize
21016 Calls to subprograms in @emph{with}ed units are normally not inlined.
21017 To achieve actual inlining (that is, replacement of the call by the code
21018 in the body of the subprogram), the following conditions must all be true:
21021 @itemize *
21023 @item 
21024 The optimization level is at least @emph{-O1}.
21026 @item 
21027 The called subprogram is suitable for inlining: It must be small enough
21028 and not contain something that @emph{gcc} cannot support in inlined
21029 subprograms.
21031 @item 
21032 There is a @cite{pragma Inline} for the subprogram.
21034 @item 
21035 The @emph{-gnatn} switch is used on the command line.
21036 @end itemize
21038 Even if all these conditions are met, it may not be possible for
21039 the compiler to inline the call, due to the length of the body,
21040 or features in the body that make it impossible for the compiler
21041 to do the inlining.
21043 Note that specifying the @emph{-gnatn} switch causes additional
21044 compilation dependencies. Consider the following:
21046 @quotation
21048 @example
21049 package R is
21050    procedure Q;
21051    pragma Inline (Q);
21052 end R;
21053 package body R is
21054    ...
21055 end R;
21057 with R;
21058 procedure Main is
21059 begin
21060    ...
21061    R.Q;
21062 end Main;
21063 @end example
21064 @end quotation
21066 With the default behavior (no @emph{-gnatn} switch specified), the
21067 compilation of the @cite{Main} procedure depends only on its own source,
21068 @code{main.adb}, and the spec of the package in file @code{r.ads}. This
21069 means that editing the body of @cite{R} does not require recompiling
21070 @cite{Main}.
21072 On the other hand, the call @cite{R.Q} is not inlined under these
21073 circumstances. If the @emph{-gnatn} switch is present when @cite{Main}
21074 is compiled, the call will be inlined if the body of @cite{Q} is small
21075 enough, but now @cite{Main} depends on the body of @cite{R} in
21076 @code{r.adb} as well as on the spec. This means that if this body is edited,
21077 the main program must be recompiled. Note that this extra dependency
21078 occurs whether or not the call is in fact inlined by @emph{gcc}.
21080 The use of front end inlining with @emph{-gnatN} generates similar
21081 additional dependencies.
21083 @geindex -fno-inline (gcc)
21085 Note: The @emph{-fno-inline} switch overrides all other conditions and ensures that
21086 no inlining occurs, unless requested with pragma Inline_Always for @emph{gcc}
21087 back-ends. The extra dependences resulting from @emph{-gnatn} will still be active,
21088 even if this switch is used to suppress the resulting inlining actions.
21090 @geindex -fno-inline-functions (gcc)
21092 Note: The @emph{-fno-inline-functions} switch can be used to prevent
21093 automatic inlining of subprograms if @emph{-O3} is used.
21095 @geindex -fno-inline-small-functions (gcc)
21097 Note: The @emph{-fno-inline-small-functions} switch can be used to prevent
21098 automatic inlining of small subprograms if @emph{-O2} is used.
21100 @geindex -fno-inline-functions-called-once (gcc)
21102 Note: The @emph{-fno-inline-functions-called-once} switch
21103 can be used to prevent inlining of subprograms local to the unit
21104 and called once from within it if @emph{-O1} is used.
21106 Note regarding the use of @emph{-O3}: @emph{-gnatn} is made up of two
21107 sub-switches @emph{-gnatn1} and @emph{-gnatn2} that can be directly
21108 specified in lieu of it, @emph{-gnatn} being translated into one of them
21109 based on the optimization level. With @emph{-O2} or below, @emph{-gnatn}
21110 is equivalent to @emph{-gnatn1} which activates pragma @cite{Inline} with
21111 moderate inlining across modules. With @emph{-O3}, @emph{-gnatn} is
21112 equivalent to @emph{-gnatn2} which activates pragma @cite{Inline} with
21113 full inlining across modules. If you have used pragma @cite{Inline} in
21114 appropriate cases, then it is usually much better to use @emph{-O2}
21115 and @emph{-gnatn} and avoid the use of @emph{-O3} which has the additional
21116 effect of inlining subprograms you did not think should be inlined. We have
21117 found that the use of @emph{-O3} may slow down the compilation and increase
21118 the code size by performing excessive inlining, leading to increased
21119 instruction cache pressure from the increased code size and thus minor
21120 performance improvements. So the bottom line here is that you should not
21121 automatically assume that @emph{-O3} is better than @emph{-O2}, and
21122 indeed you should use @emph{-O3} only if tests show that it actually
21123 improves performance for your program.
21125 @node Floating_Point_Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
21126 @anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{1a8}@anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{1a9}
21127 @subsubsection Floating_Point_Operations
21130 @geindex Floating-Point Operations
21132 On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
21133 64-bit standard IEEE floating-point representations, and operations will
21134 use standard IEEE arithmetic as provided by the processor. On most, but
21135 not all, architectures, the attribute Machine_Overflows is False for these
21136 types, meaning that the semantics of overflow is implementation-defined.
21137 In the case of GNAT, these semantics correspond to the normal IEEE
21138 treatment of infinities and NaN (not a number) values. For example,
21139 1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
21140 avoiding explicit overflow checks, the performance is greatly improved
21141 on many targets. However, if required, floating-point overflow can be
21142 enabled by the use of the pragma Check_Float_Overflow.
21144 Another consideration that applies specifically to x86 32-bit
21145 architectures is which form of floating-point arithmetic is used.
21146 By default the operations use the old style x86 floating-point,
21147 which implements an 80-bit extended precision form (on these
21148 architectures the type Long_Long_Float corresponds to that form).
21149 In addition, generation of efficient code in this mode means that
21150 the extended precision form will be used for intermediate results.
21151 This may be helpful in improving the final precision of a complex
21152 expression. However it means that the results obtained on the x86
21153 will be different from those on other architectures, and for some
21154 algorithms, the extra intermediate precision can be detrimental.
21156 In addition to this old-style floating-point, all modern x86 chips
21157 implement an alternative floating-point operation model referred
21158 to as SSE2. In this model there is no extended form, and furthermore
21159 execution performance is significantly enhanced. To force GNAT to use
21160 this more modern form, use both of the switches:
21162 @quotation
21164 -msse2 -mfpmath=sse
21165 @end quotation
21167 A unit compiled with these switches will automatically use the more
21168 efficient SSE2 instruction set for Float and Long_Float operations.
21169 Note that the ABI has the same form for both floating-point models,
21170 so it is permissible to mix units compiled with and without these
21171 switches.
21173 @node Vectorization of loops,Other Optimization Switches,Floating_Point_Operations,Performance Considerations
21174 @anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{1aa}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{1ab}
21175 @subsubsection Vectorization of loops
21178 @geindex Optimization Switches
21180 You can take advantage of the auto-vectorizer present in the @emph{gcc}
21181 back end to vectorize loops with GNAT.  The corresponding command line switch
21182 is @emph{-ftree-vectorize} but, as it is enabled by default at @emph{-O3}
21183 and other aggressive optimizations helpful for vectorization also are enabled
21184 by default at this level, using @emph{-O3} directly is recommended.
21186 You also need to make sure that the target architecture features a supported
21187 SIMD instruction set.  For example, for the x86 architecture, you should at
21188 least specify @emph{-msse2} to get significant vectorization (but you don't
21189 need to specify it for x86-64 as it is part of the base 64-bit architecture).
21190 Similarly, for the PowerPC architecture, you should specify @emph{-maltivec}.
21192 The preferred loop form for vectorization is the @cite{for} iteration scheme.
21193 Loops with a @cite{while} iteration scheme can also be vectorized if they are
21194 very simple, but the vectorizer will quickly give up otherwise.  With either
21195 iteration scheme, the flow of control must be straight, in particular no
21196 @cite{exit} statement may appear in the loop body.  The loop may however
21197 contain a single nested loop, if it can be vectorized when considered alone:
21199 @quotation
21201 @example
21202 A : array (1..4, 1..4) of Long_Float;
21203 S : array (1..4) of Long_Float;
21205 procedure Sum is
21206 begin
21207    for I in A'Range(1) loop
21208       for J in A'Range(2) loop
21209          S (I) := S (I) + A (I, J);
21210       end loop;
21211    end loop;
21212 end Sum;
21213 @end example
21214 @end quotation
21216 The vectorizable operations depend on the targeted SIMD instruction set, but
21217 the adding and some of the multiplying operators are generally supported, as
21218 well as the logical operators for modular types. Note that compiling
21219 with @emph{-gnatp} might well reveal cases where some checks do thwart
21220 vectorization.
21222 Type conversions may also prevent vectorization if they involve semantics that
21223 are not directly supported by the code generator or the SIMD instruction set.
21224 A typical example is direct conversion from floating-point to integer types.
21225 The solution in this case is to use the following idiom:
21227 @quotation
21229 @example
21230 Integer (S'Truncation (F))
21231 @end example
21232 @end quotation
21234 if @cite{S} is the subtype of floating-point object @cite{F}.
21236 In most cases, the vectorizable loops are loops that iterate over arrays.
21237 All kinds of array types are supported, i.e. constrained array types with
21238 static bounds:
21240 @quotation
21242 @example
21243 type Array_Type is array (1 .. 4) of Long_Float;
21244 @end example
21245 @end quotation
21247 constrained array types with dynamic bounds:
21249 @quotation
21251 @example
21252 type Array_Type is array (1 .. Q.N) of Long_Float;
21254 type Array_Type is array (Q.K .. 4) of Long_Float;
21256 type Array_Type is array (Q.K .. Q.N) of Long_Float;
21257 @end example
21258 @end quotation
21260 or unconstrained array types:
21262 @quotation
21264 @example
21265 type Array_Type is array (Positive range <>) of Long_Float;
21266 @end example
21267 @end quotation
21269 The quality of the generated code decreases when the dynamic aspect of the
21270 array type increases, the worst code being generated for unconstrained array
21271 types.  This is so because, the less information the compiler has about the
21272 bounds of the array, the more fallback code it needs to generate in order to
21273 fix things up at run time.
21275 It is possible to specify that a given loop should be subject to vectorization
21276 preferably to other optimizations by means of pragma @cite{Loop_Optimize}:
21278 @quotation
21280 @example
21281 pragma Loop_Optimize (Vector);
21282 @end example
21283 @end quotation
21285 placed immediately within the loop will convey the appropriate hint to the
21286 compiler for this loop.
21288 It is also possible to help the compiler generate better vectorized code
21289 for a given loop by asserting that there are no loop-carried dependencies
21290 in the loop.  Consider for example the procedure:
21292 @quotation
21294 @example
21295 type Arr is array (1 .. 4) of Long_Float;
21297 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
21298 begin
21299   for I in Arr'Range loop
21300     R(I) := X(I) + Y(I);
21301   end loop;
21302 end;
21303 @end example
21304 @end quotation
21306 By default, the compiler cannot unconditionally vectorize the loop because
21307 assigning to a component of the array designated by R in one iteration could
21308 change the value read from the components of the array designated by X or Y
21309 in a later iteration.  As a result, the compiler will generate two versions
21310 of the loop in the object code, one vectorized and the other not vectorized,
21311 as well as a test to select the appropriate version at run time.  This can
21312 be overcome by another hint:
21314 @quotation
21316 @example
21317 pragma Loop_Optimize (Ivdep);
21318 @end example
21319 @end quotation
21321 placed immediately within the loop will tell the compiler that it can safely
21322 omit the non-vectorized version of the loop as well as the run-time test.
21324 @node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
21325 @anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{1ac}@anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{1ad}
21326 @subsubsection Other Optimization Switches
21329 @geindex Optimization Switches
21331 Since @cite{GNAT} uses the @emph{gcc} back end, all the specialized
21332 @emph{gcc} optimization switches are potentially usable. These switches
21333 have not been extensively tested with GNAT but can generally be expected
21334 to work. Examples of switches in this category are @emph{-funroll-loops}
21335 and the various target-specific @emph{-m} options (in particular, it has
21336 been observed that @emph{-march=xxx} can significantly improve performance
21337 on appropriate machines). For full details of these switches, see
21338 the @cite{Submodel Options} section in the @cite{Hardware Models and Configurations}
21339 chapter of @cite{Using the GNU Compiler Collection (GCC)}.
21341 @node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
21342 @anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{f3}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{1ae}
21343 @subsubsection Optimization and Strict Aliasing
21346 @geindex Aliasing
21348 @geindex Strict Aliasing
21350 @geindex No_Strict_Aliasing
21352 The strong typing capabilities of Ada allow an optimizer to generate
21353 efficient code in situations where other languages would be forced to
21354 make worst case assumptions preventing such optimizations. Consider
21355 the following example:
21357 @quotation
21359 @example
21360 procedure R is
21361    type Int1 is new Integer;
21362    type Int2 is new Integer;
21363    type Int1A is access Int1;
21364    type Int2A is access Int2;
21365    Int1V : Int1A;
21366    Int2V : Int2A;
21367    ...
21369 begin
21370    ...
21371    for J in Data'Range loop
21372       if Data (J) = Int1V.all then
21373          Int2V.all := Int2V.all + 1;
21374       end if;
21375    end loop;
21376    ...
21377 end R;
21378 @end example
21379 @end quotation
21381 In this example, since the variable @cite{Int1V} can only access objects
21382 of type @cite{Int1}, and @cite{Int2V} can only access objects of type
21383 @cite{Int2}, there is no possibility that the assignment to
21384 @cite{Int2V.all} affects the value of @cite{Int1V.all}. This means that
21385 the compiler optimizer can "know" that the value @cite{Int1V.all} is constant
21386 for all iterations of the loop and avoid the extra memory reference
21387 required to dereference it each time through the loop.
21389 This kind of optimization, called strict aliasing analysis, is
21390 triggered by specifying an optimization level of @emph{-O2} or
21391 higher or @emph{-Os} and allows @cite{GNAT} to generate more efficient code
21392 when access values are involved.
21394 However, although this optimization is always correct in terms of
21395 the formal semantics of the Ada Reference Manual, difficulties can
21396 arise if features like @cite{Unchecked_Conversion} are used to break
21397 the typing system. Consider the following complete program example:
21399 @quotation
21401 @example
21402 package p1 is
21403    type int1 is new integer;
21404    type int2 is new integer;
21405    type a1 is access int1;
21406    type a2 is access int2;
21407 end p1;
21409 with p1; use p1;
21410 package p2 is
21411    function to_a2 (Input : a1) return a2;
21412 end p2;
21414 with Unchecked_Conversion;
21415 package body p2 is
21416    function to_a2 (Input : a1) return a2 is
21417       function to_a2u is
21418         new Unchecked_Conversion (a1, a2);
21419    begin
21420       return to_a2u (Input);
21421    end to_a2;
21422 end p2;
21424 with p2; use p2;
21425 with p1; use p1;
21426 with Text_IO; use Text_IO;
21427 procedure m is
21428    v1 : a1 := new int1;
21429    v2 : a2 := to_a2 (v1);
21430 begin
21431    v1.all := 1;
21432    v2.all := 0;
21433    put_line (int1'image (v1.all));
21434 end;
21435 @end example
21436 @end quotation
21438 This program prints out 0 in @emph{-O0} or @emph{-O1}
21439 mode, but it prints out 1 in @emph{-O2} mode. That's
21440 because in strict aliasing mode, the compiler can and
21441 does assume that the assignment to @cite{v2.all} could not
21442 affect the value of @cite{v1.all}, since different types
21443 are involved.
21445 This behavior is not a case of non-conformance with the standard, since
21446 the Ada RM specifies that an unchecked conversion where the resulting
21447 bit pattern is not a correct value of the target type can result in an
21448 abnormal value and attempting to reference an abnormal value makes the
21449 execution of a program erroneous.  That's the case here since the result
21450 does not point to an object of type @cite{int2}.  This means that the
21451 effect is entirely unpredictable.
21453 However, although that explanation may satisfy a language
21454 lawyer, in practice an applications programmer expects an
21455 unchecked conversion involving pointers to create true
21456 aliases and the behavior of printing 1 seems plain wrong.
21457 In this case, the strict aliasing optimization is unwelcome.
21459 Indeed the compiler recognizes this possibility, and the
21460 unchecked conversion generates a warning:
21462 @quotation
21464 @example
21465 p2.adb:5:07: warning: possible aliasing problem with type "a2"
21466 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
21467 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
21468 @end example
21469 @end quotation
21471 Unfortunately the problem is recognized when compiling the body of
21472 package @cite{p2}, but the actual "bad" code is generated while
21473 compiling the body of @cite{m} and this latter compilation does not see
21474 the suspicious @cite{Unchecked_Conversion}.
21476 As implied by the warning message, there are approaches you can use to
21477 avoid the unwanted strict aliasing optimization in a case like this.
21479 One possibility is to simply avoid the use of @emph{-O2}, but
21480 that is a bit drastic, since it throws away a number of useful
21481 optimizations that do not involve strict aliasing assumptions.
21483 A less drastic approach is to compile the program using the
21484 option @emph{-fno-strict-aliasing}. Actually it is only the
21485 unit containing the dereferencing of the suspicious pointer
21486 that needs to be compiled. So in this case, if we compile
21487 unit @cite{m} with this switch, then we get the expected
21488 value of zero printed. Analyzing which units might need
21489 the switch can be painful, so a more reasonable approach
21490 is to compile the entire program with options @emph{-O2}
21491 and @emph{-fno-strict-aliasing}. If the performance is
21492 satisfactory with this combination of options, then the
21493 advantage is that the entire issue of possible "wrong"
21494 optimization due to strict aliasing is avoided.
21496 To avoid the use of compiler switches, the configuration
21497 pragma @cite{No_Strict_Aliasing} with no parameters may be
21498 used to specify that for all access types, the strict
21499 aliasing optimization should be suppressed.
21501 However, these approaches are still overkill, in that they causes
21502 all manipulations of all access values to be deoptimized. A more
21503 refined approach is to concentrate attention on the specific
21504 access type identified as problematic.
21506 First, if a careful analysis of uses of the pointer shows
21507 that there are no possible problematic references, then
21508 the warning can be suppressed by bracketing the
21509 instantiation of @cite{Unchecked_Conversion} to turn
21510 the warning off:
21512 @quotation
21514 @example
21515 pragma Warnings (Off);
21516 function to_a2u is
21517   new Unchecked_Conversion (a1, a2);
21518 pragma Warnings (On);
21519 @end example
21520 @end quotation
21522 Of course that approach is not appropriate for this particular
21523 example, since indeed there is a problematic reference. In this
21524 case we can take one of two other approaches.
21526 The first possibility is to move the instantiation of unchecked
21527 conversion to the unit in which the type is declared. In
21528 this example, we would move the instantiation of
21529 @cite{Unchecked_Conversion} from the body of package
21530 @cite{p2} to the spec of package @cite{p1}. Now the
21531 warning disappears. That's because any use of the
21532 access type knows there is a suspicious unchecked
21533 conversion, and the strict aliasing optimization
21534 is automatically suppressed for the type.
21536 If it is not practical to move the unchecked conversion to the same unit
21537 in which the destination access type is declared (perhaps because the
21538 source type is not visible in that unit), you may use pragma
21539 @cite{No_Strict_Aliasing} for the type. This pragma must occur in the
21540 same declarative sequence as the declaration of the access type:
21542 @quotation
21544 @example
21545 type a2 is access int2;
21546 pragma No_Strict_Aliasing (a2);
21547 @end example
21548 @end quotation
21550 Here again, the compiler now knows that the strict aliasing optimization
21551 should be suppressed for any reference to type @cite{a2} and the
21552 expected behavior is obtained.
21554 Finally, note that although the compiler can generate warnings for
21555 simple cases of unchecked conversions, there are tricker and more
21556 indirect ways of creating type incorrect aliases which the compiler
21557 cannot detect. Examples are the use of address overlays and unchecked
21558 conversions involving composite types containing access types as
21559 components. In such cases, no warnings are generated, but there can
21560 still be aliasing problems. One safe coding practice is to forbid the
21561 use of address clauses for type overlaying, and to allow unchecked
21562 conversion only for primitive types. This is not really a significant
21563 restriction since any possible desired effect can be achieved by
21564 unchecked conversion of access values.
21566 The aliasing analysis done in strict aliasing mode can certainly
21567 have significant benefits. We have seen cases of large scale
21568 application code where the time is increased by up to 5% by turning
21569 this optimization off. If you have code that includes significant
21570 usage of unchecked conversion, you might want to just stick with
21571 @emph{-O1} and avoid the entire issue. If you get adequate
21572 performance at this level of optimization level, that's probably
21573 the safest approach. If tests show that you really need higher
21574 levels of optimization, then you can experiment with @emph{-O2}
21575 and @emph{-O2 -fno-strict-aliasing} to see how much effect this
21576 has on size and speed of the code. If you really need to use
21577 @emph{-O2} with strict aliasing in effect, then you should
21578 review any uses of unchecked conversion of access types,
21579 particularly if you are getting the warnings described above.
21581 @node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
21582 @anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{1af}@anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{1b0}
21583 @subsubsection Aliased Variables and Optimization
21586 @geindex Aliasing
21588 There are scenarios in which programs may
21589 use low level techniques to modify variables
21590 that otherwise might be considered to be unassigned. For example,
21591 a variable can be passed to a procedure by reference, which takes
21592 the address of the parameter and uses the address to modify the
21593 variable's value, even though it is passed as an IN parameter.
21594 Consider the following example:
21596 @quotation
21598 @example
21599 procedure P is
21600    Max_Length : constant Natural := 16;
21601    type Char_Ptr is access all Character;
21603    procedure Get_String(Buffer: Char_Ptr; Size : Integer);
21604    pragma Import (C, Get_String, "get_string");
21606    Name : aliased String (1 .. Max_Length) := (others => ' ');
21607    Temp : Char_Ptr;
21609    function Addr (S : String) return Char_Ptr is
21610       function To_Char_Ptr is
21611         new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
21612    begin
21613       return To_Char_Ptr (S (S'First)'Address);
21614    end;
21616 begin
21617    Temp := Addr (Name);
21618    Get_String (Temp, Max_Length);
21619 end;
21620 @end example
21621 @end quotation
21623 where Get_String is a C function that uses the address in Temp to
21624 modify the variable @cite{Name}. This code is dubious, and arguably
21625 erroneous, and the compiler would be entitled to assume that
21626 @cite{Name} is never modified, and generate code accordingly.
21628 However, in practice, this would cause some existing code that
21629 seems to work with no optimization to start failing at high
21630 levels of optimzization.
21632 What the compiler does for such cases is to assume that marking
21633 a variable as aliased indicates that some "funny business" may
21634 be going on. The optimizer recognizes the aliased keyword and
21635 inhibits optimizations that assume the value cannot be assigned.
21636 This means that the above example will in fact "work" reliably,
21637 that is, it will produce the expected results.
21639 @node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
21640 @anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{1b1}@anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{1b2}
21641 @subsubsection Atomic Variables and Optimization
21644 @geindex Atomic
21646 There are two considerations with regard to performance when
21647 atomic variables are used.
21649 First, the RM only guarantees that access to atomic variables
21650 be atomic, it has nothing to say about how this is achieved,
21651 though there is a strong implication that this should not be
21652 achieved by explicit locking code. Indeed GNAT will never
21653 generate any locking code for atomic variable access (it will
21654 simply reject any attempt to make a variable or type atomic
21655 if the atomic access cannot be achieved without such locking code).
21657 That being said, it is important to understand that you cannot
21658 assume that the entire variable will always be accessed. Consider
21659 this example:
21661 @quotation
21663 @example
21664 type R is record
21665    A,B,C,D : Character;
21666 end record;
21667 for R'Size use 32;
21668 for R'Alignment use 4;
21670 RV : R;
21671 pragma Atomic (RV);
21672 X : Character;
21674 X := RV.B;
21675 @end example
21676 @end quotation
21678 You cannot assume that the reference to @cite{RV.B}
21679 will read the entire 32-bit
21680 variable with a single load instruction. It is perfectly legitimate if
21681 the hardware allows it to do a byte read of just the B field. This read
21682 is still atomic, which is all the RM requires. GNAT can and does take
21683 advantage of this, depending on the architecture and optimization level.
21684 Any assumption to the contrary is non-portable and risky. Even if you
21685 examine the assembly language and see a full 32-bit load, this might
21686 change in a future version of the compiler.
21688 If your application requires that all accesses to @cite{RV} in this
21689 example be full 32-bit loads, you need to make a copy for the access
21690 as in:
21692 @quotation
21694 @example
21695 declare
21696    RV_Copy : constant R := RV;
21697 begin
21698    X := RV_Copy.B;
21699 end;
21700 @end example
21701 @end quotation
21703 Now the reference to RV must read the whole variable.
21704 Actually one can imagine some compiler which figures
21705 out that the whole copy is not required (because only
21706 the B field is actually accessed), but GNAT
21707 certainly won't do that, and we don't know of any
21708 compiler that would not handle this right, and the
21709 above code will in practice work portably across
21710 all architectures (that permit the Atomic declaration).
21712 The second issue with atomic variables has to do with
21713 the possible requirement of generating synchronization
21714 code. For more details on this, consult the sections on
21715 the pragmas Enable/Disable_Atomic_Synchronization in the
21716 GNAT Reference Manual. If performance is critical, and
21717 such synchronization code is not required, it may be
21718 useful to disable it.
21720 @node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
21721 @anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{1b3}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{1b4}
21722 @subsubsection Passive Task Optimization
21725 @geindex Passive Task
21727 A passive task is one which is sufficiently simple that
21728 in theory a compiler could recognize it an implement it
21729 efficiently without creating a new thread. The original design
21730 of Ada 83 had in mind this kind of passive task optimization, but
21731 only a few Ada 83 compilers attempted it. The problem was that
21732 it was difficult to determine the exact conditions under which
21733 the optimization was possible. The result is a very fragile
21734 optimization where a very minor change in the program can
21735 suddenly silently make a task non-optimizable.
21737 With the revisiting of this issue in Ada 95, there was general
21738 agreement that this approach was fundamentally flawed, and the
21739 notion of protected types was introduced. When using protected
21740 types, the restrictions are well defined, and you KNOW that the
21741 operations will be optimized, and furthermore this optimized
21742 performance is fully portable.
21744 Although it would theoretically be possible for GNAT to attempt to
21745 do this optimization, but it really doesn't make sense in the
21746 context of Ada 95, and none of the Ada 95 compilers implement
21747 this optimization as far as we know. In particular GNAT never
21748 attempts to perform this optimization.
21750 In any new Ada 95 code that is written, you should always
21751 use protected types in place of tasks that might be able to
21752 be optimized in this manner.
21753 Of course this does not help if you have legacy Ada 83 code
21754 that depends on this optimization, but it is unusual to encounter
21755 a case where the performance gains from this optimization
21756 are significant.
21758 Your program should work correctly without this optimization. If
21759 you have performance problems, then the most practical
21760 approach is to figure out exactly where these performance problems
21761 arise, and update those particular tasks to be protected types. Note
21762 that typically clients of the tasks who call entries, will not have
21763 to be modified, only the task definition itself.
21765 @node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
21766 @anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{1b5}@anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{1b6}
21767 @subsection @cite{Text_IO} Suggestions
21770 @geindex Text_IO and performance
21772 The @cite{Ada.Text_IO} package has fairly high overheads due in part to
21773 the requirement of maintaining page and line counts. If performance
21774 is critical, a recommendation is to use @cite{Stream_IO} instead of
21775 @cite{Text_IO} for volume output, since this package has less overhead.
21777 If @cite{Text_IO} must be used, note that by default output to the standard
21778 output and standard error files is unbuffered (this provides better
21779 behavior when output statements are used for debugging, or if the
21780 progress of a program is observed by tracking the output, e.g. by
21781 using the Unix @emph{tail -f} command to watch redirected output.
21783 If you are generating large volumes of output with @cite{Text_IO} and
21784 performance is an important factor, use a designated file instead
21785 of the standard output file, or change the standard output file to
21786 be buffered using @cite{Interfaces.C_Streams.setvbuf}.
21788 @node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
21789 @anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{1b7}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{1b8}
21790 @subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
21793 @geindex Uunused subprogram/data elimination
21795 This section describes how you can eliminate unused subprograms and data from
21796 your executable just by setting options at compilation time.
21798 @menu
21799 * About unused subprogram/data elimination:: 
21800 * Compilation options:: 
21801 * Example of unused subprogram/data elimination:: 
21803 @end menu
21805 @node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
21806 @anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{1b9}@anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{1ba}
21807 @subsubsection About unused subprogram/data elimination
21810 By default, an executable contains all code and data of its composing objects
21811 (directly linked or coming from statically linked libraries), even data or code
21812 never used by this executable.
21814 This feature will allow you to eliminate such unused code from your
21815 executable, making it smaller (in disk and in memory).
21817 This functionality is available on all Linux platforms except for the IA-64
21818 architecture and on all cross platforms using the ELF binary file format.
21819 In both cases GNU binutils version 2.16 or later are required to enable it.
21821 @node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
21822 @anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{1bb}@anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{1bc}
21823 @subsubsection Compilation options
21826 The operation of eliminating the unused code and data from the final executable
21827 is directly performed by the linker.
21829 @geindex -ffunction-sections (gcc)
21831 @geindex -fdata-sections (gcc)
21833 In order to do this, it has to work with objects compiled with the
21834 following options:
21835 @emph{-ffunction-sections} @emph{-fdata-sections}.
21837 These options are usable with C and Ada files.
21838 They will place respectively each
21839 function or data in a separate section in the resulting object file.
21841 Once the objects and static libraries are created with these options, the
21842 linker can perform the dead code elimination. You can do this by setting
21843 the @emph{-Wl,--gc-sections} option to gcc command or in the
21844 @emph{-largs} section of @emph{gnatmake}. This will perform a
21845 garbage collection of code and data never referenced.
21847 If the linker performs a partial link (@emph{-r} linker option), then you
21848 will need to provide the entry point using the @emph{-e} / @emph{--entry}
21849 linker option.
21851 Note that objects compiled without the @emph{-ffunction-sections} and
21852 @emph{-fdata-sections} options can still be linked with the executable.
21853 However, no dead code elimination will be performed on those objects (they will
21854 be linked as is).
21856 The GNAT static library is now compiled with -ffunction-sections and
21857 -fdata-sections on some platforms. This allows you to eliminate the unused code
21858 and data of the GNAT library from your executable.
21860 @node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
21861 @anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{1bd}@anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{1be}
21862 @subsubsection Example of unused subprogram/data elimination
21865 Here is a simple example:
21867 @quotation
21869 @example
21870 with Aux;
21872 procedure Test is
21873 begin
21874    Aux.Used (10);
21875 end Test;
21877 package Aux is
21878    Used_Data   : Integer;
21879    Unused_Data : Integer;
21881    procedure Used   (Data : Integer);
21882    procedure Unused (Data : Integer);
21883 end Aux;
21885 package body Aux is
21886    procedure Used (Data : Integer) is
21887    begin
21888       Used_Data := Data;
21889    end Used;
21891    procedure Unused (Data : Integer) is
21892    begin
21893       Unused_Data := Data;
21894    end Unused;
21895 end Aux;
21896 @end example
21897 @end quotation
21899 @cite{Unused} and @cite{Unused_Data} are never referenced in this code
21900 excerpt, and hence they may be safely removed from the final executable.
21902 @quotation
21904 @example
21905 $ gnatmake test
21907 $ nm test | grep used
21908 020015f0 T aux__unused
21909 02005d88 B aux__unused_data
21910 020015cc T aux__used
21911 02005d84 B aux__used_data
21913 $ gnatmake test -cargs -fdata-sections -ffunction-sections \\
21914      -largs -Wl,--gc-sections
21916 $ nm test | grep used
21917 02005350 T aux__used
21918 0201ffe0 B aux__used_data
21919 @end example
21920 @end quotation
21922 It can be observed that the procedure @cite{Unused} and the object
21923 @cite{Unused_Data} are removed by the linker when using the
21924 appropriate options.
21926 @geindex Overflow checks
21928 @geindex Checks (overflow)
21931 @node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
21932 @anchor{gnat_ugn/gnat_and_program_execution id54}@anchor{16a}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{27}
21933 @section Overflow Check Handling in GNAT
21936 This section explains how to control the handling of overflow checks.
21938 @menu
21939 * Background:: 
21940 * Management of Overflows in GNAT:: 
21941 * Specifying the Desired Mode:: 
21942 * Default Settings:: 
21943 * Implementation Notes:: 
21945 @end menu
21947 @node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
21948 @anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{1bf}@anchor{gnat_ugn/gnat_and_program_execution background}@anchor{1c0}
21949 @subsection Background
21952 Overflow checks are checks that the compiler may make to ensure
21953 that intermediate results are not out of range. For example:
21955 @quotation
21957 @example
21958 A : Integer;
21960 A := A + 1;
21961 @end example
21962 @end quotation
21964 If @cite{A} has the value @cite{Integer'Last}, then the addition may cause
21965 overflow since the result is out of range of the type @cite{Integer}.
21966 In this case @cite{Constraint_Error} will be raised if checks are
21967 enabled.
21969 A trickier situation arises in examples like the following:
21971 @quotation
21973 @example
21974 A, C : Integer;
21976 A := (A + 1) + C;
21977 @end example
21978 @end quotation
21980 where @cite{A} is @cite{Integer'Last} and @cite{C} is @cite{-1}.
21981 Now the final result of the expression on the right hand side is
21982 @cite{Integer'Last} which is in range, but the question arises whether the
21983 intermediate addition of @cite{(A + 1)} raises an overflow error.
21985 The (perhaps surprising) answer is that the Ada language
21986 definition does not answer this question. Instead it leaves
21987 it up to the implementation to do one of two things if overflow
21988 checks are enabled.
21991 @itemize *
21993 @item 
21994 raise an exception (@cite{Constraint_Error}), or
21996 @item 
21997 yield the correct mathematical result which is then used in
21998 subsequent operations.
21999 @end itemize
22001 If the compiler chooses the first approach, then the assignment of this
22002 example will indeed raise @cite{Constraint_Error} if overflow checking is
22003 enabled, or result in erroneous execution if overflow checks are suppressed.
22005 But if the compiler
22006 chooses the second approach, then it can perform both additions yielding
22007 the correct mathematical result, which is in range, so no exception
22008 will be raised, and the right result is obtained, regardless of whether
22009 overflow checks are suppressed.
22011 Note that in the first example an
22012 exception will be raised in either case, since if the compiler
22013 gives the correct mathematical result for the addition, it will
22014 be out of range of the target type of the assignment, and thus
22015 fails the range check.
22017 This lack of specified behavior in the handling of overflow for
22018 intermediate results is a source of non-portability, and can thus
22019 be problematic when programs are ported. Most typically this arises
22020 in a situation where the original compiler did not raise an exception,
22021 and then the application is moved to a compiler where the check is
22022 performed on the intermediate result and an unexpected exception is
22023 raised.
22025 Furthermore, when using Ada 2012's preconditions and other
22026 assertion forms, another issue arises. Consider:
22028 @quotation
22030 @example
22031 procedure P (A, B : Integer) with
22032   Pre => A + B <= Integer'Last;
22033 @end example
22034 @end quotation
22036 One often wants to regard arithmetic in a context like this from
22037 a mathematical point of view. So for example, if the two actual parameters
22038 for a call to @cite{P} are both @cite{Integer'Last}, then
22039 the precondition should be regarded as False. If we are executing
22040 in a mode with run-time checks enabled for preconditions, then we would
22041 like this precondition to fail, rather than raising an exception
22042 because of the intermediate overflow.
22044 However, the language definition leaves the specification of
22045 whether the above condition fails (raising @cite{Assert_Error}) or
22046 causes an intermediate overflow (raising @cite{Constraint_Error})
22047 up to the implementation.
22049 The situation is worse in a case such as the following:
22051 @quotation
22053 @example
22054 procedure Q (A, B, C : Integer) with
22055   Pre => A + B + C <= Integer'Last;
22056 @end example
22057 @end quotation
22059 Consider the call
22061 @quotation
22063 @example
22064 Q (A => Integer'Last, B => 1, C => -1);
22065 @end example
22066 @end quotation
22068 From a mathematical point of view the precondition
22069 is True, but at run time we may (but are not guaranteed to) get an
22070 exception raised because of the intermediate overflow (and we really
22071 would prefer this precondition to be considered True at run time).
22073 @node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
22074 @anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{1c1}@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{1c2}
22075 @subsection Management of Overflows in GNAT
22078 To deal with the portability issue, and with the problem of
22079 mathematical versus run-time interpretation of the expressions in
22080 assertions, GNAT provides comprehensive control over the handling
22081 of intermediate overflow. GNAT can operate in three modes, and
22082 furthemore, permits separate selection of operating modes for
22083 the expressions within assertions (here the term 'assertions'
22084 is used in the technical sense, which includes preconditions and so forth)
22085 and for expressions appearing outside assertions.
22087 The three modes are:
22090 @itemize *
22092 @item 
22093 @emph{Use base type for intermediate operations} (@cite{STRICT})
22095 In this mode, all intermediate results for predefined arithmetic
22096 operators are computed using the base type, and the result must
22097 be in range of the base type. If this is not the
22098 case then either an exception is raised (if overflow checks are
22099 enabled) or the execution is erroneous (if overflow checks are suppressed).
22100 This is the normal default mode.
22102 @item 
22103 @emph{Most intermediate overflows avoided} (@cite{MINIMIZED})
22105 In this mode, the compiler attempts to avoid intermediate overflows by
22106 using a larger integer type, typically @cite{Long_Long_Integer},
22107 as the type in which arithmetic is
22108 performed for predefined arithmetic operators. This may be slightly more
22109 expensive at
22110 run time (compared to suppressing intermediate overflow checks), though
22111 the cost is negligible on modern 64-bit machines. For the examples given
22112 earlier, no intermediate overflows would have resulted in exceptions,
22113 since the intermediate results are all in the range of
22114 @cite{Long_Long_Integer} (typically 64-bits on nearly all implementations
22115 of GNAT). In addition, if checks are enabled, this reduces the number of
22116 checks that must be made, so this choice may actually result in an
22117 improvement in space and time behavior.
22119 However, there are cases where @cite{Long_Long_Integer} is not large
22120 enough, consider the following example:
22122 @quotation
22124 @example
22125 procedure R (A, B, C, D : Integer) with
22126   Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
22127 @end example
22128 @end quotation
22130 where @cite{A} = @cite{B} = @cite{C} = @cite{D} = @cite{Integer'Last}.
22131 Now the intermediate results are
22132 out of the range of @cite{Long_Long_Integer} even though the final result
22133 is in range and the precondition is True (from a mathematical point
22134 of view). In such a case, operating in this mode, an overflow occurs
22135 for the intermediate computation (which is why this mode
22136 says @emph{most} intermediate overflows are avoided). In this case,
22137 an exception is raised if overflow checks are enabled, and the
22138 execution is erroneous if overflow checks are suppressed.
22140 @item 
22141 @emph{All intermediate overflows avoided} (@cite{ELIMINATED})
22143 In this mode, the compiler  avoids all intermediate overflows
22144 by using arbitrary precision arithmetic as required. In this
22145 mode, the above example with @cite{A**2 * B**2} would
22146 not cause intermediate overflow, because the intermediate result
22147 would be evaluated using sufficient precision, and the result
22148 of evaluating the precondition would be True.
22150 This mode has the advantage of avoiding any intermediate
22151 overflows, but at the expense of significant run-time overhead,
22152 including the use of a library (included automatically in this
22153 mode) for multiple-precision arithmetic.
22155 This mode provides cleaner semantics for assertions, since now
22156 the run-time behavior emulates true arithmetic behavior for the
22157 predefined arithmetic operators, meaning that there is never a
22158 conflict between the mathematical view of the assertion, and its
22159 run-time behavior.
22161 Note that in this mode, the behavior is unaffected by whether or
22162 not overflow checks are suppressed, since overflow does not occur.
22163 It is possible for gigantic intermediate expressions to raise
22164 @cite{Storage_Error} as a result of attempting to compute the
22165 results of such expressions (e.g. @cite{Integer'Last ** Integer'Last})
22166 but overflow is impossible.
22167 @end itemize
22169 Note that these modes apply only to the evaluation of predefined
22170 arithmetic, membership, and comparison operators for signed integer
22171 aritmetic.
22173 For fixed-point arithmetic, checks can be suppressed. But if checks
22174 are enabled
22175 then fixed-point values are always checked for overflow against the
22176 base type for intermediate expressions (that is such checks always
22177 operate in the equivalent of @cite{STRICT} mode).
22179 For floating-point, on nearly all architectures, @cite{Machine_Overflows}
22180 is False, and IEEE infinities are generated, so overflow exceptions
22181 are never raised. If you want to avoid infinities, and check that
22182 final results of expressions are in range, then you can declare a
22183 constrained floating-point type, and range checks will be carried
22184 out in the normal manner (with infinite values always failing all
22185 range checks).
22187 @node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
22188 @anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{f8}@anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{1c3}
22189 @subsection Specifying the Desired Mode
22192 @geindex pragma Overflow_Mode
22194 The desired mode of for handling intermediate overflow can be specified using
22195 either the @cite{Overflow_Mode} pragma or an equivalent compiler switch.
22196 The pragma has the form
22198 @quotation
22200 @example
22201 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
22202 @end example
22203 @end quotation
22205 where @cite{MODE} is one of
22208 @itemize *
22210 @item 
22211 @cite{STRICT}:  intermediate overflows checked (using base type)
22213 @item 
22214 @cite{MINIMIZED}: minimize intermediate overflows
22216 @item 
22217 @cite{ELIMINATED}: eliminate intermediate overflows
22218 @end itemize
22220 The case is ignored, so @cite{MINIMIZED}, @cite{Minimized} and
22221 @cite{minimized} all have the same effect.
22223 If only the @cite{General} parameter is present, then the given @cite{MODE}
22224 applies
22225 to expressions both within and outside assertions. If both arguments
22226 are present, then @cite{General} applies to expressions outside assertions,
22227 and @cite{Assertions} applies to expressions within assertions. For example:
22229 @quotation
22231 @example
22232 pragma Overflow_Mode
22233   (General => Minimized, Assertions => Eliminated);
22234 @end example
22235 @end quotation
22237 specifies that general expressions outside assertions be evaluated
22238 in 'minimize intermediate overflows' mode, and expressions within
22239 assertions be evaluated in 'eliminate intermediate overflows' mode.
22240 This is often a reasonable choice, avoiding excessive overhead
22241 outside assertions, but assuring a high degree of portability
22242 when importing code from another compiler, while incurring
22243 the extra overhead for assertion expressions to ensure that
22244 the behavior at run time matches the expected mathematical
22245 behavior.
22247 The @cite{Overflow_Mode} pragma has the same scoping and placement
22248 rules as pragma @cite{Suppress}, so it can occur either as a
22249 configuration pragma, specifying a default for the whole
22250 program, or in a declarative scope, where it applies to the
22251 remaining declarations and statements in that scope.
22253 Note that pragma @cite{Overflow_Mode} does not affect whether
22254 overflow checks are enabled or suppressed. It only controls the
22255 method used to compute intermediate values. To control whether
22256 overflow checking is enabled or suppressed, use pragma @cite{Suppress}
22257 or @cite{Unsuppress} in the usual manner
22259 @geindex -gnato? (gcc)
22261 @geindex -gnato?? (gcc)
22263 Additionally, a compiler switch @emph{-gnato?} or @emph{-gnato??}
22264 can be used to control the checking mode default (which can be subsequently
22265 overridden using pragmas).
22267 Here @code{?} is one of the digits @code{1} through @code{3}:
22269 @quotation
22272 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
22273 @item
22275 @code{1}
22277 @tab
22279 use base type for intermediate operations (@cite{STRICT})
22281 @item
22283 @code{2}
22285 @tab
22287 minimize intermediate overflows (@cite{MINIMIZED})
22289 @item
22291 @code{3}
22293 @tab
22295 eliminate intermediate overflows (@cite{ELIMINATED})
22297 @end multitable
22299 @end quotation
22301 As with the pragma, if only one digit appears then it applies to all
22302 cases; if two digits are given, then the first applies outside
22303 assertions, and the second within assertions. Thus the equivalent
22304 of the example pragma above would be
22305 @emph{-gnato23}.
22307 If no digits follow the @emph{-gnato}, then it is equivalent to
22308 @emph{-gnato11},
22309 causing all intermediate operations to be computed using the base
22310 type (@cite{STRICT} mode).
22312 @node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
22313 @anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{1c4}@anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{1c5}
22314 @subsection Default Settings
22317 The default mode for overflow checks is
22319 @quotation
22321 @example
22322 General => Strict
22323 @end example
22324 @end quotation
22326 which causes all computations both inside and outside assertions to use
22327 the base type.
22329 This retains compatibility with previous versions of
22330 GNAT which suppressed overflow checks by default and always
22331 used the base type for computation of intermediate results.
22333 @c Sphinx allows no emphasis within :index: role. As a workaround we
22334 @c point the index to "switch" and use emphasis for "-gnato".
22336 The 
22337 @geindex -gnato (gcc)
22338 switch @emph{-gnato} (with no digits following)
22339 is equivalent to
22341 @quotation
22343 @example
22344 General => Strict
22345 @end example
22346 @end quotation
22348 which causes overflow checking of all intermediate overflows
22349 both inside and outside assertions against the base type.
22351 The pragma @cite{Suppress (Overflow_Check)} disables overflow
22352 checking, but it has no effect on the method used for computing
22353 intermediate results.
22355 The pragma @cite{Unsuppress (Overflow_Check)} enables overflow
22356 checking, but it has no effect on the method used for computing
22357 intermediate results.
22359 @node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
22360 @anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{1c6}@anchor{gnat_ugn/gnat_and_program_execution id59}@anchor{1c7}
22361 @subsection Implementation Notes
22364 In practice on typical 64-bit machines, the @cite{MINIMIZED} mode is
22365 reasonably efficient, and can be generally used. It also helps
22366 to ensure compatibility with code imported from some other
22367 compiler to GNAT.
22369 Setting all intermediate overflows checking (@cite{CHECKED} mode)
22370 makes sense if you want to
22371 make sure that your code is compatible with any other possible
22372 Ada implementation. This may be useful in ensuring portability
22373 for code that is to be exported to some other compiler than GNAT.
22375 The Ada standard allows the reassociation of expressions at
22376 the same precedence level if no parentheses are present. For
22377 example, @cite{A+B+C} parses as though it were @cite{(A+B)+C}, but
22378 the compiler can reintepret this as @cite{A+(B+C)}, possibly
22379 introducing or eliminating an overflow exception. The GNAT
22380 compiler never takes advantage of this freedom, and the
22381 expression @cite{A+B+C} will be evaluated as @cite{(A+B)+C}.
22382 If you need the other order, you can write the parentheses
22383 explicitly @cite{A+(B+C)} and GNAT will respect this order.
22385 The use of @cite{ELIMINATED} mode will cause the compiler to
22386 automatically include an appropriate arbitrary precision
22387 integer arithmetic package. The compiler will make calls
22388 to this package, though only in cases where it cannot be
22389 sure that @cite{Long_Long_Integer} is sufficient to guard against
22390 intermediate overflows. This package does not use dynamic
22391 alllocation, but it does use the secondary stack, so an
22392 appropriate secondary stack package must be present (this
22393 is always true for standard full Ada, but may require
22394 specific steps for restricted run times such as ZFP).
22396 Although @cite{ELIMINATED} mode causes expressions to use arbitrary
22397 precision arithmetic, avoiding overflow, the final result
22398 must be in an appropriate range. This is true even if the
22399 final result is of type @cite{[Long_[Long_]]Integer'Base}, which
22400 still has the same bounds as its associated constrained
22401 type at run-time.
22403 Currently, the @cite{ELIMINATED} mode is only available on target
22404 platforms for which @cite{Long_Long_Integer} is 64-bits (nearly all GNAT
22405 platforms).
22407 @node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
22408 @anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{28}@anchor{gnat_ugn/gnat_and_program_execution id60}@anchor{16b}
22409 @section Performing Dimensionality Analysis in GNAT
22412 @geindex Dimensionality analysis
22414 The GNAT compiler supports dimensionality checking. The user can
22415 specify physical units for objects, and the compiler will verify that uses
22416 of these objects are compatible with their dimensions, in a fashion that is
22417 familiar to engineering practice. The dimensions of algebraic expressions
22418 (including powers with static exponents) are computed from their constituents.
22420 @geindex Dimension_System aspect
22422 @geindex Dimension aspect
22424 This feature depends on Ada 2012 aspect specifications, and is available from
22425 version 7.0.1 of GNAT onwards.
22426 The GNAT-specific aspect @cite{Dimension_System}
22427 allows you to define a system of units; the aspect @cite{Dimension}
22428 then allows the user to declare dimensioned quantities within a given system.
22429 (These aspects are described in the @emph{Implementation Defined Aspects}
22430 chapter of the @emph{GNAT Reference Manual}).
22432 The major advantage of this model is that it does not require the declaration of
22433 multiple operators for all possible combinations of types: it is only necessary
22434 to use the proper subtypes in object declarations.
22436 @geindex System.Dim.Mks package (GNAT library)
22438 @geindex MKS_Type type
22440 The simplest way to impose dimensionality checking on a computation is to make
22441 use of the package @cite{System.Dim.Mks},
22442 which is part of the GNAT library. This
22443 package defines a floating-point type @cite{MKS_Type},
22444 for which a sequence of
22445 dimension names are specified, together with their conventional abbreviations.
22446 The following should be read together with the full specification of the
22447 package, in file @code{s-dimmks.ads}.
22449 @quotation
22451 @geindex s-dimmks.ads file
22453 @example
22454 type Mks_Type is new Long_Long_Float
22455   with
22456    Dimension_System => (
22457      (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
22458      (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
22459      (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
22460      (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
22461      (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
22462      (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
22463      (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
22464 @end example
22465 @end quotation
22467 The package then defines a series of subtypes that correspond to these
22468 conventional units. For example:
22470 @quotation
22472 @example
22473 subtype Length is Mks_Type
22474   with
22475    Dimension => (Symbol => 'm', Meter  => 1, others => 0);
22476 @end example
22477 @end quotation
22479 and similarly for @cite{Mass}, @cite{Time}, @cite{Electric_Current},
22480 @cite{Thermodynamic_Temperature}, @cite{Amount_Of_Substance}, and
22481 @cite{Luminous_Intensity} (the standard set of units of the SI system).
22483 The package also defines conventional names for values of each unit, for
22484 example:
22486 @quotation
22488 @c code-block":: ada
22489 @c 
22490 @c m   : constant Length           := 1.0;
22491 @c kg  : constant Mass             := 1.0;
22492 @c s   : constant Time             := 1.0;
22493 @c A   : constant Electric_Current := 1.0;
22494 @end quotation
22496 as well as useful multiples of these units:
22498 @quotation
22500 @example
22501  cm  : constant Length := 1.0E-02;
22502  g   : constant Mass   := 1.0E-03;
22503  min : constant Time   := 60.0;
22504  day : constant Time   := 60.0 * 24.0 * min;
22506 @end example
22507 @end quotation
22509 Using this package, you can then define a derived unit by
22510 providing the aspect that
22511 specifies its dimensions within the MKS system, as well as the string to
22512 be used for output of a value of that unit:
22514 @quotation
22516 @example
22517 subtype Acceleration is Mks_Type
22518   with Dimension => ("m/sec^2",
22519                      Meter => 1,
22520                      Second => -2,
22521                      others => 0);
22522 @end example
22523 @end quotation
22525 Here is a complete example of use:
22527 @quotation
22529 @example
22530 with System.Dim.MKS; use System.Dim.Mks;
22531 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
22532 with Text_IO; use Text_IO;
22533 procedure Free_Fall is
22534   subtype Acceleration is Mks_Type
22535     with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
22536   G : constant acceleration := 9.81 * m / (s ** 2);
22537   T : Time := 10.0*s;
22538   Distance : Length;
22540 begin
22541   Put ("Gravitational constant: ");
22542   Put (G, Aft => 2, Exp => 0); Put_Line ("");
22543   Distance := 0.5 * G * T ** 2;
22544   Put ("distance travelled in 10 seconds of free fall ");
22545   Put (Distance, Aft => 2, Exp => 0);
22546   Put_Line ("");
22547 end Free_Fall;
22548 @end example
22549 @end quotation
22551 Execution of this program yields:
22553 @quotation
22555 @example
22556 Gravitational constant:  9.81 m/sec^2
22557 distance travelled in 10 seconds of free fall 490.50 m
22558 @end example
22559 @end quotation
22561 However, incorrect assignments such as:
22563 @quotation
22565 @example
22566 Distance := 5.0;
22567 Distance := 5.0 * kg:
22568 @end example
22569 @end quotation
22571 are rejected with the following diagnoses:
22573 @quotation
22575 @example
22576 Distance := 5.0;
22577    >>> dimensions mismatch in assignment
22578    >>> left-hand side has dimension [L]
22579    >>> right-hand side is dimensionless
22581 Distance := 5.0 * kg:
22582    >>> dimensions mismatch in assignment
22583    >>> left-hand side has dimension [L]
22584    >>> right-hand side has dimension [M]
22585 @end example
22586 @end quotation
22588 The dimensions of an expression are properly displayed, even if there is
22589 no explicit subtype for it. If we add to the program:
22591 @quotation
22593 @example
22594 Put ("Final velocity: ");
22595 Put (G * T, Aft =>2, Exp =>0);
22596 Put_Line ("");
22597 @end example
22598 @end quotation
22600 then the output includes:
22602 @quotation
22604 @example
22605 Final velocity: 98.10 m.s**(-1)
22606 @end example
22607 @end quotation
22609 @node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
22610 @anchor{gnat_ugn/gnat_and_program_execution id61}@anchor{16c}@anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{29}
22611 @section Stack Related Facilities
22614 This section describes some useful tools associated with stack
22615 checking and analysis. In
22616 particular, it deals with dynamic and static stack usage measurements.
22618 @menu
22619 * Stack Overflow Checking:: 
22620 * Static Stack Usage Analysis:: 
22621 * Dynamic Stack Usage Analysis:: 
22623 @end menu
22625 @node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
22626 @anchor{gnat_ugn/gnat_and_program_execution id62}@anchor{1c8}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{f4}
22627 @subsection Stack Overflow Checking
22630 @geindex Stack Overflow Checking
22632 @geindex -fstack-check (gcc)
22634 For most operating systems, @emph{gcc} does not perform stack overflow
22635 checking by default. This means that if the main environment task or
22636 some other task exceeds the available stack space, then unpredictable
22637 behavior will occur. Most native systems offer some level of protection by
22638 adding a guard page at the end of each task stack. This mechanism is usually
22639 not enough for dealing properly with stack overflow situations because
22640 a large local variable could "jump" above the guard page.
22641 Furthermore, when the
22642 guard page is hit, there may not be any space left on the stack for executing
22643 the exception propagation code. Enabling stack checking avoids
22644 such situations.
22646 To activate stack checking, compile all units with the gcc option
22647 @cite{-fstack-check}. For example:
22649 @quotation
22651 @example
22652 $ gcc -c -fstack-check package1.adb
22653 @end example
22654 @end quotation
22656 Units compiled with this option will generate extra instructions to check
22657 that any use of the stack (for procedure calls or for declaring local
22658 variables in declare blocks) does not exceed the available stack space.
22659 If the space is exceeded, then a @cite{Storage_Error} exception is raised.
22661 For declared tasks, the stack size is controlled by the size
22662 given in an applicable @cite{Storage_Size} pragma or by the value specified
22663 at bind time with @code{-d} (@ref{11f,,Switches for gnatbind}) or is set to
22664 the default size as defined in the GNAT runtime otherwise.
22666 @geindex GNAT_STACK_LIMIT
22668 For the environment task, the stack size depends on
22669 system defaults and is unknown to the compiler. Stack checking
22670 may still work correctly if a fixed
22671 size stack is allocated, but this cannot be guaranteed.
22672 To ensure that a clean exception is signalled for stack
22673 overflow, set the environment variable
22674 @geindex GNAT_STACK_LIMIT
22675 @geindex environment variable; GNAT_STACK_LIMIT
22676 @code{GNAT_STACK_LIMIT} to indicate the maximum
22677 stack area that can be used, as in:
22679 @quotation
22681 @example
22682 $ SET GNAT_STACK_LIMIT 1600
22683 @end example
22684 @end quotation
22686 The limit is given in kilobytes, so the above declaration would
22687 set the stack limit of the environment task to 1.6 megabytes.
22688 Note that the only purpose of this usage is to limit the amount
22689 of stack used by the environment task. If it is necessary to
22690 increase the amount of stack for the environment task, then this
22691 is an operating systems issue, and must be addressed with the
22692 appropriate operating systems commands.
22694 @node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
22695 @anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{f5}@anchor{gnat_ugn/gnat_and_program_execution id63}@anchor{1c9}
22696 @subsection Static Stack Usage Analysis
22699 @geindex Static Stack Usage Analysis
22701 @geindex -fstack-usage
22703 A unit compiled with @code{-fstack-usage} will generate an extra file
22704 that specifies
22705 the maximum amount of stack used, on a per-function basis.
22706 The file has the same
22707 basename as the target object file with a @code{.su} extension.
22708 Each line of this file is made up of three fields:
22711 @itemize *
22713 @item 
22714 The name of the function.
22716 @item 
22717 A number of bytes.
22719 @item 
22720 One or more qualifiers: @cite{static}, @cite{dynamic}, @cite{bounded}.
22721 @end itemize
22723 The second field corresponds to the size of the known part of the function
22724 frame.
22726 The qualifier @cite{static} means that the function frame size
22727 is purely static.
22728 It usually means that all local variables have a static size.
22729 In this case, the second field is a reliable measure of the function stack
22730 utilization.
22732 The qualifier @cite{dynamic} means that the function frame size is not static.
22733 It happens mainly when some local variables have a dynamic size. When this
22734 qualifier appears alone, the second field is not a reliable measure
22735 of the function stack analysis. When it is qualified with  @cite{bounded}, it
22736 means that the second field is a reliable maximum of the function stack
22737 utilization.
22739 A unit compiled with @code{-Wstack-usage} will issue a warning for each
22740 subprogram whose stack usage might be larger than the specified amount of
22741 bytes.  The wording is in keeping with the qualifier documented above.
22743 @node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
22744 @anchor{gnat_ugn/gnat_and_program_execution id64}@anchor{1ca}@anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{121}
22745 @subsection Dynamic Stack Usage Analysis
22748 It is possible to measure the maximum amount of stack used by a task, by
22749 adding a switch to @emph{gnatbind}, as:
22751 @quotation
22753 @example
22754 $ gnatbind -u0 file
22755 @end example
22756 @end quotation
22758 With this option, at each task termination, its stack usage is  output on
22759 @code{stderr}.
22760 It is not always convenient to output the stack usage when the program
22761 is still running. Hence, it is possible to delay this output until program
22762 termination. for a given number of tasks specified as the argument of the
22763 @code{-u} option. For instance:
22765 @quotation
22767 @example
22768 $ gnatbind -u100 file
22769 @end example
22770 @end quotation
22772 will buffer the stack usage information of the first 100 tasks to terminate and
22773 output this info at program termination. Results are displayed in four
22774 columns:
22776 @quotation
22778 @example
22779 Index | Task Name | Stack Size | Stack Usage
22780 @end example
22781 @end quotation
22783 where:
22786 @itemize *
22788 @item 
22789 @emph{Index} is a number associated with each task.
22791 @item 
22792 @emph{Task Name} is the name of the task analyzed.
22794 @item 
22795 @emph{Stack Size} is the maximum size for the stack.
22797 @item 
22798 @emph{Stack Usage} is the measure done by the stack analyzer.
22799 In order to prevent overflow, the stack
22800 is not entirely analyzed, and it's not possible to know exactly how
22801 much has actually been used.
22802 @end itemize
22804 The environment task stack, e.g., the stack that contains the main unit, is
22805 only processed when the environment variable GNAT_STACK_LIMIT is set.
22807 The package @cite{GNAT.Task_Stack_Usage} provides facilities to get
22808 stack usage reports at run-time. See its body for the details.
22810 @node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
22811 @anchor{gnat_ugn/gnat_and_program_execution id65}@anchor{16d}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{2a}
22812 @section Memory Management Issues
22815 This section describes some useful memory pools provided in the GNAT library
22816 and in particular the GNAT Debug Pool facility, which can be used to detect
22817 incorrect uses of access values (including 'dangling references').
22820 @menu
22821 * Some Useful Memory Pools:: 
22822 * The GNAT Debug Pool Facility:: 
22824 @end menu
22826 @node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
22827 @anchor{gnat_ugn/gnat_and_program_execution id66}@anchor{1cb}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{1cc}
22828 @subsection Some Useful Memory Pools
22831 @geindex Memory Pool
22833 @geindex storage
22834 @geindex pool
22836 The @cite{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
22837 storage pool. Allocations use the standard system call @cite{malloc} while
22838 deallocations use the standard system call @cite{free}. No reclamation is
22839 performed when the pool goes out of scope. For performance reasons, the
22840 standard default Ada allocators/deallocators do not use any explicit storage
22841 pools but if they did, they could use this storage pool without any change in
22842 behavior. That is why this storage pool is used  when the user
22843 manages to make the default implicit allocator explicit as in this example:
22845 @quotation
22847 @example
22848 type T1 is access Something;
22849  -- no Storage pool is defined for T2
22851 type T2 is access Something_Else;
22852 for T2'Storage_Pool use T1'Storage_Pool;
22853 -- the above is equivalent to
22854 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
22855 @end example
22856 @end quotation
22858 The @cite{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
22859 pool. The allocation strategy is similar to @cite{Pool_Local}'s
22860 except that the all
22861 storage allocated with this pool is reclaimed when the pool object goes out of
22862 scope. This pool provides a explicit mechanism similar to the implicit one
22863 provided by several Ada 83 compilers for allocations performed through a local
22864 access type and whose purpose was to reclaim memory when exiting the
22865 scope of a given local access. As an example, the following program does not
22866 leak memory even though it does not perform explicit deallocation:
22868 @quotation
22870 @example
22871 with System.Pool_Local;
22872 procedure Pooloc1 is
22873    procedure Internal is
22874       type A is access Integer;
22875       X : System.Pool_Local.Unbounded_Reclaim_Pool;
22876       for A'Storage_Pool use X;
22877       v : A;
22878    begin
22879       for I in  1 .. 50 loop
22880          v := new Integer;
22881       end loop;
22882    end Internal;
22883 begin
22884    for I in  1 .. 100 loop
22885       Internal;
22886    end loop;
22887 end Pooloc1;
22888 @end example
22889 @end quotation
22891 The @cite{System.Pool_Size} package implements the Stack_Bounded_Pool used when
22892 @cite{Storage_Size} is specified for an access type.
22893 The whole storage for the pool is
22894 allocated at once, usually on the stack at the point where the access type is
22895 elaborated. It is automatically reclaimed when exiting the scope where the
22896 access type is defined. This package is not intended to be used directly by the
22897 user and it is implicitly used for each such declaration:
22899 @quotation
22901 @example
22902 type T1 is access Something;
22903 for T1'Storage_Size use 10_000;
22904 @end example
22905 @end quotation
22907 @node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
22908 @anchor{gnat_ugn/gnat_and_program_execution id67}@anchor{1cd}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{1ce}
22909 @subsection The GNAT Debug Pool Facility
22912 @geindex Debug Pool
22914 @geindex storage
22915 @geindex pool
22916 @geindex memory corruption
22918 The use of unchecked deallocation and unchecked conversion can easily
22919 lead to incorrect memory references. The problems generated by such
22920 references are usually difficult to tackle because the symptoms can be
22921 very remote from the origin of the problem. In such cases, it is
22922 very helpful to detect the problem as early as possible. This is the
22923 purpose of the Storage Pool provided by @cite{GNAT.Debug_Pools}.
22925 In order to use the GNAT specific debugging pool, the user must
22926 associate a debug pool object with each of the access types that may be
22927 related to suspected memory problems. See Ada Reference Manual 13.11.
22929 @quotation
22931 @example
22932 type Ptr is access Some_Type;
22933 Pool : GNAT.Debug_Pools.Debug_Pool;
22934 for Ptr'Storage_Pool use Pool;
22935 @end example
22936 @end quotation
22938 @cite{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
22939 pool: the @cite{Checked_Pool}. Such pools, like standard Ada storage pools,
22940 allow the user to redefine allocation and deallocation strategies. They
22941 also provide a checkpoint for each dereference, through the use of
22942 the primitive operation @cite{Dereference} which is implicitly called at
22943 each dereference of an access value.
22945 Once an access type has been associated with a debug pool, operations on
22946 values of the type may raise four distinct exceptions,
22947 which correspond to four potential kinds of memory corruption:
22950 @itemize *
22952 @item 
22953 @cite{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
22955 @item 
22956 @cite{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
22958 @item 
22959 @cite{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
22961 @item 
22962 @cite{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
22963 @end itemize
22965 For types associated with a Debug_Pool, dynamic allocation is performed using
22966 the standard GNAT allocation routine. References to all allocated chunks of
22967 memory are kept in an internal dictionary. Several deallocation strategies are
22968 provided, whereupon the user can choose to release the memory to the system,
22969 keep it allocated for further invalid access checks, or fill it with an easily
22970 recognizable pattern for debug sessions. The memory pattern is the old IBM
22971 hexadecimal convention: @cite{16#DEADBEEF#}.
22973 See the documentation in the file g-debpoo.ads for more information on the
22974 various strategies.
22976 Upon each dereference, a check is made that the access value denotes a
22977 properly allocated memory location. Here is a complete example of use of
22978 @cite{Debug_Pools}, that includes typical instances of  memory corruption:
22980 @quotation
22982 @example
22983 with Gnat.Io; use Gnat.Io;
22984 with Unchecked_Deallocation;
22985 with Unchecked_Conversion;
22986 with GNAT.Debug_Pools;
22987 with System.Storage_Elements;
22988 with Ada.Exceptions; use Ada.Exceptions;
22989 procedure Debug_Pool_Test is
22991    type T is access Integer;
22992    type U is access all T;
22994    P : GNAT.Debug_Pools.Debug_Pool;
22995    for T'Storage_Pool use P;
22997    procedure Free is new Unchecked_Deallocation (Integer, T);
22998    function UC is new Unchecked_Conversion (U, T);
22999    A, B : aliased T;
23001    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
23003 begin
23004    Info (P);
23005    A := new Integer;
23006    B := new Integer;
23007    B := A;
23008    Info (P);
23009    Free (A);
23010    begin
23011       Put_Line (Integer'Image(B.all));
23012    exception
23013       when E : others => Put_Line ("raised: " & Exception_Name (E));
23014    end;
23015    begin
23016       Free (B);
23017    exception
23018       when E : others => Put_Line ("raised: " & Exception_Name (E));
23019    end;
23020    B := UC(A'Access);
23021    begin
23022       Put_Line (Integer'Image(B.all));
23023    exception
23024       when E : others => Put_Line ("raised: " & Exception_Name (E));
23025    end;
23026    begin
23027       Free (B);
23028    exception
23029       when E : others => Put_Line ("raised: " & Exception_Name (E));
23030    end;
23031    Info (P);
23032 end Debug_Pool_Test;
23033 @end example
23034 @end quotation
23036 The debug pool mechanism provides the following precise diagnostics on the
23037 execution of this erroneous program:
23039 @quotation
23041 @example
23042 Debug Pool info:
23043   Total allocated bytes :  0
23044   Total deallocated bytes :  0
23045   Current Water Mark:  0
23046   High Water Mark:  0
23048 Debug Pool info:
23049   Total allocated bytes :  8
23050   Total deallocated bytes :  0
23051   Current Water Mark:  8
23052   High Water Mark:  8
23054 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
23055 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
23056 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
23057 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
23058 Debug Pool info:
23059   Total allocated bytes :  8
23060   Total deallocated bytes :  4
23061   Current Water Mark:  4
23062   High Water Mark:  8
23063 @end example
23064 @end quotation
23067 @c -- Non-breaking space in running text
23068 @c -- E.g. Ada |nbsp| 95
23070 @node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
23071 @anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{d}@anchor{gnat_ugn/platform_specific_information doc}@anchor{1cf}@anchor{gnat_ugn/platform_specific_information id1}@anchor{1d0}
23072 @chapter Platform-Specific Information
23075 This appendix contains information relating to the implementation
23076 of run-time libraries on various platforms and also covers
23077 topics related to the GNAT implementation on Windows and Mac OS.
23079 @menu
23080 * Run-Time Libraries:: 
23081 * Specifying a Run-Time Library:: 
23082 * Microsoft Windows Topics:: 
23083 * Mac OS Topics:: 
23085 @end menu
23087 @node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
23088 @anchor{gnat_ugn/platform_specific_information id2}@anchor{1d1}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{2b}
23089 @section Run-Time Libraries
23092 @geindex Tasking and threads libraries
23094 @geindex Threads libraries and tasking
23096 @geindex Run-time libraries (platform-specific information)
23098 The GNAT run-time implementation may vary with respect to both the
23099 underlying threads library and the exception handling scheme.
23100 For threads support, one or more of the following are supplied:
23103 @itemize *
23105 @item 
23106 @strong{native threads library}, a binding to the thread package from
23107 the underlying operating system
23109 @item 
23110 @strong{pthreads library} (Sparc Solaris only), a binding to the Solaris
23111 POSIX thread package
23112 @end itemize
23114 For exception handling, either or both of two models are supplied:
23116 @quotation
23118 @geindex Zero-Cost Exceptions
23120 @geindex ZCX (Zero-Cost Exceptions)
23121 @end quotation
23124 @itemize *
23126 @item 
23127 @strong{Zero-Cost Exceptions} ("ZCX"),
23128 which uses binder-generated tables that
23129 are interrogated at run time to locate a handler.
23131 @geindex setjmp/longjmp Exception Model
23133 @geindex SJLJ (setjmp/longjmp Exception Model)
23135 @item 
23136 @strong{setjmp / longjmp} ('SJLJ'),
23137 which uses dynamically-set data to establish
23138 the set of handlers
23139 @end itemize
23141 Most programs should experience a substantial speed improvement by
23142 being compiled with a ZCX run-time.
23143 This is especially true for
23144 tasking applications or applications with many exception handlers.@}
23146 This section summarizes which combinations of threads and exception support
23147 are supplied on various GNAT platforms.
23148 It then shows how to select a particular library either
23149 permanently or temporarily,
23150 explains the properties of (and tradeoffs among) the various threads
23151 libraries, and provides some additional
23152 information about several specific platforms.
23154 @menu
23155 * Summary of Run-Time Configurations:: 
23157 @end menu
23159 @node Summary of Run-Time Configurations,,,Run-Time Libraries
23160 @anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{1d2}@anchor{gnat_ugn/platform_specific_information id3}@anchor{1d3}
23161 @subsection Summary of Run-Time Configurations
23165 @multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx} 
23166 @headitem
23168 Platform
23170 @tab
23172 Run-Time
23174 @tab
23176 Tasking
23178 @tab
23180 Exceptions
23182 @item
23184 ppc-aix
23186 @tab
23188 rts-native
23189 (default)
23191 @tab
23193 native AIX threads
23195 @tab
23199 @item
23201 rts-sjlj
23203 @tab
23205 native AIX threads
23207 @tab
23209 SJLJ
23211 @item
23213 sparc-solaris
23215 @tab
23217 rts-native
23218 (default)
23220 @tab
23222 native Solaris
23223 threads library
23225 @tab
23229 @item
23231 rts-pthread
23233 @tab
23235 pthread library
23237 @tab
23241 @item
23243 rts-sjlj
23245 @tab
23247 native Solaris
23248 threads library
23250 @tab
23252 SJLJ
23254 @item
23256 sparc64-solaris
23258 @tab
23260 rts-native
23261 (default)
23263 @tab
23265 native Solaris
23266 threads library
23268 @tab
23272 @item
23274 x86-linux
23276 @tab
23278 rts-native
23279 (default)
23281 @tab
23283 pthread library
23285 @tab
23289 @item
23291 rts-sjlj
23293 @tab
23295 pthread library
23297 @tab
23299 SJLJ
23301 @item
23303 x86-lynx
23305 @tab
23307 rts-native
23308 (default)
23310 @tab
23312 native LynxOS threads
23314 @tab
23316 SJLJ
23318 @item
23320 x86-solaris
23322 @tab
23324 rts-native
23325 (default)
23327 @tab
23329 native Solaris
23330 threads library
23332 @tab
23336 @item
23338 rts-sjlj
23340 @tab
23342 native Solaris
23343 threads library
23345 @tab
23347 SJLJ
23349 @item
23351 x86-windows
23353 @tab
23355 rts-native
23356 (default)
23358 @tab
23360 native Win32 threads
23362 @tab
23366 @item
23368 rts-sjlj
23370 @tab
23372 native Win32 threads
23374 @tab
23376 SJLJ
23378 @item
23380 x86_64-linux
23382 @tab
23384 rts-native
23385 (default)
23387 @tab
23389 pthread library
23391 @tab
23395 @item
23397 rts-sjlj
23399 @tab
23401 pthread library
23403 @tab
23405 SJLJ
23407 @end multitable
23410 @node Specifying a Run-Time Library,Microsoft Windows Topics,Run-Time Libraries,Platform-Specific Information
23411 @anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{1d4}@anchor{gnat_ugn/platform_specific_information id4}@anchor{1d5}
23412 @section Specifying a Run-Time Library
23415 The @code{adainclude} subdirectory containing the sources of the GNAT
23416 run-time library, and the @code{adalib} subdirectory containing the
23417 @code{ALI} files and the static and/or shared GNAT library, are located
23418 in the gcc target-dependent area:
23420 @quotation
23422 @example
23423 target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
23424 @end example
23425 @end quotation
23427 As indicated above, on some platforms several run-time libraries are supplied.
23428 These libraries are installed in the target dependent area and
23429 contain a complete source and binary subdirectory. The detailed description
23430 below explains the differences between the different libraries in terms of
23431 their thread support.
23433 The default run-time library (when GNAT is installed) is @emph{rts-native}.
23434 This default run time is selected by the means of soft links.
23435 For example on x86-linux:
23437 @example
23439 --  $(target-dir)
23440 --      |
23441 --      +--- adainclude----------+
23442 --      |                        |
23443 --      +--- adalib-----------+  |
23444 --      |                     |  |
23445 --      +--- rts-native       |  |
23446 --      |    |                |  |
23447 --      |    +--- adainclude <---+
23448 --      |    |                |
23449 --      |    +--- adalib <----+
23450 --      |
23451 --      +--- rts-sjlj
23452 --           |
23453 --           +--- adainclude
23454 --           |
23455 --           +--- adalib
23456 @end example
23459 @example
23460                $(target-dir)
23461               __/ /      \ \___
23462       _______/   /        \    \_________________
23463      /          /          \                     \
23464     /          /            \                     \
23465 ADAINCLUDE  ADALIB      rts-native             rts-sjlj
23466    :          :            /    \                 /   \
23467    :          :           /      \               /     \
23468    :          :          /        \             /       \
23469    :          :         /          \           /         \
23470    +-------------> adainclude     adalib   adainclude   adalib
23471               :                     ^
23472               :                     :
23473               +---------------------+
23475               Run-Time Library Directory Structure
23476    (Upper-case names and dotted/dashed arrows represent soft links)
23477 @end example
23479 If the @emph{rts-sjlj} library is to be selected on a permanent basis,
23480 these soft links can be modified with the following commands:
23482 @quotation
23484 @example
23485 $ cd $target
23486 $ rm -f adainclude adalib
23487 $ ln -s rts-sjlj/adainclude adainclude
23488 $ ln -s rts-sjlj/adalib adalib
23489 @end example
23490 @end quotation
23492 Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
23493 @code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
23494 @code{$target/ada_object_path}.
23496 @geindex --RTS option
23498 Selecting another run-time library temporarily can be
23499 achieved by using the @emph{--RTS} switch, e.g., @emph{--RTS=sjlj}
23500 @anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{1d6}
23501 @geindex SCHED_FIFO scheduling policy
23503 @geindex SCHED_RR scheduling policy
23505 @geindex SCHED_OTHER scheduling policy
23507 @menu
23508 * Choosing the Scheduling Policy:: 
23509 * Solaris-Specific Considerations:: 
23510 * Solaris Threads Issues:: 
23511 * AIX-Specific Considerations:: 
23513 @end menu
23515 @node Choosing the Scheduling Policy,Solaris-Specific Considerations,,Specifying a Run-Time Library
23516 @anchor{gnat_ugn/platform_specific_information id5}@anchor{1d7}
23517 @subsection Choosing the Scheduling Policy
23520 When using a POSIX threads implementation, you have a choice of several
23521 scheduling policies: @cite{SCHED_FIFO}, @cite{SCHED_RR} and @cite{SCHED_OTHER}.
23523 Typically, the default is @cite{SCHED_OTHER}, while using @cite{SCHED_FIFO}
23524 or @cite{SCHED_RR} requires special (e.g., root) privileges.
23526 @geindex pragma Time_Slice
23528 @geindex -T0 option
23530 @geindex pragma Task_Dispatching_Policy
23532 By default, GNAT uses the @cite{SCHED_OTHER} policy. To specify
23533 @cite{SCHED_FIFO},
23534 you can use one of the following:
23537 @itemize *
23539 @item 
23540 @cite{pragma Time_Slice (0.0)}
23542 @item 
23543 the corresponding binder option @emph{-T0}
23545 @item 
23546 @cite{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23547 @end itemize
23549 To specify @cite{SCHED_RR},
23550 you should use @cite{pragma Time_Slice} with a
23551 value greater than 0.0, or else use the corresponding @emph{-T}
23552 binder option.
23554 @geindex Solaris Sparc threads libraries
23556 @node Solaris-Specific Considerations,Solaris Threads Issues,Choosing the Scheduling Policy,Specifying a Run-Time Library
23557 @anchor{gnat_ugn/platform_specific_information id6}@anchor{1d8}@anchor{gnat_ugn/platform_specific_information solaris-specific-considerations}@anchor{1d9}
23558 @subsection Solaris-Specific Considerations
23561 This section addresses some topics related to the various threads libraries
23562 on Sparc Solaris.
23564 @geindex rts-pthread threads library
23566 @node Solaris Threads Issues,AIX-Specific Considerations,Solaris-Specific Considerations,Specifying a Run-Time Library
23567 @anchor{gnat_ugn/platform_specific_information id7}@anchor{1da}@anchor{gnat_ugn/platform_specific_information solaris-threads-issues}@anchor{1db}
23568 @subsection Solaris Threads Issues
23571 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
23572 library based on POSIX threads --- @emph{rts-pthread}.
23574 @geindex PTHREAD_PRIO_INHERIT policy (under rts-pthread)
23576 @geindex PTHREAD_PRIO_PROTECT policy (under rts-pthread)
23578 @geindex pragma Locking_Policy (under rts-pthread)
23580 @geindex Inheritance_Locking (under rts-pthread)
23582 @geindex Ceiling_Locking (under rts-pthread)
23584 This run-time library has the advantage of being mostly shared across all
23585 POSIX-compliant thread implementations, and it also provides under
23586 Solaris 8 the @cite{PTHREAD_PRIO_INHERIT}
23587 and @cite{PTHREAD_PRIO_PROTECT}
23588 semantics that can be selected using the predefined pragma
23589 @cite{Locking_Policy}
23590 with respectively
23591 @cite{Inheritance_Locking} and @cite{Ceiling_Locking} as the policy.
23593 As explained above, the native run-time library is based on the Solaris thread
23594 library (@cite{libthread}) and is the default library.
23596 @geindex GNAT_PROCESSOR environment variable (on Sparc Solaris)
23598 When the Solaris threads library is used (this is the default), programs
23599 compiled with GNAT can automatically take advantage of
23600 and can thus execute on multiple processors.
23601 The user can alternatively specify a processor on which the program should run
23602 to emulate a single-processor system. The multiprocessor / uniprocessor choice
23603 is made by
23604 setting the environment variable 
23605 @geindex GNAT_PROCESSOR
23606 @geindex environment variable; GNAT_PROCESSOR
23607 @code{GNAT_PROCESSOR}
23608 to one of the following:
23610 @quotation
23613 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
23614 @headitem
23616 @code{GNAT_PROCESSOR} Value
23618 @tab
23620 Effect
23622 @item
23624 @emph{-2}
23626 @tab
23628 Use the default configuration (run the program on all
23629 available processors) - this is the same as having @cite{GNAT_PROCESSOR}
23630 unset
23632 @item
23634 @emph{-1}
23636 @tab
23638 Let the run-time implementation choose one processor and run the
23639 program on that processor
23641 @item
23643 @emph{0 .. Last_Proc}
23645 @tab
23647 Run the program on the specified processor.
23648 @cite{Last_Proc} is equal to @cite{_SC_NPROCESSORS_CONF - 1}
23649 (where @cite{_SC_NPROCESSORS_CONF} is a system variable).
23651 @end multitable
23653 @end quotation
23655 @node AIX-Specific Considerations,,Solaris Threads Issues,Specifying a Run-Time Library
23656 @anchor{gnat_ugn/platform_specific_information aix-specific-considerations}@anchor{1dc}@anchor{gnat_ugn/platform_specific_information id8}@anchor{1dd}
23657 @subsection AIX-Specific Considerations
23660 @geindex AIX resolver library
23662 On AIX, the resolver library initializes some internal structure on
23663 the first call to @cite{get*by*} functions, which are used to implement
23664 @cite{GNAT.Sockets.Get_Host_By_Name} and
23665 @cite{GNAT.Sockets.Get_Host_By_Address}.
23666 If such initialization occurs within an Ada task, and the stack size for
23667 the task is the default size, a stack overflow may occur.
23669 To avoid this overflow, the user should either ensure that the first call
23670 to @cite{GNAT.Sockets.Get_Host_By_Name} or
23671 @cite{GNAT.Sockets.Get_Host_By_Addrss}
23672 occurs in the environment task, or use @cite{pragma Storage_Size} to
23673 specify a sufficiently large size for the stack of the task that contains
23674 this call.
23676 @geindex Windows NT
23678 @geindex Windows 95
23680 @geindex Windows 98
23682 @node Microsoft Windows Topics,Mac OS Topics,Specifying a Run-Time Library,Platform-Specific Information
23683 @anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{2c}@anchor{gnat_ugn/platform_specific_information id9}@anchor{1de}
23684 @section Microsoft Windows Topics
23687 This section describes topics that are specific to the Microsoft Windows
23688 platforms.
23694 @menu
23695 * Using GNAT on Windows:: 
23696 * Using a network installation of GNAT:: 
23697 * CONSOLE and WINDOWS subsystems:: 
23698 * Temporary Files:: 
23699 * Disabling Command Line Argument Expansion:: 
23700 * Mixed-Language Programming on Windows:: 
23701 * Windows Specific Add-Ons:: 
23703 @end menu
23705 @node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
23706 @anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{1df}@anchor{gnat_ugn/platform_specific_information id10}@anchor{1e0}
23707 @subsection Using GNAT on Windows
23710 One of the strengths of the GNAT technology is that its tool set
23711 (@emph{gcc}, @emph{gnatbind}, @emph{gnatlink}, @emph{gnatmake}, the
23712 @cite{gdb} debugger, etc.) is used in the same way regardless of the
23713 platform.
23715 On Windows this tool set is complemented by a number of Microsoft-specific
23716 tools that have been provided to facilitate interoperability with Windows
23717 when this is required. With these tools:
23720 @itemize *
23722 @item 
23723 You can build applications using the @cite{CONSOLE} or @cite{WINDOWS}
23724 subsystems.
23726 @item 
23727 You can use any Dynamically Linked Library (DLL) in your Ada code (both
23728 relocatable and non-relocatable DLLs are supported).
23730 @item 
23731 You can build Ada DLLs for use in other applications. These applications
23732 can be written in a language other than Ada (e.g., C, C++, etc). Again both
23733 relocatable and non-relocatable Ada DLLs are supported.
23735 @item 
23736 You can include Windows resources in your Ada application.
23738 @item 
23739 You can use or create COM/DCOM objects.
23740 @end itemize
23742 Immediately below are listed all known general GNAT-for-Windows restrictions.
23743 Other restrictions about specific features like Windows Resources and DLLs
23744 are listed in separate sections below.
23747 @itemize *
23749 @item 
23750 It is not possible to use @cite{GetLastError} and @cite{SetLastError}
23751 when tasking, protected records, or exceptions are used. In these
23752 cases, in order to implement Ada semantics, the GNAT run-time system
23753 calls certain Win32 routines that set the last error variable to 0 upon
23754 success. It should be possible to use @cite{GetLastError} and
23755 @cite{SetLastError} when tasking, protected record, and exception
23756 features are not used, but it is not guaranteed to work.
23758 @item 
23759 It is not possible to link against Microsoft C++ libraries except for
23760 import libraries. Interfacing must be done by the mean of DLLs.
23762 @item 
23763 It is possible to link against Microsoft C libraries. Yet the preferred
23764 solution is to use C/C++ compiler that comes with GNAT, since it
23765 doesn't require having two different development environments and makes the
23766 inter-language debugging experience smoother.
23768 @item 
23769 When the compilation environment is located on FAT32 drives, users may
23770 experience recompilations of the source files that have not changed if
23771 Daylight Saving Time (DST) state has changed since the last time files
23772 were compiled. NTFS drives do not have this problem.
23774 @item 
23775 No components of the GNAT toolset use any entries in the Windows
23776 registry. The only entries that can be created are file associations and
23777 PATH settings, provided the user has chosen to create them at installation
23778 time, as well as some minimal book-keeping information needed to correctly
23779 uninstall or integrate different GNAT products.
23780 @end itemize
23782 @node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
23783 @anchor{gnat_ugn/platform_specific_information id11}@anchor{1e1}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{1e2}
23784 @subsection Using a network installation of GNAT
23787 Make sure the system on which GNAT is installed is accessible from the
23788 current machine, i.e., the install location is shared over the network.
23789 Shared resources are accessed on Windows by means of UNC paths, which
23790 have the format @cite{\\server\sharename\path}
23792 In order to use such a network installation, simply add the UNC path of the
23793 @code{bin} directory of your GNAT installation in front of your PATH. For
23794 example, if GNAT is installed in @code{\GNAT} directory of a share location
23795 called @code{c-drive} on a machine @code{LOKI}, the following command will
23796 make it available:
23798 @quotation
23800 @example
23801 $ path \\loki\c-drive\gnat\bin;%path%`
23802 @end example
23803 @end quotation
23805 Be aware that every compilation using the network installation results in the
23806 transfer of large amounts of data across the network and will likely cause
23807 serious performance penalty.
23809 @node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
23810 @anchor{gnat_ugn/platform_specific_information id12}@anchor{1e3}@anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{1e4}
23811 @subsection CONSOLE and WINDOWS subsystems
23814 @geindex CONSOLE Subsystem
23816 @geindex WINDOWS Subsystem
23818 @geindex -mwindows
23820 There are two main subsystems under Windows. The @cite{CONSOLE} subsystem
23821 (which is the default subsystem) will always create a console when
23822 launching the application. This is not something desirable when the
23823 application has a Windows GUI. To get rid of this console the
23824 application must be using the @cite{WINDOWS} subsystem. To do so
23825 the @emph{-mwindows} linker option must be specified.
23827 @quotation
23829 @example
23830 $ gnatmake winprog -largs -mwindows
23831 @end example
23832 @end quotation
23834 @node Temporary Files,Disabling Command Line Argument Expansion,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
23835 @anchor{gnat_ugn/platform_specific_information id13}@anchor{1e5}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{1e6}
23836 @subsection Temporary Files
23839 @geindex Temporary files
23841 It is possible to control where temporary files gets created by setting
23842 the 
23843 @geindex TMP
23844 @geindex environment variable; TMP
23845 @code{TMP} environment variable. The file will be created:
23848 @itemize *
23850 @item 
23851 Under the directory pointed to by the 
23852 @geindex TMP
23853 @geindex environment variable; TMP
23854 @code{TMP} environment variable if
23855 this directory exists.
23857 @item 
23858 Under @code{c:\temp}, if the 
23859 @geindex TMP
23860 @geindex environment variable; TMP
23861 @code{TMP} environment variable is not
23862 set (or not pointing to a directory) and if this directory exists.
23864 @item 
23865 Under the current working directory otherwise.
23866 @end itemize
23868 This allows you to determine exactly where the temporary
23869 file will be created. This is particularly useful in networked
23870 environments where you may not have write access to some
23871 directories.
23873 @node Disabling Command Line Argument Expansion,Mixed-Language Programming on Windows,Temporary Files,Microsoft Windows Topics
23874 @anchor{gnat_ugn/platform_specific_information disabling-command-line-argument-expansion}@anchor{1e7}
23875 @subsection Disabling Command Line Argument Expansion
23878 @geindex Command Line Argument Expansion
23880 By default, an executable compiled for the @strong{Windows} platform will do
23881 the following postprocessing on the arguments passed on the command
23882 line:
23885 @itemize *
23887 @item 
23888 If the argument contains the characters @code{*} and/or @code{?}, then
23889 file expansion will be attempted. For example, if the current directory
23890 contains @code{a.txt} and @code{b.txt}, then when calling:
23892 @example
23893 $ my_ada_program *.txt
23894 @end example
23896 The following arguments will effectively be passed to the main program
23897 (for example when using @code{Ada.Command_Line.Argument}):
23899 @example
23900 Ada.Command_Line.Argument (1) -> "a.txt"
23901 Ada.Command_Line.Argument (2) -> "b.txt"
23902 @end example
23904 @item 
23905 Filename expansion can be disabled for a given argument by using single
23906 quotes. Thus, calling:
23908 @example
23909 $ my_ada_program '*.txt'
23910 @end example
23912 will result in:
23914 @example
23915 Ada.Command_Line.Argument (1) -> "*.txt"
23916 @end example
23917 @end itemize
23919 Note that if the program is launched from a shell such as @strong{Cygwin} @strong{Bash}
23920 then quote removal might be performed by the shell.
23922 In some contexts it might be useful to disable this feature (for example if
23923 the program performs its own argument expansion). In order to do this, a C
23924 symbol needs to be defined and set to @code{0}. You can do this by
23925 adding the following code fragment in one of your @strong{Ada} units:
23927 @example
23928 Do_Argv_Expansion : Integer := 0;
23929 pragma Export (C, Do_Argv_Expansion, "__gnat_do_argv_expansion");
23930 @end example
23932 The results of previous examples will be respectively:
23934 @example
23935 Ada.Command_Line.Argument (1) -> "*.txt"
23936 @end example
23938 and:
23940 @example
23941 Ada.Command_Line.Argument (1) -> "'*.txt'"
23942 @end example
23944 @node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Disabling Command Line Argument Expansion,Microsoft Windows Topics
23945 @anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{1e8}@anchor{gnat_ugn/platform_specific_information id14}@anchor{1e9}
23946 @subsection Mixed-Language Programming on Windows
23949 Developing pure Ada applications on Windows is no different than on
23950 other GNAT-supported platforms. However, when developing or porting an
23951 application that contains a mix of Ada and C/C++, the choice of your
23952 Windows C/C++ development environment conditions your overall
23953 interoperability strategy.
23955 If you use @emph{gcc} or Microsoft C to compile the non-Ada part of
23956 your application, there are no Windows-specific restrictions that
23957 affect the overall interoperability with your Ada code. If you do want
23958 to use the Microsoft tools for your C++ code, you have two choices:
23961 @itemize *
23963 @item 
23964 Encapsulate your C++ code in a DLL to be linked with your Ada
23965 application. In this case, use the Microsoft or whatever environment to
23966 build the DLL and use GNAT to build your executable
23967 (@ref{1ea,,Using DLLs with GNAT}).
23969 @item 
23970 Or you can encapsulate your Ada code in a DLL to be linked with the
23971 other part of your application. In this case, use GNAT to build the DLL
23972 (@ref{1eb,,Building DLLs with GNAT Project files}) and use the Microsoft
23973 or whatever environment to build your executable.
23974 @end itemize
23976 In addition to the description about C main in
23977 @ref{44,,Mixed Language Programming} section, if the C main uses a
23978 stand-alone library it is required on x86-windows to
23979 setup the SEH context. For this the C main must looks like this:
23981 @quotation
23983 @example
23984 /* main.c */
23985 extern void adainit (void);
23986 extern void adafinal (void);
23987 extern void __gnat_initialize(void*);
23988 extern void call_to_ada (void);
23990 int main (int argc, char *argv[])
23992   int SEH [2];
23994   /* Initialize the SEH context */
23995   __gnat_initialize (&SEH);
23997   adainit();
23999   /* Then call Ada services in the stand-alone library */
24001   call_to_ada();
24003   adafinal();
24005 @end example
24006 @end quotation
24008 Note that this is not needed on x86_64-windows where the Windows
24009 native SEH support is used.
24011 @menu
24012 * Windows Calling Conventions:: 
24013 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs. 
24014 * Using DLLs with GNAT:: 
24015 * Building DLLs with GNAT Project files:: 
24016 * Building DLLs with GNAT:: 
24017 * Building DLLs with gnatdll:: 
24018 * Ada DLLs and Finalization:: 
24019 * Creating a Spec for Ada DLLs:: 
24020 * GNAT and Windows Resources:: 
24021 * Using GNAT DLLs from Microsoft Visual Studio Applications:: 
24022 * Debugging a DLL:: 
24023 * Setting Stack Size from gnatlink:: 
24024 * Setting Heap Size from gnatlink:: 
24026 @end menu
24028 @node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
24029 @anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{1ec}@anchor{gnat_ugn/platform_specific_information id15}@anchor{1ed}
24030 @subsubsection Windows Calling Conventions
24033 @geindex Stdcall
24035 @geindex APIENTRY
24037 This section pertain only to Win32. On Win64 there is a single native
24038 calling convention. All convention specifiers are ignored on this
24039 platform.
24041 When a subprogram @cite{F} (caller) calls a subprogram @cite{G}
24042 (callee), there are several ways to push @cite{G}'s parameters on the
24043 stack and there are several possible scenarios to clean up the stack
24044 upon @cite{G}'s return. A calling convention is an agreed upon software
24045 protocol whereby the responsibilities between the caller (@cite{F}) and
24046 the callee (@cite{G}) are clearly defined. Several calling conventions
24047 are available for Windows:
24050 @itemize *
24052 @item 
24053 @cite{C} (Microsoft defined)
24055 @item 
24056 @cite{Stdcall} (Microsoft defined)
24058 @item 
24059 @cite{Win32} (GNAT specific)
24061 @item 
24062 @cite{DLL} (GNAT specific)
24063 @end itemize
24065 @menu
24066 * C Calling Convention:: 
24067 * Stdcall Calling Convention:: 
24068 * Win32 Calling Convention:: 
24069 * DLL Calling Convention:: 
24071 @end menu
24073 @node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
24074 @anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{1ee}@anchor{gnat_ugn/platform_specific_information id16}@anchor{1ef}
24075 @subsubsection @cite{C} Calling Convention
24078 This is the default calling convention used when interfacing to C/C++
24079 routines compiled with either @emph{gcc} or Microsoft Visual C++.
24081 In the @cite{C} calling convention subprogram parameters are pushed on the
24082 stack by the caller from right to left. The caller itself is in charge of
24083 cleaning up the stack after the call. In addition, the name of a routine
24084 with @cite{C} calling convention is mangled by adding a leading underscore.
24086 The name to use on the Ada side when importing (or exporting) a routine
24087 with @cite{C} calling convention is the name of the routine. For
24088 instance the C function:
24090 @quotation
24092 @example
24093 int get_val (long);
24094 @end example
24095 @end quotation
24097 should be imported from Ada as follows:
24099 @quotation
24101 @example
24102 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24103 pragma Import (C, Get_Val, External_Name => "get_val");
24104 @end example
24105 @end quotation
24107 Note that in this particular case the @cite{External_Name} parameter could
24108 have been omitted since, when missing, this parameter is taken to be the
24109 name of the Ada entity in lower case. When the @cite{Link_Name} parameter
24110 is missing, as in the above example, this parameter is set to be the
24111 @cite{External_Name} with a leading underscore.
24113 When importing a variable defined in C, you should always use the @cite{C}
24114 calling convention unless the object containing the variable is part of a
24115 DLL (in which case you should use the @cite{Stdcall} calling
24116 convention, @ref{1f0,,Stdcall Calling Convention}).
24118 @node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
24119 @anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{1f0}@anchor{gnat_ugn/platform_specific_information id17}@anchor{1f1}
24120 @subsubsection @cite{Stdcall} Calling Convention
24123 This convention, which was the calling convention used for Pascal
24124 programs, is used by Microsoft for all the routines in the Win32 API for
24125 efficiency reasons. It must be used to import any routine for which this
24126 convention was specified.
24128 In the @cite{Stdcall} calling convention subprogram parameters are pushed
24129 on the stack by the caller from right to left. The callee (and not the
24130 caller) is in charge of cleaning the stack on routine exit. In addition,
24131 the name of a routine with @cite{Stdcall} calling convention is mangled by
24132 adding a leading underscore (as for the @cite{C} calling convention) and a
24133 trailing @code{@@@emph{nn}}, where @cite{nn} is the overall size (in
24134 bytes) of the parameters passed to the routine.
24136 The name to use on the Ada side when importing a C routine with a
24137 @cite{Stdcall} calling convention is the name of the C routine. The leading
24138 underscore and trailing @code{@@@emph{nn}} are added automatically by
24139 the compiler. For instance the Win32 function:
24141 @quotation
24143 @example
24144 APIENTRY int get_val (long);
24145 @end example
24146 @end quotation
24148 should be imported from Ada as follows:
24150 @quotation
24152 @example
24153 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24154 pragma Import (Stdcall, Get_Val);
24155 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
24156 @end example
24157 @end quotation
24159 As for the @cite{C} calling convention, when the @cite{External_Name}
24160 parameter is missing, it is taken to be the name of the Ada entity in lower
24161 case. If instead of writing the above import pragma you write:
24163 @quotation
24165 @example
24166 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24167 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
24168 @end example
24169 @end quotation
24171 then the imported routine is @cite{_retrieve_val@@4}. However, if instead
24172 of specifying the @cite{External_Name} parameter you specify the
24173 @cite{Link_Name} as in the following example:
24175 @quotation
24177 @example
24178 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24179 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
24180 @end example
24181 @end quotation
24183 then the imported routine is @cite{retrieve_val}, that is, there is no
24184 decoration at all. No leading underscore and no Stdcall suffix
24185 @code{@@@emph{nn}}.
24187 This is especially important as in some special cases a DLL's entry
24188 point name lacks a trailing @code{@@@emph{nn}} while the exported
24189 name generated for a call has it.
24191 It is also possible to import variables defined in a DLL by using an
24192 import pragma for a variable. As an example, if a DLL contains a
24193 variable defined as:
24195 @quotation
24197 @example
24198 int my_var;
24199 @end example
24200 @end quotation
24202 then, to access this variable from Ada you should write:
24204 @quotation
24206 @example
24207 My_Var : Interfaces.C.int;
24208 pragma Import (Stdcall, My_Var);
24209 @end example
24210 @end quotation
24212 Note that to ease building cross-platform bindings this convention
24213 will be handled as a @cite{C} calling convention on non-Windows platforms.
24215 @node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
24216 @anchor{gnat_ugn/platform_specific_information id18}@anchor{1f2}@anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{1f3}
24217 @subsubsection @cite{Win32} Calling Convention
24220 This convention, which is GNAT-specific is fully equivalent to the
24221 @cite{Stdcall} calling convention described above.
24223 @node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
24224 @anchor{gnat_ugn/platform_specific_information id19}@anchor{1f4}@anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{1f5}
24225 @subsubsection @cite{DLL} Calling Convention
24228 This convention, which is GNAT-specific is fully equivalent to the
24229 @cite{Stdcall} calling convention described above.
24231 @node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
24232 @anchor{gnat_ugn/platform_specific_information id20}@anchor{1f6}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{1f7}
24233 @subsubsection Introduction to Dynamic Link Libraries (DLLs)
24236 @geindex DLL
24238 A Dynamically Linked Library (DLL) is a library that can be shared by
24239 several applications running under Windows. A DLL can contain any number of
24240 routines and variables.
24242 One advantage of DLLs is that you can change and enhance them without
24243 forcing all the applications that depend on them to be relinked or
24244 recompiled. However, you should be aware than all calls to DLL routines are
24245 slower since, as you will understand below, such calls are indirect.
24247 To illustrate the remainder of this section, suppose that an application
24248 wants to use the services of a DLL @code{API.dll}. To use the services
24249 provided by @code{API.dll} you must statically link against the DLL or
24250 an import library which contains a jump table with an entry for each
24251 routine and variable exported by the DLL. In the Microsoft world this
24252 import library is called @code{API.lib}. When using GNAT this import
24253 library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
24254 @code{libAPI.a} or @code{libapi.a} (names are case insensitive).
24256 After you have linked your application with the DLL or the import library
24257 and you run your application, here is what happens:
24260 @itemize *
24262 @item 
24263 Your application is loaded into memory.
24265 @item 
24266 The DLL @code{API.dll} is mapped into the address space of your
24267 application. This means that:
24270 @itemize -
24272 @item 
24273 The DLL will use the stack of the calling thread.
24275 @item 
24276 The DLL will use the virtual address space of the calling process.
24278 @item 
24279 The DLL will allocate memory from the virtual address space of the calling
24280 process.
24282 @item 
24283 Handles (pointers) can be safely exchanged between routines in the DLL
24284 routines and routines in the application using the DLL.
24285 @end itemize
24287 @item 
24288 The entries in the jump table (from the import library @code{libAPI.dll.a}
24289 or @code{API.lib} or automatically created when linking against a DLL)
24290 which is part of your application are initialized with the addresses
24291 of the routines and variables in @code{API.dll}.
24293 @item 
24294 If present in @code{API.dll}, routines @cite{DllMain} or
24295 @cite{DllMainCRTStartup} are invoked. These routines typically contain
24296 the initialization code needed for the well-being of the routines and
24297 variables exported by the DLL.
24298 @end itemize
24300 There is an additional point which is worth mentioning. In the Windows
24301 world there are two kind of DLLs: relocatable and non-relocatable
24302 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
24303 in the target application address space. If the addresses of two
24304 non-relocatable DLLs overlap and these happen to be used by the same
24305 application, a conflict will occur and the application will run
24306 incorrectly. Hence, when possible, it is always preferable to use and
24307 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
24308 supported by GNAT. Note that the @emph{-s} linker option (see GNU Linker
24309 User's Guide) removes the debugging symbols from the DLL but the DLL can
24310 still be relocated.
24312 As a side note, an interesting difference between Microsoft DLLs and
24313 Unix shared libraries, is the fact that on most Unix systems all public
24314 routines are exported by default in a Unix shared library, while under
24315 Windows it is possible (but not required) to list exported routines in
24316 a definition file (see @ref{1f8,,The Definition File}).
24318 @node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
24319 @anchor{gnat_ugn/platform_specific_information id21}@anchor{1f9}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{1ea}
24320 @subsubsection Using DLLs with GNAT
24323 To use the services of a DLL, say @code{API.dll}, in your Ada application
24324 you must have:
24327 @itemize *
24329 @item 
24330 The Ada spec for the routines and/or variables you want to access in
24331 @code{API.dll}. If not available this Ada spec must be built from the C/C++
24332 header files provided with the DLL.
24334 @item 
24335 The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
24336 mentioned an import library is a statically linked library containing the
24337 import table which will be filled at load time to point to the actual
24338 @code{API.dll} routines. Sometimes you don't have an import library for the
24339 DLL you want to use. The following sections will explain how to build
24340 one. Note that this is optional.
24342 @item 
24343 The actual DLL, @code{API.dll}.
24344 @end itemize
24346 Once you have all the above, to compile an Ada application that uses the
24347 services of @code{API.dll} and whose main subprogram is @cite{My_Ada_App},
24348 you simply issue the command
24350 @quotation
24352 @example
24353 $ gnatmake my_ada_app -largs -lAPI
24354 @end example
24355 @end quotation
24357 The argument @emph{-largs -lAPI} at the end of the @emph{gnatmake} command
24358 tells the GNAT linker to look for an import library. The linker will
24359 look for a library name in this specific order:
24362 @itemize *
24364 @item 
24365 @code{libAPI.dll.a}
24367 @item 
24368 @code{API.dll.a}
24370 @item 
24371 @code{libAPI.a}
24373 @item 
24374 @code{API.lib}
24376 @item 
24377 @code{libAPI.dll}
24379 @item 
24380 @code{API.dll}
24381 @end itemize
24383 The first three are the GNU style import libraries. The third is the
24384 Microsoft style import libraries. The last two are the actual DLL names.
24386 Note that if the Ada package spec for @code{API.dll} contains the
24387 following pragma
24389 @quotation
24391 @example
24392 pragma Linker_Options ("-lAPI");
24393 @end example
24394 @end quotation
24396 you do not have to add @emph{-largs -lAPI} at the end of the
24397 @emph{gnatmake} command.
24399 If any one of the items above is missing you will have to create it
24400 yourself. The following sections explain how to do so using as an
24401 example a fictitious DLL called @code{API.dll}.
24403 @menu
24404 * Creating an Ada Spec for the DLL Services:: 
24405 * Creating an Import Library:: 
24407 @end menu
24409 @node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
24410 @anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{1fa}@anchor{gnat_ugn/platform_specific_information id22}@anchor{1fb}
24411 @subsubsection Creating an Ada Spec for the DLL Services
24414 A DLL typically comes with a C/C++ header file which provides the
24415 definitions of the routines and variables exported by the DLL. The Ada
24416 equivalent of this header file is a package spec that contains definitions
24417 for the imported entities. If the DLL you intend to use does not come with
24418 an Ada spec you have to generate one such spec yourself. For example if
24419 the header file of @code{API.dll} is a file @code{api.h} containing the
24420 following two definitions:
24422 @quotation
24424 @example
24425 int some_var;
24426 int get (char *);
24427 @end example
24428 @end quotation
24430 then the equivalent Ada spec could be:
24432 @quotation
24434 @example
24435 with Interfaces.C.Strings;
24436 package API is
24437    use Interfaces;
24439    Some_Var : C.int;
24440    function Get (Str : C.Strings.Chars_Ptr) return C.int;
24442 private
24443    pragma Import (C, Get);
24444    pragma Import (DLL, Some_Var);
24445 end API;
24446 @end example
24447 @end quotation
24449 @node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
24450 @anchor{gnat_ugn/platform_specific_information id23}@anchor{1fc}@anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{1fd}
24451 @subsubsection Creating an Import Library
24454 @geindex Import library
24456 If a Microsoft-style import library @code{API.lib} or a GNAT-style
24457 import library @code{libAPI.dll.a} or @code{libAPI.a} is available
24458 with @code{API.dll} you can skip this section. You can also skip this
24459 section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
24460 as in this case it is possible to link directly against the
24461 DLL. Otherwise read on.
24463 @geindex Definition file
24464 @anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{1f8}
24465 @subsubheading The Definition File
24468 As previously mentioned, and unlike Unix systems, the list of symbols
24469 that are exported from a DLL must be provided explicitly in Windows.
24470 The main goal of a definition file is precisely that: list the symbols
24471 exported by a DLL. A definition file (usually a file with a @cite{.def}
24472 suffix) has the following structure:
24474 @quotation
24476 @example
24477 [LIBRARY `name`]
24478 [DESCRIPTION `string`]
24479 EXPORTS
24480    `symbol1`
24481    `symbol2`
24482    ...
24483 @end example
24484 @end quotation
24487 @table @asis
24489 @item @emph{LIBRARY `name`}
24491 This section, which is optional, gives the name of the DLL.
24493 @item @emph{DESCRIPTION `string`}
24495 This section, which is optional, gives a description string that will be
24496 embedded in the import library.
24498 @item @emph{EXPORTS}
24500 This section gives the list of exported symbols (procedures, functions or
24501 variables). For instance in the case of @code{API.dll} the @cite{EXPORTS}
24502 section of @code{API.def} looks like:
24504 @example
24505 EXPORTS
24506    some_var
24507    get
24508 @end example
24509 @end table
24511 Note that you must specify the correct suffix (@code{@@@emph{nn}})
24512 (see @ref{1ec,,Windows Calling Conventions}) for a Stdcall
24513 calling convention function in the exported symbols list.
24515 There can actually be other sections in a definition file, but these
24516 sections are not relevant to the discussion at hand.
24517 @anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{1fe}
24518 @subsubheading Creating a Definition File Automatically
24521 You can automatically create the definition file @code{API.def}
24522 (see @ref{1f8,,The Definition File}) from a DLL.
24523 For that use the @cite{dlltool} program as follows:
24525 @quotation
24527 @example
24528 $ dlltool API.dll -z API.def --export-all-symbols
24529 @end example
24531 Note that if some routines in the DLL have the @cite{Stdcall} convention
24532 (@ref{1ec,,Windows Calling Conventions}) with stripped @code{@@@emph{nn}}
24533 suffix then you'll have to edit @code{api.def} to add it, and specify
24534 @emph{-k} to @emph{gnatdll} when creating the import library.
24536 Here are some hints to find the right @code{@@@emph{nn}} suffix.
24539 @itemize -
24541 @item 
24542 If you have the Microsoft import library (.lib), it is possible to get
24543 the right symbols by using Microsoft @cite{dumpbin} tool (see the
24544 corresponding Microsoft documentation for further details).
24546 @example
24547 $ dumpbin /exports api.lib
24548 @end example
24550 @item 
24551 If you have a message about a missing symbol at link time the compiler
24552 tells you what symbol is expected. You just have to go back to the
24553 definition file and add the right suffix.
24554 @end itemize
24555 @end quotation
24556 @anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{1ff}
24557 @subsubheading GNAT-Style Import Library
24560 To create a static import library from @code{API.dll} with the GNAT tools
24561 you should create the .def file, then use @cite{gnatdll} tool
24562 (see @ref{200,,Using gnatdll}) as follows:
24564 @quotation
24566 @example
24567 $ gnatdll -e API.def -d API.dll
24568 @end example
24570 @cite{gnatdll} takes as input a definition file @code{API.def} and the
24571 name of the DLL containing the services listed in the definition file
24572 @code{API.dll}. The name of the static import library generated is
24573 computed from the name of the definition file as follows: if the
24574 definition file name is @cite{xyz`}.def`, the import library name will
24575 be @cite{lib`@w{`}xyz`}.a`. Note that in the previous example option
24576 @emph{-e} could have been removed because the name of the definition
24577 file (before the '@cite{.def}' suffix) is the same as the name of the
24578 DLL (@ref{200,,Using gnatdll} for more information about @cite{gnatdll}).
24579 @end quotation
24580 @anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{201}
24581 @subsubheading Microsoft-Style Import Library
24584 A Microsoft import library is needed only if you plan to make an
24585 Ada DLL available to applications developed with Microsoft
24586 tools (@ref{1e8,,Mixed-Language Programming on Windows}).
24588 To create a Microsoft-style import library for @code{API.dll} you
24589 should create the .def file, then build the actual import library using
24590 Microsoft's @cite{lib} utility:
24592 @quotation
24594 @example
24595 $ lib -machine:IX86 -def:API.def -out:API.lib
24596 @end example
24598 If you use the above command the definition file @code{API.def} must
24599 contain a line giving the name of the DLL:
24601 @example
24602 LIBRARY      "API"
24603 @end example
24605 See the Microsoft documentation for further details about the usage of
24606 @cite{lib}.
24607 @end quotation
24609 @node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
24610 @anchor{gnat_ugn/platform_specific_information id24}@anchor{202}@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{1eb}
24611 @subsubsection Building DLLs with GNAT Project files
24614 @geindex DLLs
24615 @geindex building
24617 There is nothing specific to Windows in the build process.
24618 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24619 chapter of the @emph{GPRbuild User's Guide}.
24621 Due to a system limitation, it is not possible under Windows to create threads
24622 when inside the @cite{DllMain} routine which is used for auto-initialization
24623 of shared libraries, so it is not possible to have library level tasks in SALs.
24625 @node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
24626 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{203}@anchor{gnat_ugn/platform_specific_information id25}@anchor{204}
24627 @subsubsection Building DLLs with GNAT
24630 @geindex DLLs
24631 @geindex building
24633 This section explain how to build DLLs using the GNAT built-in DLL
24634 support. With the following procedure it is straight forward to build
24635 and use DLLs with GNAT.
24638 @itemize *
24640 @item 
24641 Building object files.
24642 The first step is to build all objects files that are to be included
24643 into the DLL. This is done by using the standard @emph{gnatmake} tool.
24645 @item 
24646 Building the DLL.
24647 To build the DLL you must use @emph{gcc}'s @emph{-shared} and
24648 @emph{-shared-libgcc} options. It is quite simple to use this method:
24650 @example
24651 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
24652 @end example
24654 It is important to note that in this case all symbols found in the
24655 object files are automatically exported. It is possible to restrict
24656 the set of symbols to export by passing to @emph{gcc} a definition
24657 file (see @ref{1f8,,The Definition File}).
24658 For example:
24660 @example
24661 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
24662 @end example
24664 If you use a definition file you must export the elaboration procedures
24665 for every package that required one. Elaboration procedures are named
24666 using the package name followed by "_E".
24668 @item 
24669 Preparing DLL to be used.
24670 For the DLL to be used by client programs the bodies must be hidden
24671 from it and the .ali set with read-only attribute. This is very important
24672 otherwise GNAT will recompile all packages and will not actually use
24673 the code in the DLL. For example:
24675 @example
24676 $ mkdir apilib
24677 $ copy *.ads *.ali api.dll apilib
24678 $ attrib +R apilib\\*.ali
24679 @end example
24680 @end itemize
24682 At this point it is possible to use the DLL by directly linking
24683 against it. Note that you must use the GNAT shared runtime when using
24684 GNAT shared libraries. This is achieved by using @emph{-shared} binder's
24685 option.
24687 @quotation
24689 @example
24690 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
24691 @end example
24692 @end quotation
24694 @node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
24695 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{205}@anchor{gnat_ugn/platform_specific_information id26}@anchor{206}
24696 @subsubsection Building DLLs with gnatdll
24699 @geindex DLLs
24700 @geindex building
24702 Note that it is preferred to use GNAT Project files
24703 (@ref{1eb,,Building DLLs with GNAT Project files}) or the built-in GNAT
24704 DLL support (@ref{203,,Building DLLs with GNAT}) or to build DLLs.
24706 This section explains how to build DLLs containing Ada code using
24707 @cite{gnatdll}. These DLLs will be referred to as Ada DLLs in the
24708 remainder of this section.
24710 The steps required to build an Ada DLL that is to be used by Ada as well as
24711 non-Ada applications are as follows:
24714 @itemize *
24716 @item 
24717 You need to mark each Ada @emph{entity} exported by the DLL with a @cite{C} or
24718 @cite{Stdcall} calling convention to avoid any Ada name mangling for the
24719 entities exported by the DLL
24720 (see @ref{207,,Exporting Ada Entities}). You can
24721 skip this step if you plan to use the Ada DLL only from Ada applications.
24723 @item 
24724 Your Ada code must export an initialization routine which calls the routine
24725 @cite{adainit} generated by @emph{gnatbind} to perform the elaboration of
24726 the Ada code in the DLL (@ref{208,,Ada DLLs and Elaboration}). The initialization
24727 routine exported by the Ada DLL must be invoked by the clients of the DLL
24728 to initialize the DLL.
24730 @item 
24731 When useful, the DLL should also export a finalization routine which calls
24732 routine @cite{adafinal} generated by @emph{gnatbind} to perform the
24733 finalization of the Ada code in the DLL (@ref{209,,Ada DLLs and Finalization}).
24734 The finalization routine exported by the Ada DLL must be invoked by the
24735 clients of the DLL when the DLL services are no further needed.
24737 @item 
24738 You must provide a spec for the services exported by the Ada DLL in each
24739 of the programming languages to which you plan to make the DLL available.
24741 @item 
24742 You must provide a definition file listing the exported entities
24743 (@ref{1f8,,The Definition File}).
24745 @item 
24746 Finally you must use @cite{gnatdll} to produce the DLL and the import
24747 library (@ref{200,,Using gnatdll}).
24748 @end itemize
24750 Note that a relocatable DLL stripped using the @cite{strip}
24751 binutils tool will not be relocatable anymore. To build a DLL without
24752 debug information pass @cite{-largs -s} to @cite{gnatdll}. This
24753 restriction does not apply to a DLL built using a Library Project.
24754 See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24755 chapter of the @emph{GPRbuild User's Guide}.
24757 @c Limitations_When_Using_Ada_DLLs_from Ada:
24759 @menu
24760 * Limitations When Using Ada DLLs from Ada:: 
24761 * Exporting Ada Entities:: 
24762 * Ada DLLs and Elaboration:: 
24764 @end menu
24766 @node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
24767 @anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{20a}
24768 @subsubsection Limitations When Using Ada DLLs from Ada
24771 When using Ada DLLs from Ada applications there is a limitation users
24772 should be aware of. Because on Windows the GNAT run time is not in a DLL of
24773 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
24774 each Ada DLL includes the services of the GNAT run time that are necessary
24775 to the Ada code inside the DLL. As a result, when an Ada program uses an
24776 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
24777 one in the main program.
24779 It is therefore not possible to exchange GNAT run-time objects between the
24780 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
24781 handles (e.g., @cite{Text_IO.File_Type}), tasks types, protected objects
24782 types, etc.
24784 It is completely safe to exchange plain elementary, array or record types,
24785 Windows object handles, etc.
24787 @node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
24788 @anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{207}@anchor{gnat_ugn/platform_specific_information id27}@anchor{20b}
24789 @subsubsection Exporting Ada Entities
24792 @geindex Export table
24794 Building a DLL is a way to encapsulate a set of services usable from any
24795 application. As a result, the Ada entities exported by a DLL should be
24796 exported with the @cite{C} or @cite{Stdcall} calling conventions to avoid
24797 any Ada name mangling. As an example here is an Ada package
24798 @cite{API}, spec and body, exporting two procedures, a function, and a
24799 variable:
24801 @quotation
24803 @example
24804 with Interfaces.C; use Interfaces;
24805 package API is
24806    Count : C.int := 0;
24807    function Factorial (Val : C.int) return C.int;
24809    procedure Initialize_API;
24810    procedure Finalize_API;
24811    --  Initialization & Finalization routines. More in the next section.
24812 private
24813    pragma Export (C, Initialize_API);
24814    pragma Export (C, Finalize_API);
24815    pragma Export (C, Count);
24816    pragma Export (C, Factorial);
24817 end API;
24818 @end example
24820 @example
24821 package body API is
24822    function Factorial (Val : C.int) return C.int is
24823       Fact : C.int := 1;
24824    begin
24825       Count := Count + 1;
24826       for K in 1 .. Val loop
24827          Fact := Fact * K;
24828       end loop;
24829       return Fact;
24830    end Factorial;
24832    procedure Initialize_API is
24833       procedure Adainit;
24834       pragma Import (C, Adainit);
24835    begin
24836       Adainit;
24837    end Initialize_API;
24839    procedure Finalize_API is
24840       procedure Adafinal;
24841       pragma Import (C, Adafinal);
24842    begin
24843       Adafinal;
24844    end Finalize_API;
24845 end API;
24846 @end example
24847 @end quotation
24849 If the Ada DLL you are building will only be used by Ada applications
24850 you do not have to export Ada entities with a @cite{C} or @cite{Stdcall}
24851 convention. As an example, the previous package could be written as
24852 follows:
24854 @quotation
24856 @example
24857 package API is
24858    Count : Integer := 0;
24859    function Factorial (Val : Integer) return Integer;
24861    procedure Initialize_API;
24862    procedure Finalize_API;
24863    --  Initialization and Finalization routines.
24864 end API;
24865 @end example
24867 @example
24868 package body API is
24869    function Factorial (Val : Integer) return Integer is
24870       Fact : Integer := 1;
24871    begin
24872       Count := Count + 1;
24873       for K in 1 .. Val loop
24874          Fact := Fact * K;
24875       end loop;
24876       return Fact;
24877    end Factorial;
24879    ...
24880    --  The remainder of this package body is unchanged.
24881 end API;
24882 @end example
24883 @end quotation
24885 Note that if you do not export the Ada entities with a @cite{C} or
24886 @cite{Stdcall} convention you will have to provide the mangled Ada names
24887 in the definition file of the Ada DLL
24888 (@ref{20c,,Creating the Definition File}).
24890 @node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
24891 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{208}@anchor{gnat_ugn/platform_specific_information id28}@anchor{20d}
24892 @subsubsection Ada DLLs and Elaboration
24895 @geindex DLLs and elaboration
24897 The DLL that you are building contains your Ada code as well as all the
24898 routines in the Ada library that are needed by it. The first thing a
24899 user of your DLL must do is elaborate the Ada code
24900 (@ref{f,,Elaboration Order Handling in GNAT}).
24902 To achieve this you must export an initialization routine
24903 (@cite{Initialize_API} in the previous example), which must be invoked
24904 before using any of the DLL services. This elaboration routine must call
24905 the Ada elaboration routine @cite{adainit} generated by the GNAT binder
24906 (@ref{b4,,Binding with Non-Ada Main Programs}). See the body of
24907 @cite{Initialize_Api} for an example. Note that the GNAT binder is
24908 automatically invoked during the DLL build process by the @cite{gnatdll}
24909 tool (@ref{200,,Using gnatdll}).
24911 When a DLL is loaded, Windows systematically invokes a routine called
24912 @cite{DllMain}. It would therefore be possible to call @cite{adainit}
24913 directly from @cite{DllMain} without having to provide an explicit
24914 initialization routine. Unfortunately, it is not possible to call
24915 @cite{adainit} from the @cite{DllMain} if your program has library level
24916 tasks because access to the @cite{DllMain} entry point is serialized by
24917 the system (that is, only a single thread can execute 'through' it at a
24918 time), which means that the GNAT run time will deadlock waiting for the
24919 newly created task to complete its initialization.
24921 @node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
24922 @anchor{gnat_ugn/platform_specific_information id29}@anchor{20e}@anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{209}
24923 @subsubsection Ada DLLs and Finalization
24926 @geindex DLLs and finalization
24928 When the services of an Ada DLL are no longer needed, the client code should
24929 invoke the DLL finalization routine, if available. The DLL finalization
24930 routine is in charge of releasing all resources acquired by the DLL. In the
24931 case of the Ada code contained in the DLL, this is achieved by calling
24932 routine @cite{adafinal} generated by the GNAT binder
24933 (@ref{b4,,Binding with Non-Ada Main Programs}).
24934 See the body of @cite{Finalize_Api} for an
24935 example. As already pointed out the GNAT binder is automatically invoked
24936 during the DLL build process by the @cite{gnatdll} tool
24937 (@ref{200,,Using gnatdll}).
24939 @node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
24940 @anchor{gnat_ugn/platform_specific_information id30}@anchor{20f}@anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{210}
24941 @subsubsection Creating a Spec for Ada DLLs
24944 To use the services exported by the Ada DLL from another programming
24945 language (e.g., C), you have to translate the specs of the exported Ada
24946 entities in that language. For instance in the case of @cite{API.dll},
24947 the corresponding C header file could look like:
24949 @quotation
24951 @example
24952 extern int *_imp__count;
24953 #define count (*_imp__count)
24954 int factorial (int);
24955 @end example
24956 @end quotation
24958 It is important to understand that when building an Ada DLL to be used by
24959 other Ada applications, you need two different specs for the packages
24960 contained in the DLL: one for building the DLL and the other for using
24961 the DLL. This is because the @cite{DLL} calling convention is needed to
24962 use a variable defined in a DLL, but when building the DLL, the variable
24963 must have either the @cite{Ada} or @cite{C} calling convention. As an
24964 example consider a DLL comprising the following package @cite{API}:
24966 @quotation
24968 @example
24969 package API is
24970    Count : Integer := 0;
24971    ...
24972    --  Remainder of the package omitted.
24973 end API;
24974 @end example
24975 @end quotation
24977 After producing a DLL containing package @cite{API}, the spec that
24978 must be used to import @cite{API.Count} from Ada code outside of the
24979 DLL is:
24981 @quotation
24983 @example
24984 package API is
24985    Count : Integer;
24986    pragma Import (DLL, Count);
24987 end API;
24988 @end example
24989 @end quotation
24991 @menu
24992 * Creating the Definition File:: 
24993 * Using gnatdll:: 
24995 @end menu
24997 @node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
24998 @anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{20c}@anchor{gnat_ugn/platform_specific_information id31}@anchor{211}
24999 @subsubsection Creating the Definition File
25002 The definition file is the last file needed to build the DLL. It lists
25003 the exported symbols. As an example, the definition file for a DLL
25004 containing only package @cite{API} (where all the entities are exported
25005 with a @cite{C} calling convention) is:
25007 @quotation
25009 @example
25010 EXPORTS
25011     count
25012     factorial
25013     finalize_api
25014     initialize_api
25015 @end example
25016 @end quotation
25018 If the @cite{C} calling convention is missing from package @cite{API},
25019 then the definition file contains the mangled Ada names of the above
25020 entities, which in this case are:
25022 @quotation
25024 @example
25025 EXPORTS
25026     api__count
25027     api__factorial
25028     api__finalize_api
25029     api__initialize_api
25030 @end example
25031 @end quotation
25033 @node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
25034 @anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{200}@anchor{gnat_ugn/platform_specific_information id32}@anchor{212}
25035 @subsubsection Using @cite{gnatdll}
25038 @geindex gnatdll
25040 @cite{gnatdll} is a tool to automate the DLL build process once all the Ada
25041 and non-Ada sources that make up your DLL have been compiled.
25042 @cite{gnatdll} is actually in charge of two distinct tasks: build the
25043 static import library for the DLL and the actual DLL. The form of the
25044 @cite{gnatdll} command is
25046 @quotation
25048 @example
25049 $ gnatdll [`switches`] `list-of-files` [-largs `opts`]
25050 @end example
25051 @end quotation
25053 where @cite{list-of-files} is a list of ALI and object files. The object
25054 file list must be the exact list of objects corresponding to the non-Ada
25055 sources whose services are to be included in the DLL. The ALI file list
25056 must be the exact list of ALI files for the corresponding Ada sources
25057 whose services are to be included in the DLL. If @cite{list-of-files} is
25058 missing, only the static import library is generated.
25060 You may specify any of the following switches to @cite{gnatdll}:
25062 @quotation
25064 @geindex -a (gnatdll)
25065 @end quotation
25068 @table @asis
25070 @item @code{-a[@emph{address}]}
25072 Build a non-relocatable DLL at @cite{address}. If @cite{address} is not
25073 specified the default address @cite{0x11000000} will be used. By default,
25074 when this switch is missing, @cite{gnatdll} builds relocatable DLL. We
25075 advise the reader to build relocatable DLL.
25077 @geindex -b (gnatdll)
25079 @item @code{-b @emph{address}}
25081 Set the relocatable DLL base address. By default the address is
25082 @cite{0x11000000}.
25084 @geindex -bargs (gnatdll)
25086 @item @code{-bargs @emph{opts}}
25088 Binder options. Pass @cite{opts} to the binder.
25090 @geindex -d (gnatdll)
25092 @item @code{-d @emph{dllfile}}
25094 @cite{dllfile} is the name of the DLL. This switch must be present for
25095 @cite{gnatdll} to do anything. The name of the generated import library is
25096 obtained algorithmically from @cite{dllfile} as shown in the following
25097 example: if @cite{dllfile} is @cite{xyz.dll}, the import library name is
25098 @cite{libxyz.dll.a}. The name of the definition file to use (if not specified
25099 by option @emph{-e}) is obtained algorithmically from @cite{dllfile}
25100 as shown in the following example:
25101 if @cite{dllfile} is @cite{xyz.dll}, the definition
25102 file used is @cite{xyz.def}.
25104 @geindex -e (gnatdll)
25106 @item @code{-e @emph{deffile}}
25108 @cite{deffile} is the name of the definition file.
25110 @geindex -g (gnatdll)
25112 @item @code{-g}
25114 Generate debugging information. This information is stored in the object
25115 file and copied from there to the final DLL file by the linker,
25116 where it can be read by the debugger. You must use the
25117 @emph{-g} switch if you plan on using the debugger or the symbolic
25118 stack traceback.
25120 @geindex -h (gnatdll)
25122 @item @code{-h}
25124 Help mode. Displays @cite{gnatdll} switch usage information.
25126 @geindex -I (gnatdll)
25128 @item @code{-I@emph{dir}}
25130 Direct @cite{gnatdll} to search the @cite{dir} directory for source and
25131 object files needed to build the DLL.
25132 (@ref{89,,Search Paths and the Run-Time Library (RTL)}).
25134 @geindex -k (gnatdll)
25136 @item @code{-k}
25138 Removes the @code{@@@emph{nn}} suffix from the import library's exported
25139 names, but keeps them for the link names. You must specify this
25140 option if you want to use a @cite{Stdcall} function in a DLL for which
25141 the @code{@@@emph{nn}} suffix has been removed. This is the case for most
25142 of the Windows NT DLL for example. This option has no effect when
25143 @emph{-n} option is specified.
25145 @geindex -l (gnatdll)
25147 @item @code{-l @emph{file}}
25149 The list of ALI and object files used to build the DLL are listed in
25150 @cite{file}, instead of being given in the command line. Each line in
25151 @cite{file} contains the name of an ALI or object file.
25153 @geindex -n (gnatdll)
25155 @item @code{-n}
25157 No Import. Do not create the import library.
25159 @geindex -q (gnatdll)
25161 @item @code{-q}
25163 Quiet mode. Do not display unnecessary messages.
25165 @geindex -v (gnatdll)
25167 @item @code{-v}
25169 Verbose mode. Display extra information.
25171 @geindex -largs (gnatdll)
25173 @item @code{-largs @emph{opts}}
25175 Linker options. Pass @cite{opts} to the linker.
25176 @end table
25178 @subsubheading @cite{gnatdll} Example
25181 As an example the command to build a relocatable DLL from @code{api.adb}
25182 once @code{api.adb} has been compiled and @code{api.def} created is
25184 @quotation
25186 @example
25187 $ gnatdll -d api.dll api.ali
25188 @end example
25189 @end quotation
25191 The above command creates two files: @code{libapi.dll.a} (the import
25192 library) and @code{api.dll} (the actual DLL). If you want to create
25193 only the DLL, just type:
25195 @quotation
25197 @example
25198 $ gnatdll -d api.dll -n api.ali
25199 @end example
25200 @end quotation
25202 Alternatively if you want to create just the import library, type:
25204 @quotation
25206 @example
25207 $ gnatdll -d api.dll
25208 @end example
25209 @end quotation
25211 @subsubheading @cite{gnatdll} behind the Scenes
25214 This section details the steps involved in creating a DLL. @cite{gnatdll}
25215 does these steps for you. Unless you are interested in understanding what
25216 goes on behind the scenes, you should skip this section.
25218 We use the previous example of a DLL containing the Ada package @cite{API},
25219 to illustrate the steps necessary to build a DLL. The starting point is a
25220 set of objects that will make up the DLL and the corresponding ALI
25221 files. In the case of this example this means that @code{api.o} and
25222 @code{api.ali} are available. To build a relocatable DLL, @cite{gnatdll} does
25223 the following:
25226 @itemize *
25228 @item 
25229 @cite{gnatdll} builds the base file (@code{api.base}). A base file gives
25230 the information necessary to generate relocation information for the
25231 DLL.
25233 @example
25234 $ gnatbind -n api
25235 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
25236 @end example
25238 In addition to the base file, the @emph{gnatlink} command generates an
25239 output file @code{api.jnk} which can be discarded. The @emph{-mdll} switch
25240 asks @emph{gnatlink} to generate the routines @cite{DllMain} and
25241 @cite{DllMainCRTStartup} that are called by the Windows loader when the DLL
25242 is loaded into memory.
25244 @item 
25245 @cite{gnatdll} uses @cite{dlltool} (see @ref{213,,Using dlltool}) to build the
25246 export table (@code{api.exp}). The export table contains the relocation
25247 information in a form which can be used during the final link to ensure
25248 that the Windows loader is able to place the DLL anywhere in memory.
25250 @example
25251 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
25252           --output-exp api.exp
25253 @end example
25255 @item 
25256 @cite{gnatdll} builds the base file using the new export table. Note that
25257 @emph{gnatbind} must be called once again since the binder generated file
25258 has been deleted during the previous call to @emph{gnatlink}.
25260 @example
25261 $ gnatbind -n api
25262 $ gnatlink api -o api.jnk api.exp -mdll
25263       -Wl,--base-file,api.base
25264 @end example
25266 @item 
25267 @cite{gnatdll} builds the new export table using the new base file and
25268 generates the DLL import library @code{libAPI.dll.a}.
25270 @example
25271 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
25272           --output-exp api.exp --output-lib libAPI.a
25273 @end example
25275 @item 
25276 Finally @cite{gnatdll} builds the relocatable DLL using the final export
25277 table.
25279 @example
25280 $ gnatbind -n api
25281 $ gnatlink api api.exp -o api.dll -mdll
25282 @end example
25283 @end itemize
25284 @anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{213}
25285 @subsubheading Using @cite{dlltool}
25288 @cite{dlltool} is the low-level tool used by @cite{gnatdll} to build
25289 DLLs and static import libraries. This section summarizes the most
25290 common @cite{dlltool} switches. The form of the @cite{dlltool} command
25293 @quotation
25295 @example
25296 $ dlltool [`switches`]
25297 @end example
25298 @end quotation
25300 @cite{dlltool} switches include:
25302 @geindex --base-file (dlltool)
25305 @table @asis
25307 @item @code{--base-file @emph{basefile}}
25309 Read the base file @cite{basefile} generated by the linker. This switch
25310 is used to create a relocatable DLL.
25311 @end table
25313 @geindex --def (dlltool)
25316 @table @asis
25318 @item @code{--def @emph{deffile}}
25320 Read the definition file.
25321 @end table
25323 @geindex --dllname (dlltool)
25326 @table @asis
25328 @item @code{--dllname @emph{name}}
25330 Gives the name of the DLL. This switch is used to embed the name of the
25331 DLL in the static import library generated by @cite{dlltool} with switch
25332 @emph{--output-lib}.
25333 @end table
25335 @geindex -k (dlltool)
25338 @table @asis
25340 @item @code{-k}
25342 Kill @code{@@@emph{nn}} from exported names
25343 (@ref{1ec,,Windows Calling Conventions}
25344 for a discussion about @cite{Stdcall}-style symbols.
25345 @end table
25347 @geindex --help (dlltool)
25350 @table @asis
25352 @item @code{--help}
25354 Prints the @cite{dlltool} switches with a concise description.
25355 @end table
25357 @geindex --output-exp (dlltool)
25360 @table @asis
25362 @item @code{--output-exp @emph{exportfile}}
25364 Generate an export file @cite{exportfile}. The export file contains the
25365 export table (list of symbols in the DLL) and is used to create the DLL.
25366 @end table
25368 @geindex --output-lib (dlltool)
25371 @table @asis
25373 @item @code{--output-lib @emph{libfile}}
25375 Generate a static import library @cite{libfile}.
25376 @end table
25378 @geindex -v (dlltool)
25381 @table @asis
25383 @item @code{-v}
25385 Verbose mode.
25386 @end table
25388 @geindex --as (dlltool)
25391 @table @asis
25393 @item @code{--as @emph{assembler-name}}
25395 Use @cite{assembler-name} as the assembler. The default is @cite{as}.
25396 @end table
25398 @node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
25399 @anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{214}@anchor{gnat_ugn/platform_specific_information id33}@anchor{215}
25400 @subsubsection GNAT and Windows Resources
25403 @geindex Resources
25404 @geindex windows
25406 Resources are an easy way to add Windows specific objects to your
25407 application. The objects that can be added as resources include:
25410 @itemize *
25412 @item 
25413 menus
25415 @item 
25416 accelerators
25418 @item 
25419 dialog boxes
25421 @item 
25422 string tables
25424 @item 
25425 bitmaps
25427 @item 
25428 cursors
25430 @item 
25431 icons
25433 @item 
25434 fonts
25436 @item 
25437 version information
25438 @end itemize
25440 For example, a version information resource can be defined as follow and
25441 embedded into an executable or DLL:
25443 A version information resource can be used to embed information into an
25444 executable or a DLL. These information can be viewed using the file properties
25445 from the Windows Explorer. Here is an example of a version information
25446 resource:
25448 @quotation
25450 @example
25451 1 VERSIONINFO
25452 FILEVERSION     1,0,0,0
25453 PRODUCTVERSION  1,0,0,0
25454 BEGIN
25455   BLOCK "StringFileInfo"
25456   BEGIN
25457     BLOCK "080904E4"
25458     BEGIN
25459       VALUE "CompanyName", "My Company Name"
25460       VALUE "FileDescription", "My application"
25461       VALUE "FileVersion", "1.0"
25462       VALUE "InternalName", "my_app"
25463       VALUE "LegalCopyright", "My Name"
25464       VALUE "OriginalFilename", "my_app.exe"
25465       VALUE "ProductName", "My App"
25466       VALUE "ProductVersion", "1.0"
25467     END
25468   END
25470   BLOCK "VarFileInfo"
25471   BEGIN
25472     VALUE "Translation", 0x809, 1252
25473   END
25475 @end example
25476 @end quotation
25478 The value @cite{0809} (langID) is for the U.K English language and
25479 @cite{04E4} (charsetID), which is equal to @cite{1252} decimal, for
25480 multilingual.
25482 This section explains how to build, compile and use resources. Note that this
25483 section does not cover all resource objects, for a complete description see
25484 the corresponding Microsoft documentation.
25486 @menu
25487 * Building Resources:: 
25488 * Compiling Resources:: 
25489 * Using Resources:: 
25491 @end menu
25493 @node Building Resources,Compiling Resources,,GNAT and Windows Resources
25494 @anchor{gnat_ugn/platform_specific_information building-resources}@anchor{216}@anchor{gnat_ugn/platform_specific_information id34}@anchor{217}
25495 @subsubsection Building Resources
25498 @geindex Resources
25499 @geindex building
25501 A resource file is an ASCII file. By convention resource files have an
25502 @code{.rc} extension.
25503 The easiest way to build a resource file is to use Microsoft tools
25504 such as @cite{imagedit.exe} to build bitmaps, icons and cursors and
25505 @cite{dlgedit.exe} to build dialogs.
25506 It is always possible to build an @code{.rc} file yourself by writing a
25507 resource script.
25509 It is not our objective to explain how to write a resource file. A
25510 complete description of the resource script language can be found in the
25511 Microsoft documentation.
25513 @node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
25514 @anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{218}@anchor{gnat_ugn/platform_specific_information id35}@anchor{219}
25515 @subsubsection Compiling Resources
25518 @geindex rc
25520 @geindex windres
25522 @geindex Resources
25523 @geindex compiling
25525 This section describes how to build a GNAT-compatible (COFF) object file
25526 containing the resources. This is done using the Resource Compiler
25527 @cite{windres} as follows:
25529 @quotation
25531 @example
25532 $ windres -i myres.rc -o myres.o
25533 @end example
25534 @end quotation
25536 By default @cite{windres} will run @emph{gcc} to preprocess the @code{.rc}
25537 file. You can specify an alternate preprocessor (usually named
25538 @code{cpp.exe}) using the @cite{windres} @emph{--preprocessor}
25539 parameter. A list of all possible options may be obtained by entering
25540 the command @cite{windres} @emph{--help}.
25542 It is also possible to use the Microsoft resource compiler @cite{rc.exe}
25543 to produce a @code{.res} file (binary resource file). See the
25544 corresponding Microsoft documentation for further details. In this case
25545 you need to use @cite{windres} to translate the @code{.res} file to a
25546 GNAT-compatible object file as follows:
25548 @quotation
25550 @example
25551 $ windres -i myres.res -o myres.o
25552 @end example
25553 @end quotation
25555 @node Using Resources,,Compiling Resources,GNAT and Windows Resources
25556 @anchor{gnat_ugn/platform_specific_information id36}@anchor{21a}@anchor{gnat_ugn/platform_specific_information using-resources}@anchor{21b}
25557 @subsubsection Using Resources
25560 @geindex Resources
25561 @geindex using
25563 To include the resource file in your program just add the
25564 GNAT-compatible object file for the resource(s) to the linker
25565 arguments. With @emph{gnatmake} this is done by using the @emph{-largs}
25566 option:
25568 @quotation
25570 @example
25571 $ gnatmake myprog -largs myres.o
25572 @end example
25573 @end quotation
25575 @node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
25576 @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}
25577 @subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
25580 @geindex Microsoft Visual Studio
25581 @geindex use with GNAT DLLs
25583 This section describes a common case of mixed GNAT/Microsoft Visual Studio
25584 application development, where the main program is developed using MSVS, and
25585 is linked with a DLL developed using GNAT. Such a mixed application should
25586 be developed following the general guidelines outlined above; below is the
25587 cookbook-style sequence of steps to follow:
25590 @enumerate 
25592 @item 
25593 First develop and build the GNAT shared library using a library project
25594 (let's assume the project is @cite{mylib.gpr}, producing the library @cite{libmylib.dll}):
25595 @end enumerate
25597 @quotation
25599 @example
25600 $ gprbuild -p mylib.gpr
25601 @end example
25602 @end quotation
25605 @enumerate 2
25607 @item 
25608 Produce a .def file for the symbols you need to interface with, either by
25609 hand or automatically with possibly some manual adjustments
25610 (see @ref{1fe,,Creating Definition File Automatically}):
25611 @end enumerate
25613 @quotation
25615 @example
25616 $ dlltool libmylib.dll -z libmylib.def --export-all-symbols
25617 @end example
25618 @end quotation
25621 @enumerate 3
25623 @item 
25624 Make sure that MSVS command-line tools are accessible on the path.
25626 @item 
25627 Create the Microsoft-style import library (see @ref{201,,MSVS-Style Import Library}):
25628 @end enumerate
25630 @quotation
25632 @example
25633 $ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
25634 @end example
25635 @end quotation
25637 If you are using a 64-bit toolchain, the above becomes...
25639 @quotation
25641 @example
25642 $ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
25643 @end example
25644 @end quotation
25647 @enumerate 5
25649 @item 
25650 Build the C main
25651 @end enumerate
25653 @quotation
25655 @example
25656 $ cl /O2 /MD main.c libmylib.lib
25657 @end example
25658 @end quotation
25661 @enumerate 6
25663 @item 
25664 Before running the executable, make sure you have set the PATH to the DLL,
25665 or copy the DLL into into the directory containing the .exe.
25666 @end enumerate
25668 @node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
25669 @anchor{gnat_ugn/platform_specific_information id37}@anchor{21e}@anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{21f}
25670 @subsubsection Debugging a DLL
25673 @geindex DLL debugging
25675 Debugging a DLL is similar to debugging a standard program. But
25676 we have to deal with two different executable parts: the DLL and the
25677 program that uses it. We have the following four possibilities:
25680 @itemize *
25682 @item 
25683 The program and the DLL are built with @cite{GCC/GNAT}.
25685 @item 
25686 The program is built with foreign tools and the DLL is built with
25687 @cite{GCC/GNAT}.
25689 @item 
25690 The program is built with @cite{GCC/GNAT} and the DLL is built with
25691 foreign tools.
25692 @end itemize
25694 In this section we address only cases one and two above.
25695 There is no point in trying to debug
25696 a DLL with @cite{GNU/GDB}, if there is no GDB-compatible debugging
25697 information in it. To do so you must use a debugger compatible with the
25698 tools suite used to build the DLL.
25700 @menu
25701 * Program and DLL Both Built with GCC/GNAT:: 
25702 * Program Built with Foreign Tools and DLL Built with GCC/GNAT:: 
25704 @end menu
25706 @node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
25707 @anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{220}@anchor{gnat_ugn/platform_specific_information id38}@anchor{221}
25708 @subsubsection Program and DLL Both Built with GCC/GNAT
25711 This is the simplest case. Both the DLL and the program have @cite{GDB}
25712 compatible debugging information. It is then possible to break anywhere in
25713 the process. Let's suppose here that the main procedure is named
25714 @cite{ada_main} and that in the DLL there is an entry point named
25715 @cite{ada_dll}.
25717 The DLL (@ref{1f7,,Introduction to Dynamic Link Libraries (DLLs)}) and
25718 program must have been built with the debugging information (see GNAT -g
25719 switch). Here are the step-by-step instructions for debugging it:
25722 @itemize *
25724 @item 
25725 Launch @cite{GDB} on the main program.
25727 @example
25728 $ gdb -nw ada_main
25729 @end example
25731 @item 
25732 Start the program and stop at the beginning of the main procedure
25734 @example
25735 (gdb) start
25736 @end example
25738 This step is required to be able to set a breakpoint inside the DLL. As long
25739 as the program is not run, the DLL is not loaded. This has the
25740 consequence that the DLL debugging information is also not loaded, so it is not
25741 possible to set a breakpoint in the DLL.
25743 @item 
25744 Set a breakpoint inside the DLL
25746 @example
25747 (gdb) break ada_dll
25748 (gdb) cont
25749 @end example
25750 @end itemize
25752 At this stage a breakpoint is set inside the DLL. From there on
25753 you can use the standard approach to debug the whole program
25754 (@ref{24,,Running and Debugging Ada Programs}).
25756 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
25757 @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 id39}@anchor{223}
25758 @subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
25761 In this case things are slightly more complex because it is not possible to
25762 start the main program and then break at the beginning to load the DLL and the
25763 associated DLL debugging information. It is not possible to break at the
25764 beginning of the program because there is no @cite{GDB} debugging information,
25765 and therefore there is no direct way of getting initial control. This
25766 section addresses this issue by describing some methods that can be used
25767 to break somewhere in the DLL to debug it.
25769 First suppose that the main procedure is named @cite{main} (this is for
25770 example some C code built with Microsoft Visual C) and that there is a
25771 DLL named @cite{test.dll} containing an Ada entry point named
25772 @cite{ada_dll}.
25774 The DLL (see @ref{1f7,,Introduction to Dynamic Link Libraries (DLLs)}) must have
25775 been built with debugging information (see GNAT @cite{-g} option).
25777 @subsubheading Debugging the DLL Directly
25781 @itemize *
25783 @item 
25784 Find out the executable starting address
25786 @example
25787 $ objdump --file-header main.exe
25788 @end example
25790 The starting address is reported on the last line. For example:
25792 @example
25793 main.exe:     file format pei-i386
25794 architecture: i386, flags 0x0000010a:
25795 EXEC_P, HAS_DEBUG, D_PAGED
25796 start address 0x00401010
25797 @end example
25799 @item 
25800 Launch the debugger on the executable.
25802 @example
25803 $ gdb main.exe
25804 @end example
25806 @item 
25807 Set a breakpoint at the starting address, and launch the program.
25809 @example
25810 $ (gdb) break *0x00401010
25811 $ (gdb) run
25812 @end example
25814 The program will stop at the given address.
25816 @item 
25817 Set a breakpoint on a DLL subroutine.
25819 @example
25820 (gdb) break ada_dll.adb:45
25821 @end example
25823 Or if you want to break using a symbol on the DLL, you need first to
25824 select the Ada language (language used by the DLL).
25826 @example
25827 (gdb) set language ada
25828 (gdb) break ada_dll
25829 @end example
25831 @item 
25832 Continue the program.
25834 @example
25835 (gdb) cont
25836 @end example
25838 This will run the program until it reaches the breakpoint that has been
25839 set. From that point you can use the standard way to debug a program
25840 as described in (@ref{24,,Running and Debugging Ada Programs}).
25841 @end itemize
25843 It is also possible to debug the DLL by attaching to a running process.
25845 @subsubheading Attaching to a Running Process
25848 @geindex DLL debugging
25849 @geindex attach to process
25851 With @cite{GDB} it is always possible to debug a running process by
25852 attaching to it. It is possible to debug a DLL this way. The limitation
25853 of this approach is that the DLL must run long enough to perform the
25854 attach operation. It may be useful for instance to insert a time wasting
25855 loop in the code of the DLL to meet this criterion.
25858 @itemize *
25860 @item 
25861 Launch the main program @code{main.exe}.
25863 @example
25864 $ main
25865 @end example
25867 @item 
25868 Use the Windows @emph{Task Manager} to find the process ID. Let's say
25869 that the process PID for @code{main.exe} is 208.
25871 @item 
25872 Launch gdb.
25874 @example
25875 $ gdb
25876 @end example
25878 @item 
25879 Attach to the running process to be debugged.
25881 @example
25882 (gdb) attach 208
25883 @end example
25885 @item 
25886 Load the process debugging information.
25888 @example
25889 (gdb) symbol-file main.exe
25890 @end example
25892 @item 
25893 Break somewhere in the DLL.
25895 @example
25896 (gdb) break ada_dll
25897 @end example
25899 @item 
25900 Continue process execution.
25902 @example
25903 (gdb) cont
25904 @end example
25905 @end itemize
25907 This last step will resume the process execution, and stop at
25908 the breakpoint we have set. From there you can use the standard
25909 approach to debug a program as described in
25910 @ref{24,,Running and Debugging Ada Programs}.
25912 @node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
25913 @anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{136}@anchor{gnat_ugn/platform_specific_information id40}@anchor{224}
25914 @subsubsection Setting Stack Size from @emph{gnatlink}
25917 It is possible to specify the program stack size at link time. On modern
25918 versions of Windows, starting with XP, this is mostly useful to set the size of
25919 the main stack (environment task). The other task stacks are set with pragma
25920 Storage_Size or with the @emph{gnatbind -d} command.
25922 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
25923 reserve size of individual tasks, the link-time stack size applies to all
25924 tasks, and pragma Storage_Size has no effect.
25925 In particular, Stack Overflow checks are made against this
25926 link-time specified size.
25928 This setting can be done with @emph{gnatlink} using either of the following:
25931 @itemize *
25933 @item 
25934 @emph{-Xlinker} linker option
25936 @example
25937 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
25938 @end example
25940 This sets the stack reserve size to 0x10000 bytes and the stack commit
25941 size to 0x1000 bytes.
25943 @item 
25944 @emph{-Wl} linker option
25946 @example
25947 $ gnatlink hello -Wl,--stack=0x1000000
25948 @end example
25950 This sets the stack reserve size to 0x1000000 bytes. Note that with
25951 @emph{-Wl} option it is not possible to set the stack commit size
25952 because the coma is a separator for this option.
25953 @end itemize
25955 @node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
25956 @anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{137}@anchor{gnat_ugn/platform_specific_information id41}@anchor{225}
25957 @subsubsection Setting Heap Size from @emph{gnatlink}
25960 Under Windows systems, it is possible to specify the program heap size from
25961 @emph{gnatlink} using either of the following:
25964 @itemize *
25966 @item 
25967 @emph{-Xlinker} linker option
25969 @example
25970 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
25971 @end example
25973 This sets the heap reserve size to 0x10000 bytes and the heap commit
25974 size to 0x1000 bytes.
25976 @item 
25977 @emph{-Wl} linker option
25979 @example
25980 $ gnatlink hello -Wl,--heap=0x1000000
25981 @end example
25983 This sets the heap reserve size to 0x1000000 bytes. Note that with
25984 @emph{-Wl} option it is not possible to set the heap commit size
25985 because the coma is a separator for this option.
25986 @end itemize
25988 @node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
25989 @anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{226}@anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{227}
25990 @subsection Windows Specific Add-Ons
25993 This section describes the Windows specific add-ons.
25995 @menu
25996 * Win32Ada:: 
25997 * wPOSIX:: 
25999 @end menu
26001 @node Win32Ada,wPOSIX,,Windows Specific Add-Ons
26002 @anchor{gnat_ugn/platform_specific_information win32ada}@anchor{228}@anchor{gnat_ugn/platform_specific_information id42}@anchor{229}
26003 @subsubsection Win32Ada
26006 Win32Ada is a binding for the Microsoft Win32 API. This binding can be
26007 easily installed from the provided installer. To use the Win32Ada
26008 binding you need to use a project file, and adding a single with_clause
26009 will give you full access to the Win32Ada binding sources and ensure
26010 that the proper libraries are passed to the linker.
26012 @quotation
26014 @example
26015 with "win32ada";
26016 project P is
26017    for Sources use ...;
26018 end P;
26019 @end example
26020 @end quotation
26022 To build the application you just need to call gprbuild for the
26023 application's project, here p.gpr:
26025 @quotation
26027 @example
26028 gprbuild p.gpr
26029 @end example
26030 @end quotation
26032 @node wPOSIX,,Win32Ada,Windows Specific Add-Ons
26033 @anchor{gnat_ugn/platform_specific_information id43}@anchor{22a}@anchor{gnat_ugn/platform_specific_information wposix}@anchor{22b}
26034 @subsubsection wPOSIX
26037 wPOSIX is a minimal POSIX binding whose goal is to help with building
26038 cross-platforms applications. This binding is not complete though, as
26039 the Win32 API does not provide the necessary support for all POSIX APIs.
26041 To use the wPOSIX binding you need to use a project file, and adding
26042 a single with_clause will give you full access to the wPOSIX binding
26043 sources and ensure that the proper libraries are passed to the linker.
26045 @quotation
26047 @example
26048 with "wposix";
26049 project P is
26050    for Sources use ...;
26051 end P;
26052 @end example
26053 @end quotation
26055 To build the application you just need to call gprbuild for the
26056 application's project, here p.gpr:
26058 @quotation
26060 @example
26061 gprbuild p.gpr
26062 @end example
26063 @end quotation
26065 @node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
26066 @anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{2d}@anchor{gnat_ugn/platform_specific_information id44}@anchor{22c}
26067 @section Mac OS Topics
26070 @geindex OS X
26072 This section describes topics that are specific to Apple's OS X
26073 platform.
26075 @menu
26076 * Codesigning the Debugger:: 
26078 @end menu
26080 @node Codesigning the Debugger,,,Mac OS Topics
26081 @anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{22d}
26082 @subsection Codesigning the Debugger
26085 The Darwin Kernel requires the debugger to have special permissions
26086 before it is allowed to control other processes. These permissions
26087 are granted by codesigning the GDB executable. Without these
26088 permissions, the debugger will report error messages such as:
26090 @example
26091 Starting program: /x/y/foo
26092 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
26093 (please check gdb is codesigned - see taskgated(8))
26094 @end example
26096 Codesigning requires a certificate.  The following procedure explains
26097 how to create one:
26100 @itemize *
26102 @item 
26103 Start the Keychain Access application (in
26104 /Applications/Utilities/Keychain Access.app)
26106 @item 
26107 Select the Keychain Access -> Certificate Assistant ->
26108 Create a Certificate... menu
26110 @item 
26111 Then:
26114 @itemize *
26116 @item 
26117 Choose a name for the new certificate (this procedure will use
26118 "gdb-cert" as an example)
26120 @item 
26121 Set "Identity Type" to "Self Signed Root"
26123 @item 
26124 Set "Certificate Type" to "Code Signing"
26126 @item 
26127 Activate the "Let me override defaults" option
26128 @end itemize
26130 @item 
26131 Click several times on "Continue" until the "Specify a Location
26132 For The Certificate" screen appears, then set "Keychain" to "System"
26134 @item 
26135 Click on "Continue" until the certificate is created
26137 @item 
26138 Finally, in the view, double-click on the new certificate,
26139 and set "When using this certificate" to "Always Trust"
26141 @item 
26142 Exit the Keychain Access application and restart the computer
26143 (this is unfortunately required)
26144 @end itemize
26146 Once a certificate has been created, the debugger can be codesigned
26147 as follow. In a Terminal, run the following command:
26149 @quotation
26151 @example
26152 $ codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
26153 @end example
26154 @end quotation
26156 where "gdb-cert" should be replaced by the actual certificate
26157 name chosen above, and <gnat_install_prefix> should be replaced by
26158 the location where you installed GNAT.  Also, be sure that users are
26159 in the Unix group @code{_developer}.
26161 @node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
26162 @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}
26163 @chapter Example of Binder Output File
26166 @geindex Binder output (example)
26168 This Appendix displays the source code for the output file
26169 generated by @emph{gnatbind} for a simple 'Hello World' program.
26170 Comments have been added for clarification purposes.
26172 @example
26173 --  The package is called Ada_Main unless this name is actually used
26174 --  as a unit name in the partition, in which case some other unique
26175 --  name is used.
26177 pragma Ada_95;
26178 with System;
26179 package ada_main is
26180    pragma Warnings (Off);
26182    --  The main program saves the parameters (argument count,
26183    --  argument values, environment pointer) in global variables
26184    --  for later access by other units including
26185    --  Ada.Command_Line.
26187    gnat_argc : Integer;
26188    gnat_argv : System.Address;
26189    gnat_envp : System.Address;
26191    --  The actual variables are stored in a library routine. This
26192    --  is useful for some shared library situations, where there
26193    --  are problems if variables are not in the library.
26195    pragma Import (C, gnat_argc);
26196    pragma Import (C, gnat_argv);
26197    pragma Import (C, gnat_envp);
26199    --  The exit status is similarly an external location
26201    gnat_exit_status : Integer;
26202    pragma Import (C, gnat_exit_status);
26204    GNAT_Version : constant String :=
26205                     "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
26206    pragma Export (C, GNAT_Version, "__gnat_version");
26208    Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
26209    pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
26211    --  This is the generated adainit routine that performs
26212    --  initialization at the start of execution. In the case
26213    --  where Ada is the main program, this main program makes
26214    --  a call to adainit at program startup.
26216    procedure adainit;
26217    pragma Export (C, adainit, "adainit");
26219    --  This is the generated adafinal routine that performs
26220    --  finalization at the end of execution. In the case where
26221    --  Ada is the main program, this main program makes a call
26222    --  to adafinal at program termination.
26224    procedure adafinal;
26225    pragma Export (C, adafinal, "adafinal");
26227    --  This routine is called at the start of execution. It is
26228    --  a dummy routine that is used by the debugger to breakpoint
26229    --  at the start of execution.
26231    --  This is the actual generated main program (it would be
26232    --  suppressed if the no main program switch were used). As
26233    --  required by standard system conventions, this program has
26234    --  the external name main.
26236    function main
26237      (argc : Integer;
26238       argv : System.Address;
26239       envp : System.Address)
26240       return Integer;
26241    pragma Export (C, main, "main");
26243    --  The following set of constants give the version
26244    --  identification values for every unit in the bound
26245    --  partition. This identification is computed from all
26246    --  dependent semantic units, and corresponds to the
26247    --  string that would be returned by use of the
26248    --  Body_Version or Version attributes.
26250    --  The following Export pragmas export the version numbers
26251    --  with symbolic names ending in B (for body) or S
26252    --  (for spec) so that they can be located in a link. The
26253    --  information provided here is sufficient to track down
26254    --  the exact versions of units used in a given build.
26256    type Version_32 is mod 2 ** 32;
26257    u00001 : constant Version_32 := 16#8ad6e54a#;
26258    pragma Export (C, u00001, "helloB");
26259    u00002 : constant Version_32 := 16#fbff4c67#;
26260    pragma Export (C, u00002, "system__standard_libraryB");
26261    u00003 : constant Version_32 := 16#1ec6fd90#;
26262    pragma Export (C, u00003, "system__standard_libraryS");
26263    u00004 : constant Version_32 := 16#3ffc8e18#;
26264    pragma Export (C, u00004, "adaS");
26265    u00005 : constant Version_32 := 16#28f088c2#;
26266    pragma Export (C, u00005, "ada__text_ioB");
26267    u00006 : constant Version_32 := 16#f372c8ac#;
26268    pragma Export (C, u00006, "ada__text_ioS");
26269    u00007 : constant Version_32 := 16#2c143749#;
26270    pragma Export (C, u00007, "ada__exceptionsB");
26271    u00008 : constant Version_32 := 16#f4f0cce8#;
26272    pragma Export (C, u00008, "ada__exceptionsS");
26273    u00009 : constant Version_32 := 16#a46739c0#;
26274    pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
26275    u00010 : constant Version_32 := 16#3aac8c92#;
26276    pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
26277    u00011 : constant Version_32 := 16#1d274481#;
26278    pragma Export (C, u00011, "systemS");
26279    u00012 : constant Version_32 := 16#a207fefe#;
26280    pragma Export (C, u00012, "system__soft_linksB");
26281    u00013 : constant Version_32 := 16#467d9556#;
26282    pragma Export (C, u00013, "system__soft_linksS");
26283    u00014 : constant Version_32 := 16#b01dad17#;
26284    pragma Export (C, u00014, "system__parametersB");
26285    u00015 : constant Version_32 := 16#630d49fe#;
26286    pragma Export (C, u00015, "system__parametersS");
26287    u00016 : constant Version_32 := 16#b19b6653#;
26288    pragma Export (C, u00016, "system__secondary_stackB");
26289    u00017 : constant Version_32 := 16#b6468be8#;
26290    pragma Export (C, u00017, "system__secondary_stackS");
26291    u00018 : constant Version_32 := 16#39a03df9#;
26292    pragma Export (C, u00018, "system__storage_elementsB");
26293    u00019 : constant Version_32 := 16#30e40e85#;
26294    pragma Export (C, u00019, "system__storage_elementsS");
26295    u00020 : constant Version_32 := 16#41837d1e#;
26296    pragma Export (C, u00020, "system__stack_checkingB");
26297    u00021 : constant Version_32 := 16#93982f69#;
26298    pragma Export (C, u00021, "system__stack_checkingS");
26299    u00022 : constant Version_32 := 16#393398c1#;
26300    pragma Export (C, u00022, "system__exception_tableB");
26301    u00023 : constant Version_32 := 16#b33e2294#;
26302    pragma Export (C, u00023, "system__exception_tableS");
26303    u00024 : constant Version_32 := 16#ce4af020#;
26304    pragma Export (C, u00024, "system__exceptionsB");
26305    u00025 : constant Version_32 := 16#75442977#;
26306    pragma Export (C, u00025, "system__exceptionsS");
26307    u00026 : constant Version_32 := 16#37d758f1#;
26308    pragma Export (C, u00026, "system__exceptions__machineS");
26309    u00027 : constant Version_32 := 16#b895431d#;
26310    pragma Export (C, u00027, "system__exceptions_debugB");
26311    u00028 : constant Version_32 := 16#aec55d3f#;
26312    pragma Export (C, u00028, "system__exceptions_debugS");
26313    u00029 : constant Version_32 := 16#570325c8#;
26314    pragma Export (C, u00029, "system__img_intB");
26315    u00030 : constant Version_32 := 16#1ffca443#;
26316    pragma Export (C, u00030, "system__img_intS");
26317    u00031 : constant Version_32 := 16#b98c3e16#;
26318    pragma Export (C, u00031, "system__tracebackB");
26319    u00032 : constant Version_32 := 16#831a9d5a#;
26320    pragma Export (C, u00032, "system__tracebackS");
26321    u00033 : constant Version_32 := 16#9ed49525#;
26322    pragma Export (C, u00033, "system__traceback_entriesB");
26323    u00034 : constant Version_32 := 16#1d7cb2f1#;
26324    pragma Export (C, u00034, "system__traceback_entriesS");
26325    u00035 : constant Version_32 := 16#8c33a517#;
26326    pragma Export (C, u00035, "system__wch_conB");
26327    u00036 : constant Version_32 := 16#065a6653#;
26328    pragma Export (C, u00036, "system__wch_conS");
26329    u00037 : constant Version_32 := 16#9721e840#;
26330    pragma Export (C, u00037, "system__wch_stwB");
26331    u00038 : constant Version_32 := 16#2b4b4a52#;
26332    pragma Export (C, u00038, "system__wch_stwS");
26333    u00039 : constant Version_32 := 16#92b797cb#;
26334    pragma Export (C, u00039, "system__wch_cnvB");
26335    u00040 : constant Version_32 := 16#09eddca0#;
26336    pragma Export (C, u00040, "system__wch_cnvS");
26337    u00041 : constant Version_32 := 16#6033a23f#;
26338    pragma Export (C, u00041, "interfacesS");
26339    u00042 : constant Version_32 := 16#ece6fdb6#;
26340    pragma Export (C, u00042, "system__wch_jisB");
26341    u00043 : constant Version_32 := 16#899dc581#;
26342    pragma Export (C, u00043, "system__wch_jisS");
26343    u00044 : constant Version_32 := 16#10558b11#;
26344    pragma Export (C, u00044, "ada__streamsB");
26345    u00045 : constant Version_32 := 16#2e6701ab#;
26346    pragma Export (C, u00045, "ada__streamsS");
26347    u00046 : constant Version_32 := 16#db5c917c#;
26348    pragma Export (C, u00046, "ada__io_exceptionsS");
26349    u00047 : constant Version_32 := 16#12c8cd7d#;
26350    pragma Export (C, u00047, "ada__tagsB");
26351    u00048 : constant Version_32 := 16#ce72c228#;
26352    pragma Export (C, u00048, "ada__tagsS");
26353    u00049 : constant Version_32 := 16#c3335bfd#;
26354    pragma Export (C, u00049, "system__htableB");
26355    u00050 : constant Version_32 := 16#99e5f76b#;
26356    pragma Export (C, u00050, "system__htableS");
26357    u00051 : constant Version_32 := 16#089f5cd0#;
26358    pragma Export (C, u00051, "system__string_hashB");
26359    u00052 : constant Version_32 := 16#3bbb9c15#;
26360    pragma Export (C, u00052, "system__string_hashS");
26361    u00053 : constant Version_32 := 16#807fe041#;
26362    pragma Export (C, u00053, "system__unsigned_typesS");
26363    u00054 : constant Version_32 := 16#d27be59e#;
26364    pragma Export (C, u00054, "system__val_lluB");
26365    u00055 : constant Version_32 := 16#fa8db733#;
26366    pragma Export (C, u00055, "system__val_lluS");
26367    u00056 : constant Version_32 := 16#27b600b2#;
26368    pragma Export (C, u00056, "system__val_utilB");
26369    u00057 : constant Version_32 := 16#b187f27f#;
26370    pragma Export (C, u00057, "system__val_utilS");
26371    u00058 : constant Version_32 := 16#d1060688#;
26372    pragma Export (C, u00058, "system__case_utilB");
26373    u00059 : constant Version_32 := 16#392e2d56#;
26374    pragma Export (C, u00059, "system__case_utilS");
26375    u00060 : constant Version_32 := 16#84a27f0d#;
26376    pragma Export (C, u00060, "interfaces__c_streamsB");
26377    u00061 : constant Version_32 := 16#8bb5f2c0#;
26378    pragma Export (C, u00061, "interfaces__c_streamsS");
26379    u00062 : constant Version_32 := 16#6db6928f#;
26380    pragma Export (C, u00062, "system__crtlS");
26381    u00063 : constant Version_32 := 16#4e6a342b#;
26382    pragma Export (C, u00063, "system__file_ioB");
26383    u00064 : constant Version_32 := 16#ba56a5e4#;
26384    pragma Export (C, u00064, "system__file_ioS");
26385    u00065 : constant Version_32 := 16#b7ab275c#;
26386    pragma Export (C, u00065, "ada__finalizationB");
26387    u00066 : constant Version_32 := 16#19f764ca#;
26388    pragma Export (C, u00066, "ada__finalizationS");
26389    u00067 : constant Version_32 := 16#95817ed8#;
26390    pragma Export (C, u00067, "system__finalization_rootB");
26391    u00068 : constant Version_32 := 16#52d53711#;
26392    pragma Export (C, u00068, "system__finalization_rootS");
26393    u00069 : constant Version_32 := 16#769e25e6#;
26394    pragma Export (C, u00069, "interfaces__cB");
26395    u00070 : constant Version_32 := 16#4a38bedb#;
26396    pragma Export (C, u00070, "interfaces__cS");
26397    u00071 : constant Version_32 := 16#07e6ee66#;
26398    pragma Export (C, u00071, "system__os_libB");
26399    u00072 : constant Version_32 := 16#d7b69782#;
26400    pragma Export (C, u00072, "system__os_libS");
26401    u00073 : constant Version_32 := 16#1a817b8e#;
26402    pragma Export (C, u00073, "system__stringsB");
26403    u00074 : constant Version_32 := 16#639855e7#;
26404    pragma Export (C, u00074, "system__stringsS");
26405    u00075 : constant Version_32 := 16#e0b8de29#;
26406    pragma Export (C, u00075, "system__file_control_blockS");
26407    u00076 : constant Version_32 := 16#b5b2aca1#;
26408    pragma Export (C, u00076, "system__finalization_mastersB");
26409    u00077 : constant Version_32 := 16#69316dc1#;
26410    pragma Export (C, u00077, "system__finalization_mastersS");
26411    u00078 : constant Version_32 := 16#57a37a42#;
26412    pragma Export (C, u00078, "system__address_imageB");
26413    u00079 : constant Version_32 := 16#bccbd9bb#;
26414    pragma Export (C, u00079, "system__address_imageS");
26415    u00080 : constant Version_32 := 16#7268f812#;
26416    pragma Export (C, u00080, "system__img_boolB");
26417    u00081 : constant Version_32 := 16#e8fe356a#;
26418    pragma Export (C, u00081, "system__img_boolS");
26419    u00082 : constant Version_32 := 16#d7aac20c#;
26420    pragma Export (C, u00082, "system__ioB");
26421    u00083 : constant Version_32 := 16#8365b3ce#;
26422    pragma Export (C, u00083, "system__ioS");
26423    u00084 : constant Version_32 := 16#6d4d969a#;
26424    pragma Export (C, u00084, "system__storage_poolsB");
26425    u00085 : constant Version_32 := 16#e87cc305#;
26426    pragma Export (C, u00085, "system__storage_poolsS");
26427    u00086 : constant Version_32 := 16#e34550ca#;
26428    pragma Export (C, u00086, "system__pool_globalB");
26429    u00087 : constant Version_32 := 16#c88d2d16#;
26430    pragma Export (C, u00087, "system__pool_globalS");
26431    u00088 : constant Version_32 := 16#9d39c675#;
26432    pragma Export (C, u00088, "system__memoryB");
26433    u00089 : constant Version_32 := 16#445a22b5#;
26434    pragma Export (C, u00089, "system__memoryS");
26435    u00090 : constant Version_32 := 16#6a859064#;
26436    pragma Export (C, u00090, "system__storage_pools__subpoolsB");
26437    u00091 : constant Version_32 := 16#e3b008dc#;
26438    pragma Export (C, u00091, "system__storage_pools__subpoolsS");
26439    u00092 : constant Version_32 := 16#63f11652#;
26440    pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
26441    u00093 : constant Version_32 := 16#fe2f4b3a#;
26442    pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
26444    --  BEGIN ELABORATION ORDER
26445    --  ada%s
26446    --  interfaces%s
26447    --  system%s
26448    --  system.case_util%s
26449    --  system.case_util%b
26450    --  system.htable%s
26451    --  system.img_bool%s
26452    --  system.img_bool%b
26453    --  system.img_int%s
26454    --  system.img_int%b
26455    --  system.io%s
26456    --  system.io%b
26457    --  system.parameters%s
26458    --  system.parameters%b
26459    --  system.crtl%s
26460    --  interfaces.c_streams%s
26461    --  interfaces.c_streams%b
26462    --  system.standard_library%s
26463    --  system.exceptions_debug%s
26464    --  system.exceptions_debug%b
26465    --  system.storage_elements%s
26466    --  system.storage_elements%b
26467    --  system.stack_checking%s
26468    --  system.stack_checking%b
26469    --  system.string_hash%s
26470    --  system.string_hash%b
26471    --  system.htable%b
26472    --  system.strings%s
26473    --  system.strings%b
26474    --  system.os_lib%s
26475    --  system.traceback_entries%s
26476    --  system.traceback_entries%b
26477    --  ada.exceptions%s
26478    --  system.soft_links%s
26479    --  system.unsigned_types%s
26480    --  system.val_llu%s
26481    --  system.val_util%s
26482    --  system.val_util%b
26483    --  system.val_llu%b
26484    --  system.wch_con%s
26485    --  system.wch_con%b
26486    --  system.wch_cnv%s
26487    --  system.wch_jis%s
26488    --  system.wch_jis%b
26489    --  system.wch_cnv%b
26490    --  system.wch_stw%s
26491    --  system.wch_stw%b
26492    --  ada.exceptions.last_chance_handler%s
26493    --  ada.exceptions.last_chance_handler%b
26494    --  system.address_image%s
26495    --  system.exception_table%s
26496    --  system.exception_table%b
26497    --  ada.io_exceptions%s
26498    --  ada.tags%s
26499    --  ada.streams%s
26500    --  ada.streams%b
26501    --  interfaces.c%s
26502    --  system.exceptions%s
26503    --  system.exceptions%b
26504    --  system.exceptions.machine%s
26505    --  system.finalization_root%s
26506    --  system.finalization_root%b
26507    --  ada.finalization%s
26508    --  ada.finalization%b
26509    --  system.storage_pools%s
26510    --  system.storage_pools%b
26511    --  system.finalization_masters%s
26512    --  system.storage_pools.subpools%s
26513    --  system.storage_pools.subpools.finalization%s
26514    --  system.storage_pools.subpools.finalization%b
26515    --  system.memory%s
26516    --  system.memory%b
26517    --  system.standard_library%b
26518    --  system.pool_global%s
26519    --  system.pool_global%b
26520    --  system.file_control_block%s
26521    --  system.file_io%s
26522    --  system.secondary_stack%s
26523    --  system.file_io%b
26524    --  system.storage_pools.subpools%b
26525    --  system.finalization_masters%b
26526    --  interfaces.c%b
26527    --  ada.tags%b
26528    --  system.soft_links%b
26529    --  system.os_lib%b
26530    --  system.secondary_stack%b
26531    --  system.address_image%b
26532    --  system.traceback%s
26533    --  ada.exceptions%b
26534    --  system.traceback%b
26535    --  ada.text_io%s
26536    --  ada.text_io%b
26537    --  hello%b
26538    --  END ELABORATION ORDER
26540 end ada_main;
26541 @end example
26543 @example
26544 pragma Ada_95;
26545 --  The following source file name pragmas allow the generated file
26546 --  names to be unique for different main programs. They are needed
26547 --  since the package name will always be Ada_Main.
26549 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26550 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26552 pragma Suppress (Overflow_Check);
26553 with Ada.Exceptions;
26555 --  Generated package body for Ada_Main starts here
26557 package body ada_main is
26558    pragma Warnings (Off);
26560    --  These values are reference counter associated to units which have
26561    --  been elaborated. It is also used to avoid elaborating the
26562    --  same unit twice.
26564    E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
26565    E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
26566    E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
26567    E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
26568    E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
26569    E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
26570    E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
26571    E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
26572    E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
26573    E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
26574    E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
26575    E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
26576    E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
26577    E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
26578    E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
26579    E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
26580    E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
26581    E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
26583    Local_Priority_Specific_Dispatching : constant String := "";
26584    Local_Interrupt_States : constant String := "";
26586    Is_Elaborated : Boolean := False;
26588    procedure finalize_library is
26589    begin
26590       E06 := E06 - 1;
26591       declare
26592          procedure F1;
26593          pragma Import (Ada, F1, "ada__text_io__finalize_spec");
26594       begin
26595          F1;
26596       end;
26597       E77 := E77 - 1;
26598       E91 := E91 - 1;
26599       declare
26600          procedure F2;
26601          pragma Import (Ada, F2, "system__file_io__finalize_body");
26602       begin
26603          E64 := E64 - 1;
26604          F2;
26605       end;
26606       declare
26607          procedure F3;
26608          pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
26609       begin
26610          E75 := E75 - 1;
26611          F3;
26612       end;
26613       E87 := E87 - 1;
26614       declare
26615          procedure F4;
26616          pragma Import (Ada, F4, "system__pool_global__finalize_spec");
26617       begin
26618          F4;
26619       end;
26620       declare
26621          procedure F5;
26622          pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
26623       begin
26624          F5;
26625       end;
26626       declare
26627          procedure F6;
26628          pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
26629       begin
26630          F6;
26631       end;
26632       declare
26633          procedure Reraise_Library_Exception_If_Any;
26634          pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
26635       begin
26636          Reraise_Library_Exception_If_Any;
26637       end;
26638    end finalize_library;
26640    -------------
26641    -- adainit --
26642    -------------
26644    procedure adainit is
26646       Main_Priority : Integer;
26647       pragma Import (C, Main_Priority, "__gl_main_priority");
26648       Time_Slice_Value : Integer;
26649       pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
26650       WC_Encoding : Character;
26651       pragma Import (C, WC_Encoding, "__gl_wc_encoding");
26652       Locking_Policy : Character;
26653       pragma Import (C, Locking_Policy, "__gl_locking_policy");
26654       Queuing_Policy : Character;
26655       pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
26656       Task_Dispatching_Policy : Character;
26657       pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
26658       Priority_Specific_Dispatching : System.Address;
26659       pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
26660       Num_Specific_Dispatching : Integer;
26661       pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
26662       Main_CPU : Integer;
26663       pragma Import (C, Main_CPU, "__gl_main_cpu");
26664       Interrupt_States : System.Address;
26665       pragma Import (C, Interrupt_States, "__gl_interrupt_states");
26666       Num_Interrupt_States : Integer;
26667       pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
26668       Unreserve_All_Interrupts : Integer;
26669       pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
26670       Detect_Blocking : Integer;
26671       pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
26672       Default_Stack_Size : Integer;
26673       pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
26674       Leap_Seconds_Support : Integer;
26675       pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
26677       procedure Runtime_Initialize;
26678       pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
26680       Finalize_Library_Objects : No_Param_Proc;
26681       pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
26683    --  Start of processing for adainit
26685    begin
26687       --  Record various information for this partition.  The values
26688       --  are derived by the binder from information stored in the ali
26689       --  files by the compiler.
26691       if Is_Elaborated then
26692          return;
26693       end if;
26694       Is_Elaborated := True;
26695       Main_Priority := -1;
26696       Time_Slice_Value := -1;
26697       WC_Encoding := 'b';
26698       Locking_Policy := ' ';
26699       Queuing_Policy := ' ';
26700       Task_Dispatching_Policy := ' ';
26701       Priority_Specific_Dispatching :=
26702         Local_Priority_Specific_Dispatching'Address;
26703       Num_Specific_Dispatching := 0;
26704       Main_CPU := -1;
26705       Interrupt_States := Local_Interrupt_States'Address;
26706       Num_Interrupt_States := 0;
26707       Unreserve_All_Interrupts := 0;
26708       Detect_Blocking := 0;
26709       Default_Stack_Size := -1;
26710       Leap_Seconds_Support := 0;
26712       Runtime_Initialize;
26714       Finalize_Library_Objects := finalize_library'access;
26716       --  Now we have the elaboration calls for all units in the partition.
26717       --  The Elab_Spec and Elab_Body attributes generate references to the
26718       --  implicit elaboration procedures generated by the compiler for
26719       --  each unit that requires elaboration. Increment a counter of
26720       --  reference for each unit.
26722       System.Soft_Links'Elab_Spec;
26723       System.Exception_Table'Elab_Body;
26724       E23 := E23 + 1;
26725       Ada.Io_Exceptions'Elab_Spec;
26726       E46 := E46 + 1;
26727       Ada.Tags'Elab_Spec;
26728       Ada.Streams'Elab_Spec;
26729       E45 := E45 + 1;
26730       Interfaces.C'Elab_Spec;
26731       System.Exceptions'Elab_Spec;
26732       E25 := E25 + 1;
26733       System.Finalization_Root'Elab_Spec;
26734       E68 := E68 + 1;
26735       Ada.Finalization'Elab_Spec;
26736       E66 := E66 + 1;
26737       System.Storage_Pools'Elab_Spec;
26738       E85 := E85 + 1;
26739       System.Finalization_Masters'Elab_Spec;
26740       System.Storage_Pools.Subpools'Elab_Spec;
26741       System.Pool_Global'Elab_Spec;
26742       E87 := E87 + 1;
26743       System.File_Control_Block'Elab_Spec;
26744       E75 := E75 + 1;
26745       System.File_Io'Elab_Body;
26746       E64 := E64 + 1;
26747       E91 := E91 + 1;
26748       System.Finalization_Masters'Elab_Body;
26749       E77 := E77 + 1;
26750       E70 := E70 + 1;
26751       Ada.Tags'Elab_Body;
26752       E48 := E48 + 1;
26753       System.Soft_Links'Elab_Body;
26754       E13 := E13 + 1;
26755       System.Os_Lib'Elab_Body;
26756       E72 := E72 + 1;
26757       System.Secondary_Stack'Elab_Body;
26758       E17 := E17 + 1;
26759       Ada.Text_Io'Elab_Spec;
26760       Ada.Text_Io'Elab_Body;
26761       E06 := E06 + 1;
26762    end adainit;
26764    --------------
26765    -- adafinal --
26766    --------------
26768    procedure adafinal is
26769       procedure s_stalib_adafinal;
26770       pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
26772       procedure Runtime_Finalize;
26773       pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
26775    begin
26776       if not Is_Elaborated then
26777          return;
26778       end if;
26779       Is_Elaborated := False;
26780       Runtime_Finalize;
26781       s_stalib_adafinal;
26782    end adafinal;
26784    --  We get to the main program of the partition by using
26785    --  pragma Import because if we try to with the unit and
26786    --  call it Ada style, then not only do we waste time
26787    --  recompiling it, but also, we don't really know the right
26788    --  switches (e.g.@@: identifier character set) to be used
26789    --  to compile it.
26791    procedure Ada_Main_Program;
26792    pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26794    ----------
26795    -- main --
26796    ----------
26798    --  main is actually a function, as in the ANSI C standard,
26799    --  defined to return the exit status. The three parameters
26800    --  are the argument count, argument values and environment
26801    --  pointer.
26803    function main
26804      (argc : Integer;
26805       argv : System.Address;
26806       envp : System.Address)
26807       return Integer
26808    is
26809       --  The initialize routine performs low level system
26810       --  initialization using a standard library routine which
26811       --  sets up signal handling and performs any other
26812       --  required setup. The routine can be found in file
26813       --  a-init.c.
26815       procedure initialize;
26816       pragma Import (C, initialize, "__gnat_initialize");
26818       --  The finalize routine performs low level system
26819       --  finalization using a standard library routine. The
26820       --  routine is found in file a-final.c and in the standard
26821       --  distribution is a dummy routine that does nothing, so
26822       --  really this is a hook for special user finalization.
26824       procedure finalize;
26825       pragma Import (C, finalize, "__gnat_finalize");
26827       --  The following is to initialize the SEH exceptions
26829       SEH : aliased array (1 .. 2) of Integer;
26831       Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
26832       pragma Volatile (Ensure_Reference);
26834    --  Start of processing for main
26836    begin
26837       --  Save global variables
26839       gnat_argc := argc;
26840       gnat_argv := argv;
26841       gnat_envp := envp;
26843       --  Call low level system initialization
26845       Initialize (SEH'Address);
26847       --  Call our generated Ada initialization routine
26849       adainit;
26851       --  Now we call the main program of the partition
26853       Ada_Main_Program;
26855       --  Perform Ada finalization
26857       adafinal;
26859       --  Perform low level system finalization
26861       Finalize;
26863       --  Return the proper exit status
26864       return (gnat_exit_status);
26865    end;
26867 --  This section is entirely comments, so it has no effect on the
26868 --  compilation of the Ada_Main package. It provides the list of
26869 --  object files and linker options, as well as some standard
26870 --  libraries needed for the link. The gnatlink utility parses
26871 --  this b~hello.adb file to read these comment lines to generate
26872 --  the appropriate command line arguments for the call to the
26873 --  system linker. The BEGIN/END lines are used for sentinels for
26874 --  this parsing operation.
26876 --  The exact file names will of course depend on the environment,
26877 --  host/target and location of files on the host system.
26879 -- BEGIN Object file/option list
26880    --   ./hello.o
26881    --   -L./
26882    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
26883    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
26884 -- END Object file/option list
26886 end ada_main;
26887 @end example
26889 The Ada code in the above example is exactly what is generated by the
26890 binder. We have added comments to more clearly indicate the function
26891 of each part of the generated @cite{Ada_Main} package.
26893 The code is standard Ada in all respects, and can be processed by any
26894 tools that handle Ada. In particular, it is possible to use the debugger
26895 in Ada mode to debug the generated @cite{Ada_Main} package. For example,
26896 suppose that for reasons that you do not understand, your program is crashing
26897 during elaboration of the body of @cite{Ada.Text_IO}. To locate this bug,
26898 you can place a breakpoint on the call:
26900 @quotation
26902 @example
26903 Ada.Text_Io'Elab_Body;
26904 @end example
26905 @end quotation
26907 and trace the elaboration routine for this package to find out where
26908 the problem might be (more usually of course you would be debugging
26909 elaboration code in your own application).
26911 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
26913 @node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
26914 @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}
26915 @chapter Elaboration Order Handling in GNAT
26918 @geindex Order of elaboration
26920 @geindex Elaboration control
26922 This appendix describes the handling of elaboration code in Ada and
26923 in GNAT, and discusses how the order of elaboration of program units can
26924 be controlled in GNAT, either automatically or with explicit programming
26925 features.
26927 @menu
26928 * Elaboration Code:: 
26929 * Checking the Elaboration Order:: 
26930 * Controlling the Elaboration Order:: 
26931 * Controlling Elaboration in GNAT - Internal Calls:: 
26932 * Controlling Elaboration in GNAT - External Calls:: 
26933 * Default Behavior in GNAT - Ensuring Safety:: 
26934 * Treatment of Pragma Elaborate:: 
26935 * Elaboration Issues for Library Tasks:: 
26936 * Mixing Elaboration Models:: 
26937 * What to Do If the Default Elaboration Behavior Fails:: 
26938 * Elaboration for Indirect Calls:: 
26939 * Summary of Procedures for Elaboration Control:: 
26940 * Other Elaboration Order Considerations:: 
26941 * Determining the Chosen Elaboration Order:: 
26943 @end menu
26945 @node Elaboration Code,Checking the Elaboration Order,,Elaboration Order Handling in GNAT
26946 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{232}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{233}
26947 @section Elaboration Code
26950 Ada provides rather general mechanisms for executing code at elaboration
26951 time, that is to say before the main program starts executing. Such code arises
26952 in three contexts:
26955 @itemize *
26957 @item 
26958 @emph{Initializers for variables}
26960 Variables declared at the library level, in package specs or bodies, can
26961 require initialization that is performed at elaboration time, as in:
26963 @example
26964 Sqrt_Half : Float := Sqrt (0.5);
26965 @end example
26967 @item 
26968 @emph{Package initialization code}
26970 Code in a @cite{BEGIN-END} section at the outer level of a package body is
26971 executed as part of the package body elaboration code.
26973 @item 
26974 @emph{Library level task allocators}
26976 Tasks that are declared using task allocators at the library level
26977 start executing immediately and hence can execute at elaboration time.
26978 @end itemize
26980 Subprogram calls are possible in any of these contexts, which means that
26981 any arbitrary part of the program may be executed as part of the elaboration
26982 code. It is even possible to write a program which does all its work at
26983 elaboration time, with a null main program, although stylistically this
26984 would usually be considered an inappropriate way to structure
26985 a program.
26987 An important concern arises in the context of elaboration code:
26988 we have to be sure that it is executed in an appropriate order. What we
26989 have is a series of elaboration code sections, potentially one section
26990 for each unit in the program. It is important that these execute
26991 in the correct order. Correctness here means that, taking the above
26992 example of the declaration of @cite{Sqrt_Half},
26993 if some other piece of
26994 elaboration code references @cite{Sqrt_Half},
26995 then it must run after the
26996 section of elaboration code that contains the declaration of
26997 @cite{Sqrt_Half}.
26999 There would never be any order of elaboration problem if we made a rule
27000 that whenever you @emph{with} a unit, you must elaborate both the spec and body
27001 of that unit before elaborating the unit doing the @emph{with}ing:
27003 @example
27004 with Unit_1;
27005 package Unit_2 is ...
27006 @end example
27008 would require that both the body and spec of @cite{Unit_1} be elaborated
27009 before the spec of @cite{Unit_2}. However, a rule like that would be far too
27010 restrictive. In particular, it would make it impossible to have routines
27011 in separate packages that were mutually recursive.
27013 You might think that a clever enough compiler could look at the actual
27014 elaboration code and determine an appropriate correct order of elaboration,
27015 but in the general case, this is not possible. Consider the following
27016 example.
27018 In the body of @cite{Unit_1}, we have a procedure @cite{Func_1}
27019 that references
27020 the variable @cite{Sqrt_1}, which is declared in the elaboration code
27021 of the body of @cite{Unit_1}:
27023 @example
27024 Sqrt_1 : Float := Sqrt (0.1);
27025 @end example
27027 The elaboration code of the body of @cite{Unit_1} also contains:
27029 @example
27030 if expression_1 = 1 then
27031    Q := Unit_2.Func_2;
27032 end if;
27033 @end example
27035 @cite{Unit_2} is exactly parallel,
27036 it has a procedure @cite{Func_2} that references
27037 the variable @cite{Sqrt_2}, which is declared in the elaboration code of
27038 the body @cite{Unit_2}:
27040 @example
27041 Sqrt_2 : Float := Sqrt (0.1);
27042 @end example
27044 The elaboration code of the body of @cite{Unit_2} also contains:
27046 @example
27047 if expression_2 = 2 then
27048    Q := Unit_1.Func_1;
27049 end if;
27050 @end example
27052 Now the question is, which of the following orders of elaboration is
27053 acceptable:
27055 @example
27056 Spec of Unit_1
27057 Spec of Unit_2
27058 Body of Unit_1
27059 Body of Unit_2
27060 @end example
27064 @example
27065 Spec of Unit_2
27066 Spec of Unit_1
27067 Body of Unit_2
27068 Body of Unit_1
27069 @end example
27071 If you carefully analyze the flow here, you will see that you cannot tell
27072 at compile time the answer to this question.
27073 If @cite{expression_1} is not equal to 1,
27074 and @cite{expression_2} is not equal to 2,
27075 then either order is acceptable, because neither of the function calls is
27076 executed. If both tests evaluate to true, then neither order is acceptable
27077 and in fact there is no correct order.
27079 If one of the two expressions is true, and the other is false, then one
27080 of the above orders is correct, and the other is incorrect. For example,
27081 if @cite{expression_1} /= 1 and @cite{expression_2} = 2,
27082 then the call to @cite{Func_1}
27083 will occur, but not the call to @cite{Func_2.}
27084 This means that it is essential
27085 to elaborate the body of @cite{Unit_1} before
27086 the body of @cite{Unit_2}, so the first
27087 order of elaboration is correct and the second is wrong.
27089 By making @cite{expression_1} and @cite{expression_2}
27090 depend on input data, or perhaps
27091 the time of day, we can make it impossible for the compiler or binder
27092 to figure out which of these expressions will be true, and hence it
27093 is impossible to guarantee a safe order of elaboration at run time.
27095 @node Checking the Elaboration Order,Controlling the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
27096 @anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{234}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{235}
27097 @section Checking the Elaboration Order
27100 In some languages that involve the same kind of elaboration problems,
27101 e.g., Java and C++, the programmer needs to take these
27102 ordering problems into account, and it is common to
27103 write a program in which an incorrect elaboration order  gives
27104 surprising results, because it references variables before they
27105 are initialized.
27106 Ada is designed to be a safe language, and a programmer-beware approach is
27107 clearly not sufficient. Consequently, the language provides three lines
27108 of defense:
27111 @itemize *
27113 @item 
27114 @emph{Standard rules}
27116 Some standard rules restrict the possible choice of elaboration
27117 order. In particular, if you @emph{with} a unit, then its spec is always
27118 elaborated before the unit doing the @emph{with}. Similarly, a parent
27119 spec is always elaborated before the child spec, and finally
27120 a spec is always elaborated before its corresponding body.
27121 @end itemize
27123 @geindex Elaboration checks
27125 @geindex Checks
27126 @geindex elaboration
27129 @itemize *
27131 @item 
27132 @emph{Dynamic elaboration checks}
27134 Dynamic checks are made at run time, so that if some entity is accessed
27135 before it is elaborated (typically  by means of a subprogram call)
27136 then the exception (@cite{Program_Error}) is raised.
27138 @item 
27139 @emph{Elaboration control}
27141 Facilities are provided for the programmer to specify the desired order
27142 of elaboration.
27143 @end itemize
27145 Let's look at these facilities in more detail. First, the rules for
27146 dynamic checking. One possible rule would be simply to say that the
27147 exception is raised if you access a variable which has not yet been
27148 elaborated. The trouble with this approach is that it could require
27149 expensive checks on every variable reference. Instead Ada has two
27150 rules which are a little more restrictive, but easier to check, and
27151 easier to state:
27154 @itemize *
27156 @item 
27157 @emph{Restrictions on calls}
27159 A subprogram can only be called at elaboration time if its body
27160 has been elaborated. The rules for elaboration given above guarantee
27161 that the spec of the subprogram has been elaborated before the
27162 call, but not the body. If this rule is violated, then the
27163 exception @cite{Program_Error} is raised.
27165 @item 
27166 @emph{Restrictions on instantiations}
27168 A generic unit can only be instantiated if the body of the generic
27169 unit has been elaborated. Again, the rules for elaboration given above
27170 guarantee that the spec of the generic unit has been elaborated
27171 before the instantiation, but not the body. If this rule is
27172 violated, then the exception @cite{Program_Error} is raised.
27173 @end itemize
27175 The idea is that if the body has been elaborated, then any variables
27176 it references must have been elaborated; by checking for the body being
27177 elaborated we guarantee that none of its references causes any
27178 trouble. As we noted above, this is a little too restrictive, because a
27179 subprogram that has no non-local references in its body may in fact be safe
27180 to call. However, it really would be unsafe to rely on this, because
27181 it would mean that the caller was aware of details of the implementation
27182 in the body. This goes against the basic tenets of Ada.
27184 A plausible implementation can be described as follows.
27185 A Boolean variable is associated with each subprogram
27186 and each generic unit. This variable is initialized to False, and is set to
27187 True at the point body is elaborated. Every call or instantiation checks the
27188 variable, and raises @cite{Program_Error} if the variable is False.
27190 Note that one might think that it would be good enough to have one Boolean
27191 variable for each package, but that would not deal with cases of trying
27192 to call a body in the same package as the call
27193 that has not been elaborated yet.
27194 Of course a compiler may be able to do enough analysis to optimize away
27195 some of the Boolean variables as unnecessary, and @cite{GNAT} indeed
27196 does such optimizations, but still the easiest conceptual model is to
27197 think of there being one variable per subprogram.
27199 @node Controlling the Elaboration Order,Controlling Elaboration in GNAT - Internal Calls,Checking the Elaboration Order,Elaboration Order Handling in GNAT
27200 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{236}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order}@anchor{237}
27201 @section Controlling the Elaboration Order
27204 In the previous section we discussed the rules in Ada which ensure
27205 that @cite{Program_Error} is raised if an incorrect elaboration order is
27206 chosen. This prevents erroneous executions, but we need mechanisms to
27207 specify a correct execution and avoid the exception altogether.
27208 To achieve this, Ada provides a number of features for controlling
27209 the order of elaboration. We discuss these features in this section.
27211 First, there are several ways of indicating to the compiler that a given
27212 unit has no elaboration problems:
27215 @itemize *
27217 @item 
27218 @emph{packages that do not require a body}
27220 A library package that does not require a body does not permit
27221 a body (this rule was introduced in Ada 95).
27222 Thus if we have a such a package, as in:
27224 @example
27225 package Definitions is
27226    generic
27227       type m is new integer;
27228    package Subp is
27229       type a is array (1 .. 10) of m;
27230       type b is array (1 .. 20) of m;
27231    end Subp;
27232 end Definitions;
27233 @end example
27235 A package that @emph{with}s @cite{Definitions} may safely instantiate
27236 @cite{Definitions.Subp} because the compiler can determine that there
27237 definitely is no package body to worry about in this case
27238 @end itemize
27240 @geindex pragma Pure
27243 @itemize *
27245 @item 
27246 @emph{pragma Pure}
27248 This pragma places sufficient restrictions on a unit to guarantee that
27249 no call to any subprogram in the unit can result in an
27250 elaboration problem. This means that the compiler does not need
27251 to worry about the point of elaboration of such units, and in
27252 particular, does not need to check any calls to any subprograms
27253 in this unit.
27254 @end itemize
27256 @geindex pragma Preelaborate
27259 @itemize *
27261 @item 
27262 @emph{pragma Preelaborate}
27264 This pragma places slightly less stringent restrictions on a unit than
27265 does pragma Pure,
27266 but these restrictions are still sufficient to ensure that there
27267 are no elaboration problems with any calls to the unit.
27268 @end itemize
27270 @geindex pragma Elaborate_Body
27273 @itemize *
27275 @item 
27276 @emph{pragma Elaborate_Body}
27278 This pragma requires that the body of a unit be elaborated immediately
27279 after its spec. Suppose a unit @cite{A} has such a pragma,
27280 and unit @cite{B} does
27281 a @emph{with} of unit @cite{A}. Recall that the standard rules require
27282 the spec of unit @cite{A}
27283 to be elaborated before the @emph{with}ing unit; given the pragma in
27284 @cite{A}, we also know that the body of @cite{A}
27285 will be elaborated before @cite{B}, so
27286 that calls to @cite{A} are safe and do not need a check.
27288 Note that, unlike pragma @cite{Pure} and pragma @cite{Preelaborate},
27289 the use of @cite{Elaborate_Body} does not guarantee that the program is
27290 free of elaboration problems, because it may not be possible
27291 to satisfy the requested elaboration order.
27292 Let's go back to the example with @cite{Unit_1} and @cite{Unit_2}.
27293 If a programmer marks @cite{Unit_1} as @cite{Elaborate_Body},
27294 and not @cite{Unit_2@comma{}} then the order of
27295 elaboration will be:
27297 @example
27298 Spec of Unit_2
27299 Spec of Unit_1
27300 Body of Unit_1
27301 Body of Unit_2
27302 @end example
27304 Now that means that the call to @cite{Func_1} in @cite{Unit_2}
27305 need not be checked,
27306 it must be safe. But the call to @cite{Func_2} in
27307 @cite{Unit_1} may still fail if
27308 @cite{Expression_1} is equal to 1,
27309 and the programmer must still take
27310 responsibility for this not being the case.
27312 If all units carry a pragma @cite{Elaborate_Body}, then all problems are
27313 eliminated, except for calls entirely within a body, which are
27314 in any case fully under programmer control. However, using the pragma
27315 everywhere is not always possible.
27316 In particular, for our @cite{Unit_1}/@cite{Unit_2} example, if
27317 we marked both of them as having pragma @cite{Elaborate_Body}, then
27318 clearly there would be no possible elaboration order.
27319 @end itemize
27321 The above pragmas allow a server to guarantee safe use by clients, and
27322 clearly this is the preferable approach. Consequently a good rule
27323 is to mark units as @cite{Pure} or @cite{Preelaborate} if possible,
27324 and if this is not possible,
27325 mark them as @cite{Elaborate_Body} if possible.
27326 As we have seen, there are situations where neither of these
27327 three pragmas can be used.
27328 So we also provide methods for clients to control the
27329 order of elaboration of the servers on which they depend:
27331 @geindex pragma Elaborate
27334 @itemize *
27336 @item 
27337 @emph{pragma Elaborate (unit)}
27339 This pragma is placed in the context clause, after a @emph{with} clause,
27340 and it requires that the body of the named unit be elaborated before
27341 the unit in which the pragma occurs. The idea is to use this pragma
27342 if the current unit calls at elaboration time, directly or indirectly,
27343 some subprogram in the named unit.
27344 @end itemize
27346 @geindex pragma Elaborate_All
27349 @itemize *
27351 @item 
27352 @emph{pragma Elaborate_All (unit)}
27354 This is a stronger version of the Elaborate pragma. Consider the
27355 following example:
27357 @example
27358 Unit A |withs| unit B and calls B.Func in elab code
27359 Unit B |withs| unit C, and B.Func calls C.Func
27360 @end example
27362 Now if we put a pragma @cite{Elaborate (B)}
27363 in unit @cite{A}, this ensures that the
27364 body of @cite{B} is elaborated before the call, but not the
27365 body of @cite{C}, so
27366 the call to @cite{C.Func} could still cause @cite{Program_Error} to
27367 be raised.
27369 The effect of a pragma @cite{Elaborate_All} is stronger, it requires
27370 not only that the body of the named unit be elaborated before the
27371 unit doing the @emph{with}, but also the bodies of all units that the
27372 named unit uses, following @emph{with} links transitively. For example,
27373 if we put a pragma @cite{Elaborate_All (B)} in unit @cite{A},
27374 then it requires not only that the body of @cite{B} be elaborated before @cite{A},
27375 but also the body of @cite{C}, because @cite{B} @emph{with}s @cite{C}.
27376 @end itemize
27378 We are now in a position to give a usage rule in Ada for avoiding
27379 elaboration problems, at least if dynamic dispatching and access to
27380 subprogram values are not used. We will handle these cases separately
27381 later.
27383 The rule is simple:
27385 @emph{If a unit has elaboration code that can directly or
27386 indirectly make a call to a subprogram in a |withed| unit, or instantiate
27387 a generic package in a |withed| unit,
27388 then if the |withed| unit does not have
27389 pragma `Pure` or `Preelaborate`, then the client should have
27390 a pragma `Elaborate_All`for the |withed| unit.*}
27392 By following this rule a client is
27393 assured that calls can be made without risk of an exception.
27395 For generic subprogram instantiations, the rule can be relaxed to
27396 require only a pragma @cite{Elaborate} since elaborating the body
27397 of a subprogram cannot cause any transitive elaboration (we are
27398 not calling the subprogram in this case, just elaborating its
27399 declaration).
27401 If this rule is not followed, then a program may be in one of four
27402 states:
27405 @itemize *
27407 @item 
27408 @emph{No order exists}
27410 No order of elaboration exists which follows the rules, taking into
27411 account any @cite{Elaborate}, @cite{Elaborate_All},
27412 or @cite{Elaborate_Body} pragmas. In
27413 this case, an Ada compiler must diagnose the situation at bind
27414 time, and refuse to build an executable program.
27416 @item 
27417 @emph{One or more orders exist, all incorrect}
27419 One or more acceptable elaboration orders exist, and all of them
27420 generate an elaboration order problem. In this case, the binder
27421 can build an executable program, but @cite{Program_Error} will be raised
27422 when the program is run.
27424 @item 
27425 @emph{Several orders exist, some right, some incorrect}
27427 One or more acceptable elaboration orders exists, and some of them
27428 work, and some do not. The programmer has not controlled
27429 the order of elaboration, so the binder may or may not pick one of
27430 the correct orders, and the program may or may not raise an
27431 exception when it is run. This is the worst case, because it means
27432 that the program may fail when moved to another compiler, or even
27433 another version of the same compiler.
27435 @item 
27436 @emph{One or more orders exists, all correct}
27438 One ore more acceptable elaboration orders exist, and all of them
27439 work. In this case the program runs successfully. This state of
27440 affairs can be guaranteed by following the rule we gave above, but
27441 may be true even if the rule is not followed.
27442 @end itemize
27444 Note that one additional advantage of following our rules on the use
27445 of @cite{Elaborate} and @cite{Elaborate_All}
27446 is that the program continues to stay in the ideal (all orders OK) state
27447 even if maintenance
27448 changes some bodies of some units. Conversely, if a program that does
27449 not follow this rule happens to be safe at some point, this state of affairs
27450 may deteriorate silently as a result of maintenance changes.
27452 You may have noticed that the above discussion did not mention
27453 the use of @cite{Elaborate_Body}. This was a deliberate omission. If you
27454 @emph{with} an @cite{Elaborate_Body} unit, it still may be the case that
27455 code in the body makes calls to some other unit, so it is still necessary
27456 to use @cite{Elaborate_All} on such units.
27458 @node Controlling Elaboration in GNAT - Internal Calls,Controlling Elaboration in GNAT - External Calls,Controlling the Elaboration Order,Elaboration Order Handling in GNAT
27459 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{238}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-internal-calls}@anchor{239}
27460 @section Controlling Elaboration in GNAT - Internal Calls
27463 In the case of internal calls, i.e., calls within a single package, the
27464 programmer has full control over the order of elaboration, and it is up
27465 to the programmer to elaborate declarations in an appropriate order. For
27466 example writing:
27468 @example
27469 function One return Float;
27471 Q : Float := One;
27473 function One return Float is
27474 begin
27475      return 1.0;
27476 end One;
27477 @end example
27479 will obviously raise @cite{Program_Error} at run time, because function
27480 One will be called before its body is elaborated. In this case GNAT will
27481 generate a warning that the call will raise @cite{Program_Error}:
27483 @example
27484  1. procedure y is
27485  2.    function One return Float;
27486  3.
27487  4.    Q : Float := One;
27488                     |
27489     >>> warning: cannot call "One" before body is elaborated
27490     >>> warning: Program_Error will be raised at run time
27492  5.
27493  6.    function One return Float is
27494  7.    begin
27495  8.         return 1.0;
27496  9.    end One;
27498 11. begin
27499 12.    null;
27500 13. end;
27501 @end example
27503 Note that in this particular case, it is likely that the call is safe, because
27504 the function @cite{One} does not access any global variables.
27505 Nevertheless in Ada, we do not want the validity of the check to depend on
27506 the contents of the body (think about the separate compilation case), so this
27507 is still wrong, as we discussed in the previous sections.
27509 The error is easily corrected by rearranging the declarations so that the
27510 body of @cite{One} appears before the declaration containing the call
27511 (note that in Ada 95 as well as later versions of the Ada standard,
27512 declarations can appear in any order, so there is no restriction that
27513 would prevent this reordering, and if we write:
27515 @example
27516 function One return Float;
27518 function One return Float is
27519 begin
27520      return 1.0;
27521 end One;
27523 Q : Float := One;
27524 @end example
27526 then all is well, no warning is generated, and no
27527 @cite{Program_Error} exception
27528 will be raised.
27529 Things are more complicated when a chain of subprograms is executed:
27531 @example
27532 function A return Integer;
27533 function B return Integer;
27534 function C return Integer;
27536 function B return Integer is begin return A; end;
27537 function C return Integer is begin return B; end;
27539 X : Integer := C;
27541 function A return Integer is begin return 1; end;
27542 @end example
27544 Now the call to @cite{C}
27545 at elaboration time in the declaration of @cite{X} is correct, because
27546 the body of @cite{C} is already elaborated,
27547 and the call to @cite{B} within the body of
27548 @cite{C} is correct, but the call
27549 to @cite{A} within the body of @cite{B} is incorrect, because the body
27550 of @cite{A} has not been elaborated, so @cite{Program_Error}
27551 will be raised on the call to @cite{A}.
27552 In this case GNAT will generate a
27553 warning that @cite{Program_Error} may be
27554 raised at the point of the call. Let's look at the warning:
27556 @example
27557  1. procedure x is
27558  2.    function A return Integer;
27559  3.    function B return Integer;
27560  4.    function C return Integer;
27561  5.
27562  6.    function B return Integer is begin return A; end;
27563                                                     |
27564     >>> warning: call to "A" before body is elaborated may
27565                  raise Program_Error
27566     >>> warning: "B" called at line 7
27567     >>> warning: "C" called at line 9
27569  7.    function C return Integer is begin return B; end;
27570  8.
27571  9.    X : Integer := C;
27573 11.    function A return Integer is begin return 1; end;
27575 13. begin
27576 14.    null;
27577 15. end;
27578 @end example
27580 Note that the message here says 'may raise', instead of the direct case,
27581 where the message says 'will be raised'. That's because whether
27582 @cite{A} is
27583 actually called depends in general on run-time flow of control.
27584 For example, if the body of @cite{B} said
27586 @example
27587 function B return Integer is
27588 begin
27589    if some-condition-depending-on-input-data then
27590       return A;
27591    else
27592       return 1;
27593    end if;
27594 end B;
27595 @end example
27597 then we could not know until run time whether the incorrect call to A would
27598 actually occur, so @cite{Program_Error} might
27599 or might not be raised. It is possible for a compiler to
27600 do a better job of analyzing bodies, to
27601 determine whether or not @cite{Program_Error}
27602 might be raised, but it certainly
27603 couldn't do a perfect job (that would require solving the halting problem
27604 and is provably impossible), and because this is a warning anyway, it does
27605 not seem worth the effort to do the analysis. Cases in which it
27606 would be relevant are rare.
27608 In practice, warnings of either of the forms given
27609 above will usually correspond to
27610 real errors, and should be examined carefully and eliminated.
27611 In the rare case where a warning is bogus, it can be suppressed by any of
27612 the following methods:
27615 @itemize *
27617 @item 
27618 Compile with the @emph{-gnatws} switch set
27620 @item 
27621 Suppress @cite{Elaboration_Check} for the called subprogram
27623 @item 
27624 Use pragma @cite{Warnings_Off} to turn warnings off for the call
27625 @end itemize
27627 For the internal elaboration check case,
27628 GNAT by default generates the
27629 necessary run-time checks to ensure
27630 that @cite{Program_Error} is raised if any
27631 call fails an elaboration check. Of course this can only happen if a
27632 warning has been issued as described above. The use of pragma
27633 @cite{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
27634 some of these checks, meaning that it may be possible (but is not
27635 guaranteed) for a program to be able to call a subprogram whose body
27636 is not yet elaborated, without raising a @cite{Program_Error} exception.
27638 @node Controlling Elaboration in GNAT - External Calls,Default Behavior in GNAT - Ensuring Safety,Controlling Elaboration in GNAT - Internal Calls,Elaboration Order Handling in GNAT
27639 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{23a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-external-calls}@anchor{23b}
27640 @section Controlling Elaboration in GNAT - External Calls
27643 The previous section discussed the case in which the execution of a
27644 particular thread of elaboration code occurred entirely within a
27645 single unit. This is the easy case to handle, because a programmer
27646 has direct and total control over the order of elaboration, and
27647 furthermore, checks need only be generated in cases which are rare
27648 and which the compiler can easily detect.
27649 The situation is more complex when separate compilation is taken into account.
27650 Consider the following:
27652 @example
27653 package Math is
27654    function Sqrt (Arg : Float) return Float;
27655 end Math;
27657 package body Math is
27658    function Sqrt (Arg : Float) return Float is
27659    begin
27660          ...
27661    end Sqrt;
27662 end Math;
27664 with Math;
27665 package Stuff is
27666    X : Float := Math.Sqrt (0.5);
27667 end Stuff;
27669 with Stuff;
27670 procedure Main is
27671 begin
27672    ...
27673 end Main;
27674 @end example
27676 where @cite{Main} is the main program. When this program is executed, the
27677 elaboration code must first be executed, and one of the jobs of the
27678 binder is to determine the order in which the units of a program are
27679 to be elaborated. In this case we have four units: the spec and body
27680 of @cite{Math},
27681 the spec of @cite{Stuff} and the body of @cite{Main}).
27682 In what order should the four separate sections of elaboration code
27683 be executed?
27685 There are some restrictions in the order of elaboration that the binder
27686 can choose. In particular, if unit U has a @emph{with}
27687 for a package @cite{X}, then you
27688 are assured that the spec of @cite{X}
27689 is elaborated before U , but you are
27690 not assured that the body of @cite{X}
27691 is elaborated before U.
27692 This means that in the above case, the binder is allowed to choose the
27693 order:
27695 @example
27696 spec of Math
27697 spec of Stuff
27698 body of Math
27699 body of Main
27700 @end example
27702 but that's not good, because now the call to @cite{Math.Sqrt}
27703 that happens during
27704 the elaboration of the @cite{Stuff}
27705 spec happens before the body of @cite{Math.Sqrt} is
27706 elaborated, and hence causes @cite{Program_Error} exception to be raised.
27707 At first glance, one might say that the binder is misbehaving, because
27708 obviously you want to elaborate the body of something you @emph{with} first, but
27709 that is not a general rule that can be followed in all cases. Consider
27711 @example
27712 package X is ...
27714 package Y is ...
27716 with X;
27717 package body Y is ...
27719 with Y;
27720 package body X is ...
27721 @end example
27723 This is a common arrangement, and, apart from the order of elaboration
27724 problems that might arise in connection with elaboration code, this works fine.
27725 A rule that says that you must first elaborate the body of anything you
27726 @emph{with} cannot work in this case:
27727 the body of @cite{X} @emph{with}s @cite{Y},
27728 which means you would have to
27729 elaborate the body of @cite{Y} first, but that @emph{with}s @cite{X},
27730 which means
27731 you have to elaborate the body of @cite{X} first, but ... and we have a
27732 loop that cannot be broken.
27734 It is true that the binder can in many cases guess an order of elaboration
27735 that is unlikely to cause a @cite{Program_Error}
27736 exception to be raised, and it tries to do so (in the
27737 above example of @cite{Math/Stuff/Spec}, the GNAT binder will
27738 by default
27739 elaborate the body of @cite{Math} right after its spec, so all will be well).
27741 However, a program that blindly relies on the binder to be helpful can
27742 get into trouble, as we discussed in the previous sections, so GNAT
27743 provides a number of facilities for assisting the programmer in
27744 developing programs that are robust with respect to elaboration order.
27746 @node Default Behavior in GNAT - Ensuring Safety,Treatment of Pragma Elaborate,Controlling Elaboration in GNAT - External Calls,Elaboration Order Handling in GNAT
27747 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{23c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat default-behavior-in-gnat-ensuring-safety}@anchor{23d}
27748 @section Default Behavior in GNAT - Ensuring Safety
27751 The default behavior in GNAT ensures elaboration safety. In its
27752 default mode GNAT implements the
27753 rule we previously described as the right approach. Let's restate it:
27755 @emph{If a unit has elaboration code that can directly or indirectly make a
27756 call to a subprogram in a |withed| unit, or instantiate a generic
27757 package in a |withed| unit, then if the |withed| unit
27758 does not have pragma `Pure` or `Preelaborate`, then the client should have an
27759 `Elaborate_All` pragma for the |withed| unit.}
27761 @emph{In the case of instantiating a generic subprogram, it is always
27762 sufficient to have only an `Elaborate` pragma for the
27763 |withed| unit.}
27765 By following this rule a client is assured that calls and instantiations
27766 can be made without risk of an exception.
27768 In this mode GNAT traces all calls that are potentially made from
27769 elaboration code, and puts in any missing implicit @cite{Elaborate}
27770 and @cite{Elaborate_All} pragmas.
27771 The advantage of this approach is that no elaboration problems
27772 are possible if the binder can find an elaboration order that is
27773 consistent with these implicit @cite{Elaborate} and
27774 @cite{Elaborate_All} pragmas. The
27775 disadvantage of this approach is that no such order may exist.
27777 If the binder does not generate any diagnostics, then it means that it has
27778 found an elaboration order that is guaranteed to be safe. However, the binder
27779 may still be relying on implicitly generated @cite{Elaborate} and
27780 @cite{Elaborate_All} pragmas so portability to other compilers than GNAT is not
27781 guaranteed.
27783 If it is important to guarantee portability, then the compilations should
27784 use the @emph{-gnatel}
27785 (info messages for elaboration pragmas) switch. This will cause info messages
27786 to be generated indicating the missing @cite{Elaborate} and
27787 @cite{Elaborate_All} pragmas.
27788 Consider the following source program:
27790 @example
27791 with k;
27792 package j is
27793   m : integer := k.r;
27794 end;
27795 @end example
27797 where it is clear that there
27798 should be a pragma @cite{Elaborate_All}
27799 for unit @cite{k}. An implicit pragma will be generated, and it is
27800 likely that the binder will be able to honor it. However, if you want
27801 to port this program to some other Ada compiler than GNAT.
27802 it is safer to include the pragma explicitly in the source. If this
27803 unit is compiled with the @emph{-gnatel}
27804 switch, then the compiler outputs an information message:
27806 @example
27807 1. with k;
27808 2. package j is
27809 3.   m : integer := k.r;
27810                      |
27811    >>> info: call to "r" may raise Program_Error
27812    >>> info: missing pragma Elaborate_All for "k"
27814 4. end;
27815 @end example
27817 and these messages can be used as a guide for supplying manually
27818 the missing pragmas. It is usually a bad idea to use this
27819 option during development. That's because it will tell you when
27820 you need to put in a pragma, but cannot tell you when it is time
27821 to take it out. So the use of pragma @cite{Elaborate_All} may lead to
27822 unnecessary dependencies and even false circularities.
27824 This default mode is more restrictive than the Ada Reference
27825 Manual, and it is possible to construct programs which will compile
27826 using the dynamic model described there, but will run into a
27827 circularity using the safer static model we have described.
27829 Of course any Ada compiler must be able to operate in a mode
27830 consistent with the requirements of the Ada Reference Manual,
27831 and in particular must have the capability of implementing the
27832 standard dynamic model of elaboration with run-time checks.
27834 In GNAT, this standard mode can be achieved either by the use of
27835 the @emph{-gnatE} switch on the compiler (@emph{gcc} or
27836 @emph{gnatmake}) command, or by the use of the configuration pragma:
27838 @example
27839 pragma Elaboration_Checks (DYNAMIC);
27840 @end example
27842 Either approach will cause the unit affected to be compiled using the
27843 standard dynamic run-time elaboration checks described in the Ada
27844 Reference Manual. The static model is generally preferable, since it
27845 is clearly safer to rely on compile and link time checks rather than
27846 run-time checks. However, in the case of legacy code, it may be
27847 difficult to meet the requirements of the static model. This
27848 issue is further discussed in
27849 @ref{23e,,What to Do If the Default Elaboration Behavior Fails}.
27851 Note that the static model provides a strict subset of the allowed
27852 behavior and programs of the Ada Reference Manual, so if you do
27853 adhere to the static model and no circularities exist,
27854 then you are assured that your program will
27855 work using the dynamic model, providing that you remove any
27856 pragma Elaborate statements from the source.
27858 @node Treatment of Pragma Elaborate,Elaboration Issues for Library Tasks,Default Behavior in GNAT - Ensuring Safety,Elaboration Order Handling in GNAT
27859 @anchor{gnat_ugn/elaboration_order_handling_in_gnat treatment-of-pragma-elaborate}@anchor{23f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{240}
27860 @section Treatment of Pragma Elaborate
27863 @geindex Pragma Elaborate
27865 The use of @cite{pragma Elaborate}
27866 should generally be avoided in Ada 95 and Ada 2005 programs,
27867 since there is no guarantee that transitive calls
27868 will be properly handled. Indeed at one point, this pragma was placed
27869 in Annex J (Obsolescent Features), on the grounds that it is never useful.
27871 Now that's a bit restrictive. In practice, the case in which
27872 @cite{pragma Elaborate} is useful is when the caller knows that there
27873 are no transitive calls, or that the called unit contains all necessary
27874 transitive @cite{pragma Elaborate} statements, and legacy code often
27875 contains such uses.
27877 Strictly speaking the static mode in GNAT should ignore such pragmas,
27878 since there is no assurance at compile time that the necessary safety
27879 conditions are met. In practice, this would cause GNAT to be incompatible
27880 with correctly written Ada 83 code that had all necessary
27881 @cite{pragma Elaborate} statements in place. Consequently, we made the
27882 decision that GNAT in its default mode will believe that if it encounters
27883 a @cite{pragma Elaborate} then the programmer knows what they are doing,
27884 and it will trust that no elaboration errors can occur.
27886 The result of this decision is two-fold. First to be safe using the
27887 static mode, you should remove all @cite{pragma Elaborate} statements.
27888 Second, when fixing circularities in existing code, you can selectively
27889 use @cite{pragma Elaborate} statements to convince the static mode of
27890 GNAT that it need not generate an implicit @cite{pragma Elaborate_All}
27891 statement.
27893 When using the static mode with @emph{-gnatwl}, any use of
27894 @cite{pragma Elaborate} will generate a warning about possible
27895 problems.
27897 @node Elaboration Issues for Library Tasks,Mixing Elaboration Models,Treatment of Pragma Elaborate,Elaboration Order Handling in GNAT
27898 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-issues-for-library-tasks}@anchor{241}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{242}
27899 @section Elaboration Issues for Library Tasks
27902 @geindex Library tasks
27903 @geindex elaboration issues
27905 @geindex Elaboration of library tasks
27907 In this section we examine special elaboration issues that arise for
27908 programs that declare library level tasks.
27910 Generally the model of execution of an Ada program is that all units are
27911 elaborated, and then execution of the program starts. However, the
27912 declaration of library tasks definitely does not fit this model. The
27913 reason for this is that library tasks start as soon as they are declared
27914 (more precisely, as soon as the statement part of the enclosing package
27915 body is reached), that is to say before elaboration
27916 of the program is complete. This means that if such a task calls a
27917 subprogram, or an entry in another task, the callee may or may not be
27918 elaborated yet, and in the standard
27919 Reference Manual model of dynamic elaboration checks, you can even
27920 get timing dependent Program_Error exceptions, since there can be
27921 a race between the elaboration code and the task code.
27923 The static model of elaboration in GNAT seeks to avoid all such
27924 dynamic behavior, by being conservative, and the conservative
27925 approach in this particular case is to assume that all the code
27926 in a task body is potentially executed at elaboration time if
27927 a task is declared at the library level.
27929 This can definitely result in unexpected circularities. Consider
27930 the following example
27932 @example
27933 package Decls is
27934   task Lib_Task is
27935      entry Start;
27936   end Lib_Task;
27938   type My_Int is new Integer;
27940   function Ident (M : My_Int) return My_Int;
27941 end Decls;
27943 with Utils;
27944 package body Decls is
27945   task body Lib_Task is
27946   begin
27947      accept Start;
27948      Utils.Put_Val (2);
27949   end Lib_Task;
27951   function Ident (M : My_Int) return My_Int is
27952   begin
27953      return M;
27954   end Ident;
27955 end Decls;
27957 with Decls;
27958 package Utils is
27959   procedure Put_Val (Arg : Decls.My_Int);
27960 end Utils;
27962 with Text_IO;
27963 package body Utils is
27964   procedure Put_Val (Arg : Decls.My_Int) is
27965   begin
27966      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
27967   end Put_Val;
27968 end Utils;
27970 with Decls;
27971 procedure Main is
27972 begin
27973    Decls.Lib_Task.Start;
27974 end;
27975 @end example
27977 If the above example is compiled in the default static elaboration
27978 mode, then a circularity occurs. The circularity comes from the call
27979 @cite{Utils.Put_Val} in the task body of @cite{Decls.Lib_Task}. Since
27980 this call occurs in elaboration code, we need an implicit pragma
27981 @cite{Elaborate_All} for @cite{Utils}. This means that not only must
27982 the spec and body of @cite{Utils} be elaborated before the body
27983 of @cite{Decls}, but also the spec and body of any unit that is
27984 @emph{with}ed by the body of @cite{Utils} must also be elaborated before
27985 the body of @cite{Decls}. This is the transitive implication of
27986 pragma @cite{Elaborate_All} and it makes sense, because in general
27987 the body of @cite{Put_Val} might have a call to something in a
27988 @emph{with}ed unit.
27990 In this case, the body of Utils (actually its spec) @emph{with}s
27991 @cite{Decls}. Unfortunately this means that the body of @cite{Decls}
27992 must be elaborated before itself, in case there is a call from the
27993 body of @cite{Utils}.
27995 Here is the exact chain of events we are worrying about:
27998 @itemize *
28000 @item 
28001 In the body of @cite{Decls} a call is made from within the body of a library
28002 task to a subprogram in the package @cite{Utils}. Since this call may
28003 occur at elaboration time (given that the task is activated at elaboration
28004 time), we have to assume the worst, i.e., that the
28005 call does happen at elaboration time.
28007 @item 
28008 This means that the body and spec of @cite{Util} must be elaborated before
28009 the body of @cite{Decls} so that this call does not cause an access before
28010 elaboration.
28012 @item 
28013 Within the body of @cite{Util}, specifically within the body of
28014 @cite{Util.Put_Val} there may be calls to any unit @emph{with}ed
28015 by this package.
28017 @item 
28018 One such @emph{with}ed package is package @cite{Decls}, so there
28019 might be a call to a subprogram in @cite{Decls} in @cite{Put_Val}.
28020 In fact there is such a call in this example, but we would have to
28021 assume that there was such a call even if it were not there, since
28022 we are not supposed to write the body of @cite{Decls} knowing what
28023 is in the body of @cite{Utils}; certainly in the case of the
28024 static elaboration model, the compiler does not know what is in
28025 other bodies and must assume the worst.
28027 @item 
28028 This means that the spec and body of @cite{Decls} must also be
28029 elaborated before we elaborate the unit containing the call, but
28030 that unit is @cite{Decls}! This means that the body of @cite{Decls}
28031 must be elaborated before itself, and that's a circularity.
28032 @end itemize
28034 Indeed, if you add an explicit pragma @cite{Elaborate_All} for @cite{Utils} in
28035 the body of @cite{Decls} you will get a true Ada Reference Manual
28036 circularity that makes the program illegal.
28038 In practice, we have found that problems with the static model of
28039 elaboration in existing code often arise from library tasks, so
28040 we must address this particular situation.
28042 Note that if we compile and run the program above, using the dynamic model of
28043 elaboration (that is to say use the @emph{-gnatE} switch),
28044 then it compiles, binds,
28045 links, and runs, printing the expected result of 2. Therefore in some sense
28046 the circularity here is only apparent, and we need to capture
28047 the properties of this program that  distinguish it from other library-level
28048 tasks that have real elaboration problems.
28050 We have four possible answers to this question:
28053 @itemize *
28055 @item 
28056 Use the dynamic model of elaboration.
28058 If we use the @emph{-gnatE} switch, then as noted above, the program works.
28059 Why is this? If we examine the task body, it is apparent that the task cannot
28060 proceed past the
28061 @cite{accept} statement until after elaboration has been completed, because
28062 the corresponding entry call comes from the main program, not earlier.
28063 This is why the dynamic model works here. But that's really giving
28064 up on a precise analysis, and we prefer to take this approach only if we cannot
28065 solve the
28066 problem in any other manner. So let us examine two ways to reorganize
28067 the program to avoid the potential elaboration problem.
28069 @item 
28070 Split library tasks into separate packages.
28072 Write separate packages, so that library tasks are isolated from
28073 other declarations as much as possible. Let us look at a variation on
28074 the above program.
28076 @example
28077 package Decls1 is
28078   task Lib_Task is
28079      entry Start;
28080   end Lib_Task;
28081 end Decls1;
28083 with Utils;
28084 package body Decls1 is
28085   task body Lib_Task is
28086   begin
28087      accept Start;
28088      Utils.Put_Val (2);
28089   end Lib_Task;
28090 end Decls1;
28092 package Decls2 is
28093   type My_Int is new Integer;
28094   function Ident (M : My_Int) return My_Int;
28095 end Decls2;
28097 with Utils;
28098 package body Decls2 is
28099   function Ident (M : My_Int) return My_Int is
28100   begin
28101      return M;
28102   end Ident;
28103 end Decls2;
28105 with Decls2;
28106 package Utils is
28107   procedure Put_Val (Arg : Decls2.My_Int);
28108 end Utils;
28110 with Text_IO;
28111 package body Utils is
28112   procedure Put_Val (Arg : Decls2.My_Int) is
28113   begin
28114      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
28115   end Put_Val;
28116 end Utils;
28118 with Decls1;
28119 procedure Main is
28120 begin
28121    Decls1.Lib_Task.Start;
28122 end;
28123 @end example
28125 All we have done is to split @cite{Decls} into two packages, one
28126 containing the library task, and one containing everything else. Now
28127 there is no cycle, and the program compiles, binds, links and executes
28128 using the default static model of elaboration.
28130 @item 
28131 Declare separate task types.
28133 A significant part of the problem arises because of the use of the
28134 single task declaration form. This means that the elaboration of
28135 the task type, and the elaboration of the task itself (i.e., the
28136 creation of the task) happen at the same time. A good rule
28137 of style in Ada is to always create explicit task types. By
28138 following the additional step of placing task objects in separate
28139 packages from the task type declaration, many elaboration problems
28140 are avoided. Here is another modified example of the example program:
28142 @example
28143 package Decls is
28144   task type Lib_Task_Type is
28145      entry Start;
28146   end Lib_Task_Type;
28148   type My_Int is new Integer;
28150   function Ident (M : My_Int) return My_Int;
28151 end Decls;
28153 with Utils;
28154 package body Decls is
28155   task body Lib_Task_Type is
28156   begin
28157      accept Start;
28158      Utils.Put_Val (2);
28159   end Lib_Task_Type;
28161   function Ident (M : My_Int) return My_Int is
28162   begin
28163      return M;
28164   end Ident;
28165 end Decls;
28167 with Decls;
28168 package Utils is
28169   procedure Put_Val (Arg : Decls.My_Int);
28170 end Utils;
28172 with Text_IO;
28173 package body Utils is
28174   procedure Put_Val (Arg : Decls.My_Int) is
28175   begin
28176      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
28177   end Put_Val;
28178 end Utils;
28180 with Decls;
28181 package Declst is
28182    Lib_Task : Decls.Lib_Task_Type;
28183 end Declst;
28185 with Declst;
28186 procedure Main is
28187 begin
28188    Declst.Lib_Task.Start;
28189 end;
28190 @end example
28192 What we have done here is to replace the @cite{task} declaration in
28193 package @cite{Decls} with a @cite{task type} declaration. Then we
28194 introduce a separate package @cite{Declst} to contain the actual
28195 task object. This separates the elaboration issues for
28196 the @cite{task type}
28197 declaration, which causes no trouble, from the elaboration issues
28198 of the task object, which is also unproblematic, since it is now independent
28199 of the elaboration of  @cite{Utils}.
28200 This separation of concerns also corresponds to
28201 a generally sound engineering principle of separating declarations
28202 from instances. This version of the program also compiles, binds, links,
28203 and executes, generating the expected output.
28204 @end itemize
28206 @geindex No_Entry_Calls_In_Elaboration_Code restriction
28209 @itemize *
28211 @item 
28212 Use No_Entry_Calls_In_Elaboration_Code restriction.
28214 The previous two approaches described how a program can be restructured
28215 to avoid the special problems caused by library task bodies. in practice,
28216 however, such restructuring may be difficult to apply to existing legacy code,
28217 so we must consider solutions that do not require massive rewriting.
28219 Let us consider more carefully why our original sample program works
28220 under the dynamic model of elaboration. The reason is that the code
28221 in the task body blocks immediately on the @cite{accept}
28222 statement. Now of course there is nothing to prohibit elaboration
28223 code from making entry calls (for example from another library level task),
28224 so we cannot tell in isolation that
28225 the task will not execute the accept statement  during elaboration.
28227 However, in practice it is very unusual to see elaboration code
28228 make any entry calls, and the pattern of tasks starting
28229 at elaboration time and then immediately blocking on @cite{accept} or
28230 @cite{select} statements is very common. What this means is that
28231 the compiler is being too pessimistic when it analyzes the
28232 whole package body as though it might be executed at elaboration
28233 time.
28235 If we know that the elaboration code contains no entry calls, (a very safe
28236 assumption most of the time, that could almost be made the default
28237 behavior), then we can compile all units of the program under control
28238 of the following configuration pragma:
28240 @example
28241 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28242 @end example
28244 This pragma can be placed in the @code{gnat.adc} file in the usual
28245 manner. If we take our original unmodified program and compile it
28246 in the presence of a @code{gnat.adc} containing the above pragma,
28247 then once again, we can compile, bind, link, and execute, obtaining
28248 the expected result. In the presence of this pragma, the compiler does
28249 not trace calls in a task body, that appear after the first @cite{accept}
28250 or @cite{select} statement, and therefore does not report a potential
28251 circularity in the original program.
28253 The compiler will check to the extent it can that the above
28254 restriction is not violated, but it is not always possible to do a
28255 complete check at compile time, so it is important to use this
28256 pragma only if the stated restriction is in fact met, that is to say
28257 no task receives an entry call before elaboration of all units is completed.
28258 @end itemize
28260 @node Mixing Elaboration Models,What to Do If the Default Elaboration Behavior Fails,Elaboration Issues for Library Tasks,Elaboration Order Handling in GNAT
28261 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{243}@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{244}
28262 @section Mixing Elaboration Models
28265 So far, we have assumed that the entire program is either compiled
28266 using the dynamic model or static model, ensuring consistency. It
28267 is possible to mix the two models, but rules have to be followed
28268 if this mixing is done to ensure that elaboration checks are not
28269 omitted.
28271 The basic rule is that
28272 @strong{a unit compiled with the static model cannot
28273 be |withed| by a unit compiled with the dynamic model}.
28274 The reason for this is that in the static model, a unit assumes that
28275 its clients guarantee to use (the equivalent of) pragma
28276 @cite{Elaborate_All} so that no elaboration checks are required
28277 in inner subprograms, and this assumption is violated if the
28278 client is compiled with dynamic checks.
28280 The precise rule is as follows. A unit that is compiled with dynamic
28281 checks can only @emph{with} a unit that meets at least one of the
28282 following criteria:
28285 @itemize *
28287 @item 
28288 The @emph{with}ed unit is itself compiled with dynamic elaboration
28289 checks (that is with the @emph{-gnatE} switch.
28291 @item 
28292 The @emph{with}ed unit is an internal GNAT implementation unit from
28293 the System, Interfaces, Ada, or GNAT hierarchies.
28295 @item 
28296 The @emph{with}ed unit has pragma Preelaborate or pragma Pure.
28298 @item 
28299 The @emph{with}ing unit (that is the client) has an explicit pragma
28300 @cite{Elaborate_All} for the @emph{with}ed unit.
28301 @end itemize
28303 If this rule is violated, that is if a unit with dynamic elaboration
28304 checks @emph{with}s a unit that does not meet one of the above four
28305 criteria, then the binder (@cite{gnatbind}) will issue a warning
28306 similar to that in the following example:
28308 @example
28309 warning: "x.ads" has dynamic elaboration checks and with's
28310 warning:   "y.ads" which has static elaboration checks
28311 @end example
28313 These warnings indicate that the rule has been violated, and that as a result
28314 elaboration checks may be missed in the resulting executable file.
28315 This warning may be suppressed using the @emph{-ws} binder switch
28316 in the usual manner.
28318 One useful application of this mixing rule is in the case of a subsystem
28319 which does not itself @emph{with} units from the remainder of the
28320 application. In this case, the entire subsystem can be compiled with
28321 dynamic checks to resolve a circularity in the subsystem, while
28322 allowing the main application that uses this subsystem to be compiled
28323 using the more reliable default static model.
28325 @node What to Do If the Default Elaboration Behavior Fails,Elaboration for Indirect Calls,Mixing Elaboration Models,Elaboration Order Handling in GNAT
28326 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{245}@anchor{gnat_ugn/elaboration_order_handling_in_gnat what-to-do-if-the-default-elaboration-behavior-fails}@anchor{23e}
28327 @section What to Do If the Default Elaboration Behavior Fails
28330 If the binder cannot find an acceptable order, it outputs detailed
28331 diagnostics. For example:
28333 @example
28334 error: elaboration circularity detected
28335 info:   "proc (body)" must be elaborated before "pack (body)"
28336 info:     reason: Elaborate_All probably needed in unit "pack (body)"
28337 info:     recompile "pack (body)" with -gnatel
28338 info:                             for full details
28339 info:       "proc (body)"
28340 info:         is needed by its spec:
28341 info:       "proc (spec)"
28342 info:         which is withed by:
28343 info:       "pack (body)"
28344 info:  "pack (body)" must be elaborated before "proc (body)"
28345 info:     reason: pragma Elaborate in unit "proc (body)"
28346 @end example
28348 In this case we have a cycle that the binder cannot break. On the one
28349 hand, there is an explicit pragma Elaborate in @cite{proc} for
28350 @cite{pack}. This means that the body of @cite{pack} must be elaborated
28351 before the body of @cite{proc}. On the other hand, there is elaboration
28352 code in @cite{pack} that calls a subprogram in @cite{proc}. This means
28353 that for maximum safety, there should really be a pragma
28354 Elaborate_All in @cite{pack} for @cite{proc} which would require that
28355 the body of @cite{proc} be elaborated before the body of
28356 @cite{pack}. Clearly both requirements cannot be satisfied.
28357 Faced with a circularity of this kind, you have three different options.
28360 @itemize *
28362 @item 
28363 @emph{Fix the program}
28365 The most desirable option from the point of view of long-term maintenance
28366 is to rearrange the program so that the elaboration problems are avoided.
28367 One useful technique is to place the elaboration code into separate
28368 child packages. Another is to move some of the initialization code to
28369 explicitly called subprograms, where the program controls the order
28370 of initialization explicitly. Although this is the most desirable option,
28371 it may be impractical and involve too much modification, especially in
28372 the case of complex legacy code.
28374 @item 
28375 @emph{Perform dynamic checks}
28377 If the compilations are done using the @emph{-gnatE}
28378 (dynamic elaboration check) switch, then GNAT behaves in a quite different
28379 manner. Dynamic checks are generated for all calls that could possibly result
28380 in raising an exception. With this switch, the compiler does not generate
28381 implicit @cite{Elaborate} or @cite{Elaborate_All} pragmas. The behavior then is
28382 exactly as specified in the @cite{Ada Reference Manual}.
28383 The binder will generate
28384 an executable program that may or may not raise @cite{Program_Error}, and then
28385 it is the programmer's job to ensure that it does not raise an exception. Note
28386 that it is important to compile all units with the switch, it cannot be used
28387 selectively.
28389 @item 
28390 @emph{Suppress checks}
28392 The drawback of dynamic checks is that they generate a
28393 significant overhead at run time, both in space and time. If you
28394 are absolutely sure that your program cannot raise any elaboration
28395 exceptions, and you still want to use the dynamic elaboration model,
28396 then you can use the configuration pragma
28397 @cite{Suppress (Elaboration_Check)} to suppress all such checks. For
28398 example this pragma could be placed in the @code{gnat.adc} file.
28400 @item 
28401 @emph{Suppress checks selectively}
28403 When you know that certain calls or instantiations in elaboration code cannot
28404 possibly lead to an elaboration error, and the binder nevertheless complains
28405 about implicit @cite{Elaborate} and @cite{Elaborate_All} pragmas that lead to
28406 elaboration circularities, it is possible to remove those warnings locally and
28407 obtain a program that will bind. Clearly this can be unsafe, and it is the
28408 responsibility of the programmer to make sure that the resulting program has no
28409 elaboration anomalies. The pragma @cite{Suppress (Elaboration_Check)} can be
28410 used with different granularity to suppress warnings and break elaboration
28411 circularities:
28414 @itemize *
28416 @item 
28417 Place the pragma that names the called subprogram in the declarative part
28418 that contains the call.
28420 @item 
28421 Place the pragma in the declarative part, without naming an entity. This
28422 disables warnings on all calls in the corresponding  declarative region.
28424 @item 
28425 Place the pragma in the package spec that declares the called subprogram,
28426 and name the subprogram. This disables warnings on all elaboration calls to
28427 that subprogram.
28429 @item 
28430 Place the pragma in the package spec that declares the called subprogram,
28431 without naming any entity. This disables warnings on all elaboration calls to
28432 all subprograms declared in this spec.
28434 @item 
28435 Use Pragma Elaborate.
28437 As previously described in section @ref{23f,,Treatment of Pragma Elaborate},
28438 GNAT in static mode assumes that a @cite{pragma} Elaborate indicates correctly
28439 that no elaboration checks are required on calls to the designated unit.
28440 There may be cases in which the caller knows that no transitive calls
28441 can occur, so that a @cite{pragma Elaborate} will be sufficient in a
28442 case where @cite{pragma Elaborate_All} would cause a circularity.
28443 @end itemize
28445 These five cases are listed in order of decreasing safety, and therefore
28446 require increasing programmer care in their application. Consider the
28447 following program:
28449 @example
28450 package Pack1 is
28451   function F1 return Integer;
28452   X1 : Integer;
28453 end Pack1;
28455 package Pack2 is
28456   function F2 return Integer;
28457   function Pure (x : integer) return integer;
28458   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
28459   --  pragma Suppress (Elaboration_Check);              -- (4)
28460 end Pack2;
28462 with Pack2;
28463 package body Pack1 is
28464   function F1 return Integer is
28465   begin
28466     return 100;
28467   end F1;
28468   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
28469 begin
28470   declare
28471     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
28472     --  pragma Suppress(Elaboration_Check);             -- (2)
28473   begin
28474     X1 := Pack2.F2 + 1;                --  Elab. call (2)
28475   end;
28476 end Pack1;
28478 with Pack1;
28479 package body Pack2 is
28480   function F2 return Integer is
28481   begin
28482      return Pack1.F1;
28483   end F2;
28484   function Pure (x : integer) return integer is
28485   begin
28486      return x ** 3 - 3 * x;
28487   end;
28488 end Pack2;
28490 with Pack1, Ada.Text_IO;
28491 procedure Proc3 is
28492 begin
28493   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
28494 end Proc3;
28495 @end example
28497 In the absence of any pragmas, an attempt to bind this program produces
28498 the following diagnostics:
28500 @example
28501 error: elaboration circularity detected
28502 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
28503 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
28504 info:       recompile "pack1 (body)" with -gnatel for full details
28505 info:          "pack1 (body)"
28506 info:             must be elaborated along with its spec:
28507 info:          "pack1 (spec)"
28508 info:             which is withed by:
28509 info:          "pack2 (body)"
28510 info:             which must be elaborated along with its spec:
28511 info:          "pack2 (spec)"
28512 info:             which is withed by:
28513 info:          "pack1 (body)"
28514 @end example
28516 The sources of the circularity are the two calls to @cite{Pack2.Pure} and
28517 @cite{Pack2.F2} in the body of @cite{Pack1}. We can see that the call to
28518 F2 is safe, even though F2 calls F1, because the call appears after the
28519 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
28520 remove the warning on the call. It is also possible to use pragma (2)
28521 because there are no other potentially unsafe calls in the block.
28523 The call to @cite{Pure} is safe because this function does not depend on the
28524 state of @cite{Pack2}. Therefore any call to this function is safe, and it
28525 is correct to place pragma (3) in the corresponding package spec.
28527 Finally, we could place pragma (4) in the spec of @cite{Pack2} to disable
28528 warnings on all calls to functions declared therein. Note that this is not
28529 necessarily safe, and requires more detailed examination of the subprogram
28530 bodies involved. In particular, a call to @cite{F2} requires that @cite{F1}
28531 be already elaborated.
28532 @end itemize
28534 It is hard to generalize on which of these four approaches should be
28535 taken. Obviously if it is possible to fix the program so that the default
28536 treatment works, this is preferable, but this may not always be practical.
28537 It is certainly simple enough to use @emph{-gnatE}
28538 but the danger in this case is that, even if the GNAT binder
28539 finds a correct elaboration order, it may not always do so,
28540 and certainly a binder from another Ada compiler might not. A
28541 combination of testing and analysis (for which the
28542 information messages generated with the @emph{-gnatel}
28543 switch can be useful) must be used to ensure that the program is free
28544 of errors. One switch that is useful in this testing is the
28545 @emph{-p (pessimistic elaboration order)} switch for @cite{gnatbind}.
28546 Normally the binder tries to find an order that has the best chance
28547 of avoiding elaboration problems. However, if this switch is used, the binder
28548 plays a devil's advocate role, and tries to choose the order that
28549 has the best chance of failing. If your program works even with this
28550 switch, then it has a better chance of being error free, but this is still
28551 not a guarantee.
28553 For an example of this approach in action, consider the C-tests (executable
28554 tests) from the ACATS suite. If these are compiled and run with the default
28555 treatment, then all but one of them succeed without generating any error
28556 diagnostics from the binder. However, there is one test that fails, and
28557 this is not surprising, because the whole point of this test is to ensure
28558 that the compiler can handle cases where it is impossible to determine
28559 a correct order statically, and it checks that an exception is indeed
28560 raised at run time.
28562 This one test must be compiled and run using the @emph{-gnatE}
28563 switch, and then it passes. Alternatively, the entire suite can
28564 be run using this switch. It is never wrong to run with the dynamic
28565 elaboration switch if your code is correct, and we assume that the
28566 C-tests are indeed correct (it is less efficient, but efficiency is
28567 not a factor in running the ACATS tests.)
28569 @node Elaboration for Indirect Calls,Summary of Procedures for Elaboration Control,What to Do If the Default Elaboration Behavior Fails,Elaboration Order Handling in GNAT
28570 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{246}@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-for-indirect-calls}@anchor{247}
28571 @section Elaboration for Indirect Calls
28574 @geindex Dispatching calls
28576 @geindex Indirect calls
28578 In rare cases, the static elaboration model fails to prevent
28579 dispatching calls to not-yet-elaborated subprograms. In such cases, we
28580 fall back to run-time checks; premature calls to any primitive
28581 operation of a tagged type before the body of the operation has been
28582 elaborated will raise @cite{Program_Error}.
28584 Access-to-subprogram types, however, are handled conservatively in many
28585 cases. This was not true in earlier versions of the compiler; you can use
28586 the @emph{-gnatd.U} debug switch to revert to the old behavior if the new
28587 conservative behavior causes elaboration cycles. Here, 'conservative' means
28588 that if you do @cite{P'Access} during elaboration, the compiler will normally
28589 assume that you might call @cite{P} indirectly during elaboration, so it adds an
28590 implicit @cite{pragma Elaborate_All} on the library unit containing @cite{P}. The
28591 @emph{-gnatd.U} switch is safe if you know there are no such calls. If the
28592 program worked before, it will continue to work with @emph{-gnatd.U}. But beware
28593 that code modifications such as adding an indirect call can cause erroneous
28594 behavior in the presence of @emph{-gnatd.U}.
28596 These implicit Elaborate_All pragmas are not added in all cases, because
28597 they cause elaboration cycles in certain common code patterns. If you want
28598 even more conservative handling of P'Access, you can use the @emph{-gnatd.o}
28599 switch.
28601 See @cite{debug.adb} for documentation on the @emph{-gnatd...} debug switches.
28603 @node Summary of Procedures for Elaboration Control,Other Elaboration Order Considerations,Elaboration for Indirect Calls,Elaboration Order Handling in GNAT
28604 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{248}@anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{249}
28605 @section Summary of Procedures for Elaboration Control
28608 @geindex Elaboration control
28610 First, compile your program with the default options, using none of
28611 the special elaboration-control switches. If the binder successfully
28612 binds your program, then you can be confident that, apart from issues
28613 raised by the use of access-to-subprogram types and dynamic dispatching,
28614 the program is free of elaboration errors. If it is important that the
28615 program be portable to other compilers than GNAT, then use the
28616 @emph{-gnatel}
28617 switch to generate messages about missing @cite{Elaborate} or
28618 @cite{Elaborate_All} pragmas, and supply the missing pragmas.
28620 If the program fails to bind using the default static elaboration
28621 handling, then you can fix the program to eliminate the binder
28622 message, or recompile the entire program with the
28623 @emph{-gnatE} switch to generate dynamic elaboration checks,
28624 and, if you are sure there really are no elaboration problems,
28625 use a global pragma @cite{Suppress (Elaboration_Check)}.
28627 @node Other Elaboration Order Considerations,Determining the Chosen Elaboration Order,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
28628 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{24a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat other-elaboration-order-considerations}@anchor{24b}
28629 @section Other Elaboration Order Considerations
28632 This section has been entirely concerned with the issue of finding a valid
28633 elaboration order, as defined by the Ada Reference Manual. In a case
28634 where several elaboration orders are valid, the task is to find one
28635 of the possible valid elaboration orders (and the static model in GNAT
28636 will ensure that this is achieved).
28638 The purpose of the elaboration rules in the Ada Reference Manual is to
28639 make sure that no entity is accessed before it has been elaborated. For
28640 a subprogram, this means that the spec and body must have been elaborated
28641 before the subprogram is called. For an object, this means that the object
28642 must have been elaborated before its value is read or written. A violation
28643 of either of these two requirements is an access before elaboration order,
28644 and this section has been all about avoiding such errors.
28646 In the case where more than one order of elaboration is possible, in the
28647 sense that access before elaboration errors are avoided, then any one of
28648 the orders is 'correct' in the sense that it meets the requirements of
28649 the Ada Reference Manual, and no such error occurs.
28651 However, it may be the case for a given program, that there are
28652 constraints on the order of elaboration that come not from consideration
28653 of avoiding elaboration errors, but rather from extra-lingual logic
28654 requirements. Consider this example:
28656 @example
28657 with Init_Constants;
28658 package Constants is
28659    X : Integer := 0;
28660    Y : Integer := 0;
28661 end Constants;
28663 package Init_Constants is
28664    procedure P; --* require a body*
28665 end Init_Constants;
28667 with Constants;
28668 package body Init_Constants is
28669    procedure P is begin null; end;
28670 begin
28671    Constants.X := 3;
28672    Constants.Y := 4;
28673 end Init_Constants;
28675 with Constants;
28676 package Calc is
28677    Z : Integer := Constants.X + Constants.Y;
28678 end Calc;
28680 with Calc;
28681 with Text_IO; use Text_IO;
28682 procedure Main is
28683 begin
28684    Put_Line (Calc.Z'Img);
28685 end Main;
28686 @end example
28688 In this example, there is more than one valid order of elaboration. For
28689 example both the following are correct orders:
28691 @example
28692 Init_Constants spec
28693 Constants spec
28694 Calc spec
28695 Init_Constants body
28696 Main body
28697 @end example
28701 @example
28702 Init_Constants spec
28703 Constants spec
28704 Init_Constants body
28705 Calc spec
28706 Main body
28707 @end example
28709 There is no language rule to prefer one or the other, both are correct
28710 from an order of elaboration point of view. But the programmatic effects
28711 of the two orders are very different. In the first, the elaboration routine
28712 of @cite{Calc} initializes @cite{Z} to zero, and then the main program
28713 runs with this value of zero. But in the second order, the elaboration
28714 routine of @cite{Calc} runs after the body of Init_Constants has set
28715 @cite{X} and @cite{Y} and thus @cite{Z} is set to 7 before @cite{Main} runs.
28717 One could perhaps by applying pretty clever non-artificial intelligence
28718 to the situation guess that it is more likely that the second order of
28719 elaboration is the one desired, but there is no formal linguistic reason
28720 to prefer one over the other. In fact in this particular case, GNAT will
28721 prefer the second order, because of the rule that bodies are elaborated
28722 as soon as possible, but it's just luck that this is what was wanted
28723 (if indeed the second order was preferred).
28725 If the program cares about the order of elaboration routines in a case like
28726 this, it is important to specify the order required. In this particular
28727 case, that could have been achieved by adding to the spec of Calc:
28729 @example
28730 pragma Elaborate_All (Constants);
28731 @end example
28733 which requires that the body (if any) and spec of @cite{Constants},
28734 as well as the body and spec of any unit @emph{with}ed by
28735 @cite{Constants} be elaborated before @cite{Calc} is elaborated.
28737 Clearly no automatic method can always guess which alternative you require,
28738 and if you are working with legacy code that had constraints of this kind
28739 which were not properly specified by adding @cite{Elaborate} or
28740 @cite{Elaborate_All} pragmas, then indeed it is possible that two different
28741 compilers can choose different orders.
28743 However, GNAT does attempt to diagnose the common situation where there
28744 are uninitialized variables in the visible part of a package spec, and the
28745 corresponding package body has an elaboration block that directly or
28746 indirectly initializes one or more of these variables. This is the situation
28747 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
28748 a warning that suggests this addition if it detects this situation.
28750 The @cite{gnatbind} @emph{-p} switch may be useful in smoking
28751 out problems. This switch causes bodies to be elaborated as late as possible
28752 instead of as early as possible. In the example above, it would have forced
28753 the choice of the first elaboration order. If you get different results
28754 when using this switch, and particularly if one set of results is right,
28755 and one is wrong as far as you are concerned, it shows that you have some
28756 missing @cite{Elaborate} pragmas. For the example above, we have the
28757 following output:
28759 @example
28760 $ gnatmake -f -q main
28761 $ main
28763 $ gnatmake -f -q main -bargs -p
28764 $ main
28766 @end example
28768 It is of course quite unlikely that both these results are correct, so
28769 it is up to you in a case like this to investigate the source of the
28770 difference, by looking at the two elaboration orders that are chosen,
28771 and figuring out which is correct, and then adding the necessary
28772 @cite{Elaborate} or @cite{Elaborate_All} pragmas to ensure the desired order.
28774 @node Determining the Chosen Elaboration Order,,Other Elaboration Order Considerations,Elaboration Order Handling in GNAT
28775 @anchor{gnat_ugn/elaboration_order_handling_in_gnat determining-the-chosen-elaboration-order}@anchor{24c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id15}@anchor{24d}
28776 @section Determining the Chosen Elaboration Order
28779 To see the elaboration order that the binder chooses, you can look at
28780 the last part of the file:@cite{b~xxx.adb} binder output file. Here is an example:
28782 @example
28783 System.Soft_Links'Elab_Body;
28784 E14 := True;
28785 System.Secondary_Stack'Elab_Body;
28786 E18 := True;
28787 System.Exception_Table'Elab_Body;
28788 E24 := True;
28789 Ada.Io_Exceptions'Elab_Spec;
28790 E67 := True;
28791 Ada.Tags'Elab_Spec;
28792 Ada.Streams'Elab_Spec;
28793 E43 := True;
28794 Interfaces.C'Elab_Spec;
28795 E69 := True;
28796 System.Finalization_Root'Elab_Spec;
28797 E60 := True;
28798 System.Os_Lib'Elab_Body;
28799 E71 := True;
28800 System.Finalization_Implementation'Elab_Spec;
28801 System.Finalization_Implementation'Elab_Body;
28802 E62 := True;
28803 Ada.Finalization'Elab_Spec;
28804 E58 := True;
28805 Ada.Finalization.List_Controller'Elab_Spec;
28806 E76 := True;
28807 System.File_Control_Block'Elab_Spec;
28808 E74 := True;
28809 System.File_Io'Elab_Body;
28810 E56 := True;
28811 Ada.Tags'Elab_Body;
28812 E45 := True;
28813 Ada.Text_Io'Elab_Spec;
28814 Ada.Text_Io'Elab_Body;
28815 E07 := True;
28816 @end example
28818 Here Elab_Spec elaborates the spec
28819 and Elab_Body elaborates the body. The assignments to the @code{E@emph{xx}} flags
28820 flag that the corresponding body is now elaborated.
28822 You can also ask the binder to generate a more
28823 readable list of the elaboration order using the
28824 @cite{-l} switch when invoking the binder. Here is
28825 an example of the output generated by this switch:
28827 @example
28828 ada (spec)
28829 interfaces (spec)
28830 system (spec)
28831 system.case_util (spec)
28832 system.case_util (body)
28833 system.concat_2 (spec)
28834 system.concat_2 (body)
28835 system.concat_3 (spec)
28836 system.concat_3 (body)
28837 system.htable (spec)
28838 system.parameters (spec)
28839 system.parameters (body)
28840 system.crtl (spec)
28841 interfaces.c_streams (spec)
28842 interfaces.c_streams (body)
28843 system.restrictions (spec)
28844 system.restrictions (body)
28845 system.standard_library (spec)
28846 system.exceptions (spec)
28847 system.exceptions (body)
28848 system.storage_elements (spec)
28849 system.storage_elements (body)
28850 system.secondary_stack (spec)
28851 system.stack_checking (spec)
28852 system.stack_checking (body)
28853 system.string_hash (spec)
28854 system.string_hash (body)
28855 system.htable (body)
28856 system.strings (spec)
28857 system.strings (body)
28858 system.traceback (spec)
28859 system.traceback (body)
28860 system.traceback_entries (spec)
28861 system.traceback_entries (body)
28862 ada.exceptions (spec)
28863 ada.exceptions.last_chance_handler (spec)
28864 system.soft_links (spec)
28865 system.soft_links (body)
28866 ada.exceptions.last_chance_handler (body)
28867 system.secondary_stack (body)
28868 system.exception_table (spec)
28869 system.exception_table (body)
28870 ada.io_exceptions (spec)
28871 ada.tags (spec)
28872 ada.streams (spec)
28873 interfaces.c (spec)
28874 interfaces.c (body)
28875 system.finalization_root (spec)
28876 system.finalization_root (body)
28877 system.memory (spec)
28878 system.memory (body)
28879 system.standard_library (body)
28880 system.os_lib (spec)
28881 system.os_lib (body)
28882 system.unsigned_types (spec)
28883 system.stream_attributes (spec)
28884 system.stream_attributes (body)
28885 system.finalization_implementation (spec)
28886 system.finalization_implementation (body)
28887 ada.finalization (spec)
28888 ada.finalization (body)
28889 ada.finalization.list_controller (spec)
28890 ada.finalization.list_controller (body)
28891 system.file_control_block (spec)
28892 system.file_io (spec)
28893 system.file_io (body)
28894 system.val_uns (spec)
28895 system.val_util (spec)
28896 system.val_util (body)
28897 system.val_uns (body)
28898 system.wch_con (spec)
28899 system.wch_con (body)
28900 system.wch_cnv (spec)
28901 system.wch_jis (spec)
28902 system.wch_jis (body)
28903 system.wch_cnv (body)
28904 system.wch_stw (spec)
28905 system.wch_stw (body)
28906 ada.tags (body)
28907 ada.exceptions (body)
28908 ada.text_io (spec)
28909 ada.text_io (body)
28910 text_io (spec)
28911 gdbstr (body)
28912 @end example
28914 @node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
28915 @anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{10}@anchor{gnat_ugn/inline_assembler doc}@anchor{24e}@anchor{gnat_ugn/inline_assembler id1}@anchor{24f}
28916 @chapter Inline Assembler
28919 @geindex Inline Assembler
28921 If you need to write low-level software that interacts directly
28922 with the hardware, Ada provides two ways to incorporate assembly
28923 language code into your program.  First, you can import and invoke
28924 external routines written in assembly language, an Ada feature fully
28925 supported by GNAT.  However, for small sections of code it may be simpler
28926 or more efficient to include assembly language statements directly
28927 in your Ada source program, using the facilities of the implementation-defined
28928 package @cite{System.Machine_Code}, which incorporates the gcc
28929 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
28930 including the following:
28933 @itemize *
28935 @item 
28936 No need to use non-Ada tools
28938 @item 
28939 Consistent interface over different targets
28941 @item 
28942 Automatic usage of the proper calling conventions
28944 @item 
28945 Access to Ada constants and variables
28947 @item 
28948 Definition of intrinsic routines
28950 @item 
28951 Possibility of inlining a subprogram comprising assembler code
28953 @item 
28954 Code optimizer can take Inline Assembler code into account
28955 @end itemize
28957 This appendix presents a series of examples to show you how to use
28958 the Inline Assembler.  Although it focuses on the Intel x86,
28959 the general approach applies also to other processors.
28960 It is assumed that you are familiar with Ada
28961 and with assembly language programming.
28963 @menu
28964 * Basic Assembler Syntax:: 
28965 * A Simple Example of Inline Assembler:: 
28966 * Output Variables in Inline Assembler:: 
28967 * Input Variables in Inline Assembler:: 
28968 * Inlining Inline Assembler Code:: 
28969 * Other Asm Functionality:: 
28971 @end menu
28973 @node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
28974 @anchor{gnat_ugn/inline_assembler id2}@anchor{250}@anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{251}
28975 @section Basic Assembler Syntax
28978 The assembler used by GNAT and gcc is based not on the Intel assembly
28979 language, but rather on a language that descends from the AT&T Unix
28980 assembler @emph{as} (and which is often referred to as 'AT&T syntax').
28981 The following table summarizes the main features of @emph{as} syntax
28982 and points out the differences from the Intel conventions.
28983 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
28984 pre-processor) documentation for further information.
28987 @display
28988 @emph{Register names}@w{ }
28989 @display
28990 gcc / @emph{as}: Prefix with '%'; for example @cite{%eax}@w{ }
28991 Intel: No extra punctuation; for example @cite{eax}@w{ }
28992 @end display
28993 @end display
28998 @display
28999 @emph{Immediate operand}@w{ }
29000 @display
29001 gcc / @emph{as}: Prefix with '$'; for example @cite{$4}@w{ }
29002 Intel: No extra punctuation; for example @cite{4}@w{ }
29003 @end display
29004 @end display
29009 @display
29010 @emph{Address}@w{ }
29011 @display
29012 gcc / @emph{as}: Prefix with '$'; for example @cite{$loc}@w{ }
29013 Intel: No extra punctuation; for example @cite{loc}@w{ }
29014 @end display
29015 @end display
29020 @display
29021 @emph{Memory contents}@w{ }
29022 @display
29023 gcc / @emph{as}: No extra punctuation; for example @cite{loc}@w{ }
29024 Intel: Square brackets; for example @cite{[loc]}@w{ }
29025 @end display
29026 @end display
29031 @display
29032 @emph{Register contents}@w{ }
29033 @display
29034 gcc / @emph{as}: Parentheses; for example @cite{(%eax)}@w{ }
29035 Intel: Square brackets; for example @cite{[eax]}@w{ }
29036 @end display
29037 @end display
29042 @display
29043 @emph{Hexadecimal numbers}@w{ }
29044 @display
29045 gcc / @emph{as}: Leading '0x' (C language syntax); for example @cite{0xA0}@w{ }
29046 Intel: Trailing 'h'; for example @cite{A0h}@w{ }
29047 @end display
29048 @end display
29053 @display
29054 @emph{Operand size}@w{ }
29055 @display
29056 gcc / @emph{as}: Explicit in op code; for example @cite{movw} to move a 16-bit word@w{ }
29057 Intel: Implicit, deduced by assembler; for example @cite{mov}@w{ }
29058 @end display
29059 @end display
29064 @display
29065 @emph{Instruction repetition}@w{ }
29066 @display
29067 gcc / @emph{as}: Split into two lines; for example@w{ }
29068 @display
29069 @cite{rep}@w{ }
29070 @cite{stosl}@w{ }
29071 @end display
29072 Intel: Keep on one line; for example @cite{rep stosl}@w{ }
29073 @end display
29074 @end display
29079 @display
29080 @emph{Order of operands}@w{ }
29081 @display
29082 gcc / @emph{as}: Source first; for example @cite{movw $4@comma{} %eax}@w{ }
29083 Intel: Destination first; for example @cite{mov eax@comma{} 4}@w{ }
29084 @end display
29085 @end display
29089 @node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
29090 @anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{252}@anchor{gnat_ugn/inline_assembler id3}@anchor{253}
29091 @section A Simple Example of Inline Assembler
29094 The following example will generate a single assembly language statement,
29095 @cite{nop}, which does nothing.  Despite its lack of run-time effect,
29096 the example will be useful in illustrating the basics of
29097 the Inline Assembler facility.
29099 @quotation
29101 @example
29102 with System.Machine_Code; use System.Machine_Code;
29103 procedure Nothing is
29104 begin
29105    Asm ("nop");
29106 end Nothing;
29107 @end example
29108 @end quotation
29110 @cite{Asm} is a procedure declared in package @cite{System.Machine_Code};
29111 here it takes one parameter, a @emph{template string} that must be a static
29112 expression and that will form the generated instruction.
29113 @cite{Asm} may be regarded as a compile-time procedure that parses
29114 the template string and additional parameters (none here),
29115 from which it generates a sequence of assembly language instructions.
29117 The examples in this chapter will illustrate several of the forms
29118 for invoking @cite{Asm}; a complete specification of the syntax
29119 is found in the @cite{Machine_Code_Insertions} section of the
29120 @cite{GNAT Reference Manual}.
29122 Under the standard GNAT conventions, the @cite{Nothing} procedure
29123 should be in a file named @code{nothing.adb}.
29124 You can build the executable in the usual way:
29126 @quotation
29128 @example
29129 $ gnatmake nothing
29130 @end example
29131 @end quotation
29133 However, the interesting aspect of this example is not its run-time behavior
29134 but rather the generated assembly code.
29135 To see this output, invoke the compiler as follows:
29137 @quotation
29139 @example
29140 $  gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
29141 @end example
29142 @end quotation
29144 where the options are:
29147 @itemize *
29149 @item 
29151 @table @asis
29153 @item @code{-c}
29155 compile only (no bind or link)
29156 @end table
29158 @item 
29160 @table @asis
29162 @item @code{-S}
29164 generate assembler listing
29165 @end table
29167 @item 
29169 @table @asis
29171 @item @code{-fomit-frame-pointer}
29173 do not set up separate stack frames
29174 @end table
29176 @item 
29178 @table @asis
29180 @item @code{-gnatp}
29182 do not add runtime checks
29183 @end table
29184 @end itemize
29186 This gives a human-readable assembler version of the code. The resulting
29187 file will have the same name as the Ada source file, but with a @cite{.s}
29188 extension. In our example, the file @code{nothing.s} has the following
29189 contents:
29191 @quotation
29193 @example
29194 .file "nothing.adb"
29195 gcc2_compiled.:
29196 ___gnu_compiled_ada:
29197 .text
29198    .align 4
29199 .globl __ada_nothing
29200 __ada_nothing:
29201 #APP
29202    nop
29203 #NO_APP
29204    jmp L1
29205    .align 2,0x90
29207    ret
29208 @end example
29209 @end quotation
29211 The assembly code you included is clearly indicated by
29212 the compiler, between the @cite{#APP} and @cite{#NO_APP}
29213 delimiters. The character before the 'APP' and 'NOAPP'
29214 can differ on different targets. For example, GNU/Linux uses '#APP' while
29215 on NT you will see '/APP'.
29217 If you make a mistake in your assembler code (such as using the
29218 wrong size modifier, or using a wrong operand for the instruction) GNAT
29219 will report this error in a temporary file, which will be deleted when
29220 the compilation is finished.  Generating an assembler file will help
29221 in such cases, since you can assemble this file separately using the
29222 @emph{as} assembler that comes with gcc.
29224 Assembling the file using the command
29226 @quotation
29228 @example
29229 $ as nothing.s
29230 @end example
29231 @end quotation
29233 will give you error messages whose lines correspond to the assembler
29234 input file, so you can easily find and correct any mistakes you made.
29235 If there are no errors, @emph{as} will generate an object file
29236 @code{nothing.out}.
29238 @node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
29239 @anchor{gnat_ugn/inline_assembler id4}@anchor{254}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{255}
29240 @section Output Variables in Inline Assembler
29243 The examples in this section, showing how to access the processor flags,
29244 illustrate how to specify the destination operands for assembly language
29245 statements.
29247 @quotation
29249 @example
29250 with Interfaces; use Interfaces;
29251 with Ada.Text_IO; use Ada.Text_IO;
29252 with System.Machine_Code; use System.Machine_Code;
29253 procedure Get_Flags is
29254    Flags : Unsigned_32;
29255    use ASCII;
29256 begin
29257    Asm ("pushfl"          & LF & HT & -- push flags on stack
29258         "popl %%eax"      & LF & HT & -- load eax with flags
29259         "movl %%eax, %0",             -- store flags in variable
29260         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29261    Put_Line ("Flags register:" & Flags'Img);
29262 end Get_Flags;
29263 @end example
29264 @end quotation
29266 In order to have a nicely aligned assembly listing, we have separated
29267 multiple assembler statements in the Asm template string with linefeed
29268 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
29269 The resulting section of the assembly output file is:
29271 @quotation
29273 @example
29274 #APP
29275    pushfl
29276    popl %eax
29277    movl %eax, -40(%ebp)
29278 #NO_APP
29279 @end example
29280 @end quotation
29282 It would have been legal to write the Asm invocation as:
29284 @quotation
29286 @example
29287 Asm ("pushfl popl %%eax movl %%eax, %0")
29288 @end example
29289 @end quotation
29291 but in the generated assembler file, this would come out as:
29293 @quotation
29295 @example
29296 #APP
29297    pushfl popl %eax movl %eax, -40(%ebp)
29298 #NO_APP
29299 @end example
29300 @end quotation
29302 which is not so convenient for the human reader.
29304 We use Ada comments
29305 at the end of each line to explain what the assembler instructions
29306 actually do.  This is a useful convention.
29308 When writing Inline Assembler instructions, you need to precede each register
29309 and variable name with a percent sign.  Since the assembler already requires
29310 a percent sign at the beginning of a register name, you need two consecutive
29311 percent signs for such names in the Asm template string, thus @cite{%%eax}.
29312 In the generated assembly code, one of the percent signs will be stripped off.
29314 Names such as @cite{%0}, @cite{%1}, @cite{%2}, etc., denote input or output
29315 variables: operands you later define using @cite{Input} or @cite{Output}
29316 parameters to @cite{Asm}.
29317 An output variable is illustrated in
29318 the third statement in the Asm template string:
29320 @quotation
29322 @example
29323 movl %%eax, %0
29324 @end example
29325 @end quotation
29327 The intent is to store the contents of the eax register in a variable that can
29328 be accessed in Ada.  Simply writing @cite{movl %%eax@comma{} Flags} would not
29329 necessarily work, since the compiler might optimize by using a register
29330 to hold Flags, and the expansion of the @cite{movl} instruction would not be
29331 aware of this optimization.  The solution is not to store the result directly
29332 but rather to advise the compiler to choose the correct operand form;
29333 that is the purpose of the @cite{%0} output variable.
29335 Information about the output variable is supplied in the @cite{Outputs}
29336 parameter to @cite{Asm}:
29338 @quotation
29340 @example
29341 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29342 @end example
29343 @end quotation
29345 The output is defined by the @cite{Asm_Output} attribute of the target type;
29346 the general format is
29348 @quotation
29350 @example
29351 Type'Asm_Output (constraint_string, variable_name)
29352 @end example
29353 @end quotation
29355 The constraint string directs the compiler how
29356 to store/access the associated variable.  In the example
29358 @quotation
29360 @example
29361 Unsigned_32'Asm_Output ("=m", Flags);
29362 @end example
29363 @end quotation
29365 the @cite{"m"} (memory) constraint tells the compiler that the variable
29366 @cite{Flags} should be stored in a memory variable, thus preventing
29367 the optimizer from keeping it in a register.  In contrast,
29369 @quotation
29371 @example
29372 Unsigned_32'Asm_Output ("=r", Flags);
29373 @end example
29374 @end quotation
29376 uses the @cite{"r"} (register) constraint, telling the compiler to
29377 store the variable in a register.
29379 If the constraint is preceded by the equal character '=', it tells
29380 the compiler that the variable will be used to store data into it.
29382 In the @cite{Get_Flags} example, we used the @cite{"g"} (global) constraint,
29383 allowing the optimizer to choose whatever it deems best.
29385 There are a fairly large number of constraints, but the ones that are
29386 most useful (for the Intel x86 processor) are the following:
29388 @quotation
29391 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} 
29392 @item
29394 @emph{=}
29396 @tab
29398 output constraint
29400 @item
29402 @emph{g}
29404 @tab
29406 global (i.e., can be stored anywhere)
29408 @item
29410 @emph{m}
29412 @tab
29414 in memory
29416 @item
29418 @emph{I}
29420 @tab
29422 a constant
29424 @item
29426 @emph{a}
29428 @tab
29430 use eax
29432 @item
29434 @emph{b}
29436 @tab
29438 use ebx
29440 @item
29442 @emph{c}
29444 @tab
29446 use ecx
29448 @item
29450 @emph{d}
29452 @tab
29454 use edx
29456 @item
29458 @emph{S}
29460 @tab
29462 use esi
29464 @item
29466 @emph{D}
29468 @tab
29470 use edi
29472 @item
29474 @emph{r}
29476 @tab
29478 use one of eax, ebx, ecx or edx
29480 @item
29482 @emph{q}
29484 @tab
29486 use one of eax, ebx, ecx, edx, esi or edi
29488 @end multitable
29490 @end quotation
29492 The full set of constraints is described in the gcc and @emph{as}
29493 documentation; note that it is possible to combine certain constraints
29494 in one constraint string.
29496 You specify the association of an output variable with an assembler operand
29497 through the @code{%@emph{n}} notation, where @emph{n} is a non-negative
29498 integer.  Thus in
29500 @quotation
29502 @example
29503 Asm ("pushfl"          & LF & HT & -- push flags on stack
29504      "popl %%eax"      & LF & HT & -- load eax with flags
29505      "movl %%eax, %0",             -- store flags in variable
29506      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29507 @end example
29508 @end quotation
29510 @cite{%0} will be replaced in the expanded code by the appropriate operand,
29511 whatever
29512 the compiler decided for the @cite{Flags} variable.
29514 In general, you may have any number of output variables:
29517 @itemize *
29519 @item 
29520 Count the operands starting at 0; thus @cite{%0}, @cite{%1}, etc.
29522 @item 
29523 Specify the @cite{Outputs} parameter as a parenthesized comma-separated list
29524 of @cite{Asm_Output} attributes
29525 @end itemize
29527 For example:
29529 @quotation
29531 @example
29532 Asm ("movl %%eax, %0" & LF & HT &
29533      "movl %%ebx, %1" & LF & HT &
29534      "movl %%ecx, %2",
29535      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
29536                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
29537                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
29538 @end example
29539 @end quotation
29541 where @cite{Var_A}, @cite{Var_B}, and @cite{Var_C} are variables
29542 in the Ada program.
29544 As a variation on the @cite{Get_Flags} example, we can use the constraints
29545 string to direct the compiler to store the eax register into the @cite{Flags}
29546 variable, instead of including the store instruction explicitly in the
29547 @cite{Asm} template string:
29549 @quotation
29551 @example
29552 with Interfaces; use Interfaces;
29553 with Ada.Text_IO; use Ada.Text_IO;
29554 with System.Machine_Code; use System.Machine_Code;
29555 procedure Get_Flags_2 is
29556    Flags : Unsigned_32;
29557    use ASCII;
29558 begin
29559    Asm ("pushfl"      & LF & HT & -- push flags on stack
29560         "popl %%eax",             -- save flags in eax
29561         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29562    Put_Line ("Flags register:" & Flags'Img);
29563 end Get_Flags_2;
29564 @end example
29565 @end quotation
29567 The @cite{"a"} constraint tells the compiler that the @cite{Flags}
29568 variable will come from the eax register. Here is the resulting code:
29570 @quotation
29572 @example
29573 #APP
29574    pushfl
29575    popl %eax
29576 #NO_APP
29577    movl %eax,-40(%ebp)
29578 @end example
29579 @end quotation
29581 The compiler generated the store of eax into Flags after
29582 expanding the assembler code.
29584 Actually, there was no need to pop the flags into the eax register;
29585 more simply, we could just pop the flags directly into the program variable:
29587 @quotation
29589 @example
29590 with Interfaces; use Interfaces;
29591 with Ada.Text_IO; use Ada.Text_IO;
29592 with System.Machine_Code; use System.Machine_Code;
29593 procedure Get_Flags_3 is
29594    Flags : Unsigned_32;
29595    use ASCII;
29596 begin
29597    Asm ("pushfl"  & LF & HT & -- push flags on stack
29598         "pop %0",             -- save flags in Flags
29599         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29600    Put_Line ("Flags register:" & Flags'Img);
29601 end Get_Flags_3;
29602 @end example
29603 @end quotation
29605 @node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
29606 @anchor{gnat_ugn/inline_assembler id5}@anchor{256}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{257}
29607 @section Input Variables in Inline Assembler
29610 The example in this section illustrates how to specify the source operands
29611 for assembly language statements.
29612 The program simply increments its input value by 1:
29614 @quotation
29616 @example
29617 with Interfaces; use Interfaces;
29618 with Ada.Text_IO; use Ada.Text_IO;
29619 with System.Machine_Code; use System.Machine_Code;
29620 procedure Increment is
29622    function Incr (Value : Unsigned_32) return Unsigned_32 is
29623       Result : Unsigned_32;
29624    begin
29625       Asm ("incl %0",
29626            Outputs => Unsigned_32'Asm_Output ("=a", Result),
29627            Inputs  => Unsigned_32'Asm_Input ("a", Value));
29628       return Result;
29629    end Incr;
29631    Value : Unsigned_32;
29633 begin
29634    Value := 5;
29635    Put_Line ("Value before is" & Value'Img);
29636    Value := Incr (Value);
29637   Put_Line ("Value after is" & Value'Img);
29638 end Increment;
29639 @end example
29640 @end quotation
29642 The @cite{Outputs} parameter to @cite{Asm} specifies
29643 that the result will be in the eax register and that it is to be stored
29644 in the @cite{Result} variable.
29646 The @cite{Inputs} parameter looks much like the @cite{Outputs} parameter,
29647 but with an @cite{Asm_Input} attribute.
29648 The @cite{"="} constraint, indicating an output value, is not present.
29650 You can have multiple input variables, in the same way that you can have more
29651 than one output variable.
29653 The parameter count (%0, %1) etc, still starts at the first output statement,
29654 and continues with the input statements.
29656 Just as the @cite{Outputs} parameter causes the register to be stored into the
29657 target variable after execution of the assembler statements, so does the
29658 @cite{Inputs} parameter cause its variable to be loaded into the register
29659 before execution of the assembler statements.
29661 Thus the effect of the @cite{Asm} invocation is:
29664 @itemize *
29666 @item 
29667 load the 32-bit value of @cite{Value} into eax
29669 @item 
29670 execute the @cite{incl %eax} instruction
29672 @item 
29673 store the contents of eax into the @cite{Result} variable
29674 @end itemize
29676 The resulting assembler file (with @emph{-O2} optimization) contains:
29678 @quotation
29680 @example
29681 _increment__incr.1:
29682    subl $4,%esp
29683    movl 8(%esp),%eax
29684 #APP
29685    incl %eax
29686 #NO_APP
29687    movl %eax,%edx
29688    movl %ecx,(%esp)
29689    addl $4,%esp
29690    ret
29691 @end example
29692 @end quotation
29694 @node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
29695 @anchor{gnat_ugn/inline_assembler id6}@anchor{258}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{259}
29696 @section Inlining Inline Assembler Code
29699 For a short subprogram such as the @cite{Incr} function in the previous
29700 section, the overhead of the call and return (creating / deleting the stack
29701 frame) can be significant, compared to the amount of code in the subprogram
29702 body.  A solution is to apply Ada's @cite{Inline} pragma to the subprogram,
29703 which directs the compiler to expand invocations of the subprogram at the
29704 point(s) of call, instead of setting up a stack frame for out-of-line calls.
29705 Here is the resulting program:
29707 @quotation
29709 @example
29710 with Interfaces; use Interfaces;
29711 with Ada.Text_IO; use Ada.Text_IO;
29712 with System.Machine_Code; use System.Machine_Code;
29713 procedure Increment_2 is
29715    function Incr (Value : Unsigned_32) return Unsigned_32 is
29716       Result : Unsigned_32;
29717    begin
29718       Asm ("incl %0",
29719            Outputs => Unsigned_32'Asm_Output ("=a", Result),
29720            Inputs  => Unsigned_32'Asm_Input ("a", Value));
29721       return Result;
29722    end Incr;
29723    pragma Inline (Increment);
29725    Value : Unsigned_32;
29727 begin
29728    Value := 5;
29729    Put_Line ("Value before is" & Value'Img);
29730    Value := Increment (Value);
29731    Put_Line ("Value after is" & Value'Img);
29732 end Increment_2;
29733 @end example
29734 @end quotation
29736 Compile the program with both optimization (@emph{-O2}) and inlining
29737 (@emph{-gnatn}) enabled.
29739 The @cite{Incr} function is still compiled as usual, but at the
29740 point in @cite{Increment} where our function used to be called:
29742 @quotation
29744 @example
29745 pushl %edi
29746 call _increment__incr.1
29747 @end example
29748 @end quotation
29750 the code for the function body directly appears:
29752 @quotation
29754 @example
29755 movl %esi,%eax
29756 #APP
29757    incl %eax
29758 #NO_APP
29759    movl %eax,%edx
29760 @end example
29761 @end quotation
29763 thus saving the overhead of stack frame setup and an out-of-line call.
29765 @node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
29766 @anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{25a}@anchor{gnat_ugn/inline_assembler id7}@anchor{25b}
29767 @section Other @cite{Asm} Functionality
29770 This section describes two important parameters to the @cite{Asm}
29771 procedure: @cite{Clobber}, which identifies register usage;
29772 and @cite{Volatile}, which inhibits unwanted optimizations.
29774 @menu
29775 * The Clobber Parameter:: 
29776 * The Volatile Parameter:: 
29778 @end menu
29780 @node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
29781 @anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{25c}@anchor{gnat_ugn/inline_assembler id8}@anchor{25d}
29782 @subsection The @cite{Clobber} Parameter
29785 One of the dangers of intermixing assembly language and a compiled language
29786 such as Ada is that the compiler needs to be aware of which registers are
29787 being used by the assembly code.  In some cases, such as the earlier examples,
29788 the constraint string is sufficient to indicate register usage (e.g.,
29789 @cite{"a"} for
29790 the eax register).  But more generally, the compiler needs an explicit
29791 identification of the registers that are used by the Inline Assembly
29792 statements.
29794 Using a register that the compiler doesn't know about
29795 could be a side effect of an instruction (like @cite{mull}
29796 storing its result in both eax and edx).
29797 It can also arise from explicit register usage in your
29798 assembly code; for example:
29800 @quotation
29802 @example
29803 Asm ("movl %0, %%ebx" & LF & HT &
29804      "movl %%ebx, %1",
29805      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29806      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
29807 @end example
29808 @end quotation
29810 where the compiler (since it does not analyze the @cite{Asm} template string)
29811 does not know you are using the ebx register.
29813 In such cases you need to supply the @cite{Clobber} parameter to @cite{Asm},
29814 to identify the registers that will be used by your assembly code:
29816 @quotation
29818 @example
29819 Asm ("movl %0, %%ebx" & LF & HT &
29820      "movl %%ebx, %1",
29821      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29822      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
29823      Clobber => "ebx");
29824 @end example
29825 @end quotation
29827 The Clobber parameter is a static string expression specifying the
29828 register(s) you are using.  Note that register names are @emph{not} prefixed
29829 by a percent sign. Also, if more than one register is used then their names
29830 are separated by commas; e.g., @cite{"eax@comma{} ebx"}
29832 The @cite{Clobber} parameter has several additional uses:
29835 @itemize *
29837 @item 
29838 Use 'register' name @cite{cc} to indicate that flags might have changed
29840 @item 
29841 Use 'register' name @cite{memory} if you changed a memory location
29842 @end itemize
29844 @node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
29845 @anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{25e}@anchor{gnat_ugn/inline_assembler id9}@anchor{25f}
29846 @subsection The @cite{Volatile} Parameter
29849 @geindex Volatile parameter
29851 Compiler optimizations in the presence of Inline Assembler may sometimes have
29852 unwanted effects.  For example, when an @cite{Asm} invocation with an input
29853 variable is inside a loop, the compiler might move the loading of the input
29854 variable outside the loop, regarding it as a one-time initialization.
29856 If this effect is not desired, you can disable such optimizations by setting
29857 the @cite{Volatile} parameter to @cite{True}; for example:
29859 @quotation
29861 @example
29862 Asm ("movl %0, %%ebx" & LF & HT &
29863      "movl %%ebx, %1",
29864      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
29865      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
29866      Clobber  => "ebx",
29867      Volatile => True);
29868 @end example
29869 @end quotation
29871 By default, @cite{Volatile} is set to @cite{False} unless there is no
29872 @cite{Outputs} parameter.
29874 Although setting @cite{Volatile} to @cite{True} prevents unwanted
29875 optimizations, it will also disable other optimizations that might be
29876 important for efficiency. In general, you should set @cite{Volatile}
29877 to @cite{True} only if the compiler's optimizations have created
29878 problems.
29880 @node GNU Free Documentation License,Index,Inline Assembler,Top
29881 @anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license doc}@anchor{260}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{261}
29882 @chapter GNU Free Documentation License
29885 Version 1.3, 3 November 2008
29887 Copyright  2000, 2001, 2002, 2007, 2008  Free Software Foundation, Inc
29888 @indicateurl{http://fsf.org/}
29890 Everyone is permitted to copy and distribute verbatim copies of this
29891 license document, but changing it is not allowed.
29893 @strong{Preamble}
29895 The purpose of this License is to make a manual, textbook, or other
29896 functional and useful document "free" in the sense of freedom: to
29897 assure everyone the effective freedom to copy and redistribute it,
29898 with or without modifying it, either commercially or noncommercially.
29899 Secondarily, this License preserves for the author and publisher a way
29900 to get credit for their work, while not being considered responsible
29901 for modifications made by others.
29903 This License is a kind of "copyleft", which means that derivative
29904 works of the document must themselves be free in the same sense.  It
29905 complements the GNU General Public License, which is a copyleft
29906 license designed for free software.
29908 We have designed this License in order to use it for manuals for free
29909 software, because free software needs free documentation: a free
29910 program should come with manuals providing the same freedoms that the
29911 software does.  But this License is not limited to software manuals;
29912 it can be used for any textual work, regardless of subject matter or
29913 whether it is published as a printed book.  We recommend this License
29914 principally for works whose purpose is instruction or reference.
29916 @strong{1. APPLICABILITY AND DEFINITIONS}
29918 This License applies to any manual or other work, in any medium, that
29919 contains a notice placed by the copyright holder saying it can be
29920 distributed under the terms of this License.  Such a notice grants a
29921 world-wide, royalty-free license, unlimited in duration, to use that
29922 work under the conditions stated herein.  The @strong{Document}, below,
29923 refers to any such manual or work.  Any member of the public is a
29924 licensee, and is addressed as "@strong{you}".  You accept the license if you
29925 copy, modify or distribute the work in a way requiring permission
29926 under copyright law.
29928 A "@strong{Modified Version}" of the Document means any work containing the
29929 Document or a portion of it, either copied verbatim, or with
29930 modifications and/or translated into another language.
29932 A "@strong{Secondary Section}" is a named appendix or a front-matter section of
29933 the Document that deals exclusively with the relationship of the
29934 publishers or authors of the Document to the Document's overall subject
29935 (or to related matters) and contains nothing that could fall directly
29936 within that overall subject.  (Thus, if the Document is in part a
29937 textbook of mathematics, a Secondary Section may not explain any
29938 mathematics.)  The relationship could be a matter of historical
29939 connection with the subject or with related matters, or of legal,
29940 commercial, philosophical, ethical or political position regarding
29941 them.
29943 The "@strong{Invariant Sections}" are certain Secondary Sections whose titles
29944 are designated, as being those of Invariant Sections, in the notice
29945 that says that the Document is released under this License.  If a
29946 section does not fit the above definition of Secondary then it is not
29947 allowed to be designated as Invariant.  The Document may contain zero
29948 Invariant Sections.  If the Document does not identify any Invariant
29949 Sections then there are none.
29951 The "@strong{Cover Texts}" are certain short passages of text that are listed,
29952 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
29953 the Document is released under this License.  A Front-Cover Text may
29954 be at most 5 words, and a Back-Cover Text may be at most 25 words.
29956 A "@strong{Transparent}" copy of the Document means a machine-readable copy,
29957 represented in a format whose specification is available to the
29958 general public, that is suitable for revising the document
29959 straightforwardly with generic text editors or (for images composed of
29960 pixels) generic paint programs or (for drawings) some widely available
29961 drawing editor, and that is suitable for input to text formatters or
29962 for automatic translation to a variety of formats suitable for input
29963 to text formatters.  A copy made in an otherwise Transparent file
29964 format whose markup, or absence of markup, has been arranged to thwart
29965 or discourage subsequent modification by readers is not Transparent.
29966 An image format is not Transparent if used for any substantial amount
29967 of text.  A copy that is not "Transparent" is called @strong{Opaque}.
29969 Examples of suitable formats for Transparent copies include plain
29970 ASCII without markup, Texinfo input format, LaTeX input format, SGML
29971 or XML using a publicly available DTD, and standard-conforming simple
29972 HTML, PostScript or PDF designed for human modification.  Examples of
29973 transparent image formats include PNG, XCF and JPG.  Opaque formats
29974 include proprietary formats that can be read and edited only by
29975 proprietary word processors, SGML or XML for which the DTD and/or
29976 processing tools are not generally available, and the
29977 machine-generated HTML, PostScript or PDF produced by some word
29978 processors for output purposes only.
29980 The "@strong{Title Page}" means, for a printed book, the title page itself,
29981 plus such following pages as are needed to hold, legibly, the material
29982 this License requires to appear in the title page.  For works in
29983 formats which do not have any title page as such, "Title Page" means
29984 the text near the most prominent appearance of the work's title,
29985 preceding the beginning of the body of the text.
29987 The "@strong{publisher}" means any person or entity that distributes
29988 copies of the Document to the public.
29990 A section "@strong{Entitled XYZ}" means a named subunit of the Document whose
29991 title either is precisely XYZ or contains XYZ in parentheses following
29992 text that translates XYZ in another language.  (Here XYZ stands for a
29993 specific section name mentioned below, such as "@strong{Acknowledgements}",
29994 "@strong{Dedications}", "@strong{Endorsements}", or "@strong{History}".)
29995 To "@strong{Preserve the Title}"
29996 of such a section when you modify the Document means that it remains a
29997 section "Entitled XYZ" according to this definition.
29999 The Document may include Warranty Disclaimers next to the notice which
30000 states that this License applies to the Document.  These Warranty
30001 Disclaimers are considered to be included by reference in this
30002 License, but only as regards disclaiming warranties: any other
30003 implication that these Warranty Disclaimers may have is void and has
30004 no effect on the meaning of this License.
30006 @strong{2. VERBATIM COPYING}
30008 You may copy and distribute the Document in any medium, either
30009 commercially or noncommercially, provided that this License, the
30010 copyright notices, and the license notice saying this License applies
30011 to the Document are reproduced in all copies, and that you add no other
30012 conditions whatsoever to those of this License.  You may not use
30013 technical measures to obstruct or control the reading or further
30014 copying of the copies you make or distribute.  However, you may accept
30015 compensation in exchange for copies.  If you distribute a large enough
30016 number of copies you must also follow the conditions in section 3.
30018 You may also lend copies, under the same conditions stated above, and
30019 you may publicly display copies.
30021 @strong{3. COPYING IN QUANTITY}
30023 If you publish printed copies (or copies in media that commonly have
30024 printed covers) of the Document, numbering more than 100, and the
30025 Document's license notice requires Cover Texts, you must enclose the
30026 copies in covers that carry, clearly and legibly, all these Cover
30027 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
30028 the back cover.  Both covers must also clearly and legibly identify
30029 you as the publisher of these copies.  The front cover must present
30030 the full title with all words of the title equally prominent and
30031 visible.  You may add other material on the covers in addition.
30032 Copying with changes limited to the covers, as long as they preserve
30033 the title of the Document and satisfy these conditions, can be treated
30034 as verbatim copying in other respects.
30036 If the required texts for either cover are too voluminous to fit
30037 legibly, you should put the first ones listed (as many as fit
30038 reasonably) on the actual cover, and continue the rest onto adjacent
30039 pages.
30041 If you publish or distribute Opaque copies of the Document numbering
30042 more than 100, you must either include a machine-readable Transparent
30043 copy along with each Opaque copy, or state in or with each Opaque copy
30044 a computer-network location from which the general network-using
30045 public has access to download using public-standard network protocols
30046 a complete Transparent copy of the Document, free of added material.
30047 If you use the latter option, you must take reasonably prudent steps,
30048 when you begin distribution of Opaque copies in quantity, to ensure
30049 that this Transparent copy will remain thus accessible at the stated
30050 location until at least one year after the last time you distribute an
30051 Opaque copy (directly or through your agents or retailers) of that
30052 edition to the public.
30054 It is requested, but not required, that you contact the authors of the
30055 Document well before redistributing any large number of copies, to give
30056 them a chance to provide you with an updated version of the Document.
30058 @strong{4. MODIFICATIONS}
30060 You may copy and distribute a Modified Version of the Document under
30061 the conditions of sections 2 and 3 above, provided that you release
30062 the Modified Version under precisely this License, with the Modified
30063 Version filling the role of the Document, thus licensing distribution
30064 and modification of the Modified Version to whoever possesses a copy
30065 of it.  In addition, you must do these things in the Modified Version:
30068 @enumerate A
30070 @item 
30071 Use in the Title Page (and on the covers, if any) a title distinct
30072 from that of the Document, and from those of previous versions
30073 (which should, if there were any, be listed in the History section
30074 of the Document).  You may use the same title as a previous version
30075 if the original publisher of that version gives permission.
30077 @item 
30078 List on the Title Page, as authors, one or more persons or entities
30079 responsible for authorship of the modifications in the Modified
30080 Version, together with at least five of the principal authors of the
30081 Document (all of its principal authors, if it has fewer than five),
30082 unless they release you from this requirement.
30084 @item 
30085 State on the Title page the name of the publisher of the
30086 Modified Version, as the publisher.
30088 @item 
30089 Preserve all the copyright notices of the Document.
30091 @item 
30092 Add an appropriate copyright notice for your modifications
30093 adjacent to the other copyright notices.
30095 @item 
30096 Include, immediately after the copyright notices, a license notice
30097 giving the public permission to use the Modified Version under the
30098 terms of this License, in the form shown in the Addendum below.
30100 @item 
30101 Preserve in that license notice the full lists of Invariant Sections
30102 and required Cover Texts given in the Document's license notice.
30104 @item 
30105 Include an unaltered copy of this License.
30107 @item 
30108 Preserve the section Entitled "History", Preserve its Title, and add
30109 to it an item stating at least the title, year, new authors, and
30110 publisher of the Modified Version as given on the Title Page.  If
30111 there is no section Entitled "History" in the Document, create one
30112 stating the title, year, authors, and publisher of the Document as
30113 given on its Title Page, then add an item describing the Modified
30114 Version as stated in the previous sentence.
30116 @item 
30117 Preserve the network location, if any, given in the Document for
30118 public access to a Transparent copy of the Document, and likewise
30119 the network locations given in the Document for previous versions
30120 it was based on.  These may be placed in the "History" section.
30121 You may omit a network location for a work that was published at
30122 least four years before the Document itself, or if the original
30123 publisher of the version it refers to gives permission.
30125 @item 
30126 For any section Entitled "Acknowledgements" or "Dedications",
30127 Preserve the Title of the section, and preserve in the section all
30128 the substance and tone of each of the contributor acknowledgements
30129 and/or dedications given therein.
30131 @item 
30132 Preserve all the Invariant Sections of the Document,
30133 unaltered in their text and in their titles.  Section numbers
30134 or the equivalent are not considered part of the section titles.
30136 @item 
30137 Delete any section Entitled "Endorsements".  Such a section
30138 may not be included in the Modified Version.
30140 @item 
30141 Do not retitle any existing section to be Entitled "Endorsements"
30142 or to conflict in title with any Invariant Section.
30144 @item 
30145 Preserve any Warranty Disclaimers.
30146 @end enumerate
30148 If the Modified Version includes new front-matter sections or
30149 appendices that qualify as Secondary Sections and contain no material
30150 copied from the Document, you may at your option designate some or all
30151 of these sections as invariant.  To do this, add their titles to the
30152 list of Invariant Sections in the Modified Version's license notice.
30153 These titles must be distinct from any other section titles.
30155 You may add a section Entitled "Endorsements", provided it contains
30156 nothing but endorsements of your Modified Version by various
30157 parties---for example, statements of peer review or that the text has
30158 been approved by an organization as the authoritative definition of a
30159 standard.
30161 You may add a passage of up to five words as a Front-Cover Text, and a
30162 passage of up to 25 words as a Back-Cover Text, to the end of the list
30163 of Cover Texts in the Modified Version.  Only one passage of
30164 Front-Cover Text and one of Back-Cover Text may be added by (or
30165 through arrangements made by) any one entity.  If the Document already
30166 includes a cover text for the same cover, previously added by you or
30167 by arrangement made by the same entity you are acting on behalf of,
30168 you may not add another; but you may replace the old one, on explicit
30169 permission from the previous publisher that added the old one.
30171 The author(s) and publisher(s) of the Document do not by this License
30172 give permission to use their names for publicity for or to assert or
30173 imply endorsement of any Modified Version.
30175 @strong{5. COMBINING DOCUMENTS}
30177 You may combine the Document with other documents released under this
30178 License, under the terms defined in section 4 above for modified
30179 versions, provided that you include in the combination all of the
30180 Invariant Sections of all of the original documents, unmodified, and
30181 list them all as Invariant Sections of your combined work in its
30182 license notice, and that you preserve all their Warranty Disclaimers.
30184 The combined work need only contain one copy of this License, and
30185 multiple identical Invariant Sections may be replaced with a single
30186 copy.  If there are multiple Invariant Sections with the same name but
30187 different contents, make the title of each such section unique by
30188 adding at the end of it, in parentheses, the name of the original
30189 author or publisher of that section if known, or else a unique number.
30190 Make the same adjustment to the section titles in the list of
30191 Invariant Sections in the license notice of the combined work.
30193 In the combination, you must combine any sections Entitled "History"
30194 in the various original documents, forming one section Entitled
30195 "History"; likewise combine any sections Entitled "Acknowledgements",
30196 and any sections Entitled "Dedications".  You must delete all sections
30197 Entitled "Endorsements".
30199 @strong{6. COLLECTIONS OF DOCUMENTS}
30201 You may make a collection consisting of the Document and other documents
30202 released under this License, and replace the individual copies of this
30203 License in the various documents with a single copy that is included in
30204 the collection, provided that you follow the rules of this License for
30205 verbatim copying of each of the documents in all other respects.
30207 You may extract a single document from such a collection, and distribute
30208 it individually under this License, provided you insert a copy of this
30209 License into the extracted document, and follow this License in all
30210 other respects regarding verbatim copying of that document.
30212 @strong{7. AGGREGATION WITH INDEPENDENT WORKS}
30214 A compilation of the Document or its derivatives with other separate
30215 and independent documents or works, in or on a volume of a storage or
30216 distribution medium, is called an "aggregate" if the copyright
30217 resulting from the compilation is not used to limit the legal rights
30218 of the compilation's users beyond what the individual works permit.
30219 When the Document is included in an aggregate, this License does not
30220 apply to the other works in the aggregate which are not themselves
30221 derivative works of the Document.
30223 If the Cover Text requirement of section 3 is applicable to these
30224 copies of the Document, then if the Document is less than one half of
30225 the entire aggregate, the Document's Cover Texts may be placed on
30226 covers that bracket the Document within the aggregate, or the
30227 electronic equivalent of covers if the Document is in electronic form.
30228 Otherwise they must appear on printed covers that bracket the whole
30229 aggregate.
30231 @strong{8. TRANSLATION}
30233 Translation is considered a kind of modification, so you may
30234 distribute translations of the Document under the terms of section 4.
30235 Replacing Invariant Sections with translations requires special
30236 permission from their copyright holders, but you may include
30237 translations of some or all Invariant Sections in addition to the
30238 original versions of these Invariant Sections.  You may include a
30239 translation of this License, and all the license notices in the
30240 Document, and any Warranty Disclaimers, provided that you also include
30241 the original English version of this License and the original versions
30242 of those notices and disclaimers.  In case of a disagreement between
30243 the translation and the original version of this License or a notice
30244 or disclaimer, the original version will prevail.
30246 If a section in the Document is Entitled "Acknowledgements",
30247 "Dedications", or "History", the requirement (section 4) to Preserve
30248 its Title (section 1) will typically require changing the actual
30249 title.
30251 @strong{9. TERMINATION}
30253 You may not copy, modify, sublicense, or distribute the Document
30254 except as expressly provided under this License.  Any attempt
30255 otherwise to copy, modify, sublicense, or distribute it is void, and
30256 will automatically terminate your rights under this License.
30258 However, if you cease all violation of this License, then your license
30259 from a particular copyright holder is reinstated (a) provisionally,
30260 unless and until the copyright holder explicitly and finally
30261 terminates your license, and (b) permanently, if the copyright holder
30262 fails to notify you of the violation by some reasonable means prior to
30263 60 days after the cessation.
30265 Moreover, your license from a particular copyright holder is
30266 reinstated permanently if the copyright holder notifies you of the
30267 violation by some reasonable means, this is the first time you have
30268 received notice of violation of this License (for any work) from that
30269 copyright holder, and you cure the violation prior to 30 days after
30270 your receipt of the notice.
30272 Termination of your rights under this section does not terminate the
30273 licenses of parties who have received copies or rights from you under
30274 this License.  If your rights have been terminated and not permanently
30275 reinstated, receipt of a copy of some or all of the same material does
30276 not give you any rights to use it.
30278 @strong{10. FUTURE REVISIONS OF THIS LICENSE}
30280 The Free Software Foundation may publish new, revised versions
30281 of the GNU Free Documentation License from time to time.  Such new
30282 versions will be similar in spirit to the present version, but may
30283 differ in detail to address new problems or concerns.  See
30284 @indicateurl{http://www.gnu.org/copyleft/}.
30286 Each version of the License is given a distinguishing version number.
30287 If the Document specifies that a particular numbered version of this
30288 License "or any later version" applies to it, you have the option of
30289 following the terms and conditions either of that specified version or
30290 of any later version that has been published (not as a draft) by the
30291 Free Software Foundation.  If the Document does not specify a version
30292 number of this License, you may choose any version ever published (not
30293 as a draft) by the Free Software Foundation.  If the Document
30294 specifies that a proxy can decide which future versions of this
30295 License can be used, that proxy's public statement of acceptance of a
30296 version permanently authorizes you to choose that version for the
30297 Document.
30299 @strong{11. RELICENSING}
30301 "Massive Multiauthor Collaboration Site" (or "MMC Site") means any
30302 World Wide Web server that publishes copyrightable works and also
30303 provides prominent facilities for anybody to edit those works.  A
30304 public wiki that anybody can edit is an example of such a server.  A
30305 "Massive Multiauthor Collaboration" (or "MMC") contained in the
30306 site means any set of copyrightable works thus published on the MMC
30307 site.
30309 "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0
30310 license published by Creative Commons Corporation, a not-for-profit
30311 corporation with a principal place of business in San Francisco,
30312 California, as well as future copyleft versions of that license
30313 published by that same organization.
30315 "Incorporate" means to publish or republish a Document, in whole or
30316 in part, as part of another Document.
30318 An MMC is "eligible for relicensing" if it is licensed under this
30319 License, and if all works that were first published under this License
30320 somewhere other than this MMC, and subsequently incorporated in whole
30321 or in part into the MMC, (1) had no cover texts or invariant sections,
30322 and (2) were thus incorporated prior to November 1, 2008.
30324 The operator of an MMC Site may republish an MMC contained in the site
30325 under CC-BY-SA on the same site at any time before August 1, 2009,
30326 provided the MMC is eligible for relicensing.
30328 @strong{ADDENDUM: How to use this License for your documents}
30330 To use this License in a document you have written, include a copy of
30331 the License in the document and put the following copyright and
30332 license notices just after the title page:
30334 @quotation
30336 Copyright © YEAR  YOUR NAME.
30337 Permission is granted to copy, distribute and/or modify this document
30338 under the terms of the GNU Free Documentation License, Version 1.3
30339 or any later version published by the Free Software Foundation;
30340 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
30341 A copy of the license is included in the section entitled "GNU
30342 Free Documentation License".
30343 @end quotation
30345 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
30346 replace the "with ... Texts." line with this:
30348 @quotation
30350 with the Invariant Sections being LIST THEIR TITLES, with the
30351 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
30352 @end quotation
30354 If you have Invariant Sections without Cover Texts, or some other
30355 combination of the three, merge those two alternatives to suit the
30356 situation.
30358 If your document contains nontrivial examples of program code, we
30359 recommend releasing these examples in parallel under your choice of
30360 free software license, such as the GNU General Public License,
30361 to permit their use in free software.
30363 @node Index,,GNU Free Documentation License,Top
30364 @unnumbered Index
30367 @printindex ge
30369 @anchor{de}@w{                              }
30370 @anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{                              }
30372 @c %**end of body
30373 @bye