1 \input texinfo @c -*-texinfo-*-
3 @setfilename gnat_ugn.info
4 @documentencoding UTF-8
6 @*Generated by Sphinx 1.3b2.@*
8 @settitle GNAT User's Guide for Native Platforms
13 @dircategory GNU Ada Tools
15 * gnat_ugn: (gnat_ugn.info). gnat_ugn
18 @definfoenclose strong,`,'
19 @definfoenclose emph,`,'
24 GNAT User's Guide for Native Platforms , November 18, 2015
28 Copyright @copyright{} 2008-2016, Free Software Foundation
34 @title GNAT User's Guide for Native Platforms
39 @c %** start of user preamble
41 @c %** end of user preamble
45 @top GNAT User's Guide for Native Platforms
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}@*
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}.
68 * Getting Started with GNAT::
69 * The GNAT Compilation Model::
70 * Building Executable Programs with GNAT::
71 * GNAT Project Manager::
72 * Tools Supporting Project Files::
73 * GNAT Utility Programs::
74 * GNAT and Program Execution::
75 * Platform-Specific Information::
76 * Example of Binder Output File::
77 * Elaboration Order Handling in GNAT::
79 * GNU Free Documentation License::
83 --- The Detailed Node Listing ---
87 * What This Guide Contains::
88 * What You Should Know before Reading This Guide::
89 * Related Information::
90 * A Note to Readers of Previous Versions of the Manual::
93 Getting Started with GNAT
96 * Running a Simple Ada Program::
97 * Running a Program with Multiple Units::
98 * Using the gnatmake Utility::
100 The GNAT Compilation Model
102 * Source Representation::
103 * Foreign Language Representation::
104 * File Naming Topics and Utilities::
105 * Configuration Pragmas::
106 * Generating Object Files::
107 * Source Dependencies::
108 * The Ada Library Information Files::
109 * Binding an Ada Program::
110 * GNAT and Libraries::
111 * Conditional Compilation::
112 * Mixed Language Programming::
113 * GNAT and Other Compilation Models::
114 * Using GNAT Files with External Tools::
116 Foreign Language Representation
119 * Other 8-Bit Codes::
120 * Wide_Character Encodings::
121 * Wide_Wide_Character Encodings::
123 File Naming Topics and Utilities
125 * File Naming Rules::
126 * Using Other File Names::
127 * Alternative File Naming Schemes::
128 * Handling Arbitrary File Naming Conventions with gnatname::
129 * File Name Krunching with gnatkr::
130 * Renaming Files with gnatchop::
132 Handling Arbitrary File Naming Conventions with gnatname
134 * Arbitrary File Naming Conventions::
136 * Switches for gnatname::
137 * Examples of gnatname Usage::
139 File Name Krunching with gnatkr
144 * Examples of gnatkr Usage::
146 Renaming Files with gnatchop
148 * Handling Files with Multiple Units::
149 * Operating gnatchop in Compilation Mode::
150 * Command Line for gnatchop::
151 * Switches for gnatchop::
152 * Examples of gnatchop Usage::
154 Configuration Pragmas
156 * Handling of Configuration Pragmas::
157 * The Configuration Pragmas Files::
161 * Introduction to Libraries in GNAT::
162 * General Ada Libraries::
163 * Stand-alone Ada Libraries::
164 * Rebuilding the GNAT Run-Time Library::
166 General Ada Libraries
168 * Building a library::
169 * Installing a library::
172 Stand-alone Ada Libraries
174 * Introduction to Stand-alone Libraries::
175 * Building a Stand-alone Library::
176 * Creating a Stand-alone Library to be used in a non-Ada context::
177 * Restrictions in Stand-alone Libraries::
179 Conditional Compilation
181 * Modeling Conditional Compilation in Ada::
182 * Preprocessing with gnatprep::
183 * Integrated Preprocessing::
185 Modeling Conditional Compilation in Ada
187 * Use of Boolean Constants::
188 * Debugging - A Special Case::
189 * Conditionalizing Declarations::
190 * Use of Alternative Implementations::
193 Preprocessing with gnatprep
195 * Preprocessing Symbols::
197 * Switches for gnatprep::
198 * Form of Definitions File::
199 * Form of Input Text for gnatprep::
201 Mixed Language Programming
204 * Calling Conventions::
205 * Building Mixed Ada and C++ Programs::
206 * Generating Ada Bindings for C and C++ headers::
207 * Generating C Headers for Ada Specifications::
209 Building Mixed Ada and C++ Programs
211 * Interfacing to C++::
212 * Linking a Mixed C++ & Ada Program::
214 * Interfacing with C++ constructors::
215 * Interfacing with C++ at the Class Level::
217 Generating Ada Bindings for C and C++ headers
219 * Running the Binding Generator::
220 * Generating Bindings for C++ Headers::
223 Generating C Headers for Ada Specifications
225 * Running the C Header Generator::
227 GNAT and Other Compilation Models
229 * Comparison between GNAT and C/C++ Compilation Models::
230 * Comparison between GNAT and Conventional Ada Library Models::
232 Using GNAT Files with External Tools
234 * Using Other Utility Programs with GNAT::
235 * The External Symbol Naming Scheme of GNAT::
237 Building Executable Programs with GNAT
239 * Building with gnatmake::
240 * Compiling with gcc::
241 * Compiler Switches::
242 * Binding with gnatbind::
243 * Linking with gnatlink::
244 * Using the GNU make Utility::
246 Building with gnatmake
249 * Switches for gnatmake::
250 * Mode Switches for gnatmake::
251 * Notes on the Command Line::
252 * How gnatmake Works::
253 * Examples of gnatmake Usage::
257 * Compiling Programs::
258 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL.
259 * Order of Compilation Issues::
264 * Alphabetical List of All Switches::
265 * Output and Error Message Control::
266 * Warning Message Control::
267 * Debugging and Assertion Control::
268 * Validity Checking::
271 * Using gcc for Syntax Checking::
272 * Using gcc for Semantic Checking::
273 * Compiling Different Versions of Ada::
274 * Character Set Control::
275 * File Naming Control::
276 * Subprogram Inlining Control::
277 * Auxiliary Output Control::
278 * Debugging Control::
279 * Exception Handling Control::
280 * Units to Sources Mapping Files::
281 * Code Generation Control::
283 Binding with gnatbind
286 * Switches for gnatbind::
287 * Command-Line Access::
288 * Search Paths for gnatbind::
289 * Examples of gnatbind Usage::
291 Switches for gnatbind
293 * Consistency-Checking Modes::
294 * Binder Error Message Control::
295 * Elaboration Control::
297 * Dynamic Allocation Control::
298 * Binding with Non-Ada Main Programs::
299 * Binding Programs with No Main Subprogram::
301 Linking with gnatlink
304 * Switches for gnatlink::
306 Using the GNU make Utility
308 * Using gnatmake in a Makefile::
309 * Automatically Creating a List of Directories::
310 * Generating the Command Line Switches::
311 * Overcoming Command Line Length Limits::
316 * Building With Projects::
317 * Organizing Projects into Subsystems::
318 * Scenarios in Projects::
320 * Project Extension::
321 * Aggregate Projects::
322 * Aggregate Library Projects::
323 * Project File Reference::
325 Building With Projects
327 * Source Files and Directories::
328 * Duplicate Sources in Projects::
329 * Object and Exec Directory::
331 * Tools Options in Project Files::
332 * Compiling with Project Files::
333 * Executable File Names::
334 * Avoid Duplication With Variables::
337 * Distributed support::
339 Organizing Projects into Subsystems
341 * Project Dependencies::
342 * Cyclic Project Dependencies::
343 * Sharing Between Projects::
344 * Global Attributes::
348 * Building Libraries::
349 * Using Library Projects::
350 * Stand-alone Library Projects::
351 * Installing a library with project files::
355 * Project Hierarchy Extension::
359 * Building all main programs from a single project tree::
360 * Building a set of projects with a single command::
361 * Define a build environment::
362 * Performance improvements in builder::
363 * Syntax of aggregate projects::
364 * package Builder in aggregate projects::
366 Aggregate Library Projects
368 * Building aggregate library projects::
369 * Syntax of aggregate library projects::
371 Project File Reference
373 * Project Declaration::
374 * Qualified Projects::
379 * Typed String Declaration::
381 * Case Constructions::
386 * Project Level Attributes::
387 * Package Binder Attributes::
388 * Package Builder Attributes::
389 * Package Clean Attributes::
390 * Package Compiler Attributes::
391 * Package Cross_Reference Attributes::
392 * Package Finder Attributes::
393 * Package gnatls Attributes::
394 * Package IDE Attributes::
395 * Package Install Attributes::
396 * Package Linker Attributes::
397 * Package Naming Attributes::
398 * Package Remote Attributes::
399 * Package Stack Attributes::
400 * Package Synchronize Attributes::
402 Tools Supporting Project Files
404 * gnatmake and Project Files::
405 * The GNAT Driver and Project Files::
407 gnatmake and Project Files
409 * Switches Related to Project Files::
410 * Switches and Project Files::
411 * Specifying Configuration Pragmas::
412 * Project Files and Main Subprograms::
413 * Library Project Files::
415 GNAT Utility Programs
417 * The File Cleanup Utility gnatclean::
418 * The GNAT Library Browser gnatls::
419 * The Cross-Referencing Tools gnatxref and gnatfind::
420 * The Ada to HTML Converter gnathtml::
422 The File Cleanup Utility gnatclean
424 * Running gnatclean::
425 * Switches for gnatclean::
427 The GNAT Library Browser gnatls
430 * Switches for gnatls::
431 * Example of gnatls Usage::
433 The Cross-Referencing Tools gnatxref and gnatfind
435 * gnatxref Switches::
436 * gnatfind Switches::
437 * Project Files for gnatxref and gnatfind::
438 * Regular Expressions in gnatfind and gnatxref::
439 * Examples of gnatxref Usage::
440 * Examples of gnatfind Usage::
442 Examples of gnatxref Usage
445 * Using gnatxref with vi::
447 The Ada to HTML Converter gnathtml
449 * Invoking gnathtml::
450 * Installing gnathtml::
452 GNAT and Program Execution
454 * Running and Debugging Ada Programs::
455 * Code Coverage and Profiling::
456 * Improving Performance::
457 * Overflow Check Handling in GNAT::
458 * Performing Dimensionality Analysis in GNAT::
459 * Stack Related Facilities::
460 * Memory Management Issues::
462 Running and Debugging Ada Programs
464 * The GNAT Debugger GDB::
466 * Introduction to GDB Commands::
467 * Using Ada Expressions::
468 * Calling User-Defined Subprograms::
469 * Using the next Command in a Function::
470 * Stopping When Ada Exceptions Are Raised::
472 * Debugging Generic Units::
473 * Remote Debugging with gdbserver::
474 * GNAT Abnormal Termination or Failure to Terminate::
475 * Naming Conventions for GNAT Source Files::
476 * Getting Internal Debugging Information::
481 * Non-Symbolic Traceback::
482 * Symbolic Traceback::
484 Code Coverage and Profiling
486 * Code Coverage of Ada Programs with gcov::
487 * Profiling an Ada Program with gprof::
489 Code Coverage of Ada Programs with gcov
491 * Quick startup guide::
494 Profiling an Ada Program with gprof
496 * Compilation for profiling::
497 * Program execution::
499 * Interpretation of profiling results::
501 Improving Performance
503 * Performance Considerations::
504 * Text_IO Suggestions::
505 * Reducing Size of Executables with Unused Subprogram/Data Elimination::
507 Performance Considerations
509 * Controlling Run-Time Checks::
510 * Use of Restrictions::
511 * Optimization Levels::
512 * Debugging Optimized Code::
513 * Inlining of Subprograms::
514 * Floating_Point_Operations::
515 * Vectorization of loops::
516 * Other Optimization Switches::
517 * Optimization and Strict Aliasing::
518 * Aliased Variables and Optimization::
519 * Atomic Variables and Optimization::
520 * Passive Task Optimization::
522 Reducing Size of Executables with Unused Subprogram/Data Elimination
524 * About unused subprogram/data elimination::
525 * Compilation options::
526 * Example of unused subprogram/data elimination::
528 Overflow Check Handling in GNAT
531 * Management of Overflows in GNAT::
532 * Specifying the Desired Mode::
534 * Implementation Notes::
536 Stack Related Facilities
538 * Stack Overflow Checking::
539 * Static Stack Usage Analysis::
540 * Dynamic Stack Usage Analysis::
542 Memory Management Issues
544 * Some Useful Memory Pools::
545 * The GNAT Debug Pool Facility::
547 Platform-Specific Information
549 * Run-Time Libraries::
550 * Specifying a Run-Time Library::
551 * Microsoft Windows Topics::
556 * Summary of Run-Time Configurations::
558 Specifying a Run-Time Library
560 * Choosing the Scheduling Policy::
561 * Solaris-Specific Considerations::
562 * Solaris Threads Issues::
563 * AIX-Specific Considerations::
565 Microsoft Windows Topics
567 * Using GNAT on Windows::
568 * Using a network installation of GNAT::
569 * CONSOLE and WINDOWS subsystems::
571 * Mixed-Language Programming on Windows::
572 * Windows Specific Add-Ons::
574 Mixed-Language Programming on Windows
576 * Windows Calling Conventions::
577 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs.
578 * Using DLLs with GNAT::
579 * Building DLLs with GNAT Project files::
580 * Building DLLs with GNAT::
581 * Building DLLs with gnatdll::
582 * Ada DLLs and Finalization::
583 * Creating a Spec for Ada DLLs::
584 * GNAT and Windows Resources::
585 * Using GNAT DLLs from Microsoft Visual Studio Applications::
587 * Setting Stack Size from gnatlink::
588 * Setting Heap Size from gnatlink::
590 Windows Calling Conventions
592 * C Calling Convention::
593 * Stdcall Calling Convention::
594 * Win32 Calling Convention::
595 * DLL Calling Convention::
599 * Creating an Ada Spec for the DLL Services::
600 * Creating an Import Library::
602 Building DLLs with gnatdll
604 * Limitations When Using Ada DLLs from Ada::
605 * Exporting Ada Entities::
606 * Ada DLLs and Elaboration::
608 Creating a Spec for Ada DLLs
610 * Creating the Definition File::
613 GNAT and Windows Resources
615 * Building Resources::
616 * Compiling Resources::
621 * Program and DLL Both Built with GCC/GNAT::
622 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
624 Windows Specific Add-Ons
631 * Codesigning the Debugger::
633 Elaboration Order Handling in GNAT
636 * Checking the Elaboration Order::
637 * Controlling the Elaboration Order::
638 * Controlling Elaboration in GNAT - Internal Calls::
639 * Controlling Elaboration in GNAT - External Calls::
640 * Default Behavior in GNAT - Ensuring Safety::
641 * Treatment of Pragma Elaborate::
642 * Elaboration Issues for Library Tasks::
643 * Mixing Elaboration Models::
644 * What to Do If the Default Elaboration Behavior Fails::
645 * Elaboration for Indirect Calls::
646 * Summary of Procedures for Elaboration Control::
647 * Other Elaboration Order Considerations::
648 * Determining the Chosen Elaboration Order::
652 * Basic Assembler Syntax::
653 * A Simple Example of Inline Assembler::
654 * Output Variables in Inline Assembler::
655 * Input Variables in Inline Assembler::
656 * Inlining Inline Assembler Code::
657 * Other Asm Functionality::
659 Other Asm Functionality
661 * The Clobber Parameter::
662 * The Volatile Parameter::
667 @node About This Guide,Getting Started with GNAT,Top,Top
668 @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}
669 @chapter About This Guide
673 This guide describes the use of GNAT,
674 a compiler and software development
675 toolset for the full Ada programming language.
676 It documents the features of the compiler and tools, and explains
677 how to use them to build Ada applications.
679 GNAT implements Ada 95, Ada 2005 and Ada 2012, and it may also be
680 invoked in Ada 83 compatibility mode.
681 By default, GNAT assumes Ada 2012, but you can override with a
682 compiler switch (@ref{6,,Compiling Different Versions of Ada})
683 to explicitly specify the language version.
684 Throughout this manual, references to 'Ada' without a year suffix
685 apply to all Ada 95/2005/2012 versions of the language.
688 * What This Guide Contains::
689 * What You Should Know before Reading This Guide::
690 * Related Information::
691 * A Note to Readers of Previous Versions of the Manual::
696 @node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
697 @anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
698 @section What This Guide Contains
701 This guide contains the following chapters:
707 @ref{8,,Getting Started with GNAT} describes how to get started compiling
708 and running Ada programs with the GNAT Ada programming environment.
711 @ref{9,,The GNAT Compilation Model} describes the compilation model used
715 @ref{a,,Building Executable Programs with GNAT} describes how to use the
716 main GNAT tools to build executable programs, and it also gives examples of
717 using the GNU make utility with GNAT.
720 @ref{b,,GNAT Project Manager} describes how to use project files
721 to organize large projects.
724 @ref{c,,Tools Supporting Project Files} described how to use the project
725 facility in conjunction with various GNAT tools.
728 @ref{d,,GNAT Utility Programs} explains the various utility programs that
729 are included in the GNAT environment
732 @ref{e,,GNAT and Program Execution} covers a number of topics related to
733 running, debugging, and tuning the performace of programs developed
737 Appendices cover several additional topics:
743 @ref{f,,Platform-Specific Information} describes the different run-time
744 library implementations and also presents information on how to use
745 GNAT on several specific platforms
748 @ref{10,,Example of Binder Output File} shows the source code for the binder
749 output file for a sample program.
752 @ref{11,,Elaboration Order Handling in GNAT} describes how GNAT helps
753 you deal with elaboration order issues.
756 @ref{12,,Inline Assembler} shows how to use the inline assembly facility
760 @node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
761 @anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{13}
762 @section What You Should Know before Reading This Guide
765 @geindex Ada 95 Language Reference Manual
767 @geindex Ada 2005 Language Reference Manual
769 This guide assumes a basic familiarity with the Ada 95 language, as
770 described in the International Standard ANSI/ISO/IEC-8652:1995, January
772 It does not require knowledge of the features introduced by Ada 2005
774 Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
775 the GNAT documentation package.
777 @node Related Information,A Note to Readers of Previous Versions of the Manual,What You Should Know before Reading This Guide,About This Guide
778 @anchor{gnat_ugn/about_this_guide related-information}@anchor{14}
779 @section Related Information
782 For further information about Ada and related tools, please refer to the
789 @cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
790 @cite{Ada 2012 Reference Manual}, which contain reference
791 material for the several revisions of the Ada language standard.
794 @cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
795 implementation of Ada.
798 @cite{Using the GNAT Programming Studio}, which describes the GPS
799 Integrated Development Environment.
802 @cite{GNAT Programming Studio Tutorial}, which introduces the
803 main GPS features through examples.
806 @cite{Debugging with GDB},
807 for all details on the use of the GNU source-level debugger.
810 @cite{GNU Emacs Manual},
811 for full information on the extensible editor and programming
815 @node A Note to Readers of Previous Versions of the Manual,Conventions,Related Information,About This Guide
816 @anchor{gnat_ugn/about_this_guide a-note-to-readers-of-previous-versions-of-the-manual}@anchor{15}
817 @section A Note to Readers of Previous Versions of the Manual
820 In early 2015 the GNAT manuals were transitioned to the
821 reStructuredText (rst) / Sphinx documentation generator technology.
822 During that process the @cite{GNAT User's Guide} was reorganized
823 so that related topics would be described together in the same chapter
824 or appendix. Here's a summary of the major changes realized in
825 the new document structure.
831 @ref{9,,The GNAT Compilation Model} has been extended so that it now covers
832 the following material:
838 The @cite{gnatname}, @cite{gnatkr}, and @cite{gnatchop} tools
841 @ref{16,,Configuration Pragmas}
844 @ref{17,,GNAT and Libraries}
847 @ref{18,,Conditional Compilation} including @ref{19,,Preprocessing with gnatprep}
848 and @ref{1a,,Integrated Preprocessing}
851 @ref{1b,,Generating Ada Bindings for C and C++ headers}
854 @ref{1c,,Using GNAT Files with External Tools}
858 @ref{a,,Building Executable Programs with GNAT} is a new chapter consolidating
859 the following content:
865 @ref{1d,,Building with gnatmake}
868 @ref{1e,,Compiling with gcc}
871 @ref{1f,,Binding with gnatbind}
874 @ref{20,,Linking with gnatlink}
877 @ref{21,,Using the GNU make Utility}
881 @ref{d,,GNAT Utility Programs} is a new chapter consolidating the information about several
889 @ref{22,,The File Cleanup Utility gnatclean}
892 @ref{23,,The GNAT Library Browser gnatls}
895 @ref{24,,The Cross-Referencing Tools gnatxref and gnatfind}
898 @ref{25,,The Ada to HTML Converter gnathtml}
902 @ref{e,,GNAT and Program Execution} is a new chapter consolidating the following:
908 @ref{26,,Running and Debugging Ada Programs}
911 @ref{27,,Code Coverage and Profiling}
914 @ref{28,,Improving Performance}
917 @ref{29,,Overflow Check Handling in GNAT}
920 @ref{2a,,Performing Dimensionality Analysis in GNAT}
923 @ref{2b,,Stack Related Facilities}
926 @ref{2c,,Memory Management Issues}
930 @ref{f,,Platform-Specific Information} is a new appendix consolidating the following:
936 @ref{2d,,Run-Time Libraries}
939 @ref{2e,,Microsoft Windows Topics}
942 @ref{2f,,Mac OS Topics}
946 The @cite{Compatibility and Porting Guide} appendix has been moved to the
947 @cite{GNAT Reference Manual}. It now includes a section
948 @cite{Writing Portable Fixed-Point Declarations} which was previously
949 a separate chapter in the @cite{GNAT User's Guide}.
952 @node Conventions,,A Note to Readers of Previous Versions of the Manual,About This Guide
953 @anchor{gnat_ugn/about_this_guide conventions}@anchor{30}
958 @geindex typographical
960 @geindex Typographical conventions
962 Following are examples of the typographical and graphic conventions used
969 @cite{Functions}, @cite{utility program names}, @cite{standard names},
985 [optional information or parameters]
988 Examples are described by text
991 and then shown this way.
995 Commands that are entered by the user are shown as preceded by a prompt string
996 comprising the @code{$} character followed by a space.
999 Full file names are shown with the '/' character
1000 as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
1001 If you are using GNAT on a Windows platform, please note that
1002 the '\' character should be used instead.
1005 @node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
1006 @anchor{gnat_ugn/getting_started_with_gnat getting-started-with-gnat}@anchor{8}@anchor{gnat_ugn/getting_started_with_gnat doc}@anchor{31}@anchor{gnat_ugn/getting_started_with_gnat id1}@anchor{32}
1007 @chapter Getting Started with GNAT
1010 This chapter describes how to use GNAT's command line interface to build
1011 executable Ada programs.
1012 On most platforms a visually oriented Integrated Development Environment
1013 is also available, the GNAT Programming Studio (GPS).
1014 GPS offers a graphical "look and feel", support for development in
1015 other programming languages, comprehensive browsing features, and
1016 many other capabilities.
1017 For information on GPS please refer to
1018 @cite{Using the GNAT Programming Studio}.
1022 * Running a Simple Ada Program::
1023 * Running a Program with Multiple Units::
1024 * Using the gnatmake Utility::
1028 @node Running GNAT,Running a Simple Ada Program,,Getting Started with GNAT
1029 @anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{33}@anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{34}
1030 @section Running GNAT
1033 Three steps are needed to create an executable file from an Ada source
1040 The source file(s) must be compiled.
1043 The file(s) must be bound using the GNAT binder.
1046 All appropriate object files must be linked to produce an executable.
1049 All three steps are most commonly handled by using the @emph{gnatmake}
1050 utility program that, given the name of the main program, automatically
1051 performs the necessary compilation, binding and linking steps.
1053 @node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
1054 @anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{35}@anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{36}
1055 @section Running a Simple Ada Program
1058 Any text editor may be used to prepare an Ada program.
1059 (If Emacs is used, the optional Ada mode may be helpful in laying out the
1061 The program text is a normal text file. We will assume in our initial
1062 example that you have used your editor to prepare the following
1063 standard format text file:
1066 with Ada.Text_IO; use Ada.Text_IO;
1069 Put_Line ("Hello WORLD!");
1073 This file should be named @code{hello.adb}.
1074 With the normal default file naming conventions, GNAT requires
1076 contain a single compilation unit whose file name is the
1078 with periods replaced by hyphens; the
1079 extension is @code{ads} for a
1080 spec and @code{adb} for a body.
1081 You can override this default file naming convention by use of the
1082 special pragma @cite{Source_File_Name} (for further information please
1083 see @ref{37,,Using Other File Names}).
1084 Alternatively, if you want to rename your files according to this default
1085 convention, which is probably more convenient if you will be using GNAT
1086 for all your compilations, then the @cite{gnatchop} utility
1087 can be used to generate correctly-named source files
1088 (see @ref{38,,Renaming Files with gnatchop}).
1090 You can compile the program using the following command (@cite{$} is used
1091 as the command prompt in the examples in this document):
1097 @emph{gcc} is the command used to run the compiler. This compiler is
1098 capable of compiling programs in several languages, including Ada and
1099 C. It assumes that you have given it an Ada program if the file extension is
1100 either @code{.ads} or @code{.adb}, and it will then call
1101 the GNAT compiler to compile the specified file.
1103 The @code{-c} switch is required. It tells @emph{gcc} to only do a
1104 compilation. (For C programs, @emph{gcc} can also do linking, but this
1105 capability is not used directly for Ada programs, so the @code{-c}
1106 switch must always be present.)
1108 This compile command generates a file
1109 @code{hello.o}, which is the object
1110 file corresponding to your Ada program. It also generates
1111 an 'Ada Library Information' file @code{hello.ali},
1112 which contains additional information used to check
1113 that an Ada program is consistent.
1114 To build an executable file,
1115 use @cite{gnatbind} to bind the program
1116 and @emph{gnatlink} to link it. The
1117 argument to both @cite{gnatbind} and @emph{gnatlink} is the name of the
1118 @code{ALI} file, but the default extension of @code{.ali} can
1119 be omitted. This means that in the most common case, the argument
1120 is simply the name of the main program:
1127 A simpler method of carrying out these steps is to use @emph{gnatmake},
1128 a master program that invokes all the required
1129 compilation, binding and linking tools in the correct order. In particular,
1130 @emph{gnatmake} automatically recompiles any sources that have been
1131 modified since they were last compiled, or sources that depend
1132 on such modified sources, so that 'version skew' is avoided.
1134 @geindex Version skew (avoided by *gnatmake*)
1137 $ gnatmake hello.adb
1140 The result is an executable program called @code{hello}, which can be
1147 assuming that the current directory is on the search path
1148 for executable programs.
1150 and, if all has gone well, you will see:
1156 appear in response to this command.
1158 @node Running a Program with Multiple Units,Using the gnatmake Utility,Running a Simple Ada Program,Getting Started with GNAT
1159 @anchor{gnat_ugn/getting_started_with_gnat id4}@anchor{39}@anchor{gnat_ugn/getting_started_with_gnat running-a-program-with-multiple-units}@anchor{3a}
1160 @section Running a Program with Multiple Units
1163 Consider a slightly more complicated example that has three files: a
1164 main program, and the spec and body of a package:
1167 package Greetings is
1172 with Ada.Text_IO; use Ada.Text_IO;
1173 package body Greetings is
1176 Put_Line ("Hello WORLD!");
1179 procedure Goodbye is
1181 Put_Line ("Goodbye WORLD!");
1193 Following the one-unit-per-file rule, place this program in the
1194 following three separate files:
1199 @item @emph{greetings.ads}
1201 spec of package @cite{Greetings}
1203 @item @emph{greetings.adb}
1205 body of package @cite{Greetings}
1207 @item @emph{gmain.adb}
1209 body of main program
1212 To build an executable version of
1213 this program, we could use four separate steps to compile, bind, and link
1214 the program, as follows:
1218 $ gcc -c greetings.adb
1223 Note that there is no required order of compilation when using GNAT.
1224 In particular it is perfectly fine to compile the main program first.
1225 Also, it is not necessary to compile package specs in the case where
1226 there is an accompanying body; you only need to compile the body. If you want
1227 to submit these files to the compiler for semantic checking and not code
1228 generation, then use the @code{-gnatc} switch:
1231 $ gcc -c greetings.ads -gnatc
1234 Although the compilation can be done in separate steps as in the
1235 above example, in practice it is almost always more convenient
1236 to use the @emph{gnatmake} tool. All you need to know in this case
1237 is the name of the main program's source file. The effect of the above four
1238 commands can be achieved with a single one:
1241 $ gnatmake gmain.adb
1244 In the next section we discuss the advantages of using @emph{gnatmake} in
1247 @node Using the gnatmake Utility,,Running a Program with Multiple Units,Getting Started with GNAT
1248 @anchor{gnat_ugn/getting_started_with_gnat using-the-gnatmake-utility}@anchor{3b}@anchor{gnat_ugn/getting_started_with_gnat id5}@anchor{3c}
1249 @section Using the @emph{gnatmake} Utility
1252 If you work on a program by compiling single components at a time using
1253 @emph{gcc}, you typically keep track of the units you modify. In order to
1254 build a consistent system, you compile not only these units, but also any
1255 units that depend on the units you have modified.
1256 For example, in the preceding case,
1257 if you edit @code{gmain.adb}, you only need to recompile that file. But if
1258 you edit @code{greetings.ads}, you must recompile both
1259 @code{greetings.adb} and @code{gmain.adb}, because both files contain
1260 units that depend on @code{greetings.ads}.
1262 @emph{gnatbind} will warn you if you forget one of these compilation
1263 steps, so that it is impossible to generate an inconsistent program as a
1264 result of forgetting to do a compilation. Nevertheless it is tedious and
1265 error-prone to keep track of dependencies among units.
1266 One approach to handle the dependency-bookkeeping is to use a
1267 makefile. However, makefiles present maintenance problems of their own:
1268 if the dependencies change as you change the program, you must make
1269 sure that the makefile is kept up-to-date manually, which is also an
1270 error-prone process.
1272 The @emph{gnatmake} utility takes care of these details automatically.
1273 Invoke it using either one of the following forms:
1276 $ gnatmake gmain.adb
1280 The argument is the name of the file containing the main program;
1281 you may omit the extension. @emph{gnatmake}
1282 examines the environment, automatically recompiles any files that need
1283 recompiling, and binds and links the resulting set of object files,
1284 generating the executable file, @code{gmain}.
1285 In a large program, it
1286 can be extremely helpful to use @emph{gnatmake}, because working out by hand
1287 what needs to be recompiled can be difficult.
1289 Note that @emph{gnatmake} takes into account all the Ada rules that
1290 establish dependencies among units. These include dependencies that result
1291 from inlining subprogram bodies, and from
1292 generic instantiation. Unlike some other
1293 Ada make tools, @emph{gnatmake} does not rely on the dependencies that were
1294 found by the compiler on a previous compilation, which may possibly
1295 be wrong when sources change. @emph{gnatmake} determines the exact set of
1296 dependencies from scratch each time it is run.
1298 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
1300 @node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
1301 @anchor{gnat_ugn/the_gnat_compilation_model doc}@anchor{3d}@anchor{gnat_ugn/the_gnat_compilation_model the-gnat-compilation-model}@anchor{9}@anchor{gnat_ugn/the_gnat_compilation_model id1}@anchor{3e}
1302 @chapter The GNAT Compilation Model
1305 @geindex GNAT compilation model
1307 @geindex Compilation model
1309 This chapter describes the compilation model used by GNAT. Although
1310 similar to that used by other languages such as C and C++, this model
1311 is substantially different from the traditional Ada compilation models,
1312 which are based on a centralized program library. The chapter covers
1313 the following material:
1319 Topics related to source file makeup and naming
1325 @ref{3f,,Source Representation}
1328 @ref{40,,Foreign Language Representation}
1331 @ref{41,,File Naming Topics and Utilities}
1335 @ref{16,,Configuration Pragmas}
1338 @ref{42,,Generating Object Files}
1341 @ref{43,,Source Dependencies}
1344 @ref{44,,The Ada Library Information Files}
1347 @ref{45,,Binding an Ada Program}
1350 @ref{17,,GNAT and Libraries}
1353 @ref{18,,Conditional Compilation}
1356 @ref{46,,Mixed Language Programming}
1359 @ref{47,,GNAT and Other Compilation Models}
1362 @ref{1c,,Using GNAT Files with External Tools}
1366 * Source Representation::
1367 * Foreign Language Representation::
1368 * File Naming Topics and Utilities::
1369 * Configuration Pragmas::
1370 * Generating Object Files::
1371 * Source Dependencies::
1372 * The Ada Library Information Files::
1373 * Binding an Ada Program::
1374 * GNAT and Libraries::
1375 * Conditional Compilation::
1376 * Mixed Language Programming::
1377 * GNAT and Other Compilation Models::
1378 * Using GNAT Files with External Tools::
1382 @node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1383 @anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{3f}@anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{48}
1384 @section Source Representation
1395 Ada source programs are represented in standard text files, using
1396 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1397 7-bit ASCII set, plus additional characters used for
1398 representing foreign languages (see @ref{40,,Foreign Language Representation}
1399 for support of non-USA character sets). The format effector characters
1400 are represented using their standard ASCII encodings, as follows:
1405 @multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxx}
1482 Source files are in standard text file format. In addition, GNAT will
1483 recognize a wide variety of stream formats, in which the end of
1484 physical lines is marked by any of the following sequences:
1485 @cite{LF}, @cite{CR}, @cite{CR-LF}, or @cite{LF-CR}. This is useful
1486 in accommodating files that are imported from other operating systems.
1488 @geindex End of source file; Source file@comma{} end
1490 @geindex SUB (control character)
1492 The end of a source file is normally represented by the physical end of
1493 file. However, the control character @cite{16#1A#} (@code{SUB}) is also
1494 recognized as signalling the end of the source file. Again, this is
1495 provided for compatibility with other operating systems where this
1496 code is used to represent the end of file.
1498 @geindex spec (definition)
1499 @geindex compilation (definition)
1501 Each file contains a single Ada compilation unit, including any pragmas
1502 associated with the unit. For example, this means you must place a
1503 package declaration (a package @cite{spec}) and the corresponding body in
1504 separate files. An Ada @cite{compilation} (which is a sequence of
1505 compilation units) is represented using a sequence of files. Similarly,
1506 you will place each subunit or child unit in a separate file.
1508 @node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1509 @anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{49}
1510 @section Foreign Language Representation
1513 GNAT supports the standard character sets defined in Ada as well as
1514 several other non-standard character sets for use in localized versions
1515 of the compiler (@ref{4a,,Character Set Control}).
1519 * Other 8-Bit Codes::
1520 * Wide_Character Encodings::
1521 * Wide_Wide_Character Encodings::
1525 @node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1526 @anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{4b}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{4c}
1532 The basic character set is Latin-1. This character set is defined by ISO
1533 standard 8859, part 1. The lower half (character codes @cite{16#00#}
1534 ... @cite{16#7F#)} is identical to standard ASCII coding, but the upper
1535 half is used to represent additional characters. These include extended letters
1536 used by European languages, such as French accents, the vowels with umlauts
1537 used in German, and the extra letter A-ring used in Swedish.
1539 @geindex Ada.Characters.Latin_1
1541 For a complete list of Latin-1 codes and their encodings, see the source
1542 file of library unit @cite{Ada.Characters.Latin_1} in file
1543 @code{a-chlat1.ads}.
1544 You may use any of these extended characters freely in character or
1545 string literals. In addition, the extended characters that represent
1546 letters can be used in identifiers.
1548 @node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1549 @anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{4d}@anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{4e}
1550 @subsection Other 8-Bit Codes
1553 GNAT also supports several other 8-bit coding schemes:
1562 @item @emph{ISO 8859-2 (Latin-2)}
1564 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1575 @item @emph{ISO 8859-3 (Latin-3)}
1577 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1588 @item @emph{ISO 8859-4 (Latin-4)}
1590 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1601 @item @emph{ISO 8859-5 (Cyrillic)}
1603 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1604 lowercase equivalence.
1607 @geindex ISO 8859-15
1614 @item @emph{ISO 8859-15 (Latin-9)}
1616 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1617 lowercase equivalence
1620 @geindex code page 437 (IBM PC)
1625 @item @emph{IBM PC (code page 437)}
1627 This code page is the normal default for PCs in the U.S. It corresponds
1628 to the original IBM PC character set. This set has some, but not all, of
1629 the extended Latin-1 letters, but these letters do not have the same
1630 encoding as Latin-1. In this mode, these letters are allowed in
1631 identifiers with uppercase and lowercase equivalence.
1634 @geindex code page 850 (IBM PC)
1639 @item @emph{IBM PC (code page 850)}
1641 This code page is a modification of 437 extended to include all the
1642 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1643 mode, all these letters are allowed in identifiers with uppercase and
1644 lowercase equivalence.
1646 @item @emph{Full Upper 8-bit}
1648 Any character in the range 80-FF allowed in identifiers, and all are
1649 considered distinct. In other words, there are no uppercase and lowercase
1650 equivalences in this range. This is useful in conjunction with
1651 certain encoding schemes used for some foreign character sets (e.g.,
1652 the typical method of representing Chinese characters on the PC).
1654 @item @emph{No Upper-Half}
1656 No upper-half characters in the range 80-FF are allowed in identifiers.
1657 This gives Ada 83 compatibility for identifier names.
1660 For precise data on the encodings permitted, and the uppercase and lowercase
1661 equivalences that are recognized, see the file @code{csets.adb} in
1662 the GNAT compiler sources. You will need to obtain a full source release
1663 of GNAT to obtain this file.
1665 @node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1666 @anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{4f}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{50}
1667 @subsection Wide_Character Encodings
1670 GNAT allows wide character codes to appear in character and string
1671 literals, and also optionally in identifiers, by means of the following
1672 possible encoding schemes:
1677 @item @emph{Hex Coding}
1679 In this encoding, a wide character is represented by the following five
1686 where @cite{a}, @cite{b}, @cite{c}, @cite{d} are the four hexadecimal
1687 characters (using uppercase letters) of the wide character code. For
1688 example, ESC A345 is used to represent the wide character with code
1690 This scheme is compatible with use of the full Wide_Character set.
1692 @item @emph{Upper-Half Coding}
1694 @geindex Upper-Half Coding
1696 The wide character with encoding @cite{16#abcd#} where the upper bit is on
1697 (in other words, 'a' is in the range 8-F) is represented as two bytes,
1698 @cite{16#ab#} and @cite{16#cd#}. The second byte cannot be a format control
1699 character, but is not required to be in the upper half. This method can
1700 be also used for shift-JIS or EUC, where the internal coding matches the
1703 @item @emph{Shift JIS Coding}
1705 @geindex Shift JIS Coding
1707 A wide character is represented by a two-character sequence,
1709 @cite{16#cd#}, with the restrictions described for upper-half encoding as
1710 described above. The internal character code is the corresponding JIS
1711 character according to the standard algorithm for Shift-JIS
1712 conversion. Only characters defined in the JIS code set table can be
1713 used with this encoding method.
1715 @item @emph{EUC Coding}
1719 A wide character is represented by a two-character sequence
1721 @cite{16#cd#}, with both characters being in the upper half. The internal
1722 character code is the corresponding JIS character according to the EUC
1723 encoding algorithm. Only characters defined in the JIS code set table
1724 can be used with this encoding method.
1726 @item @emph{UTF-8 Coding}
1728 A wide character is represented using
1729 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1730 10646-1/Am.2. Depending on the character value, the representation
1731 is a one, two, or three byte sequence:
1734 16#0000#-16#007f#: 2#0`xxxxxxx`#
1735 16#0080#-16#07ff#: 2#110`xxxxx`# 2#10`xxxxxx`#
1736 16#0800#-16#ffff#: 2#1110`xxxx`# 2#10`xxxxxx`# 2#10`xxxxxx`#
1739 where the @cite{xxx} bits correspond to the left-padded bits of the
1740 16-bit character value. Note that all lower half ASCII characters
1741 are represented as ASCII bytes and all upper half characters and
1742 other wide characters are represented as sequences of upper-half
1743 (The full UTF-8 scheme allows for encoding 31-bit characters as
1744 6-byte sequences, and in the following section on wide wide
1745 characters, the use of these sequences is documented).
1747 @item @emph{Brackets Coding}
1749 In this encoding, a wide character is represented by the following eight
1756 where @cite{a}, @cite{b}, @cite{c}, @cite{d} are the four hexadecimal
1757 characters (using uppercase letters) of the wide character code. For
1758 example, ['A345'] is used to represent the wide character with code
1759 @cite{16#A345#}. It is also possible (though not required) to use the
1760 Brackets coding for upper half characters. For example, the code
1761 @cite{16#A3#} can be represented as @cite{['A3']}.
1763 This scheme is compatible with use of the full Wide_Character set,
1764 and is also the method used for wide character encoding in some standard
1765 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1770 Some of these coding schemes do not permit the full use of the
1771 Ada character set. For example, neither Shift JIS nor EUC allow the
1772 use of the upper half of the Latin-1 set.
1776 @node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1777 @anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{52}
1778 @subsection Wide_Wide_Character Encodings
1781 GNAT allows wide wide character codes to appear in character and string
1782 literals, and also optionally in identifiers, by means of the following
1783 possible encoding schemes:
1788 @item @emph{UTF-8 Coding}
1790 A wide character is represented using
1791 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1792 10646-1/Am.2. Depending on the character value, the representation
1793 of character codes with values greater than 16#FFFF# is a
1794 is a four, five, or six byte sequence:
1797 16#01_0000#-16#10_FFFF#: 11110xxx 10xxxxxx 10xxxxxx
1799 16#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1801 16#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1802 10xxxxxx 10xxxxxx 10xxxxxx
1805 where the @cite{xxx} bits correspond to the left-padded bits of the
1806 32-bit character value.
1808 @item @emph{Brackets Coding}
1810 In this encoding, a wide wide character is represented by the following ten or
1811 twelve byte character sequence:
1815 [ " a b c d e f g h " ]
1818 where @cite{a-h} are the six or eight hexadecimal
1819 characters (using uppercase letters) of the wide wide character code. For
1820 example, ["1F4567"] is used to represent the wide wide character with code
1821 @cite{16#001F_4567#}.
1823 This scheme is compatible with use of the full Wide_Wide_Character set,
1824 and is also the method used for wide wide character encoding in some standard
1825 ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1828 @node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1829 @anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{53}@anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{41}
1830 @section File Naming Topics and Utilities
1833 GNAT has a default file naming scheme and also provides the user with
1834 a high degree of control over how the names and extensions of the
1835 source files correspond to the Ada compilation units that they contain.
1838 * File Naming Rules::
1839 * Using Other File Names::
1840 * Alternative File Naming Schemes::
1841 * Handling Arbitrary File Naming Conventions with gnatname::
1842 * File Name Krunching with gnatkr::
1843 * Renaming Files with gnatchop::
1847 @node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1848 @anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{54}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{55}
1849 @subsection File Naming Rules
1852 The default file name is determined by the name of the unit that the
1853 file contains. The name is formed by taking the full expanded name of
1854 the unit and replacing the separating dots with hyphens and using
1855 lowercase for all letters.
1857 An exception arises if the file name generated by the above rules starts
1858 with one of the characters
1859 @cite{a}, @cite{g}, @cite{i}, or @cite{s}, and the second character is a
1860 minus. In this case, the character tilde is used in place
1861 of the minus. The reason for this special rule is to avoid clashes with
1862 the standard names for child units of the packages System, Ada,
1863 Interfaces, and GNAT, which use the prefixes
1864 @cite{s-}, @cite{a-}, @cite{i-}, and @cite{g-},
1867 The file extension is @code{.ads} for a spec and
1868 @code{.adb} for a body. The following table shows some
1869 examples of these rules.
1874 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
1881 Ada Compilation Unit
1901 @code{arith_functions.ads}
1905 Arith_Functions (package spec)
1909 @code{arith_functions.adb}
1913 Arith_Functions (package body)
1917 @code{func-spec.ads}
1921 Func.Spec (child package spec)
1925 @code{func-spec.adb}
1929 Func.Spec (child package body)
1937 Sub (subunit of Main)
1945 A.Bad (child package body)
1951 Following these rules can result in excessively long
1952 file names if corresponding
1953 unit names are long (for example, if child units or subunits are
1954 heavily nested). An option is available to shorten such long file names
1955 (called file name 'krunching'). This may be particularly useful when
1956 programs being developed with GNAT are to be used on operating systems
1957 with limited file name lengths. @ref{56,,Using gnatkr}.
1959 Of course, no file shortening algorithm can guarantee uniqueness over
1960 all possible unit names; if file name krunching is used, it is your
1961 responsibility to ensure no name clashes occur. Alternatively you
1962 can specify the exact file names that you want used, as described
1963 in the next section. Finally, if your Ada programs are migrating from a
1964 compiler with a different naming convention, you can use the gnatchop
1965 utility to produce source files that follow the GNAT naming conventions.
1966 (For details see @ref{38,,Renaming Files with gnatchop}.)
1968 Note: in the case of Windows or Mac OS operating systems, case is not
1969 significant. So for example on @cite{Windows} if the canonical name is
1970 @cite{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1971 However, case is significant for other operating systems, so for example,
1972 if you want to use other than canonically cased file names on a Unix system,
1973 you need to follow the procedures described in the next section.
1975 @node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1976 @anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{57}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{37}
1977 @subsection Using Other File Names
1982 In the previous section, we have described the default rules used by
1983 GNAT to determine the file name in which a given unit resides. It is
1984 often convenient to follow these default rules, and if you follow them,
1985 the compiler knows without being explicitly told where to find all
1988 @geindex Source_File_Name pragma
1990 However, in some cases, particularly when a program is imported from
1991 another Ada compiler environment, it may be more convenient for the
1992 programmer to specify which file names contain which units. GNAT allows
1993 arbitrary file names to be used by means of the Source_File_Name pragma.
1994 The form of this pragma is as shown in the following examples:
1997 pragma Source_File_Name (My_Utilities.Stacks,
1998 Spec_File_Name => "myutilst_a.ada");
1999 pragma Source_File_name (My_Utilities.Stacks,
2000 Body_File_Name => "myutilst.ada");
2003 As shown in this example, the first argument for the pragma is the unit
2004 name (in this example a child unit). The second argument has the form
2005 of a named association. The identifier
2006 indicates whether the file name is for a spec or a body;
2007 the file name itself is given by a string literal.
2009 The source file name pragma is a configuration pragma, which means that
2010 normally it will be placed in the @code{gnat.adc}
2011 file used to hold configuration
2012 pragmas that apply to a complete compilation environment.
2013 For more details on how the @code{gnat.adc} file is created and used
2014 see @ref{58,,Handling of Configuration Pragmas}.
2018 GNAT allows completely arbitrary file names to be specified using the
2019 source file name pragma. However, if the file name specified has an
2020 extension other than @code{.ads} or @code{.adb} it is necessary to use
2021 a special syntax when compiling the file. The name in this case must be
2022 preceded by the special sequence @emph{-x} followed by a space and the name
2023 of the language, here @cite{ada}, as in:
2026 $ gcc -c -x ada peculiar_file_name.sim
2029 @cite{gnatmake} handles non-standard file names in the usual manner (the
2030 non-standard file name for the main program is simply used as the
2031 argument to gnatmake). Note that if the extension is also non-standard,
2032 then it must be included in the @cite{gnatmake} command, it may not
2035 @node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
2036 @anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{59}@anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{5a}
2037 @subsection Alternative File Naming Schemes
2040 @geindex File naming schemes
2041 @geindex alternative
2045 The previous section described the use of the @cite{Source_File_Name}
2046 pragma to allow arbitrary names to be assigned to individual source files.
2047 However, this approach requires one pragma for each file, and especially in
2048 large systems can result in very long @code{gnat.adc} files, and also create
2049 a maintenance problem.
2051 @geindex Source_File_Name pragma
2053 GNAT also provides a facility for specifying systematic file naming schemes
2054 other than the standard default naming scheme previously described. An
2055 alternative scheme for naming is specified by the use of
2056 @cite{Source_File_Name} pragmas having the following format:
2059 pragma Source_File_Name (
2060 Spec_File_Name => FILE_NAME_PATTERN
2061 [ , Casing => CASING_SPEC]
2062 [ , Dot_Replacement => STRING_LITERAL ] );
2064 pragma Source_File_Name (
2065 Body_File_Name => FILE_NAME_PATTERN
2066 [ , Casing => CASING_SPEC ]
2067 [ , Dot_Replacement => STRING_LITERAL ] ) ;
2069 pragma Source_File_Name (
2070 Subunit_File_Name => FILE_NAME_PATTERN
2071 [ , Casing => CASING_SPEC ]
2072 [ , Dot_Replacement => STRING_LITERAL ] ) ;
2074 FILE_NAME_PATTERN ::= STRING_LITERAL
2075 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
2078 The @cite{FILE_NAME_PATTERN} string shows how the file name is constructed.
2079 It contains a single asterisk character, and the unit name is substituted
2080 systematically for this asterisk. The optional parameter
2081 @cite{Casing} indicates
2082 whether the unit name is to be all upper-case letters, all lower-case letters,
2083 or mixed-case. If no
2084 @cite{Casing} parameter is used, then the default is all
2087 The optional @cite{Dot_Replacement} string is used to replace any periods
2088 that occur in subunit or child unit names. If no @cite{Dot_Replacement}
2089 argument is used then separating dots appear unchanged in the resulting
2091 Although the above syntax indicates that the
2092 @cite{Casing} argument must appear
2093 before the @cite{Dot_Replacement} argument, but it
2094 is also permissible to write these arguments in the opposite order.
2096 As indicated, it is possible to specify different naming schemes for
2097 bodies, specs, and subunits. Quite often the rule for subunits is the
2098 same as the rule for bodies, in which case, there is no need to give
2099 a separate @cite{Subunit_File_Name} rule, and in this case the
2100 @cite{Body_File_name} rule is used for subunits as well.
2102 The separate rule for subunits can also be used to implement the rather
2103 unusual case of a compilation environment (e.g., a single directory) which
2104 contains a subunit and a child unit with the same unit name. Although
2105 both units cannot appear in the same partition, the Ada Reference Manual
2106 allows (but does not require) the possibility of the two units coexisting
2107 in the same environment.
2109 The file name translation works in the following steps:
2115 If there is a specific @cite{Source_File_Name} pragma for the given unit,
2116 then this is always used, and any general pattern rules are ignored.
2119 If there is a pattern type @cite{Source_File_Name} pragma that applies to
2120 the unit, then the resulting file name will be used if the file exists. If
2121 more than one pattern matches, the latest one will be tried first, and the
2122 first attempt resulting in a reference to a file that exists will be used.
2125 If no pattern type @cite{Source_File_Name} pragma that applies to the unit
2126 for which the corresponding file exists, then the standard GNAT default
2127 naming rules are used.
2130 As an example of the use of this mechanism, consider a commonly used scheme
2131 in which file names are all lower case, with separating periods copied
2132 unchanged to the resulting file name, and specs end with @code{.1.ada}, and
2133 bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
2137 pragma Source_File_Name
2138 (Spec_File_Name => ".1.ada");
2139 pragma Source_File_Name
2140 (Body_File_Name => ".2.ada");
2143 The default GNAT scheme is actually implemented by providing the following
2144 default pragmas internally:
2147 pragma Source_File_Name
2148 (Spec_File_Name => ".ads", Dot_Replacement => "-");
2149 pragma Source_File_Name
2150 (Body_File_Name => ".adb", Dot_Replacement => "-");
2153 Our final example implements a scheme typically used with one of the
2154 Ada 83 compilers, where the separator character for subunits was '__'
2155 (two underscores), specs were identified by adding @code{_.ADA}, bodies
2156 by adding @code{.ADA}, and subunits by
2157 adding @code{.SEP}. All file names were
2158 upper case. Child units were not present of course since this was an
2159 Ada 83 compiler, but it seems reasonable to extend this scheme to use
2160 the same double underscore separator for child units.
2163 pragma Source_File_Name
2164 (Spec_File_Name => "_.ADA",
2165 Dot_Replacement => "__",
2166 Casing = Uppercase);
2167 pragma Source_File_Name
2168 (Body_File_Name => ".ADA",
2169 Dot_Replacement => "__",
2170 Casing = Uppercase);
2171 pragma Source_File_Name
2172 (Subunit_File_Name => ".SEP",
2173 Dot_Replacement => "__",
2174 Casing = Uppercase);
2179 @node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
2180 @anchor{gnat_ugn/the_gnat_compilation_model handling-arbitrary-file-naming-conventions-with-gnatname}@anchor{5b}@anchor{gnat_ugn/the_gnat_compilation_model id12}@anchor{5c}
2181 @subsection Handling Arbitrary File Naming Conventions with @cite{gnatname}
2184 @geindex File Naming Conventions
2187 * Arbitrary File Naming Conventions::
2188 * Running gnatname::
2189 * Switches for gnatname::
2190 * Examples of gnatname Usage::
2194 @node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
2195 @anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{5d}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{5e}
2196 @subsubsection Arbitrary File Naming Conventions
2199 The GNAT compiler must be able to know the source file name of a compilation
2200 unit. When using the standard GNAT default file naming conventions
2201 (@cite{.ads} for specs, @cite{.adb} for bodies), the GNAT compiler
2202 does not need additional information.
2204 When the source file names do not follow the standard GNAT default file naming
2205 conventions, the GNAT compiler must be given additional information through
2206 a configuration pragmas file (@ref{16,,Configuration Pragmas})
2208 When the non-standard file naming conventions are well-defined,
2209 a small number of pragmas @cite{Source_File_Name} specifying a naming pattern
2210 (@ref{5a,,Alternative File Naming Schemes}) may be sufficient. However,
2211 if the file naming conventions are irregular or arbitrary, a number
2212 of pragma @cite{Source_File_Name} for individual compilation units
2214 To help maintain the correspondence between compilation unit names and
2215 source file names within the compiler,
2216 GNAT provides a tool @cite{gnatname} to generate the required pragmas for a
2219 @node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
2220 @anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{5f}@anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{60}
2221 @subsubsection Running @cite{gnatname}
2224 The usual form of the @cite{gnatname} command is:
2227 $ gnatname [`switches`] `naming_pattern` [`naming_patterns`]
2228 [--and [`switches`] `naming_pattern` [`naming_patterns`]]
2231 All of the arguments are optional. If invoked without any argument,
2232 @cite{gnatname} will display its usage.
2234 When used with at least one naming pattern, @cite{gnatname} will attempt to
2235 find all the compilation units in files that follow at least one of the
2236 naming patterns. To find these compilation units,
2237 @cite{gnatname} will use the GNAT compiler in syntax-check-only mode on all
2240 One or several Naming Patterns may be given as arguments to @cite{gnatname}.
2241 Each Naming Pattern is enclosed between double quotes (or single
2243 A Naming Pattern is a regular expression similar to the wildcard patterns
2244 used in file names by the Unix shells or the DOS prompt.
2246 @cite{gnatname} may be called with several sections of directories/patterns.
2247 Sections are separated by switch @cite{--and}. In each section, there must be
2248 at least one pattern. If no directory is specified in a section, the current
2249 directory (or the project directory is @cite{-P} is used) is implied.
2250 The options other that the directory switches and the patterns apply globally
2251 even if they are in different sections.
2253 Examples of Naming Patterns are:
2261 For a more complete description of the syntax of Naming Patterns,
2262 see the second kind of regular expressions described in @code{g-regexp.ads}
2263 (the 'Glob' regular expressions).
2265 When invoked with no switch @cite{-P}, @cite{gnatname} will create a
2266 configuration pragmas file @code{gnat.adc} in the current working directory,
2267 with pragmas @cite{Source_File_Name} for each file that contains a valid Ada
2270 @node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
2271 @anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{61}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{62}
2272 @subsubsection Switches for @cite{gnatname}
2275 Switches for @cite{gnatname} must precede any specified Naming Pattern.
2277 You may specify any of the following switches to @cite{gnatname}:
2279 @geindex --version (gnatname)
2284 @item @code{--version}
2286 Display Copyright and version, then exit disregarding all other options.
2289 @geindex --help (gnatname)
2296 If @emph{--version} was not used, display usage, then exit disregarding
2299 @item @code{--subdirs=@emph{dir}}
2301 Real object, library or exec directories are subdirectories <dir> of the
2304 @item @code{--no-backup}
2306 Do not create a backup copy of an existing project file.
2310 Start another section of directories/patterns.
2313 @geindex -c (gnatname)
2318 @item @code{-c@emph{filename}}
2320 Create a configuration pragmas file @code{filename} (instead of the default
2322 There may be zero, one or more space between @emph{-c} and
2324 @code{filename} may include directory information. @code{filename} must be
2325 writable. There may be only one switch @emph{-c}.
2326 When a switch @emph{-c} is
2327 specified, no switch @emph{-P} may be specified (see below).
2330 @geindex -d (gnatname)
2335 @item @code{-d@emph{dir}}
2337 Look for source files in directory @code{dir}. There may be zero, one or more
2338 spaces between @emph{-d} and @code{dir}.
2339 @code{dir} may end with @cite{/**}, that is it may be of the form
2340 @cite{root_dir/**}. In this case, the directory @cite{root_dir} and all of its
2341 subdirectories, recursively, have to be searched for sources.
2342 When a switch @emph{-d}
2343 is specified, the current working directory will not be searched for source
2344 files, unless it is explicitly specified with a @emph{-d}
2345 or @emph{-D} switch.
2346 Several switches @emph{-d} may be specified.
2347 If @code{dir} is a relative path, it is relative to the directory of
2348 the configuration pragmas file specified with switch
2350 or to the directory of the project file specified with switch
2352 if neither switch @emph{-c}
2353 nor switch @emph{-P} are specified, it is relative to the
2354 current working directory. The directory
2355 specified with switch @emph{-d} must exist and be readable.
2358 @geindex -D (gnatname)
2363 @item @code{-D@emph{filename}}
2365 Look for source files in all directories listed in text file @code{filename}.
2366 There may be zero, one or more spaces between @emph{-D}
2367 and @code{filename}.
2368 @code{filename} must be an existing, readable text file.
2369 Each nonempty line in @code{filename} must be a directory.
2370 Specifying switch @emph{-D} is equivalent to specifying as many
2371 switches @emph{-d} as there are nonempty lines in
2376 Follow symbolic links when processing project files.
2378 @geindex -f (gnatname)
2380 @item @code{-f@emph{pattern}}
2382 Foreign patterns. Using this switch, it is possible to add sources of languages
2383 other than Ada to the list of sources of a project file.
2384 It is only useful if a -P switch is used.
2388 gnatname -Pprj -f"*.c" "*.ada"
2391 will look for Ada units in all files with the @code{.ada} extension,
2392 and will add to the list of file for project @code{prj.gpr} the C files
2393 with extension @code{.c}.
2395 @geindex -h (gnatname)
2399 Output usage (help) information. The output is written to @code{stdout}.
2401 @geindex -P (gnatname)
2403 @item @code{-P@emph{proj}}
2405 Create or update project file @code{proj}. There may be zero, one or more space
2406 between @emph{-P} and @code{proj}. @code{proj} may include directory
2407 information. @code{proj} must be writable.
2408 There may be only one switch @emph{-P}.
2409 When a switch @emph{-P} is specified,
2410 no switch @emph{-c} may be specified.
2411 On all platforms, except on VMS, when @cite{gnatname} is invoked for an
2412 existing project file <proj>.gpr, a backup copy of the project file is created
2413 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
2414 non negative number that makes this backup copy a new file.
2416 @geindex -v (gnatname)
2420 Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2421 This includes name of the file written, the name of the directories to search
2422 and, for each file in those directories whose name matches at least one of
2423 the Naming Patterns, an indication of whether the file contains a unit,
2424 and if so the name of the unit.
2427 @geindex -v -v (gnatname)
2434 Very Verbose mode. In addition to the output produced in verbose mode,
2435 for each file in the searched directories whose name matches none of
2436 the Naming Patterns, an indication is given that there is no match.
2438 @geindex -x (gnatname)
2440 @item @code{-x@emph{pattern}}
2442 Excluded patterns. Using this switch, it is possible to exclude some files
2443 that would match the name patterns. For example,
2446 gnatname -x "*_nt.ada" "*.ada"
2449 will look for Ada units in all files with the @code{.ada} extension,
2450 except those whose names end with @code{_nt.ada}.
2453 @node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2454 @anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{63}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{64}
2455 @subsubsection Examples of @cite{gnatname} Usage
2459 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2462 In this example, the directory @code{/home/me} must already exist
2463 and be writable. In addition, the directory
2464 @code{/home/me/sources} (specified by
2465 @emph{-d sources}) must exist and be readable.
2467 Note the optional spaces after @emph{-c} and @emph{-d}.
2470 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
2471 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2474 Note that several switches @emph{-d} may be used,
2475 even in conjunction with one or several switches
2476 @emph{-D}. Several Naming Patterns and one excluded pattern
2477 are used in this example.
2479 @node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2480 @anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{66}
2481 @subsection File Name Krunching with @cite{gnatkr}
2486 This chapter discusses the method used by the compiler to shorten
2487 the default file names chosen for Ada units so that they do not
2488 exceed the maximum length permitted. It also describes the
2489 @cite{gnatkr} utility that can be used to determine the result of
2490 applying this shortening.
2495 * Krunching Method::
2496 * Examples of gnatkr Usage::
2500 @node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2501 @anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{67}@anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{68}
2502 @subsubsection About @cite{gnatkr}
2505 The default file naming rule in GNAT
2506 is that the file name must be derived from
2507 the unit name. The exact default rule is as follows:
2513 Take the unit name and replace all dots by hyphens.
2516 If such a replacement occurs in the
2517 second character position of a name, and the first character is
2518 @code{a}, @code{g}, @code{s}, or @code{i},
2519 then replace the dot by the character
2523 The reason for this exception is to avoid clashes
2524 with the standard names for children of System, Ada, Interfaces,
2525 and GNAT, which use the prefixes
2526 @code{s-}, @code{a-}, @code{i-}, and @code{g-},
2530 The @code{-gnatk@emph{nn}}
2531 switch of the compiler activates a 'krunching'
2532 circuit that limits file names to nn characters (where nn is a decimal
2535 The @cite{gnatkr} utility can be used to determine the krunched name for
2536 a given file, when krunched to a specified maximum length.
2538 @node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2539 @anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{69}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{56}
2540 @subsubsection Using @cite{gnatkr}
2543 The @cite{gnatkr} command has the form:
2546 $ gnatkr `name` [`length`]
2549 @cite{name} is the uncrunched file name, derived from the name of the unit
2550 in the standard manner described in the previous section (i.e., in particular
2551 all dots are replaced by hyphens). The file name may or may not have an
2552 extension (defined as a suffix of the form period followed by arbitrary
2553 characters other than period). If an extension is present then it will
2554 be preserved in the output. For example, when krunching @code{hellofile.ads}
2555 to eight characters, the result will be hellofil.ads.
2557 Note: for compatibility with previous versions of @cite{gnatkr} dots may
2558 appear in the name instead of hyphens, but the last dot will always be
2559 taken as the start of an extension. So if @cite{gnatkr} is given an argument
2560 such as @code{Hello.World.adb} it will be treated exactly as if the first
2561 period had been a hyphen, and for example krunching to eight characters
2562 gives the result @code{hellworl.adb}.
2564 Note that the result is always all lower case.
2565 Characters of the other case are folded as required.
2567 @cite{length} represents the length of the krunched name. The default
2568 when no argument is given is 8 characters. A length of zero stands for
2569 unlimited, in other words do not chop except for system files where the
2570 implied crunching length is always eight characters.
2572 The output is the krunched name. The output has an extension only if the
2573 original argument was a file name with an extension.
2575 @node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2576 @anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{6a}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{6b}
2577 @subsubsection Krunching Method
2580 The initial file name is determined by the name of the unit that the file
2581 contains. The name is formed by taking the full expanded name of the
2582 unit and replacing the separating dots with hyphens and
2584 for all letters, except that a hyphen in the second character position is
2585 replaced by a tilde if the first character is
2586 @code{a}, @code{i}, @code{g}, or @code{s}.
2587 The extension is @cite{.ads} for a
2588 spec and @cite{.adb} for a body.
2589 Krunching does not affect the extension, but the file name is shortened to
2590 the specified length by following these rules:
2596 The name is divided into segments separated by hyphens, tildes or
2597 underscores and all hyphens, tildes, and underscores are
2598 eliminated. If this leaves the name short enough, we are done.
2601 If the name is too long, the longest segment is located (left-most
2602 if there are two of equal length), and shortened by dropping
2603 its last character. This is repeated until the name is short enough.
2605 As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2606 to fit the name into 8 characters as required by some operating systems:
2609 our-strings-wide_fixed 22
2610 our strings wide fixed 19
2611 our string wide fixed 18
2612 our strin wide fixed 17
2613 our stri wide fixed 16
2614 our stri wide fixe 15
2615 our str wide fixe 14
2622 Final file name: oustwifi.adb
2626 The file names for all predefined units are always krunched to eight
2627 characters. The krunching of these predefined units uses the following
2628 special prefix replacements:
2631 @multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx}
2675 These system files have a hyphen in the second character position. That
2676 is why normal user files replace such a character with a
2677 tilde, to avoid confusion with system file names.
2679 As an example of this special rule, consider
2680 @code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2683 ada-strings-wide_fixed 22
2684 a- strings wide fixed 18
2685 a- string wide fixed 17
2686 a- strin wide fixed 16
2687 a- stri wide fixed 15
2688 a- stri wide fixe 14
2695 Final file name: a-stwifi.adb
2699 Of course no file shortening algorithm can guarantee uniqueness over all
2700 possible unit names, and if file name krunching is used then it is your
2701 responsibility to ensure that no name clashes occur. The utility
2702 program @cite{gnatkr} is supplied for conveniently determining the
2703 krunched name of a file.
2705 @node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2706 @anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{6d}
2707 @subsubsection Examples of @cite{gnatkr} Usage
2711 $ gnatkr very_long_unit_name.ads --> velounna.ads
2712 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
2713 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2714 $ gnatkr grandparent-parent-child --> grparchi
2715 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2716 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2719 @node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2720 @anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{6e}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{38}
2721 @subsection Renaming Files with @cite{gnatchop}
2726 This chapter discusses how to handle files with multiple units by using
2727 the @cite{gnatchop} utility. This utility is also useful in renaming
2728 files to meet the standard GNAT default file naming conventions.
2731 * Handling Files with Multiple Units::
2732 * Operating gnatchop in Compilation Mode::
2733 * Command Line for gnatchop::
2734 * Switches for gnatchop::
2735 * Examples of gnatchop Usage::
2739 @node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2740 @anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{6f}@anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{70}
2741 @subsubsection Handling Files with Multiple Units
2744 The basic compilation model of GNAT requires that a file submitted to the
2745 compiler have only one unit and there be a strict correspondence
2746 between the file name and the unit name.
2748 The @cite{gnatchop} utility allows both of these rules to be relaxed,
2749 allowing GNAT to process files which contain multiple compilation units
2750 and files with arbitrary file names. @cite{gnatchop}
2751 reads the specified file and generates one or more output files,
2752 containing one unit per file. The unit and the file name correspond,
2753 as required by GNAT.
2755 If you want to permanently restructure a set of 'foreign' files so that
2756 they match the GNAT rules, and do the remaining development using the
2757 GNAT structure, you can simply use @emph{gnatchop} once, generate the
2758 new set of files and work with them from that point on.
2760 Alternatively, if you want to keep your files in the 'foreign' format,
2761 perhaps to maintain compatibility with some other Ada compilation
2762 system, you can set up a procedure where you use @emph{gnatchop} each
2763 time you compile, regarding the source files that it writes as temporary
2764 files that you throw away.
2766 Note that if your file containing multiple units starts with a byte order
2767 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2768 will each start with a copy of this BOM, meaning that they can be compiled
2769 automatically in UTF-8 mode without needing to specify an explicit encoding.
2771 @node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2772 @anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{72}
2773 @subsubsection Operating gnatchop in Compilation Mode
2776 The basic function of @cite{gnatchop} is to take a file with multiple units
2777 and split it into separate files. The boundary between files is reasonably
2778 clear, except for the issue of comments and pragmas. In default mode, the
2779 rule is that any pragmas between units belong to the previous unit, except
2780 that configuration pragmas always belong to the following unit. Any comments
2781 belong to the following unit. These rules
2782 almost always result in the right choice of
2783 the split point without needing to mark it explicitly and most users will
2784 find this default to be what they want. In this default mode it is incorrect to
2785 submit a file containing only configuration pragmas, or one that ends in
2786 configuration pragmas, to @cite{gnatchop}.
2788 However, using a special option to activate 'compilation mode',
2790 can perform another function, which is to provide exactly the semantics
2791 required by the RM for handling of configuration pragmas in a compilation.
2792 In the absence of configuration pragmas (at the main file level), this
2793 option has no effect, but it causes such configuration pragmas to be handled
2794 in a quite different manner.
2796 First, in compilation mode, if @cite{gnatchop} is given a file that consists of
2797 only configuration pragmas, then this file is appended to the
2798 @code{gnat.adc} file in the current directory. This behavior provides
2799 the required behavior described in the RM for the actions to be taken
2800 on submitting such a file to the compiler, namely that these pragmas
2801 should apply to all subsequent compilations in the same compilation
2802 environment. Using GNAT, the current directory, possibly containing a
2803 @code{gnat.adc} file is the representation
2804 of a compilation environment. For more information on the
2805 @code{gnat.adc} file, see @ref{58,,Handling of Configuration Pragmas}.
2807 Second, in compilation mode, if @cite{gnatchop}
2808 is given a file that starts with
2809 configuration pragmas, and contains one or more units, then these
2810 configuration pragmas are prepended to each of the chopped files. This
2811 behavior provides the required behavior described in the RM for the
2812 actions to be taken on compiling such a file, namely that the pragmas
2813 apply to all units in the compilation, but not to subsequently compiled
2816 Finally, if configuration pragmas appear between units, they are appended
2817 to the previous unit. This results in the previous unit being illegal,
2818 since the compiler does not accept configuration pragmas that follow
2819 a unit. This provides the required RM behavior that forbids configuration
2820 pragmas other than those preceding the first compilation unit of a
2823 For most purposes, @cite{gnatchop} will be used in default mode. The
2824 compilation mode described above is used only if you need exactly
2825 accurate behavior with respect to compilations, and you have files
2826 that contain multiple units and configuration pragmas. In this
2827 circumstance the use of @cite{gnatchop} with the compilation mode
2828 switch provides the required behavior, and is for example the mode
2829 in which GNAT processes the ACVC tests.
2831 @node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2832 @anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{73}@anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{74}
2833 @subsubsection Command Line for @cite{gnatchop}
2836 The @cite{gnatchop} command has the form:
2839 $ gnatchop switches file_name [file_name ...]
2843 The only required argument is the file name of the file to be chopped.
2844 There are no restrictions on the form of this file name. The file itself
2845 contains one or more Ada units, in normal GNAT format, concatenated
2846 together. As shown, more than one file may be presented to be chopped.
2848 When run in default mode, @cite{gnatchop} generates one output file in
2849 the current directory for each unit in each of the files.
2851 @cite{directory}, if specified, gives the name of the directory to which
2852 the output files will be written. If it is not specified, all files are
2853 written to the current directory.
2855 For example, given a
2856 file called @code{hellofiles} containing
2861 with Ada.Text_IO; use Ada.Text_IO;
2871 $ gnatchop hellofiles
2874 generates two files in the current directory, one called
2875 @code{hello.ads} containing the single line that is the procedure spec,
2876 and the other called @code{hello.adb} containing the remaining text. The
2877 original file is not affected. The generated files can be compiled in
2880 When gnatchop is invoked on a file that is empty or that contains only empty
2881 lines and/or comments, gnatchop will not fail, but will not produce any
2884 For example, given a
2885 file called @code{toto.txt} containing
2897 will not produce any new file and will result in the following warnings:
2900 toto.txt:1:01: warning: empty file, contains no compilation units
2901 no compilation units found
2902 no source files written
2905 @node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2906 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{75}@anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{76}
2907 @subsubsection Switches for @cite{gnatchop}
2910 @emph{gnatchop} recognizes the following switches:
2912 @geindex --version (gnatchop)
2917 @item @code{--version}
2919 Display Copyright and version, then exit disregarding all other options.
2922 @geindex --help (gnatchop)
2929 If @emph{--version} was not used, display usage, then exit disregarding
2933 @geindex -c (gnatchop)
2940 Causes @cite{gnatchop} to operate in compilation mode, in which
2941 configuration pragmas are handled according to strict RM rules. See
2942 previous section for a full description of this mode.
2944 @item @code{-gnat@emph{xxx}}
2946 This passes the given @emph{-gnat`xxx*` switch to `gnat` which is
2947 used to parse the given file. Not all `xxx` options make sense,
2948 but for example, the use of *-gnati2} allows @cite{gnatchop} to
2949 process a source file that uses Latin-2 coding for identifiers.
2953 Causes @cite{gnatchop} to generate a brief help summary to the standard
2954 output file showing usage information.
2957 @geindex -k (gnatchop)
2962 @item @code{-k@emph{mm}}
2964 Limit generated file names to the specified number @cite{mm}
2966 This is useful if the
2967 resulting set of files is required to be interoperable with systems
2968 which limit the length of file names.
2969 No space is allowed between the @emph{-k} and the numeric value. The numeric
2970 value may be omitted in which case a default of @emph{-k8},
2972 with DOS-like file systems, is used. If no @emph{-k} switch
2974 there is no limit on the length of file names.
2977 @geindex -p (gnatchop)
2984 Causes the file modification time stamp of the input file to be
2985 preserved and used for the time stamp of the output file(s). This may be
2986 useful for preserving coherency of time stamps in an environment where
2987 @cite{gnatchop} is used as part of a standard build process.
2990 @geindex -q (gnatchop)
2997 Causes output of informational messages indicating the set of generated
2998 files to be suppressed. Warnings and error messages are unaffected.
3001 @geindex -r (gnatchop)
3003 @geindex Source_Reference pragmas
3010 Generate @cite{Source_Reference} pragmas. Use this switch if the output
3011 files are regarded as temporary and development is to be done in terms
3012 of the original unchopped file. This switch causes
3013 @cite{Source_Reference} pragmas to be inserted into each of the
3014 generated files to refers back to the original file name and line number.
3015 The result is that all error messages refer back to the original
3017 In addition, the debugging information placed into the object file (when
3018 the @emph{-g} switch of @emph{gcc} or @emph{gnatmake} is
3020 also refers back to this original file so that tools like profilers and
3021 debuggers will give information in terms of the original unchopped file.
3023 If the original file to be chopped itself contains
3024 a @cite{Source_Reference}
3025 pragma referencing a third file, then gnatchop respects
3026 this pragma, and the generated @cite{Source_Reference} pragmas
3027 in the chopped file refer to the original file, with appropriate
3028 line numbers. This is particularly useful when @cite{gnatchop}
3029 is used in conjunction with @cite{gnatprep} to compile files that
3030 contain preprocessing statements and multiple units.
3033 @geindex -v (gnatchop)
3040 Causes @cite{gnatchop} to operate in verbose mode. The version
3041 number and copyright notice are output, as well as exact copies of
3042 the gnat1 commands spawned to obtain the chop control information.
3045 @geindex -w (gnatchop)
3052 Overwrite existing file names. Normally @cite{gnatchop} regards it as a
3053 fatal error if there is already a file with the same name as a
3054 file it would otherwise output, in other words if the files to be
3055 chopped contain duplicated units. This switch bypasses this
3056 check, and causes all but the last instance of such duplicated
3057 units to be skipped.
3060 @geindex --GCC= (gnatchop)
3065 @item @code{--GCC=@emph{xxxx}}
3067 Specify the path of the GNAT parser to be used. When this switch is used,
3068 no attempt is made to add the prefix to the GNAT parser executable.
3071 @node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
3072 @anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{78}
3073 @subsubsection Examples of @cite{gnatchop} Usage
3077 $ gnatchop -w hello_s.ada prerelease/files
3080 Chops the source file @code{hello_s.ada}. The output files will be
3081 placed in the directory @code{prerelease/files},
3083 files with matching names in that directory (no files in the current
3084 directory are modified).
3090 Chops the source file @code{archive}
3091 into the current directory. One
3092 useful application of @cite{gnatchop} is in sending sets of sources
3093 around, for example in email messages. The required sources are simply
3094 concatenated (for example, using a Unix @cite{cat}
3096 @emph{gnatchop} is used at the other end to reconstitute the original
3100 $ gnatchop file1 file2 file3 direc
3103 Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
3104 the resulting files in the directory @code{direc}. Note that if any units
3105 occur more than once anywhere within this set of files, an error message
3106 is generated, and no files are written. To override this check, use the
3108 in which case the last occurrence in the last file will
3109 be the one that is output, and earlier duplicate occurrences for a given
3110 unit will be skipped.
3112 @node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
3113 @anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{79}@anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{16}
3114 @section Configuration Pragmas
3117 @geindex Configuration pragmas
3120 @geindex configuration
3122 Configuration pragmas include those pragmas described as
3123 such in the Ada Reference Manual, as well as
3124 implementation-dependent pragmas that are configuration pragmas.
3125 See the @cite{Implementation_Defined_Pragmas} chapter in the
3126 @cite{GNAT_Reference_Manual} for details on these
3127 additional GNAT-specific configuration pragmas.
3128 Most notably, the pragma @cite{Source_File_Name}, which allows
3129 specifying non-default names for source files, is a configuration
3130 pragma. The following is a complete list of configuration pragmas
3140 Allow_Integer_Address
3143 Assume_No_Invalid_Values
3148 Compile_Time_Warning
3151 Convention_Identifier
3154 Default_Storage_Pool
3160 External_Name_Casing
3163 Float_Representation
3176 Priority_Specific_Dispatching
3179 Propagate_Exceptions
3184 Restrictions_Warnings
3186 Short_Circuit_And_Or
3188 Source_File_Name_Project
3192 Suppress_Exception_Locations
3193 Task_Dispatching_Policy
3199 Wide_Character_Encoding
3203 * Handling of Configuration Pragmas::
3204 * The Configuration Pragmas Files::
3208 @node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
3209 @anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{7a}@anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{58}
3210 @subsection Handling of Configuration Pragmas
3213 Configuration pragmas may either appear at the start of a compilation
3214 unit, or they can appear in a configuration pragma file to apply to
3215 all compilations performed in a given compilation environment.
3217 GNAT also provides the @cite{gnatchop} utility to provide an automatic
3218 way to handle configuration pragmas following the semantics for
3219 compilations (that is, files with multiple units), described in the RM.
3220 See @ref{71,,Operating gnatchop in Compilation Mode} for details.
3221 However, for most purposes, it will be more convenient to edit the
3222 @code{gnat.adc} file that contains configuration pragmas directly,
3223 as described in the following section.
3225 In the case of @cite{Restrictions} pragmas appearing as configuration
3226 pragmas in individual compilation units, the exact handling depends on
3227 the type of restriction.
3229 Restrictions that require partition-wide consistency (like
3230 @cite{No_Tasking}) are
3231 recognized wherever they appear
3232 and can be freely inherited, e.g. from a @emph{with}ed unit to the @emph{with}ing
3233 unit. This makes sense since the binder will in any case insist on seeing
3234 consistent use, so any unit not conforming to any restrictions that are
3235 anywhere in the partition will be rejected, and you might as well find
3236 that out at compile time rather than at bind time.
3238 For restrictions that do not require partition-wide consistency, e.g.
3239 SPARK or No_Implementation_Attributes, in general the restriction applies
3240 only to the unit in which the pragma appears, and not to any other units.
3242 The exception is No_Elaboration_Code which always applies to the entire
3243 object file from a compilation, i.e. to the body, spec, and all subunits.
3244 This restriction can be specified in a configuration pragma file, or it
3245 can be on the body and/or the spec (in eithe case it applies to all the
3246 relevant units). It can appear on a subunit only if it has previously
3247 appeared in the body of spec.
3249 @node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
3250 @anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{7b}@anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{7c}
3251 @subsection The Configuration Pragmas Files
3256 In GNAT a compilation environment is defined by the current
3257 directory at the time that a compile command is given. This current
3258 directory is searched for a file whose name is @code{gnat.adc}. If
3259 this file is present, it is expected to contain one or more
3260 configuration pragmas that will be applied to the current compilation.
3261 However, if the switch @emph{-gnatA} is used, @code{gnat.adc} is not
3262 considered. When taken into account, @code{gnat.adc} is added to the
3263 dependencies, so that if @code{gnat.adc} is modified later, an invocation of
3264 @emph{gnatmake} will recompile the source.
3266 Configuration pragmas may be entered into the @code{gnat.adc} file
3267 either by running @cite{gnatchop} on a source file that consists only of
3268 configuration pragmas, or more conveniently by direct editing of the
3269 @code{gnat.adc} file, which is a standard format source file.
3271 Besides @code{gnat.adc}, additional files containing configuration
3272 pragmas may be applied to the current compilation using the switch
3273 @code{-gnatec=@emph{path}} where @cite{path} must designate an existing file that
3274 contains only configuration pragmas. These configuration pragmas are
3275 in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
3276 is present and switch @emph{-gnatA} is not used).
3278 It is allowable to specify several switches @emph{-gnatec=}, all of which
3279 will be taken into account.
3281 Files containing configuration pragmas specified with switches
3282 @emph{-gnatec=} are added to the dependencies, unless they are
3283 temporary files. A file is considered temporary if its name ends in
3284 @code{.tmp} or @code{.TMP}. Certain tools follow this naming
3285 convention because they pass information to @emph{gcc} via
3286 temporary files that are immediately deleted; it doesn't make sense to
3287 depend on a file that no longer exists. Such tools include
3288 @emph{gprbuild}, @emph{gnatmake}, and @emph{gnatcheck}.
3290 If you are using project file, a separate mechanism is provided using
3291 project attributes, see @ref{7d,,Specifying Configuration Pragmas} for more
3294 @node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
3295 @anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{42}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{7e}
3296 @section Generating Object Files
3299 An Ada program consists of a set of source files, and the first step in
3300 compiling the program is to generate the corresponding object files.
3301 These are generated by compiling a subset of these source files.
3302 The files you need to compile are the following:
3308 If a package spec has no body, compile the package spec to produce the
3309 object file for the package.
3312 If a package has both a spec and a body, compile the body to produce the
3313 object file for the package. The source file for the package spec need
3314 not be compiled in this case because there is only one object file, which
3315 contains the code for both the spec and body of the package.
3318 For a subprogram, compile the subprogram body to produce the object file
3319 for the subprogram. The spec, if one is present, is as usual in a
3320 separate file, and need not be compiled.
3329 In the case of subunits, only compile the parent unit. A single object
3330 file is generated for the entire subunit tree, which includes all the
3334 Compile child units independently of their parent units
3335 (though, of course, the spec of all the ancestor unit must be present in order
3336 to compile a child unit).
3341 Compile generic units in the same manner as any other units. The object
3342 files in this case are small dummy files that contain at most the
3343 flag used for elaboration checking. This is because GNAT always handles generic
3344 instantiation by means of macro expansion. However, it is still necessary to
3345 compile generic units, for dependency checking and elaboration purposes.
3348 The preceding rules describe the set of files that must be compiled to
3349 generate the object files for a program. Each object file has the same
3350 name as the corresponding source file, except that the extension is
3353 You may wish to compile other files for the purpose of checking their
3354 syntactic and semantic correctness. For example, in the case where a
3355 package has a separate spec and body, you would not normally compile the
3356 spec. However, it is convenient in practice to compile the spec to make
3357 sure it is error-free before compiling clients of this spec, because such
3358 compilations will fail if there is an error in the spec.
3360 GNAT provides an option for compiling such files purely for the
3361 purposes of checking correctness; such compilations are not required as
3362 part of the process of building a program. To compile a file in this
3363 checking mode, use the @emph{-gnatc} switch.
3365 @node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3366 @anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{7f}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{43}
3367 @section Source Dependencies
3370 A given object file clearly depends on the source file which is compiled
3371 to produce it. Here we are using "depends" in the sense of a typical
3372 @cite{make} utility; in other words, an object file depends on a source
3373 file if changes to the source file require the object file to be
3375 In addition to this basic dependency, a given object may depend on
3376 additional source files as follows:
3382 If a file being compiled @emph{with}s a unit @cite{X}, the object file
3383 depends on the file containing the spec of unit @cite{X}. This includes
3384 files that are @emph{with}ed implicitly either because they are parents
3385 of @emph{with}ed child units or they are run-time units required by the
3386 language constructs used in a particular unit.
3389 If a file being compiled instantiates a library level generic unit, the
3390 object file depends on both the spec and body files for this generic
3394 If a file being compiled instantiates a generic unit defined within a
3395 package, the object file depends on the body file for the package as
3396 well as the spec file.
3401 @geindex -gnatn switch
3407 If a file being compiled contains a call to a subprogram for which
3408 pragma @cite{Inline} applies and inlining is activated with the
3409 @emph{-gnatn} switch, the object file depends on the file containing the
3410 body of this subprogram as well as on the file containing the spec. Note
3411 that for inlining to actually occur as a result of the use of this switch,
3412 it is necessary to compile in optimizing mode.
3414 @geindex -gnatN switch
3416 The use of @emph{-gnatN} activates inlining optimization
3417 that is performed by the front end of the compiler. This inlining does
3418 not require that the code generation be optimized. Like @emph{-gnatn},
3419 the use of this switch generates additional dependencies.
3421 When using a gcc-based back end (in practice this means using any version
3422 of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of
3423 @emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
3424 Historically front end inlining was more extensive than the gcc back end
3425 inlining, but that is no longer the case.
3428 If an object file @code{O} depends on the proper body of a subunit through
3429 inlining or instantiation, it depends on the parent unit of the subunit.
3430 This means that any modification of the parent unit or one of its subunits
3431 affects the compilation of @code{O}.
3434 The object file for a parent unit depends on all its subunit body files.
3437 The previous two rules meant that for purposes of computing dependencies and
3438 recompilation, a body and all its subunits are treated as an indivisible whole.
3440 These rules are applied transitively: if unit @cite{A} @emph{with}s
3441 unit @cite{B}, whose elaboration calls an inlined procedure in package
3442 @cite{C}, the object file for unit @cite{A} will depend on the body of
3443 @cite{C}, in file @code{c.adb}.
3445 The set of dependent files described by these rules includes all the
3446 files on which the unit is semantically dependent, as dictated by the
3447 Ada language standard. However, it is a superset of what the
3448 standard describes, because it includes generic, inline, and subunit
3451 An object file must be recreated by recompiling the corresponding source
3452 file if any of the source files on which it depends are modified. For
3453 example, if the @cite{make} utility is used to control compilation,
3454 the rule for an Ada object file must mention all the source files on
3455 which the object file depends, according to the above definition.
3456 The determination of the necessary
3457 recompilations is done automatically when one uses @emph{gnatmake}.
3460 @node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3461 @anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{80}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{44}
3462 @section The Ada Library Information Files
3465 @geindex Ada Library Information files
3469 Each compilation actually generates two output files. The first of these
3470 is the normal object file that has a @code{.o} extension. The second is a
3471 text file containing full dependency information. It has the same
3472 name as the source file, but an @code{.ali} extension.
3473 This file is known as the Ada Library Information (@code{ALI}) file.
3474 The following information is contained in the @code{ALI} file.
3480 Version information (indicates which version of GNAT was used to compile
3481 the unit(s) in question)
3484 Main program information (including priority and time slice settings,
3485 as well as the wide character encoding used during compilation).
3488 List of arguments used in the @emph{gcc} command for the compilation
3491 Attributes of the unit, including configuration pragmas used, an indication
3492 of whether the compilation was successful, exception model used etc.
3495 A list of relevant restrictions applying to the unit (used for consistency)
3499 Categorization information (e.g., use of pragma @cite{Pure}).
3502 Information on all @emph{with}ed units, including presence of
3503 Elaborate` or @cite{Elaborate_All} pragmas.
3506 Information from any @cite{Linker_Options} pragmas used in the unit
3509 Information on the use of @cite{Body_Version} or @cite{Version}
3510 attributes in the unit.
3513 Dependency information. This is a list of files, together with
3514 time stamp and checksum information. These are files on which
3515 the unit depends in the sense that recompilation is required
3516 if any of these units are modified.
3519 Cross-reference data. Contains information on all entities referenced
3520 in the unit. Used by tools like @cite{gnatxref} and @cite{gnatfind} to
3521 provide cross-reference information.
3524 For a full detailed description of the format of the @code{ALI} file,
3525 see the source of the body of unit @cite{Lib.Writ}, contained in file
3526 @code{lib-writ.adb} in the GNAT compiler sources.
3528 @node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3529 @anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{81}@anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{45}
3530 @section Binding an Ada Program
3533 When using languages such as C and C++, once the source files have been
3534 compiled the only remaining step in building an executable program
3535 is linking the object modules together. This means that it is possible to
3536 link an inconsistent version of a program, in which two units have
3537 included different versions of the same header.
3539 The rules of Ada do not permit such an inconsistent program to be built.
3540 For example, if two clients have different versions of the same package,
3541 it is illegal to build a program containing these two clients.
3542 These rules are enforced by the GNAT binder, which also determines an
3543 elaboration order consistent with the Ada rules.
3545 The GNAT binder is run after all the object files for a program have
3546 been created. It is given the name of the main program unit, and from
3547 this it determines the set of units required by the program, by reading the
3548 corresponding ALI files. It generates error messages if the program is
3549 inconsistent or if no valid order of elaboration exists.
3551 If no errors are detected, the binder produces a main program, in Ada by
3552 default, that contains calls to the elaboration procedures of those
3553 compilation unit that require them, followed by
3554 a call to the main program. This Ada program is compiled to generate the
3555 object file for the main program. The name of
3556 the Ada file is @code{b~xxx}.adb` (with the corresponding spec
3557 @code{b~xxx}.ads`) where @cite{xxx} is the name of the
3560 Finally, the linker is used to build the resulting executable program,
3561 using the object from the main program from the bind step as well as the
3562 object files for the Ada units of the program.
3564 @node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3565 @anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{17}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{82}
3566 @section GNAT and Libraries
3569 @geindex Library building and using
3571 This chapter describes how to build and use libraries with GNAT, and also shows
3572 how to recompile the GNAT run-time library. You should be familiar with the
3573 Project Manager facility (@ref{b,,GNAT Project Manager}) before reading this
3577 * Introduction to Libraries in GNAT::
3578 * General Ada Libraries::
3579 * Stand-alone Ada Libraries::
3580 * Rebuilding the GNAT Run-Time Library::
3584 @node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3585 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{83}@anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{84}
3586 @subsection Introduction to Libraries in GNAT
3589 A library is, conceptually, a collection of objects which does not have its
3590 own main thread of execution, but rather provides certain services to the
3591 applications that use it. A library can be either statically linked with the
3592 application, in which case its code is directly included in the application,
3593 or, on platforms that support it, be dynamically linked, in which case
3594 its code is shared by all applications making use of this library.
3596 GNAT supports both types of libraries.
3597 In the static case, the compiled code can be provided in different ways. The
3598 simplest approach is to provide directly the set of objects resulting from
3599 compilation of the library source files. Alternatively, you can group the
3600 objects into an archive using whatever commands are provided by the operating
3601 system. For the latter case, the objects are grouped into a shared library.
3603 In the GNAT environment, a library has three types of components:
3612 @code{ALI} files (see @ref{44,,The Ada Library Information Files}), and
3615 Object files, an archive or a shared library.
3618 A GNAT library may expose all its source files, which is useful for
3619 documentation purposes. Alternatively, it may expose only the units needed by
3620 an external user to make use of the library. That is to say, the specs
3621 reflecting the library services along with all the units needed to compile
3622 those specs, which can include generic bodies or any body implementing an
3623 inlined routine. In the case of @emph{stand-alone libraries} those exposed
3624 units are called @emph{interface units} (@ref{85,,Stand-alone Ada Libraries}).
3626 All compilation units comprising an application, including those in a library,
3627 need to be elaborated in an order partially defined by Ada's semantics. GNAT
3628 computes the elaboration order from the @code{ALI} files and this is why they
3629 constitute a mandatory part of GNAT libraries.
3630 @emph{Stand-alone libraries} are the exception to this rule because a specific
3631 library elaboration routine is produced independently of the application(s)
3634 @node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3635 @anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{86}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{87}
3636 @subsection General Ada Libraries
3640 * Building a library::
3641 * Installing a library::
3646 @node Building a library,Installing a library,,General Ada Libraries
3647 @anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{88}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{89}
3648 @subsubsection Building a library
3651 The easiest way to build a library is to use the Project Manager,
3652 which supports a special type of project called a @emph{Library Project}
3653 (see @ref{8a,,Library Projects}).
3655 A project is considered a library project, when two project-level attributes
3656 are defined in it: @cite{Library_Name} and @cite{Library_Dir}. In order to
3657 control different aspects of library configuration, additional optional
3658 project-level attributes can be specified:
3667 @item @emph{Library_Kind}
3669 This attribute controls whether the library is to be static or dynamic
3676 @item @emph{Library_Version}
3678 This attribute specifies the library version; this value is used
3679 during dynamic linking of shared libraries to determine if the currently
3680 installed versions of the binaries are compatible.
3684 @emph{Library_Options}
3690 @item @emph{Library_GCC}
3692 These attributes specify additional low-level options to be used during
3693 library generation, and redefine the actual application used to generate
3698 The GNAT Project Manager takes full care of the library maintenance task,
3699 including recompilation of the source files for which objects do not exist
3700 or are not up to date, assembly of the library archive, and installation of
3701 the library (i.e., copying associated source, object and @code{ALI} files
3702 to the specified location).
3704 Here is a simple library project file:
3708 for Source_Dirs use ("src1", "src2");
3709 for Object_Dir use "obj";
3710 for Library_Name use "mylib";
3711 for Library_Dir use "lib";
3712 for Library_Kind use "dynamic";
3716 and the compilation command to build and install the library:
3722 It is not entirely trivial to perform manually all the steps required to
3723 produce a library. We recommend that you use the GNAT Project Manager
3724 for this task. In special cases where this is not desired, the necessary
3725 steps are discussed below.
3727 There are various possibilities for compiling the units that make up the
3728 library: for example with a Makefile (@ref{21,,Using the GNU make Utility}) or
3729 with a conventional script. For simple libraries, it is also possible to create
3730 a dummy main program which depends upon all the packages that comprise the
3731 interface of the library. This dummy main program can then be given to
3732 @emph{gnatmake}, which will ensure that all necessary objects are built.
3734 After this task is accomplished, you should follow the standard procedure
3735 of the underlying operating system to produce the static or shared library.
3737 Here is an example of such a dummy program:
3740 with My_Lib.Service1;
3741 with My_Lib.Service2;
3742 with My_Lib.Service3;
3743 procedure My_Lib_Dummy is
3749 Here are the generic commands that will build an archive or a shared library.
3752 # compiling the library
3753 $ gnatmake -c my_lib_dummy.adb
3755 # we don't need the dummy object itself
3756 $ rm my_lib_dummy.o my_lib_dummy.ali
3758 # create an archive with the remaining objects
3759 $ ar rc libmy_lib.a *.o
3760 # some systems may require "ranlib" to be run as well
3762 # or create a shared library
3763 $ gcc -shared -o libmy_lib.so *.o
3764 # some systems may require the code to have been compiled with -fPIC
3766 # remove the object files that are now in the library
3769 # Make the ALI files read-only so that gnatmake will not try to
3770 # regenerate the objects that are in the library
3774 Please note that the library must have a name of the form @code{lib@emph{xxx}.a}
3775 or @code{lib@emph{xxx}.so} (or @code{lib@emph{xxx}.dll} on Windows) in order to
3776 be accessed by the directive @code{-l@emph{xxx}} at link time.
3778 @node Installing a library,Using a library,Building a library,General Ada Libraries
3779 @anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{8b}@anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{8c}
3780 @subsubsection Installing a library
3783 @geindex ADA_PROJECT_PATH
3785 @geindex GPR_PROJECT_PATH
3787 If you use project files, library installation is part of the library build
3788 process (@ref{8d,,Installing a library with project files}).
3790 When project files are not an option, it is also possible, but not recommended,
3791 to install the library so that the sources needed to use the library are on the
3792 Ada source path and the ALI files & libraries be on the Ada Object path (see
3793 @ref{8e,,Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
3794 administrator can place general-purpose libraries in the default compiler
3795 paths, by specifying the libraries' location in the configuration files
3796 @code{ada_source_path} and @code{ada_object_path}. These configuration files
3797 must be located in the GNAT installation tree at the same place as the gcc spec
3798 file. The location of the gcc spec file can be determined as follows:
3804 The configuration files mentioned above have a simple format: each line
3805 must contain one unique directory name.
3806 Those names are added to the corresponding path
3807 in their order of appearance in the file. The names can be either absolute
3808 or relative; in the latter case, they are relative to where theses files
3811 The files @code{ada_source_path} and @code{ada_object_path} might not be
3813 GNAT installation, in which case, GNAT will look for its run-time library in
3814 the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3815 objects and @code{ALI} files). When the files exist, the compiler does not
3816 look in @code{adainclude} and @code{adalib}, and thus the
3817 @code{ada_source_path} file
3818 must contain the location for the GNAT run-time sources (which can simply
3819 be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3820 contain the location for the GNAT run-time objects (which can simply
3823 You can also specify a new default path to the run-time library at compilation
3824 time with the switch @emph{--RTS=rts-path}. You can thus choose / change
3825 the run-time library you want your program to be compiled with. This switch is
3826 recognized by @emph{gcc}, @emph{gnatmake}, @emph{gnatbind},
3827 @emph{gnatls}, @emph{gnatfind} and @emph{gnatxref}.
3829 It is possible to install a library before or after the standard GNAT
3830 library, by reordering the lines in the configuration files. In general, a
3831 library must be installed before the GNAT library if it redefines
3834 @node Using a library,,Installing a library,General Ada Libraries
3835 @anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{8f}@anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{90}
3836 @subsubsection Using a library
3839 Once again, the project facility greatly simplifies the use of
3840 libraries. In this context, using a library is just a matter of adding a
3841 @emph{with} clause in the user project. For instance, to make use of the
3842 library @cite{My_Lib} shown in examples in earlier sections, you can
3852 Even if you have a third-party, non-Ada library, you can still use GNAT's
3853 Project Manager facility to provide a wrapper for it. For example, the
3854 following project, when @emph{with}ed by your main project, will link with the
3855 third-party library @code{liba.a}:
3859 for Externally_Built use "true";
3860 for Source_Files use ();
3861 for Library_Dir use "lib";
3862 for Library_Name use "a";
3863 for Library_Kind use "static";
3867 This is an alternative to the use of @cite{pragma Linker_Options}. It is
3868 especially interesting in the context of systems with several interdependent
3869 static libraries where finding a proper linker order is not easy and best be
3870 left to the tools having visibility over project dependence information.
3872 In order to use an Ada library manually, you need to make sure that this
3873 library is on both your source and object path
3874 (see @ref{8e,,Search Paths and the Run-Time Library (RTL)}
3875 and @ref{91,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3876 in an archive or a shared library, you need to specify the desired
3877 library at link time.
3879 For example, you can use the library @code{mylib} installed in
3880 @code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3883 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3887 This can be expressed more simply:
3893 when the following conditions are met:
3899 @code{/dir/my_lib_src} has been added by the user to the environment
3901 @geindex ADA_INCLUDE_PATH
3902 @geindex environment variable; ADA_INCLUDE_PATH
3903 @code{ADA_INCLUDE_PATH}, or by the administrator to the file
3904 @code{ada_source_path}
3907 @code{/dir/my_lib_obj} has been added by the user to the environment
3909 @geindex ADA_OBJECTS_PATH
3910 @geindex environment variable; ADA_OBJECTS_PATH
3911 @code{ADA_OBJECTS_PATH}, or by the administrator to the file
3912 @code{ada_object_path}
3915 a pragma @cite{Linker_Options} has been added to one of the sources.
3919 pragma Linker_Options ("-lmy_lib");
3923 Note that you may also load a library dynamically at
3924 run time given its filename, as illustrated in the GNAT @code{plugins} example
3925 in the directory @code{share/examples/gnat/plugins} within the GNAT
3928 @node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3929 @anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{85}@anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{92}
3930 @subsection Stand-alone Ada Libraries
3933 @geindex Stand-alone libraries
3936 * Introduction to Stand-alone Libraries::
3937 * Building a Stand-alone Library::
3938 * Creating a Stand-alone Library to be used in a non-Ada context::
3939 * Restrictions in Stand-alone Libraries::
3943 @node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3944 @anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{93}@anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{94}
3945 @subsubsection Introduction to Stand-alone Libraries
3948 A Stand-alone Library (abbreviated 'SAL') is a library that contains the
3950 elaborate the Ada units that are included in the library. In contrast with
3951 an ordinary library, which consists of all sources, objects and @code{ALI}
3953 library, a SAL may specify a restricted subset of compilation units
3954 to serve as a library interface. In this case, the fully
3955 self-sufficient set of files will normally consist of an objects
3956 archive, the sources of interface units' specs, and the @code{ALI}
3957 files of interface units.
3958 If an interface spec contains a generic unit or an inlined subprogram,
3960 source must also be provided; if the units that must be provided in the source
3961 form depend on other units, the source and @code{ALI} files of those must
3964 The main purpose of a SAL is to minimize the recompilation overhead of client
3965 applications when a new version of the library is installed. Specifically,
3966 if the interface sources have not changed, client applications do not need to
3967 be recompiled. If, furthermore, a SAL is provided in the shared form and its
3968 version, controlled by @cite{Library_Version} attribute, is not changed,
3969 then the clients do not need to be relinked.
3971 SALs also allow the library providers to minimize the amount of library source
3972 text exposed to the clients. Such 'information hiding' might be useful or
3973 necessary for various reasons.
3975 Stand-alone libraries are also well suited to be used in an executable whose
3976 main routine is not written in Ada.
3978 @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
3979 @anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{95}@anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{96}
3980 @subsubsection Building a Stand-alone Library
3983 GNAT's Project facility provides a simple way of building and installing
3984 stand-alone libraries; see @ref{97,,Stand-alone Library Projects}.
3985 To be a Stand-alone Library Project, in addition to the two attributes
3986 that make a project a Library Project (@cite{Library_Name} and
3987 @cite{Library_Dir}; see @ref{8a,,Library Projects}), the attribute
3988 @cite{Library_Interface} must be defined. For example:
3991 for Library_Dir use "lib_dir";
3992 for Library_Name use "dummy";
3993 for Library_Interface use ("int1", "int1.child");
3996 Attribute @cite{Library_Interface} has a non-empty string list value,
3997 each string in the list designating a unit contained in an immediate source
3998 of the project file.
4000 When a Stand-alone Library is built, first the binder is invoked to build
4001 a package whose name depends on the library name
4002 (@code{b~dummy.ads/b} in the example above).
4003 This binder-generated package includes initialization and
4004 finalization procedures whose
4005 names depend on the library name (@cite{dummyinit} and @cite{dummyfinal}
4007 above). The object corresponding to this package is included in the library.
4009 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
4010 calling of these procedures if a static SAL is built, or if a shared SAL
4012 with the project-level attribute @cite{Library_Auto_Init} set to
4015 For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
4016 (those that are listed in attribute @cite{Library_Interface}) are copied to
4017 the Library Directory. As a consequence, only the Interface Units may be
4018 imported from Ada units outside of the library. If other units are imported,
4019 the binding phase will fail.
4021 It is also possible to build an encapsulated library where not only
4022 the code to elaborate and finalize the library is embedded but also
4023 ensuring that the library is linked only against static
4024 libraries. So an encapsulated library only depends on system
4025 libraries, all other code, including the GNAT runtime, is embedded. To
4026 build an encapsulated library the attribute
4027 @cite{Library_Standalone} must be set to @cite{encapsulated}:
4030 for Library_Dir use "lib_dir";
4031 for Library_Name use "dummy";
4032 for Library_Kind use "dynamic";
4033 for Library_Interface use ("int1", "int1.child");
4034 for Library_Standalone use "encapsulated";
4037 The default value for this attribute is @cite{standard} in which case
4038 a stand-alone library is built.
4040 The attribute @cite{Library_Src_Dir} may be specified for a
4041 Stand-Alone Library. @cite{Library_Src_Dir} is a simple attribute that has a
4042 single string value. Its value must be the path (absolute or relative to the
4043 project directory) of an existing directory. This directory cannot be the
4044 object directory or one of the source directories, but it can be the same as
4045 the library directory. The sources of the Interface
4046 Units of the library that are needed by an Ada client of the library will be
4047 copied to the designated directory, called the Interface Copy directory.
4048 These sources include the specs of the Interface Units, but they may also
4049 include bodies and subunits, when pragmas @cite{Inline} or @cite{Inline_Always}
4050 are used, or when there is a generic unit in the spec. Before the sources
4051 are copied to the Interface Copy directory, an attempt is made to delete all
4052 files in the Interface Copy directory.
4054 Building stand-alone libraries by hand is somewhat tedious, but for those
4055 occasions when it is necessary here are the steps that you need to perform:
4061 Compile all library sources.
4064 Invoke the binder with the switch @emph{-n} (No Ada main program),
4065 with all the @code{ALI} files of the interfaces, and
4066 with the switch @emph{-L} to give specific names to the @cite{init}
4067 and @cite{final} procedures. For example:
4070 $ gnatbind -n int1.ali int2.ali -Lsal1
4074 Compile the binder generated file:
4081 Link the dynamic library with all the necessary object files,
4082 indicating to the linker the names of the @cite{init} (and possibly
4083 @cite{final}) procedures for automatic initialization (and finalization).
4084 The built library should be placed in a directory different from
4085 the object directory.
4088 Copy the @cite{ALI} files of the interface to the library directory,
4089 add in this copy an indication that it is an interface to a SAL
4090 (i.e., add a word @emph{SL} on the line in the @code{ALI} file that starts
4091 with letter 'P') and make the modified copy of the @code{ALI} file
4095 Using SALs is not different from using other libraries
4096 (see @ref{8f,,Using a library}).
4098 @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
4099 @anchor{gnat_ugn/the_gnat_compilation_model creating-a-stand-alone-library-to-be-used-in-a-non-ada-context}@anchor{98}@anchor{gnat_ugn/the_gnat_compilation_model id44}@anchor{99}
4100 @subsubsection Creating a Stand-alone Library to be used in a non-Ada context
4103 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
4106 The only extra step required is to ensure that library interface subprograms
4107 are compatible with the main program, by means of @cite{pragma Export}
4108 or @cite{pragma Convention}.
4110 Here is an example of simple library interface for use with C main program:
4113 package My_Package is
4115 procedure Do_Something;
4116 pragma Export (C, Do_Something, "do_something");
4118 procedure Do_Something_Else;
4119 pragma Export (C, Do_Something_Else, "do_something_else");
4124 On the foreign language side, you must provide a 'foreign' view of the
4125 library interface; remember that it should contain elaboration routines in
4126 addition to interface subprograms.
4128 The example below shows the content of @cite{mylib_interface.h} (note
4129 that there is no rule for the naming of this file, any name can be used)
4132 /* the library elaboration procedure */
4133 extern void mylibinit (void);
4135 /* the library finalization procedure */
4136 extern void mylibfinal (void);
4138 /* the interface exported by the library */
4139 extern void do_something (void);
4140 extern void do_something_else (void);
4143 Libraries built as explained above can be used from any program, provided
4144 that the elaboration procedures (named @cite{mylibinit} in the previous
4145 example) are called before the library services are used. Any number of
4146 libraries can be used simultaneously, as long as the elaboration
4147 procedure of each library is called.
4149 Below is an example of a C program that uses the @cite{mylib} library.
4152 #include "mylib_interface.h"
4157 /* First, elaborate the library before using it */
4160 /* Main program, using the library exported entities */
4162 do_something_else ();
4164 /* Library finalization at the end of the program */
4170 Note that invoking any library finalization procedure generated by
4171 @cite{gnatbind} shuts down the Ada run-time environment.
4173 finalization of all Ada libraries must be performed at the end of the program.
4174 No call to these libraries or to the Ada run-time library should be made
4175 after the finalization phase.
4177 Note also that special care must be taken with multi-tasks
4178 applications. The initialization and finalization routines are not
4179 protected against concurrent access. If such requirement is needed it
4180 must be ensured at the application level using a specific operating
4181 system services like a mutex or a critical-section.
4183 @node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
4184 @anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{9a}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{9b}
4185 @subsubsection Restrictions in Stand-alone Libraries
4188 The pragmas listed below should be used with caution inside libraries,
4189 as they can create incompatibilities with other Ada libraries:
4195 pragma @cite{Locking_Policy}
4198 pragma @cite{Partition_Elaboration_Policy}
4201 pragma @cite{Queuing_Policy}
4204 pragma @cite{Task_Dispatching_Policy}
4207 pragma @cite{Unreserve_All_Interrupts}
4210 When using a library that contains such pragmas, the user must make sure
4211 that all libraries use the same pragmas with the same values. Otherwise,
4212 @cite{Program_Error} will
4213 be raised during the elaboration of the conflicting
4214 libraries. The usage of these pragmas and its consequences for the user
4215 should therefore be well documented.
4217 Similarly, the traceback in the exception occurrence mechanism should be
4218 enabled or disabled in a consistent manner across all libraries.
4219 Otherwise, Program_Error will be raised during the elaboration of the
4220 conflicting libraries.
4222 If the @cite{Version} or @cite{Body_Version}
4223 attributes are used inside a library, then you need to
4224 perform a @cite{gnatbind} step that specifies all @code{ALI} files in all
4225 libraries, so that version identifiers can be properly computed.
4226 In practice these attributes are rarely used, so this is unlikely
4227 to be a consideration.
4229 @node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
4230 @anchor{gnat_ugn/the_gnat_compilation_model id46}@anchor{9c}@anchor{gnat_ugn/the_gnat_compilation_model rebuilding-the-gnat-run-time-library}@anchor{9d}
4231 @subsection Rebuilding the GNAT Run-Time Library
4234 @geindex GNAT Run-Time Library
4237 @geindex Building the GNAT Run-Time Library
4239 @geindex Rebuilding the GNAT Run-Time Library
4241 @geindex Run-Time Library
4244 It may be useful to recompile the GNAT library in various contexts, the
4245 most important one being the use of partition-wide configuration pragmas
4246 such as @cite{Normalize_Scalars}. A special Makefile called
4247 @cite{Makefile.adalib} is provided to that effect and can be found in
4248 the directory containing the GNAT library. The location of this
4249 directory depends on the way the GNAT environment has been installed and can
4250 be determined by means of the command:
4256 The last entry in the object search path usually contains the
4257 gnat library. This Makefile contains its own documentation and in
4258 particular the set of instructions needed to rebuild a new library and
4261 @geindex Conditional compilation
4263 @node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
4264 @anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{9e}@anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{18}
4265 @section Conditional Compilation
4268 This section presents some guidelines for modeling conditional compilation in Ada and describes the
4269 gnatprep preprocessor utility.
4271 @geindex Conditional compilation
4274 * Modeling Conditional Compilation in Ada::
4275 * Preprocessing with gnatprep::
4276 * Integrated Preprocessing::
4280 @node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
4281 @anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{a0}
4282 @subsection Modeling Conditional Compilation in Ada
4285 It is often necessary to arrange for a single source program
4286 to serve multiple purposes, where it is compiled in different
4287 ways to achieve these different goals. Some examples of the
4288 need for this feature are
4294 Adapting a program to a different hardware environment
4297 Adapting a program to a different target architecture
4300 Turning debugging features on and off
4303 Arranging for a program to compile with different compilers
4306 In C, or C++, the typical approach would be to use the preprocessor
4307 that is defined as part of the language. The Ada language does not
4308 contain such a feature. This is not an oversight, but rather a very
4309 deliberate design decision, based on the experience that overuse of
4310 the preprocessing features in C and C++ can result in programs that
4311 are extremely difficult to maintain. For example, if we have ten
4312 switches that can be on or off, this means that there are a thousand
4313 separate programs, any one of which might not even be syntactically
4314 correct, and even if syntactically correct, the resulting program
4315 might not work correctly. Testing all combinations can quickly become
4318 Nevertheless, the need to tailor programs certainly exists, and in
4319 this section we will discuss how this can
4320 be achieved using Ada in general, and GNAT in particular.
4323 * Use of Boolean Constants::
4324 * Debugging - A Special Case::
4325 * Conditionalizing Declarations::
4326 * Use of Alternative Implementations::
4331 @node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4332 @anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{a2}
4333 @subsubsection Use of Boolean Constants
4336 In the case where the difference is simply which code
4337 sequence is executed, the cleanest solution is to use Boolean
4338 constants to control which code is executed.
4341 FP_Initialize_Required : constant Boolean := True;
4343 if FP_Initialize_Required then
4348 Not only will the code inside the @cite{if} statement not be executed if
4349 the constant Boolean is @cite{False}, but it will also be completely
4350 deleted from the program.
4351 However, the code is only deleted after the @cite{if} statement
4352 has been checked for syntactic and semantic correctness.
4353 (In contrast, with preprocessors the code is deleted before the
4354 compiler ever gets to see it, so it is not checked until the switch
4357 @geindex Preprocessors (contrasted with conditional compilation)
4359 Typically the Boolean constants will be in a separate package,
4364 FP_Initialize_Required : constant Boolean := True;
4365 Reset_Available : constant Boolean := False;
4370 The @cite{Config} package exists in multiple forms for the various targets,
4371 with an appropriate script selecting the version of @cite{Config} needed.
4372 Then any other unit requiring conditional compilation can do a @emph{with}
4373 of @cite{Config} to make the constants visible.
4375 @node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4376 @anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{a4}
4377 @subsubsection Debugging - A Special Case
4380 A common use of conditional code is to execute statements (for example
4381 dynamic checks, or output of intermediate results) under control of a
4382 debug switch, so that the debugging behavior can be turned on and off.
4383 This can be done using a Boolean constant to control whether the code
4388 Put_Line ("got to the first stage!");
4395 if Debugging and then Temperature > 999.0 then
4396 raise Temperature_Crazy;
4400 @geindex pragma Assert
4402 Since this is a common case, there are special features to deal with
4403 this in a convenient manner. For the case of tests, Ada 2005 has added
4404 a pragma @cite{Assert} that can be used for such tests. This pragma is modeled
4405 on the @cite{Assert} pragma that has always been available in GNAT, so this
4406 feature may be used with GNAT even if you are not using Ada 2005 features.
4407 The use of pragma @cite{Assert} is described in the
4408 @cite{GNAT_Reference_Manual}, but as an
4409 example, the last test could be written:
4412 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4418 pragma Assert (Temperature <= 999.0);
4421 In both cases, if assertions are active and the temperature is excessive,
4422 the exception @cite{Assert_Failure} will be raised, with the given string in
4423 the first case or a string indicating the location of the pragma in the second
4424 case used as the exception message.
4426 @geindex pragma Assertion_Policy
4428 You can turn assertions on and off by using the @cite{Assertion_Policy}
4431 @geindex -gnata switch
4433 This is an Ada 2005 pragma which is implemented in all modes by
4434 GNAT. Alternatively, you can use the @emph{-gnata} switch
4435 to enable assertions from the command line, which applies to
4436 all versions of Ada.
4438 @geindex pragma Debug
4440 For the example above with the @cite{Put_Line}, the GNAT-specific pragma
4441 @cite{Debug} can be used:
4444 pragma Debug (Put_Line ("got to the first stage!"));
4447 If debug pragmas are enabled, the argument, which must be of the form of
4448 a procedure call, is executed (in this case, @cite{Put_Line} will be called).
4449 Only one call can be present, but of course a special debugging procedure
4450 containing any code you like can be included in the program and then
4451 called in a pragma @cite{Debug} argument as needed.
4453 One advantage of pragma @cite{Debug} over the @cite{if Debugging then}
4454 construct is that pragma @cite{Debug} can appear in declarative contexts,
4455 such as at the very beginning of a procedure, before local declarations have
4458 @geindex pragma Debug_Policy
4460 Debug pragmas are enabled using either the @emph{-gnata} switch that also
4461 controls assertions, or with a separate Debug_Policy pragma.
4463 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4464 in Ada 95 and Ada 83 programs as well), and is analogous to
4465 pragma @cite{Assertion_Policy} to control assertions.
4467 @cite{Assertion_Policy} and @cite{Debug_Policy} are configuration pragmas,
4468 and thus they can appear in @code{gnat.adc} if you are not using a
4469 project file, or in the file designated to contain configuration pragmas
4471 They then apply to all subsequent compilations. In practice the use of
4472 the @emph{-gnata} switch is often the most convenient method of controlling
4473 the status of these pragmas.
4475 Note that a pragma is not a statement, so in contexts where a statement
4476 sequence is required, you can't just write a pragma on its own. You have
4477 to add a @cite{null} statement.
4481 ... -- some statements
4483 pragma Assert (Num_Cases < 10);
4488 @node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4489 @anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{a6}
4490 @subsubsection Conditionalizing Declarations
4493 In some cases it may be necessary to conditionalize declarations to meet
4494 different requirements. For example we might want a bit string whose length
4495 is set to meet some hardware message requirement.
4497 This may be possible using declare blocks controlled
4498 by conditional constants:
4501 if Small_Machine then
4503 X : Bit_String (1 .. 10);
4509 X : Large_Bit_String (1 .. 1000);
4516 Note that in this approach, both declarations are analyzed by the
4517 compiler so this can only be used where both declarations are legal,
4518 even though one of them will not be used.
4520 Another approach is to define integer constants, e.g., @cite{Bits_Per_Word},
4521 or Boolean constants, e.g., @cite{Little_Endian}, and then write declarations
4522 that are parameterized by these constants. For example
4526 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4530 If @cite{Bits_Per_Word} is set to 32, this generates either
4534 Field1 at 0 range 0 .. 32;
4538 for the big endian case, or
4542 Field1 at 0 range 10 .. 32;
4546 for the little endian case. Since a powerful subset of Ada expression
4547 notation is usable for creating static constants, clever use of this
4548 feature can often solve quite difficult problems in conditionalizing
4549 compilation (note incidentally that in Ada 95, the little endian
4550 constant was introduced as @cite{System.Default_Bit_Order}, so you do not
4551 need to define this one yourself).
4553 @node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4554 @anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{a7}@anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{a8}
4555 @subsubsection Use of Alternative Implementations
4558 In some cases, none of the approaches described above are adequate. This
4559 can occur for example if the set of declarations required is radically
4560 different for two different configurations.
4562 In this situation, the official Ada way of dealing with conditionalizing
4563 such code is to write separate units for the different cases. As long as
4564 this does not result in excessive duplication of code, this can be done
4565 without creating maintenance problems. The approach is to share common
4566 code as far as possible, and then isolate the code and declarations
4567 that are different. Subunits are often a convenient method for breaking
4568 out a piece of a unit that is to be conditionalized, with separate files
4569 for different versions of the subunit for different targets, where the
4570 build script selects the right one to give to the compiler.
4572 @geindex Subunits (and conditional compilation)
4574 As an example, consider a situation where a new feature in Ada 2005
4575 allows something to be done in a really nice way. But your code must be able
4576 to compile with an Ada 95 compiler. Conceptually you want to say:
4580 ... neat Ada 2005 code
4582 ... not quite as neat Ada 95 code
4586 where @cite{Ada_2005} is a Boolean constant.
4588 But this won't work when @cite{Ada_2005} is set to @cite{False},
4589 since the @cite{then} clause will be illegal for an Ada 95 compiler.
4590 (Recall that although such unreachable code would eventually be deleted
4591 by the compiler, it still needs to be legal. If it uses features
4592 introduced in Ada 2005, it will be illegal in Ada 95.)
4597 procedure Insert is separate;
4600 Then we have two files for the subunit @cite{Insert}, with the two sets of
4602 If the package containing this is called @cite{File_Queries}, then we might
4609 @code{file_queries-insert-2005.adb}
4612 @code{file_queries-insert-95.adb}
4615 and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4617 This can also be done with project files' naming schemes. For example:
4620 for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4623 Note also that with project files it is desirable to use a different extension
4624 than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4625 conflict may arise through another commonly used feature: to declare as part
4626 of the project a set of directories containing all the sources obeying the
4627 default naming scheme.
4629 The use of alternative units is certainly feasible in all situations,
4630 and for example the Ada part of the GNAT run-time is conditionalized
4631 based on the target architecture using this approach. As a specific example,
4632 consider the implementation of the AST feature in VMS. There is one
4633 spec: @code{s-asthan.ads} which is the same for all architectures, and three
4643 @item @code{s-asthan.adb}
4645 used for all non-VMS operating systems
4652 @item @code{s-asthan-vms-alpha.adb}
4654 used for VMS on the Alpha
4661 @item @code{s-asthan-vms-ia64.adb}
4663 used for VMS on the ia64
4667 The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4668 this operating system feature is not available, and the two remaining
4669 versions interface with the corresponding versions of VMS to provide
4670 VMS-compatible AST handling. The GNAT build script knows the architecture
4671 and operating system, and automatically selects the right version,
4672 renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4674 Another style for arranging alternative implementations is through Ada's
4675 access-to-subprogram facility.
4676 In case some functionality is to be conditionally included,
4677 you can declare an access-to-procedure variable @cite{Ref} that is initialized
4678 to designate a 'do nothing' procedure, and then invoke @cite{Ref.all}
4680 In some library package, set @cite{Ref} to @cite{Proc'Access} for some
4681 procedure @cite{Proc} that performs the relevant processing.
4682 The initialization only occurs if the library package is included in the
4684 The same idea can also be implemented using tagged types and dispatching
4687 @node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4688 @anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{a9}@anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{aa}
4689 @subsubsection Preprocessing
4692 @geindex Preprocessing
4694 Although it is quite possible to conditionalize code without the use of
4695 C-style preprocessing, as described earlier in this section, it is
4696 nevertheless convenient in some cases to use the C approach. Moreover,
4697 older Ada compilers have often provided some preprocessing capability,
4698 so legacy code may depend on this approach, even though it is not
4701 To accommodate such use, GNAT provides a preprocessor (modeled to a large
4702 extent on the various preprocessors that have been used
4703 with legacy code on other compilers, to enable easier transition).
4707 The preprocessor may be used in two separate modes. It can be used quite
4708 separately from the compiler, to generate a separate output source file
4709 that is then fed to the compiler as a separate step. This is the
4710 @cite{gnatprep} utility, whose use is fully described in
4711 @ref{19,,Preprocessing with gnatprep}.
4713 The preprocessing language allows such constructs as
4716 #if DEBUG or else (PRIORITY > 4) then
4717 bunch of declarations
4719 completely different bunch of declarations
4723 The values of the symbols @cite{DEBUG} and @cite{PRIORITY} can be
4724 defined either on the command line or in a separate file.
4726 The other way of running the preprocessor is even closer to the C style and
4727 often more convenient. In this approach the preprocessing is integrated into
4728 the compilation process. The compiler is fed the preprocessor input which
4729 includes @cite{#if} lines etc, and then the compiler carries out the
4730 preprocessing internally and processes the resulting output.
4731 For more details on this approach, see @ref{1a,,Integrated Preprocessing}.
4733 @node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4734 @anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{ab}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{19}
4735 @subsection Preprocessing with @cite{gnatprep}
4740 @geindex Preprocessing (gnatprep)
4742 This section discusses how to use GNAT's @cite{gnatprep} utility for simple
4744 Although designed for use with GNAT, @cite{gnatprep} does not depend on any
4745 special GNAT features.
4746 For further discussion of conditional compilation in general, see
4747 @ref{18,,Conditional Compilation}.
4750 * Preprocessing Symbols::
4752 * Switches for gnatprep::
4753 * Form of Definitions File::
4754 * Form of Input Text for gnatprep::
4758 @node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4759 @anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{ad}
4760 @subsubsection Preprocessing Symbols
4763 Preprocessing symbols are defined in definition files and referred to in
4764 sources to be preprocessed. A Preprocessing symbol is an identifier, following
4765 normal Ada (case-insensitive) rules for its syntax, with the restriction that
4766 all characters need to be in the ASCII set (no accented letters).
4768 @node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4769 @anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{ae}@anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{af}
4770 @subsubsection Using @cite{gnatprep}
4773 To call @cite{gnatprep} use:
4776 $ gnatprep [`switches`] `infile` `outfile` [`deffile`]
4788 @item @emph{switches}
4790 is an optional sequence of switches as described in the next section.
4799 is the full name of the input file, which is an Ada source
4800 file containing preprocessor directives.
4807 @item @emph{outfile}
4809 is the full name of the output file, which is an Ada source
4810 in standard Ada form. When used with GNAT, this file name will
4811 normally have an ads or adb suffix.
4818 @item @emph{deffile}
4820 is the full name of a text file containing definitions of
4821 preprocessing symbols to be referenced by the preprocessor. This argument is
4822 optional, and can be replaced by the use of the @emph{-D} switch.
4826 @node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4827 @anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{b1}
4828 @subsubsection Switches for @cite{gnatprep}
4831 @geindex -b (gnatprep)
4838 Causes both preprocessor lines and the lines deleted by
4839 preprocessing to be replaced by blank lines in the output source file,
4840 preserving line numbers in the output file.
4843 @geindex -c (gnatprep)
4850 Causes both preprocessor lines and the lines deleted
4851 by preprocessing to be retained in the output source as comments marked
4852 with the special string @cite{"--! "}. This option will result in line numbers
4853 being preserved in the output file.
4856 @geindex -C (gnatprep)
4863 Causes comments to be scanned. Normally comments are ignored by gnatprep.
4864 If this option is specified, then comments are scanned and any $symbol
4865 substitutions performed as in program text. This is particularly useful
4866 when structured comments are used (e.g., when writing programs in the
4867 SPARK dialect of Ada). Note that this switch is not available when
4868 doing integrated preprocessing (it would be useless in this context
4869 since comments are ignored by the compiler in any case).
4872 @geindex -D (gnatprep)
4877 @item @code{-D@emph{symbol}=@emph{value}}
4879 Defines a new preprocessing symbol, associated with value. If no value is given
4880 on the command line, then symbol is considered to be @cite{True}. This switch
4881 can be used in place of a definition file.
4884 @geindex -r (gnatprep)
4891 Causes a @cite{Source_Reference} pragma to be generated that
4892 references the original input file, so that error messages will use
4893 the file name of this original file. The use of this switch implies
4894 that preprocessor lines are not to be removed from the file, so its
4895 use will force @emph{-b} mode if @emph{-c}
4896 has not been specified explicitly.
4898 Note that if the file to be preprocessed contains multiple units, then
4899 it will be necessary to @cite{gnatchop} the output file from
4900 @cite{gnatprep}. If a @cite{Source_Reference} pragma is present
4901 in the preprocessed file, it will be respected by
4903 so that the final chopped files will correctly refer to the original
4904 input source file for @cite{gnatprep}.
4907 @geindex -s (gnatprep)
4914 Causes a sorted list of symbol names and values to be
4915 listed on the standard output file.
4918 @geindex -u (gnatprep)
4925 Causes undefined symbols to be treated as having the value FALSE in the context
4926 of a preprocessor test. In the absence of this option, an undefined symbol in
4927 a @cite{#if} or @cite{#elsif} test will be treated as an error.
4930 Note: if neither @emph{-b} nor @emph{-c} is present,
4931 then preprocessor lines and
4932 deleted lines are completely removed from the output, unless -r is
4933 specified, in which case -b is assumed.
4935 @node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4936 @anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{b2}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{b3}
4937 @subsubsection Form of Definitions File
4940 The definitions file contains lines of the form:
4946 where @cite{symbol} is a preprocessing symbol, and @cite{value} is one of the following:
4952 Empty, corresponding to a null substitution,
4955 A string literal using normal Ada syntax, or
4958 Any sequence of characters from the set @{letters, digits, period, underline@}.
4961 Comment lines may also appear in the definitions file, starting with
4962 the usual @code{--},
4963 and comments may be added to the definitions lines.
4965 @node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4966 @anchor{gnat_ugn/the_gnat_compilation_model id59}@anchor{b4}@anchor{gnat_ugn/the_gnat_compilation_model form-of-input-text-for-gnatprep}@anchor{b5}
4967 @subsubsection Form of Input Text for @cite{gnatprep}
4970 The input text may contain preprocessor conditional inclusion lines,
4971 as well as general symbol substitution sequences.
4973 The preprocessor conditional inclusion commands have the form:
4976 #if <expression> [then]
4978 #elsif <expression> [then]
4980 #elsif <expression> [then]
4988 In this example, <expression> is defined by the following grammar:
4991 <expression> ::= <symbol>
4992 <expression> ::= <symbol> = "<value>"
4993 <expression> ::= <symbol> = <symbol>
4994 <expression> ::= <symbol> = <integer>
4995 <expression> ::= <symbol> > <integer>
4996 <expression> ::= <symbol> >= <integer>
4997 <expression> ::= <symbol> < <integer>
4998 <expression> ::= <symbol> <= <integer>
4999 <expression> ::= <symbol> 'Defined
5000 <expression> ::= not <expression>
5001 <expression> ::= <expression> and <expression>
5002 <expression> ::= <expression> or <expression>
5003 <expression> ::= <expression> and then <expression>
5004 <expression> ::= <expression> or else <expression>
5005 <expression> ::= ( <expression> )
5008 Note the following restriction: it is not allowed to have "and" or "or"
5009 following "not" in the same expression without parentheses. For example, this
5016 This can be expressed instead as one of the following forms:
5023 For the first test (<expression> ::= <symbol>) the symbol must have
5024 either the value true or false, that is to say the right-hand of the
5025 symbol definition must be one of the (case-insensitive) literals
5026 @cite{True} or @cite{False}. If the value is true, then the
5027 corresponding lines are included, and if the value is false, they are
5030 When comparing a symbol to an integer, the integer is any non negative
5031 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
5032 2#11#. The symbol value must also be a non negative integer. Integer values
5033 in the range 0 .. 2**31-1 are supported.
5035 The test (<expression> ::= <symbol>'Defined) is true only if
5036 the symbol has been defined in the definition file or by a @emph{-D}
5037 switch on the command line. Otherwise, the test is false.
5039 The equality tests are case insensitive, as are all the preprocessor lines.
5041 If the symbol referenced is not defined in the symbol definitions file,
5042 then the effect depends on whether or not switch @emph{-u}
5043 is specified. If so, then the symbol is treated as if it had the value
5044 false and the test fails. If this switch is not specified, then
5045 it is an error to reference an undefined symbol. It is also an error to
5046 reference a symbol that is defined with a value other than @cite{True}
5049 The use of the @cite{not} operator inverts the sense of this logical test.
5050 The @cite{not} operator cannot be combined with the @cite{or} or @cite{and}
5051 operators, without parentheses. For example, "if not X or Y then" is not
5052 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
5054 The @cite{then} keyword is optional as shown
5056 The @cite{#} must be the first non-blank character on a line, but
5057 otherwise the format is free form. Spaces or tabs may appear between
5058 the @cite{#} and the keyword. The keywords and the symbols are case
5059 insensitive as in normal Ada code. Comments may be used on a
5060 preprocessor line, but other than that, no other tokens may appear on a
5061 preprocessor line. Any number of @cite{elsif} clauses can be present,
5062 including none at all. The @cite{else} is optional, as in Ada.
5064 The @cite{#} marking the start of a preprocessor line must be the first
5065 non-blank character on the line, i.e., it must be preceded only by
5066 spaces or horizontal tabs.
5068 Symbol substitution outside of preprocessor lines is obtained by using
5075 anywhere within a source line, except in a comment or within a
5076 string literal. The identifier
5077 following the @cite{$} must match one of the symbols defined in the symbol
5078 definition file, and the result is to substitute the value of the
5079 symbol in place of @cite{$symbol} in the output file.
5081 Note that although the substitution of strings within a string literal
5082 is not possible, it is possible to have a symbol whose defined value is
5083 a string literal. So instead of setting XYZ to @cite{hello} and writing:
5086 Header : String := "$XYZ";
5089 you should set XYZ to @cite{"hello"} and write:
5092 Header : String := $XYZ;
5095 and then the substitution will occur as desired.
5097 @node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
5098 @anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{b6}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{1a}
5099 @subsection Integrated Preprocessing
5102 GNAT sources may be preprocessed immediately before compilation.
5103 In this case, the actual
5104 text of the source is not the text of the source file, but is derived from it
5105 through a process called preprocessing. Integrated preprocessing is specified
5106 through switches @emph{-gnatep} and/or @emph{-gnateD}. @emph{-gnatep}
5107 indicates, through a text file, the preprocessing data to be used.
5108 @code{-gnateD} specifies or modifies the values of preprocessing symbol.
5109 Note that integrated preprocessing applies only to Ada source files, it is
5110 not available for configuration pragma files.
5112 Note that when integrated preprocessing is used, the output from the
5113 preprocessor is not written to any external file. Instead it is passed
5114 internally to the compiler. If you need to preserve the result of
5115 preprocessing in a file, then you should use @emph{gnatprep}
5116 to perform the desired preprocessing in stand-alone mode.
5118 It is recommended that @emph{gnatmake} switch -s should be
5119 used when Integrated Preprocessing is used. The reason is that preprocessing
5120 with another Preprocessing Data file without changing the sources will
5121 not trigger recompilation without this switch.
5123 Note that @emph{gnatmake} switch -m will almost
5124 always trigger recompilation for sources that are preprocessed,
5125 because @emph{gnatmake} cannot compute the checksum of the source after
5128 The actual preprocessing function is described in detail in section
5129 @ref{19,,Preprocessing with gnatprep}. This section only describes how integrated
5130 preprocessing is triggered and parameterized.
5132 @geindex -gnatep (gcc)
5137 @item @code{-gnatep=@emph{file}}
5139 This switch indicates to the compiler the file name (without directory
5140 information) of the preprocessor data file to use. The preprocessor data file
5141 should be found in the source directories. Note that when the compiler is
5142 called by a builder such as (@emph{gnatmake} with a project
5143 file, if the object directory is not also a source directory, the builder needs
5144 to be called with @emph{-x}.
5146 A preprocessing data file is a text file with significant lines indicating
5147 how should be preprocessed either a specific source or all sources not
5148 mentioned in other lines. A significant line is a nonempty, non-comment line.
5149 Comments are similar to Ada comments.
5151 Each significant line starts with either a literal string or the character '*'.
5152 A literal string is the file name (without directory information) of the source
5153 to preprocess. A character '*' indicates the preprocessing for all the sources
5154 that are not specified explicitly on other lines (order of the lines is not
5155 significant). It is an error to have two lines with the same file name or two
5156 lines starting with the character '*'.
5158 After the file name or the character '*', another optional literal string
5159 indicating the file name of the definition file to be used for preprocessing
5160 (@ref{b2,,Form of Definitions File}). The definition files are found by the
5161 compiler in one of the source directories. In some cases, when compiling
5162 a source in a directory other than the current directory, if the definition
5163 file is in the current directory, it may be necessary to add the current
5164 directory as a source directory through switch -I., otherwise
5165 the compiler would not find the definition file.
5167 Then, optionally, switches similar to those of @cite{gnatprep} may
5168 be found. Those switches are:
5175 Causes both preprocessor lines and the lines deleted by
5176 preprocessing to be replaced by blank lines, preserving the line number.
5177 This switch is always implied; however, if specified after @emph{-c}
5178 it cancels the effect of @emph{-c}.
5182 Causes both preprocessor lines and the lines deleted
5183 by preprocessing to be retained as comments marked
5184 with the special string '@cite{--!}'.
5186 @item @code{-Dsymbol=@emph{value}}
5188 Define or redefine a symbol, associated with value. A symbol is an Ada
5189 identifier, or an Ada reserved word, with the exception of @cite{if},
5190 @cite{else}, @cite{elsif}, @cite{end}, @cite{and}, @cite{or} and @cite{then}.
5191 @cite{value} is either a literal string, an Ada identifier or any Ada reserved
5192 word. A symbol declared with this switch replaces a symbol with the
5193 same name defined in a definition file.
5197 Causes a sorted list of symbol names and values to be
5198 listed on the standard output file.
5202 Causes undefined symbols to be treated as having the value @cite{FALSE}
5204 of a preprocessor test. In the absence of this option, an undefined symbol in
5205 a @cite{#if} or @cite{#elsif} test will be treated as an error.
5208 Examples of valid lines in a preprocessor data file:
5211 "toto.adb" "prep.def" -u
5212 -- preprocess "toto.adb", using definition file "prep.def",
5213 -- undefined symbol are False.
5216 -- preprocess all other sources without a definition file;
5217 -- suppressed lined are commented; symbol VERSION has the value V101.
5219 "titi.adb" "prep2.def" -s
5220 -- preprocess "titi.adb", using definition file "prep2.def";
5221 -- list all symbols with their values.
5225 @geindex -gnateD (gcc)
5230 @item @code{-gnateDsymbol[=value]}
5232 Define or redefine a preprocessing symbol, associated with value. If no value
5233 is given on the command line, then the value of the symbol is @cite{True}.
5234 A symbol is an identifier, following normal Ada (case-insensitive)
5235 rules for its syntax, and value is either an arbitrary string between double
5236 quotes or any sequence (including an empty sequence) of characters from the
5237 set (letters, digits, period, underline).
5238 Ada reserved words may be used as symbols, with the exceptions of @cite{if},
5239 @cite{else}, @cite{elsif}, @cite{end}, @cite{and}, @cite{or} and @cite{then}.
5246 -gnateDFoo=\"Foo-Bar\"
5249 A symbol declared with this switch on the command line replaces a
5250 symbol with the same name either in a definition file or specified with a
5251 switch -D in the preprocessor data file.
5253 This switch is similar to switch @emph{-D} of @cite{gnatprep}.
5255 @item @code{-gnateG}
5257 When integrated preprocessing is performed and the preprocessor modifies
5258 the source text, write the result of this preprocessing into a file
5262 @node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5263 @anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{46}@anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{b7}
5264 @section Mixed Language Programming
5267 @geindex Mixed Language Programming
5269 This section describes how to develop a mixed-language program,
5270 with a focus on combining Ada with C or C++.
5273 * Interfacing to C::
5274 * Calling Conventions::
5275 * Building Mixed Ada and C++ Programs::
5276 * Generating Ada Bindings for C and C++ headers::
5277 * Generating C Headers for Ada Specifications::
5281 @node Interfacing to C,Calling Conventions,,Mixed Language Programming
5282 @anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{b8}@anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{b9}
5283 @subsection Interfacing to C
5286 Interfacing Ada with a foreign language such as C involves using
5287 compiler directives to import and/or export entity definitions in each
5288 language -- using @cite{extern} statements in C, for instance, and the
5289 @cite{Import}, @cite{Export}, and @cite{Convention} pragmas in Ada.
5290 A full treatment of these topics is provided in Appendix B, section 1
5291 of the Ada Reference Manual.
5293 There are two ways to build a program using GNAT that contains some Ada
5294 sources and some foreign language sources, depending on whether or not
5295 the main subprogram is written in Ada. Here is a source example with
5296 the main subprogram in Ada:
5302 void print_num (int num)
5304 printf ("num is %d.\\n", num);
5312 /* num_from_Ada is declared in my_main.adb */
5313 extern int num_from_Ada;
5317 return num_from_Ada;
5323 procedure My_Main is
5325 -- Declare then export an Integer entity called num_from_Ada
5326 My_Num : Integer := 10;
5327 pragma Export (C, My_Num, "num_from_Ada");
5329 -- Declare an Ada function spec for Get_Num, then use
5330 -- C function get_num for the implementation.
5331 function Get_Num return Integer;
5332 pragma Import (C, Get_Num, "get_num");
5334 -- Declare an Ada procedure spec for Print_Num, then use
5335 -- C function print_num for the implementation.
5336 procedure Print_Num (Num : Integer);
5337 pragma Import (C, Print_Num, "print_num";
5340 Print_Num (Get_Num);
5344 To build this example:
5350 First compile the foreign language files to
5351 generate object files:
5359 Then, compile the Ada units to produce a set of object files and ALI
5363 $ gnatmake -c my_main.adb
5367 Run the Ada binder on the Ada main program:
5370 $ gnatbind my_main.ali
5374 Link the Ada main program, the Ada objects and the other language
5378 $ gnatlink my_main.ali file1.o file2.o
5382 The last three steps can be grouped in a single command:
5385 $ gnatmake my_main.adb -largs file1.o file2.o
5388 @geindex Binder output file
5390 If the main program is in a language other than Ada, then you may have
5391 more than one entry point into the Ada subsystem. You must use a special
5392 binder option to generate callable routines that initialize and
5393 finalize the Ada units (@ref{ba,,Binding with Non-Ada Main Programs}).
5394 Calls to the initialization and finalization routines must be inserted
5395 in the main program, or some other appropriate point in the code. The
5396 call to initialize the Ada units must occur before the first Ada
5397 subprogram is called, and the call to finalize the Ada units must occur
5398 after the last Ada subprogram returns. The binder will place the
5399 initialization and finalization subprograms into the
5400 @code{b~xxx.adb} file where they can be accessed by your C
5401 sources. To illustrate, we have the following example:
5405 extern void adainit (void);
5406 extern void adafinal (void);
5407 extern int add (int, int);
5408 extern int sub (int, int);
5410 int main (int argc, char *argv[])
5416 /* Should print "21 + 7 = 28" */
5417 printf ("%d + %d = %d\\n", a, b, add (a, b));
5419 /* Should print "21 - 7 = 14" */
5420 printf ("%d - %d = %d\\n", a, b, sub (a, b));
5429 function Add (A, B : Integer) return Integer;
5430 pragma Export (C, Add, "add");
5436 package body Unit1 is
5437 function Add (A, B : Integer) return Integer is
5447 function Sub (A, B : Integer) return Integer;
5448 pragma Export (C, Sub, "sub");
5454 package body Unit2 is
5455 function Sub (A, B : Integer) return Integer is
5462 The build procedure for this application is similar to the last
5469 First, compile the foreign language files to generate object files:
5476 Next, compile the Ada units to produce a set of object files and ALI
5480 $ gnatmake -c unit1.adb
5481 $ gnatmake -c unit2.adb
5485 Run the Ada binder on every generated ALI file. Make sure to use the
5486 @code{-n} option to specify a foreign main program:
5489 $ gnatbind -n unit1.ali unit2.ali
5493 Link the Ada main program, the Ada objects and the foreign language
5494 objects. You need only list the last ALI file here:
5497 $ gnatlink unit2.ali main.o -o exec_file
5500 This procedure yields a binary executable called @code{exec_file}.
5503 Depending on the circumstances (for example when your non-Ada main object
5504 does not provide symbol @cite{main}), you may also need to instruct the
5505 GNAT linker not to include the standard startup objects by passing the
5506 @code{-nostartfiles} switch to @cite{gnatlink}.
5508 @node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5509 @anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{bb}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{bc}
5510 @subsection Calling Conventions
5513 @geindex Foreign Languages
5515 @geindex Calling Conventions
5517 GNAT follows standard calling sequence conventions and will thus interface
5518 to any other language that also follows these conventions. The following
5519 Convention identifiers are recognized by GNAT:
5521 @geindex Interfacing to Ada
5523 @geindex Other Ada compilers
5525 @geindex Convention Ada
5532 This indicates that the standard Ada calling sequence will be
5533 used and all Ada data items may be passed without any limitations in the
5534 case where GNAT is used to generate both the caller and callee. It is also
5535 possible to mix GNAT generated code and code generated by another Ada
5536 compiler. In this case, the data types should be restricted to simple
5537 cases, including primitive types. Whether complex data types can be passed
5538 depends on the situation. Probably it is safe to pass simple arrays, such
5539 as arrays of integers or floats. Records may or may not work, depending
5540 on whether both compilers lay them out identically. Complex structures
5541 involving variant records, access parameters, tasks, or protected types,
5542 are unlikely to be able to be passed.
5544 Note that in the case of GNAT running
5545 on a platform that supports HP Ada 83, a higher degree of compatibility
5546 can be guaranteed, and in particular records are laid out in an identical
5547 manner in the two compilers. Note also that if output from two different
5548 compilers is mixed, the program is responsible for dealing with elaboration
5549 issues. Probably the safest approach is to write the main program in the
5550 version of Ada other than GNAT, so that it takes care of its own elaboration
5551 requirements, and then call the GNAT-generated adainit procedure to ensure
5552 elaboration of the GNAT components. Consult the documentation of the other
5553 Ada compiler for further details on elaboration.
5555 However, it is not possible to mix the tasking run time of GNAT and
5556 HP Ada 83, All the tasking operations must either be entirely within
5557 GNAT compiled sections of the program, or entirely within HP Ada 83
5558 compiled sections of the program.
5561 @geindex Interfacing to Assembly
5563 @geindex Convention Assembler
5568 @item @emph{Assembler}
5570 Specifies assembler as the convention. In practice this has the
5571 same effect as convention Ada (but is not equivalent in the sense of being
5572 considered the same convention).
5575 @geindex Convention Asm
5584 Equivalent to Assembler.
5586 @geindex Interfacing to COBOL
5588 @geindex Convention COBOL
5598 Data will be passed according to the conventions described
5599 in section B.4 of the Ada Reference Manual.
5604 @geindex Interfacing to C
5606 @geindex Convention C
5613 Data will be passed according to the conventions described
5614 in section B.3 of the Ada Reference Manual.
5616 A note on interfacing to a C 'varargs' function:
5620 @geindex C varargs function
5622 @geindex Interfacing to C varargs function
5624 @geindex varargs function interfaces
5626 In C, @cite{varargs} allows a function to take a variable number of
5627 arguments. There is no direct equivalent in this to Ada. One
5628 approach that can be used is to create a C wrapper for each
5629 different profile and then interface to this C wrapper. For
5630 example, to print an @cite{int} value using @cite{printf},
5631 create a C function @cite{printfi} that takes two arguments, a
5632 pointer to a string and an int, and calls @cite{printf}.
5633 Then in the Ada program, use pragma @cite{Import} to
5634 interface to @cite{printfi}.
5636 It may work on some platforms to directly interface to
5637 a @cite{varargs} function by providing a specific Ada profile
5638 for a particular call. However, this does not work on
5639 all platforms, since there is no guarantee that the
5640 calling sequence for a two argument normal C function
5641 is the same as for calling a @cite{varargs} C function with
5642 the same two arguments.
5646 @geindex Convention Default
5653 @item @emph{Default}
5658 @geindex Convention External
5665 @item @emph{External}
5672 @geindex Interfacing to C++
5674 @geindex Convention C++
5679 @item @emph{C_Plus_Plus (or CPP)}
5681 This stands for C++. For most purposes this is identical to C.
5682 See the separate description of the specialized GNAT pragmas relating to
5683 C++ interfacing for further details.
5688 @geindex Interfacing to Fortran
5690 @geindex Convention Fortran
5695 @item @emph{Fortran}
5697 Data will be passed according to the conventions described
5698 in section B.5 of the Ada Reference Manual.
5700 @item @emph{Intrinsic}
5702 This applies to an intrinsic operation, as defined in the Ada
5703 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5704 this means that the body of the subprogram is provided by the compiler itself,
5705 usually by means of an efficient code sequence, and that the user does not
5706 supply an explicit body for it. In an application program, the pragma may
5707 be applied to the following sets of names:
5713 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5714 The corresponding subprogram declaration must have
5715 two formal parameters. The
5716 first one must be a signed integer type or a modular type with a binary
5717 modulus, and the second parameter must be of type Natural.
5718 The return type must be the same as the type of the first argument. The size
5719 of this type can only be 8, 16, 32, or 64.
5722 Binary arithmetic operators: '+', '-', '*', '/'.
5723 The corresponding operator declaration must have parameters and result type
5724 that have the same root numeric type (for example, all three are long_float
5725 types). This simplifies the definition of operations that use type checking
5726 to perform dimensional checks:
5730 type Distance is new Long_Float;
5731 type Time is new Long_Float;
5732 type Velocity is new Long_Float;
5733 function "/" (D : Distance; T : Time)
5735 pragma Import (Intrinsic, "/");
5737 This common idiom is often programmed with a generic definition and an
5738 explicit body. The pragma makes it simpler to introduce such declarations.
5739 It incurs no overhead in compilation time or code size, because it is
5740 implemented as a single machine instruction.
5747 General subprogram entities. This is used to bind an Ada subprogram
5749 a compiler builtin by name with back-ends where such interfaces are
5750 available. A typical example is the set of @cite{__builtin} functions
5751 exposed by the GCC back-end, as in the following example:
5754 function builtin_sqrt (F : Float) return Float;
5755 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5758 Most of the GCC builtins are accessible this way, and as for other
5759 import conventions (e.g. C), it is the user's responsibility to ensure
5760 that the Ada subprogram profile matches the underlying builtin
5767 @geindex Convention Stdcall
5772 @item @emph{Stdcall}
5774 This is relevant only to Windows implementations of GNAT,
5775 and specifies that the @cite{Stdcall} calling sequence will be used,
5776 as defined by the NT API. Nevertheless, to ease building
5777 cross-platform bindings this convention will be handled as a @cite{C} calling
5778 convention on non-Windows platforms.
5783 @geindex Convention DLL
5790 This is equivalent to @cite{Stdcall}.
5795 @geindex Convention Win32
5802 This is equivalent to @cite{Stdcall}.
5807 @geindex Convention Stubbed
5812 @item @emph{Stubbed}
5814 This is a special convention that indicates that the compiler
5815 should provide a stub body that raises @cite{Program_Error}.
5818 GNAT additionally provides a useful pragma @cite{Convention_Identifier}
5819 that can be used to parameterize conventions and allow additional synonyms
5820 to be specified. For example if you have legacy code in which the convention
5821 identifier Fortran77 was used for Fortran, you can use the configuration
5825 pragma Convention_Identifier (Fortran77, Fortran);
5828 And from now on the identifier Fortran77 may be used as a convention
5829 identifier (for example in an @cite{Import} pragma) with the same
5832 @node Building Mixed Ada and C++ Programs,Generating Ada Bindings for C and C++ headers,Calling Conventions,Mixed Language Programming
5833 @anchor{gnat_ugn/the_gnat_compilation_model id64}@anchor{bd}@anchor{gnat_ugn/the_gnat_compilation_model building-mixed-ada-and-c-programs}@anchor{be}
5834 @subsection Building Mixed Ada and C++ Programs
5837 A programmer inexperienced with mixed-language development may find that
5838 building an application containing both Ada and C++ code can be a
5839 challenge. This section gives a few hints that should make this task easier.
5842 * Interfacing to C++::
5843 * Linking a Mixed C++ & Ada Program::
5844 * A Simple Example::
5845 * Interfacing with C++ constructors::
5846 * Interfacing with C++ at the Class Level::
5850 @node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5851 @anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{bf}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{c0}
5852 @subsubsection Interfacing to C++
5855 GNAT supports interfacing with the G++ compiler (or any C++ compiler
5856 generating code that is compatible with the G++ Application Binary
5857 Interface ---see @indicateurl{http://www.codesourcery.com/archives/cxx-abi}).
5859 Interfacing can be done at 3 levels: simple data, subprograms, and
5860 classes. In the first two cases, GNAT offers a specific @cite{Convention C_Plus_Plus}
5861 (or @cite{CPP}) that behaves exactly like @cite{Convention C}.
5862 Usually, C++ mangles the names of subprograms. To generate proper mangled
5863 names automatically, see @ref{1b,,Generating Ada Bindings for C and C++ headers}).
5864 This problem can also be addressed manually in two ways:
5870 by modifying the C++ code in order to force a C convention using
5871 the @cite{extern "C"} syntax.
5874 by figuring out the mangled name (using e.g. @emph{nm}) and using it as the
5875 Link_Name argument of the pragma import.
5878 Interfacing at the class level can be achieved by using the GNAT specific
5879 pragmas such as @cite{CPP_Constructor}. See the @cite{GNAT_Reference_Manual} for additional information.
5881 @node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5882 @anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-ada-program}@anchor{c1}@anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-and-ada-program}@anchor{c2}
5883 @subsubsection Linking a Mixed C++ & Ada Program
5886 Usually the linker of the C++ development system must be used to link
5887 mixed applications because most C++ systems will resolve elaboration
5888 issues (such as calling constructors on global class instances)
5889 transparently during the link phase. GNAT has been adapted to ease the
5890 use of a foreign linker for the last phase. Three cases can be
5897 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5898 The C++ linker can simply be called by using the C++ specific driver
5901 Note that if the C++ code uses inline functions, you will need to
5902 compile your C++ code with the @cite{-fkeep-inline-functions} switch in
5903 order to provide an existing function implementation that the Ada code can
5907 $ g++ -c -fkeep-inline-functions file1.C
5908 $ g++ -c -fkeep-inline-functions file2.C
5909 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5913 Using GNAT and G++ from two different GCC installations: If both
5914 compilers are on the :envvar`PATH`, the previous method may be used. It is
5915 important to note that environment variables such as
5916 @geindex C_INCLUDE_PATH
5917 @geindex environment variable; C_INCLUDE_PATH
5918 @code{C_INCLUDE_PATH},
5919 @geindex GCC_EXEC_PREFIX
5920 @geindex environment variable; GCC_EXEC_PREFIX
5921 @code{GCC_EXEC_PREFIX},
5922 @geindex BINUTILS_ROOT
5923 @geindex environment variable; BINUTILS_ROOT
5924 @code{BINUTILS_ROOT}, and
5926 @geindex environment variable; GCC_ROOT
5927 @code{GCC_ROOT} will affect both compilers
5928 at the same time and may make one of the two compilers operate
5929 improperly if set during invocation of the wrong compiler. It is also
5930 very important that the linker uses the proper @code{libgcc.a} GCC
5931 library -- that is, the one from the C++ compiler installation. The
5932 implicit link command as suggested in the @cite{gnatmake} command
5933 from the former example can be replaced by an explicit link command with
5934 the full-verbosity option in order to verify which library is used:
5938 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5941 If there is a problem due to interfering environment variables, it can
5942 be worked around by using an intermediate script. The following example
5943 shows the proper script to use when GNAT has not been installed at its
5944 default location and g++ has been installed at its default location:
5952 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5956 Using a non-GNU C++ compiler: The commands previously described can be
5957 used to insure that the C++ linker is used. Nonetheless, you need to add
5958 a few more parameters to the link command line, depending on the exception
5961 If the @cite{setjmp/longjmp} exception mechanism is used, only the paths
5962 to the libgcc libraries are required:
5967 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
5968 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5971 where CC is the name of the non-GNU C++ compiler.
5973 If the @cite{zero cost} exception mechanism is used, and the platform
5974 supports automatic registration of exception tables (e.g., Solaris),
5975 paths to more objects are required:
5980 CC `gcc -print-file-name=crtbegin.o` $* \\
5981 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \\
5982 `gcc -print-file-name=crtend.o`
5983 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
5986 If the "zero cost exception" mechanism is used, and the platform
5987 doesn't support automatic registration of exception tables (e.g., HP-UX
5988 or AIX), the simple approach described above will not work and
5989 a pre-linking phase using GNAT will be necessary.
5992 Another alternative is to use the @code{gprbuild} multi-language builder
5993 which has a large knowledge base and knows how to link Ada and C++ code
5994 together automatically in most cases.
5996 @node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
5997 @anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{c3}@anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{c4}
5998 @subsubsection A Simple Example
6001 The following example, provided as part of the GNAT examples, shows how
6002 to achieve procedural interfacing between Ada and C++ in both
6003 directions. The C++ class A has two methods. The first method is exported
6004 to Ada by the means of an extern C wrapper function. The second method
6005 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
6006 a limited record with a layout comparable to the C++ class. The Ada
6007 subprogram, in turn, calls the C++ method. So, starting from the C++
6008 main program, the process passes back and forth between the two
6011 Here are the compilation commands:
6014 $ gnatmake -c simple_cpp_interface
6017 $ gnatbind -n simple_cpp_interface
6018 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
6021 Here are the corresponding sources:
6029 void adainit (void);
6030 void adafinal (void);
6031 void method1 (A *t);
6055 class A : public Origin @{
6057 void method1 (void);
6058 void method2 (int v);
6070 extern "C" @{ void ada_method2 (A *t, int v);@}
6072 void A::method1 (void)
6075 printf ("in A::method1, a_value = %d \\n",a_value);
6078 void A::method2 (int v)
6080 ada_method2 (this, v);
6081 printf ("in A::method2, a_value = %d \\n",a_value);
6087 printf ("in A::A, a_value = %d \\n",a_value);
6092 -- simple_cpp_interface.ads
6094 package Simple_Cpp_Interface is
6097 Vptr : System.Address;
6101 pragma Convention (C, A);
6103 procedure Method1 (This : in out A);
6104 pragma Import (C, Method1);
6106 procedure Ada_Method2 (This : in out A; V : Integer);
6107 pragma Export (C, Ada_Method2);
6109 end Simple_Cpp_Interface;
6113 -- simple_cpp_interface.adb
6114 package body Simple_Cpp_Interface is
6116 procedure Ada_Method2 (This : in out A; V : Integer) is
6122 end Simple_Cpp_Interface;
6125 @node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
6126 @anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{c5}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{c6}
6127 @subsubsection Interfacing with C++ constructors
6130 In order to interface with C++ constructors GNAT provides the
6131 @cite{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
6132 for additional information).
6133 In this section we present some common uses of C++ constructors
6134 in mixed-languages programs in GNAT.
6136 Let us assume that we need to interface with the following
6144 virtual int Get_Value ();
6145 Root(); // Default constructor
6146 Root(int v); // 1st non-default constructor
6147 Root(int v, int w); // 2nd non-default constructor
6151 For this purpose we can write the following package spec (further
6152 information on how to build this spec is available in
6153 @ref{c7,,Interfacing with C++ at the Class Level} and
6154 @ref{1b,,Generating Ada Bindings for C and C++ headers}).
6157 with Interfaces.C; use Interfaces.C;
6159 type Root is tagged limited record
6163 pragma Import (CPP, Root);
6165 function Get_Value (Obj : Root) return int;
6166 pragma Import (CPP, Get_Value);
6168 function Constructor return Root;
6169 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
6171 function Constructor (v : Integer) return Root;
6172 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
6174 function Constructor (v, w : Integer) return Root;
6175 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
6179 On the Ada side the constructor is represented by a function (whose
6180 name is arbitrary) that returns the classwide type corresponding to
6181 the imported C++ class. Although the constructor is described as a
6182 function, it is typically a procedure with an extra implicit argument
6183 (the object being initialized) at the implementation level. GNAT
6184 issues the appropriate call, whatever it is, to get the object
6185 properly initialized.
6187 Constructors can only appear in the following contexts:
6193 On the right side of an initialization of an object of type @cite{T}.
6196 On the right side of an initialization of a record component of type @cite{T}.
6199 In an Ada 2005 limited aggregate.
6202 In an Ada 2005 nested limited aggregate.
6205 In an Ada 2005 limited aggregate that initializes an object built in
6206 place by an extended return statement.
6209 In a declaration of an object whose type is a class imported from C++,
6210 either the default C++ constructor is implicitly called by GNAT, or
6211 else the required C++ constructor must be explicitly called in the
6212 expression that initializes the object. For example:
6216 Obj2 : Root := Constructor;
6217 Obj3 : Root := Constructor (v => 10);
6218 Obj4 : Root := Constructor (30, 40);
6221 The first two declarations are equivalent: in both cases the default C++
6222 constructor is invoked (in the former case the call to the constructor is
6223 implicit, and in the latter case the call is explicit in the object
6224 declaration). @cite{Obj3} is initialized by the C++ non-default constructor
6225 that takes an integer argument, and @cite{Obj4} is initialized by the
6226 non-default C++ constructor that takes two integers.
6228 Let us derive the imported C++ class in the Ada side. For example:
6231 type DT is new Root with record
6232 C_Value : Natural := 2009;
6236 In this case the components DT inherited from the C++ side must be
6237 initialized by a C++ constructor, and the additional Ada components
6238 of type DT are initialized by GNAT. The initialization of such an
6239 object is done either by default, or by means of a function returning
6240 an aggregate of type DT, or by means of an extension aggregate.
6244 Obj6 : DT := Function_Returning_DT (50);
6245 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6248 The declaration of @cite{Obj5} invokes the default constructors: the
6249 C++ default constructor of the parent type takes care of the initialization
6250 of the components inherited from Root, and GNAT takes care of the default
6251 initialization of the additional Ada components of type DT (that is,
6252 @cite{C_Value} is initialized to value 2009). The order of invocation of
6253 the constructors is consistent with the order of elaboration required by
6254 Ada and C++. That is, the constructor of the parent type is always called
6255 before the constructor of the derived type.
6257 Let us now consider a record that has components whose type is imported
6258 from C++. For example:
6261 type Rec1 is limited record
6262 Data1 : Root := Constructor (10);
6263 Value : Natural := 1000;
6266 type Rec2 (D : Integer := 20) is limited record
6268 Data2 : Root := Constructor (D, 30);
6272 The initialization of an object of type @cite{Rec2} will call the
6273 non-default C++ constructors specified for the imported components.
6280 Using Ada 2005 we can use limited aggregates to initialize an object
6281 invoking C++ constructors that differ from those specified in the type
6282 declarations. For example:
6285 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6290 The above declaration uses an Ada 2005 limited aggregate to
6291 initialize @cite{Obj9}, and the C++ constructor that has two integer
6292 arguments is invoked to initialize the @cite{Data1} component instead
6293 of the constructor specified in the declaration of type @cite{Rec1}. In
6294 Ada 2005 the box in the aggregate indicates that unspecified components
6295 are initialized using the expression (if any) available in the component
6296 declaration. That is, in this case discriminant @cite{D} is initialized
6297 to value @cite{20}, @cite{Value} is initialized to value 1000, and the
6298 non-default C++ constructor that handles two integers takes care of
6299 initializing component @cite{Data2} with values @cite{20@comma{}30}.
6301 In Ada 2005 we can use the extended return statement to build the Ada
6302 equivalent to C++ non-default constructors. For example:
6305 function Constructor (V : Integer) return Rec2 is
6307 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
6310 -- Further actions required for construction of
6311 -- objects of type Rec2
6317 In this example the extended return statement construct is used to
6318 build in place the returned object whose components are initialized
6319 by means of a limited aggregate. Any further action associated with
6320 the constructor can be placed inside the construct.
6322 @node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6323 @anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-at-the-class-level}@anchor{c7}@anchor{gnat_ugn/the_gnat_compilation_model id69}@anchor{c8}
6324 @subsubsection Interfacing with C++ at the Class Level
6327 In this section we demonstrate the GNAT features for interfacing with
6328 C++ by means of an example making use of Ada 2005 abstract interface
6329 types. This example consists of a classification of animals; classes
6330 have been used to model our main classification of animals, and
6331 interfaces provide support for the management of secondary
6332 classifications. We first demonstrate a case in which the types and
6333 constructors are defined on the C++ side and imported from the Ada
6334 side, and latter the reverse case.
6336 The root of our derivation will be the @cite{Animal} class, with a
6337 single private attribute (the @cite{Age} of the animal), a constructor,
6338 and two public primitives to set and get the value of this attribute.
6343 virtual void Set_Age (int New_Age);
6345 Animal() @{Age_Count = 0;@};
6351 Abstract interface types are defined in C++ by means of classes with pure
6352 virtual functions and no data members. In our example we will use two
6353 interfaces that provide support for the common management of @cite{Carnivore}
6354 and @cite{Domestic} animals:
6359 virtual int Number_Of_Teeth () = 0;
6364 virtual void Set_Owner (char* Name) = 0;
6368 Using these declarations, we can now say that a @cite{Dog} is an animal that is
6369 both Carnivore and Domestic, that is:
6372 class Dog : Animal, Carnivore, Domestic @{
6374 virtual int Number_Of_Teeth ();
6375 virtual void Set_Owner (char* Name);
6377 Dog(); // Constructor
6384 In the following examples we will assume that the previous declarations are
6385 located in a file named @cite{animals.h}. The following package demonstrates
6386 how to import these C++ declarations from the Ada side:
6389 with Interfaces.C.Strings; use Interfaces.C.Strings;
6391 type Carnivore is limited interface;
6392 pragma Convention (C_Plus_Plus, Carnivore);
6393 function Number_Of_Teeth (X : Carnivore)
6394 return Natural is abstract;
6396 type Domestic is limited interface;
6397 pragma Convention (C_Plus_Plus, Domestic);
6399 (X : in out Domestic;
6400 Name : Chars_Ptr) is abstract;
6402 type Animal is tagged limited record
6405 pragma Import (C_Plus_Plus, Animal);
6407 procedure Set_Age (X : in out Animal; Age : Integer);
6408 pragma Import (C_Plus_Plus, Set_Age);
6410 function Age (X : Animal) return Integer;
6411 pragma Import (C_Plus_Plus, Age);
6413 function New_Animal return Animal;
6414 pragma CPP_Constructor (New_Animal);
6415 pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6417 type Dog is new Animal and Carnivore and Domestic with record
6418 Tooth_Count : Natural;
6419 Owner : String (1 .. 30);
6421 pragma Import (C_Plus_Plus, Dog);
6423 function Number_Of_Teeth (A : Dog) return Natural;
6424 pragma Import (C_Plus_Plus, Number_Of_Teeth);
6426 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6427 pragma Import (C_Plus_Plus, Set_Owner);
6429 function New_Dog return Dog;
6430 pragma CPP_Constructor (New_Dog);
6431 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6435 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6436 interfacing with these C++ classes is easy. The only requirement is that all
6437 the primitives and components must be declared exactly in the same order in
6440 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6441 means of a @cite{pragma Convention (C_Plus_Plus)}, the convention used to pass
6442 the arguments to the called primitives will be the same as for C++. For the
6443 imported classes we use @cite{pragma Import} with convention @cite{C_Plus_Plus}
6444 to indicate that they have been defined on the C++ side; this is required
6445 because the dispatch table associated with these tagged types will be built
6446 in the C++ side and therefore will not contain the predefined Ada primitives
6447 which Ada would otherwise expect.
6449 As the reader can see there is no need to indicate the C++ mangled names
6450 associated with each subprogram because it is assumed that all the calls to
6451 these primitives will be dispatching calls. The only exception is the
6452 constructor, which must be registered with the compiler by means of
6453 @cite{pragma CPP_Constructor} and needs to provide its associated C++
6454 mangled name because the Ada compiler generates direct calls to it.
6456 With the above packages we can now declare objects of type Dog on the Ada side
6457 and dispatch calls to the corresponding subprograms on the C++ side. We can
6458 also extend the tagged type Dog with further fields and primitives, and
6459 override some of its C++ primitives on the Ada side. For example, here we have
6460 a type derivation defined on the Ada side that inherits all the dispatching
6461 primitives of the ancestor from the C++ side.
6464 with Animals; use Animals;
6465 package Vaccinated_Animals is
6466 type Vaccinated_Dog is new Dog with null record;
6467 function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6468 end Vaccinated_Animals;
6471 It is important to note that, because of the ABI compatibility, the programmer
6472 does not need to add any further information to indicate either the object
6473 layout or the dispatch table entry associated with each dispatching operation.
6475 Now let us define all the types and constructors on the Ada side and export
6476 them to C++, using the same hierarchy of our previous example:
6479 with Interfaces.C.Strings;
6480 use Interfaces.C.Strings;
6482 type Carnivore is limited interface;
6483 pragma Convention (C_Plus_Plus, Carnivore);
6484 function Number_Of_Teeth (X : Carnivore)
6485 return Natural is abstract;
6487 type Domestic is limited interface;
6488 pragma Convention (C_Plus_Plus, Domestic);
6490 (X : in out Domestic;
6491 Name : Chars_Ptr) is abstract;
6493 type Animal is tagged record
6496 pragma Convention (C_Plus_Plus, Animal);
6498 procedure Set_Age (X : in out Animal; Age : Integer);
6499 pragma Export (C_Plus_Plus, Set_Age);
6501 function Age (X : Animal) return Integer;
6502 pragma Export (C_Plus_Plus, Age);
6504 function New_Animal return Animal'Class;
6505 pragma Export (C_Plus_Plus, New_Animal);
6507 type Dog is new Animal and Carnivore and Domestic with record
6508 Tooth_Count : Natural;
6509 Owner : String (1 .. 30);
6511 pragma Convention (C_Plus_Plus, Dog);
6513 function Number_Of_Teeth (A : Dog) return Natural;
6514 pragma Export (C_Plus_Plus, Number_Of_Teeth);
6516 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6517 pragma Export (C_Plus_Plus, Set_Owner);
6519 function New_Dog return Dog'Class;
6520 pragma Export (C_Plus_Plus, New_Dog);
6524 Compared with our previous example the only differences are the use of
6525 @cite{pragma Convention} (instead of @cite{pragma Import}), and the use of
6526 @cite{pragma Export} to indicate to the GNAT compiler that the primitives will
6527 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6528 nothing else to be done; as explained above, the only requirement is that all
6529 the primitives and components are declared in exactly the same order.
6531 For completeness, let us see a brief C++ main program that uses the
6532 declarations available in @cite{animals.h} (presented in our first example) to
6533 import and use the declarations from the Ada side, properly initializing and
6534 finalizing the Ada run-time system along the way:
6537 #include "animals.h"
6539 using namespace std;
6541 void Check_Carnivore (Carnivore *obj) @{...@}
6542 void Check_Domestic (Domestic *obj) @{...@}
6543 void Check_Animal (Animal *obj) @{...@}
6544 void Check_Dog (Dog *obj) @{...@}
6547 void adainit (void);
6548 void adafinal (void);
6554 Dog *obj = new_dog(); // Ada constructor
6555 Check_Carnivore (obj); // Check secondary DT
6556 Check_Domestic (obj); // Check secondary DT
6557 Check_Animal (obj); // Check primary DT
6558 Check_Dog (obj); // Check primary DT
6563 adainit (); test(); adafinal ();
6568 @node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Building Mixed Ada and C++ Programs,Mixed Language Programming
6569 @anchor{gnat_ugn/the_gnat_compilation_model id70}@anchor{c9}@anchor{gnat_ugn/the_gnat_compilation_model generating-ada-bindings-for-c-and-c-headers}@anchor{1b}
6570 @subsection Generating Ada Bindings for C and C++ headers
6573 @geindex Binding generation (for C and C++ headers)
6575 @geindex C headers (binding generation)
6577 @geindex C++ headers (binding generation)
6579 GNAT includes a binding generator for C and C++ headers which is
6580 intended to do 95% of the tedious work of generating Ada specs from C
6581 or C++ header files.
6583 Note that this capability is not intended to generate 100% correct Ada specs,
6584 and will is some cases require manual adjustments, although it can often
6585 be used out of the box in practice.
6587 Some of the known limitations include:
6593 only very simple character constant macros are translated into Ada
6594 constants. Function macros (macros with arguments) are partially translated
6595 as comments, to be completed manually if needed.
6598 some extensions (e.g. vector types) are not supported
6601 pointers to pointers or complex structures are mapped to System.Address
6604 identifiers with identical name (except casing) will generate compilation
6605 errors (e.g. @cite{shm_get} vs @cite{SHM_GET}).
6608 The code generated is using the Ada 2005 syntax, which makes it
6609 easier to interface with other languages than previous versions of Ada.
6612 * Running the Binding Generator::
6613 * Generating Bindings for C++ Headers::
6618 @node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6619 @anchor{gnat_ugn/the_gnat_compilation_model id71}@anchor{ca}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{cb}
6620 @subsubsection Running the Binding Generator
6623 The binding generator is part of the @emph{gcc} compiler and can be
6624 invoked via the @emph{-fdump-ada-spec} switch, which will generate Ada
6625 spec files for the header files specified on the command line, and all
6626 header files needed by these files transitively. For example:
6629 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
6630 $ gcc -c -gnat05 *.ads
6633 will generate, under GNU/Linux, the following files: @code{time_h.ads},
6634 @code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6635 correspond to the files @code{/usr/include/time.h},
6636 @code{/usr/include/bits/time.h}, etc..., and will then compile in Ada 2005
6637 mode these Ada specs.
6639 The @cite{-C} switch tells @emph{gcc} to extract comments from headers,
6640 and will attempt to generate corresponding Ada comments.
6642 If you want to generate a single Ada file and not the transitive closure, you
6643 can use instead the @emph{-fdump-ada-spec-slim} switch.
6645 You can optionally specify a parent unit, of which all generated units will
6646 be children, using @cite{-fada-spec-parent=<unit>}.
6648 Note that we recommend when possible to use the @emph{g++} driver to
6649 generate bindings, even for most C headers, since this will in general
6650 generate better Ada specs. For generating bindings for C++ headers, it is
6651 mandatory to use the @emph{g++} command, or @emph{gcc -x c++} which
6652 is equivalent in this case. If @emph{g++} cannot work on your C headers
6653 because of incompatibilities between C and C++, then you can fallback to
6656 For an example of better bindings generated from the C++ front-end,
6657 the name of the parameters (when available) are actually ignored by the C
6658 front-end. Consider the following C header:
6661 extern void foo (int variable);
6664 with the C front-end, @cite{variable} is ignored, and the above is handled as:
6667 extern void foo (int);
6670 generating a generic:
6673 procedure foo (param1 : int);
6676 with the C++ front-end, the name is available, and we generate:
6679 procedure foo (variable : int);
6682 In some cases, the generated bindings will be more complete or more meaningful
6683 when defining some macros, which you can do via the @emph{-D} switch. This
6684 is for example the case with @code{Xlib.h} under GNU/Linux:
6687 $ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6690 The above will generate more complete bindings than a straight call without
6691 the @emph{-DXLIB_ILLEGAL_ACCESS} switch.
6693 In other cases, it is not possible to parse a header file in a stand-alone
6694 manner, because other include files need to be included first. In this
6695 case, the solution is to create a small header file including the needed
6696 @cite{#include} and possible @cite{#define} directives. For example, to
6697 generate Ada bindings for @code{readline/readline.h}, you need to first
6698 include @code{stdio.h}, so you can create a file with the following two
6699 lines in e.g. @code{readline1.h}:
6703 #include <readline/readline.h>
6706 and then generate Ada bindings from this file:
6709 $ g++ -c -fdump-ada-spec readline1.h
6712 @node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6713 @anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{cc}@anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{cd}
6714 @subsubsection Generating Bindings for C++ Headers
6717 Generating bindings for C++ headers is done using the same options, always
6718 with the @emph{g++} compiler. Note that generating Ada spec from C++ headers is a
6719 much more complex job and support for C++ headers is much more limited that
6720 support for C headers. As a result, you will need to modify the resulting
6721 bindings by hand more extensively when using C++ headers.
6723 In this mode, C++ classes will be mapped to Ada tagged types, constructors
6724 will be mapped using the @cite{CPP_Constructor} pragma, and when possible,
6725 multiple inheritance of abstract classes will be mapped to Ada interfaces
6726 (see the @emph{Interfacing to C++} section in the @cite{GNAT Reference Manual}
6727 for additional information on interfacing to C++).
6729 For example, given the following C++ header file:
6734 virtual int Number_Of_Teeth () = 0;
6739 virtual void Set_Owner (char* Name) = 0;
6745 virtual void Set_Age (int New_Age);
6748 class Dog : Animal, Carnivore, Domestic @{
6753 virtual int Number_Of_Teeth ();
6754 virtual void Set_Owner (char* Name);
6760 The corresponding Ada code is generated:
6763 package Class_Carnivore is
6764 type Carnivore is limited interface;
6765 pragma Import (CPP, Carnivore);
6767 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6769 use Class_Carnivore;
6771 package Class_Domestic is
6772 type Domestic is limited interface;
6773 pragma Import (CPP, Domestic);
6776 (this : access Domestic;
6777 Name : Interfaces.C.Strings.chars_ptr) is abstract;
6781 package Class_Animal is
6782 type Animal is tagged limited record
6783 Age_Count : aliased int;
6785 pragma Import (CPP, Animal);
6787 procedure Set_Age (this : access Animal; New_Age : int);
6788 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6792 package Class_Dog is
6793 type Dog is new Animal and Carnivore and Domestic with record
6794 Tooth_Count : aliased int;
6795 Owner : Interfaces.C.Strings.chars_ptr;
6797 pragma Import (CPP, Dog);
6799 function Number_Of_Teeth (this : access Dog) return int;
6800 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6803 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6804 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6806 function New_Dog return Dog;
6807 pragma CPP_Constructor (New_Dog);
6808 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6813 @node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6814 @anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{ce}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{cf}
6815 @subsubsection Switches
6818 @geindex -fdump-ada-spec (gcc)
6823 @item @code{-fdump-ada-spec}
6825 Generate Ada spec files for the given header files transitively (including
6826 all header files that these headers depend upon).
6829 @geindex -fdump-ada-spec-slim (gcc)
6834 @item @code{-fdump-ada-spec-slim}
6836 Generate Ada spec files for the header files specified on the command line
6840 @geindex -fada-spec-parent (gcc)
6845 @item @code{-fada-spec-parent=@emph{unit}}
6847 Specifies that all files generated by @emph{-fdump-ada-spec*} are
6848 to be child units of the specified parent unit.
6858 Extract comments from headers and generate Ada comments in the Ada spec files.
6861 @node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6862 @anchor{gnat_ugn/the_gnat_compilation_model generating-c-headers-for-ada-specifications}@anchor{d0}@anchor{gnat_ugn/the_gnat_compilation_model id73}@anchor{d1}
6863 @subsection Generating C Headers for Ada Specifications
6866 @geindex Binding generation (for Ada specs)
6868 @geindex C headers (binding generation)
6870 GNAT includes a C header generator for Ada specifications which supports
6871 Ada types that have a direct mapping to C types. This includes in particular
6887 Composition of the above types
6890 Constant declarations
6896 Subprogram declarations
6900 * Running the C Header Generator::
6904 @node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6905 @anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{d2}
6906 @subsubsection Running the C Header Generator
6909 The C header generator is part of the GNAT compiler and can be invoked via
6910 the @emph{-gnatceg} combination of switches, which will generate a @code{.h}
6911 file corresponding to the given input file (Ada spec or body). Note that
6912 only spec files are processed in any case, so giving a spec or a body file
6913 as input is equivalent. For example:
6916 $ gcc -c -gnatceg pack1.ads
6919 will generate a self-contained file called @code{pack1.h} including
6920 common definitions from the Ada Standard package, followed by the
6921 definitions included in @code{pack1.ads}, as well as all the other units
6922 withed by this file.
6924 For instance, given the following Ada files:
6928 type Int is range 1 .. 10;
6937 Field1, Field2 : Pack2.Int;
6940 Global : Rec := (1, 2);
6942 procedure Proc1 (R : Rec);
6943 procedure Proc2 (R : in out Rec);
6947 The above @cite{gcc} command will generate the following @code{pack1.h} file:
6950 /* Standard definitions skipped */
6953 typedef short_short_integer pack2__TintB;
6954 typedef pack2__TintB pack2__int;
6955 #endif /* PACK2_ADS */
6959 typedef struct _pack1__rec @{
6963 extern pack1__rec pack1__global;
6964 extern void pack1__proc1(const pack1__rec r);
6965 extern void pack1__proc2(pack1__rec *r);
6966 #endif /* PACK1_ADS */
6969 You can then @cite{include} @code{pack1.h} from a C source file and use the types,
6970 call subprograms, reference objects, and constants.
6972 @node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
6973 @anchor{gnat_ugn/the_gnat_compilation_model id74}@anchor{d3}@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{47}
6974 @section GNAT and Other Compilation Models
6977 This section compares the GNAT model with the approaches taken in
6978 other environents, first the C/C++ model and then the mechanism that
6979 has been used in other Ada systems, in particular those traditionally
6983 * Comparison between GNAT and C/C++ Compilation Models::
6984 * Comparison between GNAT and Conventional Ada Library Models::
6988 @node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
6989 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-c-c-compilation-models}@anchor{d4}@anchor{gnat_ugn/the_gnat_compilation_model id75}@anchor{d5}
6990 @subsection Comparison between GNAT and C/C++ Compilation Models
6993 The GNAT model of compilation is close to the C and C++ models. You can
6994 think of Ada specs as corresponding to header files in C. As in C, you
6995 don't need to compile specs; they are compiled when they are used. The
6996 Ada @emph{with} is similar in effect to the @cite{#include} of a C
6999 One notable difference is that, in Ada, you may compile specs separately
7000 to check them for semantic and syntactic accuracy. This is not always
7001 possible with C headers because they are fragments of programs that have
7002 less specific syntactic or semantic rules.
7004 The other major difference is the requirement for running the binder,
7005 which performs two important functions. First, it checks for
7006 consistency. In C or C++, the only defense against assembling
7007 inconsistent programs lies outside the compiler, in a makefile, for
7008 example. The binder satisfies the Ada requirement that it be impossible
7009 to construct an inconsistent program when the compiler is used in normal
7012 @geindex Elaboration order control
7014 The other important function of the binder is to deal with elaboration
7015 issues. There are also elaboration issues in C++ that are handled
7016 automatically. This automatic handling has the advantage of being
7017 simpler to use, but the C++ programmer has no control over elaboration.
7018 Where @cite{gnatbind} might complain there was no valid order of
7019 elaboration, a C++ compiler would simply construct a program that
7020 malfunctioned at run time.
7022 @node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
7023 @anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-conventional-ada-library-models}@anchor{d6}@anchor{gnat_ugn/the_gnat_compilation_model id76}@anchor{d7}
7024 @subsection Comparison between GNAT and Conventional Ada Library Models
7027 This section is intended for Ada programmers who have
7028 used an Ada compiler implementing the traditional Ada library
7029 model, as described in the Ada Reference Manual.
7031 @geindex GNAT library
7033 In GNAT, there is no 'library' in the normal sense. Instead, the set of
7034 source files themselves acts as the library. Compiling Ada programs does
7035 not generate any centralized information, but rather an object file and
7036 a ALI file, which are of interest only to the binder and linker.
7037 In a traditional system, the compiler reads information not only from
7038 the source file being compiled, but also from the centralized library.
7039 This means that the effect of a compilation depends on what has been
7040 previously compiled. In particular:
7046 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7047 to the version of the unit most recently compiled into the library.
7050 Inlining is effective only if the necessary body has already been
7051 compiled into the library.
7054 Compiling a unit may obsolete other units in the library.
7057 In GNAT, compiling one unit never affects the compilation of any other
7058 units because the compiler reads only source files. Only changes to source
7059 files can affect the results of a compilation. In particular:
7065 When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7066 to the source version of the unit that is currently accessible to the
7072 Inlining requires the appropriate source files for the package or
7073 subprogram bodies to be available to the compiler. Inlining is always
7074 effective, independent of the order in which units are compiled.
7077 Compiling a unit never affects any other compilations. The editing of
7078 sources may cause previous compilations to be out of date if they
7079 depended on the source file being modified.
7082 The most important result of these differences is that order of compilation
7083 is never significant in GNAT. There is no situation in which one is
7084 required to do one compilation before another. What shows up as order of
7085 compilation requirements in the traditional Ada library becomes, in
7086 GNAT, simple source dependencies; in other words, there is only a set
7087 of rules saying what source files must be present when a file is
7090 @node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
7091 @anchor{gnat_ugn/the_gnat_compilation_model using-gnat-files-with-external-tools}@anchor{1c}@anchor{gnat_ugn/the_gnat_compilation_model id77}@anchor{d8}
7092 @section Using GNAT Files with External Tools
7095 This section explains how files that are produced by GNAT may be
7096 used with tools designed for other languages.
7099 * Using Other Utility Programs with GNAT::
7100 * The External Symbol Naming Scheme of GNAT::
7104 @node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
7105 @anchor{gnat_ugn/the_gnat_compilation_model using-other-utility-programs-with-gnat}@anchor{d9}@anchor{gnat_ugn/the_gnat_compilation_model id78}@anchor{da}
7106 @subsection Using Other Utility Programs with GNAT
7109 The object files generated by GNAT are in standard system format and in
7110 particular the debugging information uses this format. This means
7111 programs generated by GNAT can be used with existing utilities that
7112 depend on these formats.
7114 In general, any utility program that works with C will also often work with
7115 Ada programs generated by GNAT. This includes software utilities such as
7116 gprof (a profiling program), gdb (the FSF debugger), and utilities such
7119 @node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
7120 @anchor{gnat_ugn/the_gnat_compilation_model the-external-symbol-naming-scheme-of-gnat}@anchor{db}@anchor{gnat_ugn/the_gnat_compilation_model id79}@anchor{dc}
7121 @subsection The External Symbol Naming Scheme of GNAT
7124 In order to interpret the output from GNAT, when using tools that are
7125 originally intended for use with other languages, it is useful to
7126 understand the conventions used to generate link names from the Ada
7129 All link names are in all lowercase letters. With the exception of library
7130 procedure names, the mechanism used is simply to use the full expanded
7131 Ada name with dots replaced by double underscores. For example, suppose
7132 we have the following package spec:
7140 @geindex pragma Export
7142 The variable @cite{MN} has a full expanded Ada name of @cite{QRS.MN}, so
7143 the corresponding link name is @cite{qrs__mn}.
7144 Of course if a @cite{pragma Export} is used this may be overridden:
7149 pragma Export (Var1, C, External_Name => "var1_name");
7151 pragma Export (Var2, C, Link_Name => "var2_link_name");
7155 In this case, the link name for @cite{Var1} is whatever link name the
7156 C compiler would assign for the C function @cite{var1_name}. This typically
7157 would be either @cite{var1_name} or @cite{_var1_name}, depending on operating
7158 system conventions, but other possibilities exist. The link name for
7159 @cite{Var2} is @cite{var2_link_name}, and this is not operating system
7162 One exception occurs for library level procedures. A potential ambiguity
7163 arises between the required name @cite{_main} for the C main program,
7164 and the name we would otherwise assign to an Ada library level procedure
7165 called @cite{Main} (which might well not be the main program).
7167 To avoid this ambiguity, we attach the prefix @cite{_ada_} to such
7168 names. So if we have a library level procedure such as:
7171 procedure Hello (S : String);
7174 the external name of this procedure will be @cite{_ada_hello}.
7176 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7178 @node Building Executable Programs with GNAT,GNAT Project Manager,The GNAT Compilation Model,Top
7179 @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{dd}@anchor{gnat_ugn/building_executable_programs_with_gnat id1}@anchor{de}
7180 @chapter Building Executable Programs with GNAT
7183 This chapter describes first the gnatmake tool
7184 (@ref{1d,,Building with gnatmake}),
7185 which automatically determines the set of sources
7186 needed by an Ada compilation unit and executes the necessary
7187 (re)compilations, binding and linking.
7188 It also explains how to use each tool individually: the
7189 compiler (gcc, see @ref{1e,,Compiling with gcc}),
7190 binder (gnatbind, see @ref{1f,,Binding with gnatbind}),
7191 and linker (gnatlink, see @ref{20,,Linking with gnatlink})
7192 to build executable programs.
7193 Finally, this chapter provides examples of
7194 how to make use of the general GNU make mechanism
7195 in a GNAT context (see @ref{21,,Using the GNU make Utility}).
7198 * Building with gnatmake::
7199 * Compiling with gcc::
7200 * Compiler Switches::
7201 * Binding with gnatbind::
7202 * Linking with gnatlink::
7203 * Using the GNU make Utility::
7207 @node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7208 @anchor{gnat_ugn/building_executable_programs_with_gnat the-gnat-make-program-gnatmake}@anchor{1d}@anchor{gnat_ugn/building_executable_programs_with_gnat building-with-gnatmake}@anchor{df}
7209 @section Building with @emph{gnatmake}
7214 A typical development cycle when working on an Ada program consists of
7215 the following steps:
7221 Edit some sources to fix bugs;
7227 Compile all sources affected;
7230 Rebind and relink; and
7236 @geindex Dependency rules (compilation)
7238 The third step in particular can be tricky, because not only do the modified
7239 files have to be compiled, but any files depending on these files must also be
7240 recompiled. The dependency rules in Ada can be quite complex, especially
7241 in the presence of overloading, @cite{use} clauses, generics and inlined
7244 @emph{gnatmake} automatically takes care of the third and fourth steps
7245 of this process. It determines which sources need to be compiled,
7246 compiles them, and binds and links the resulting object files.
7248 Unlike some other Ada make programs, the dependencies are always
7249 accurately recomputed from the new sources. The source based approach of
7250 the GNAT compilation model makes this possible. This means that if
7251 changes to the source program cause corresponding changes in
7252 dependencies, they will always be tracked exactly correctly by
7255 Note that for advanced description of project structure, we recommend creating
7256 a project file as explained in @ref{b,,GNAT Project Manager} and use the
7257 @emph{gprbuild} tool which supports building with project files and works similarly
7261 * Running gnatmake::
7262 * Switches for gnatmake::
7263 * Mode Switches for gnatmake::
7264 * Notes on the Command Line::
7265 * How gnatmake Works::
7266 * Examples of gnatmake Usage::
7270 @node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7271 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{e0}@anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{e1}
7272 @subsection Running @emph{gnatmake}
7275 The usual form of the @emph{gnatmake} command is
7278 $ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7281 The only required argument is one @cite{file_name}, which specifies
7282 a compilation unit that is a main program. Several @cite{file_names} can be
7283 specified: this will result in several executables being built.
7284 If @cite{switches} are present, they can be placed before the first
7285 @cite{file_name}, between @cite{file_names} or after the last @cite{file_name}.
7286 If @cite{mode_switches} are present, they must always be placed after
7287 the last @cite{file_name} and all @cite{switches}.
7289 If you are using standard file extensions (@code{.adb} and
7290 @code{.ads}), then the
7291 extension may be omitted from the @cite{file_name} arguments. However, if
7292 you are using non-standard extensions, then it is required that the
7293 extension be given. A relative or absolute directory path can be
7294 specified in a @cite{file_name}, in which case, the input source file will
7295 be searched for in the specified directory only. Otherwise, the input
7296 source file will first be searched in the directory where
7297 @emph{gnatmake} was invoked and if it is not found, it will be search on
7298 the source path of the compiler as described in
7299 @ref{8e,,Search Paths and the Run-Time Library (RTL)}.
7301 All @emph{gnatmake} output (except when you specify @emph{-M}) is sent to
7302 @code{stderr}. The output produced by the
7303 @emph{-M} switch is sent to @code{stdout}.
7305 @node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7306 @anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{e2}@anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{e3}
7307 @subsection Switches for @emph{gnatmake}
7310 You may specify any of the following switches to @emph{gnatmake}:
7312 @geindex --version (gnatmake)
7317 @item @code{--version}
7319 Display Copyright and version, then exit disregarding all other options.
7322 @geindex --help (gnatmake)
7329 If @code{--version} was not used, display usage, then exit disregarding
7333 @geindex --GCC=compiler_name (gnatmake)
7338 @item @code{--GCC=@emph{compiler_name}}
7340 Program used for compiling. The default is @code{gcc}. You need to use
7341 quotes around @cite{compiler_name} if @cite{compiler_name} contains
7342 spaces or other separator characters.
7343 As an example @code{--GCC="foo -x -y"}
7344 will instruct @emph{gnatmake} to use @code{foo -x -y} as your
7345 compiler. A limitation of this syntax is that the name and path name of
7346 the executable itself must not include any embedded spaces. Note that
7347 switch @code{-c} is always inserted after your command name. Thus in the
7348 above example the compiler command that will be used by @emph{gnatmake}
7349 will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7350 used, only the last @cite{compiler_name} is taken into account. However,
7351 all the additional switches are also taken into account. Thus,
7352 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7353 @code{--GCC="bar -x -y -z -t"}.
7356 @geindex --GNATBIND=binder_name (gnatmake)
7361 @item @code{--GNATBIND=@emph{binder_name}}
7363 Program used for binding. The default is @code{gnatbind}. You need to
7364 use quotes around @cite{binder_name} if @cite{binder_name} contains spaces
7365 or other separator characters.
7366 As an example @code{--GNATBIND="bar -x -y"}
7367 will instruct @emph{gnatmake} to use @cite{bar -x -y} as your
7368 binder. Binder switches that are normally appended by @emph{gnatmake}
7369 to @code{gnatbind} are now appended to the end of @cite{bar -x -y}.
7370 A limitation of this syntax is that the name and path name of the executable
7371 itself must not include any embedded spaces.
7374 @geindex --GNATLINK=linker_name (gnatmake)
7379 @item @code{--GNATLINK=@emph{linker_name}}
7381 Program used for linking. The default is @code{gnatlink}. You need to
7382 use quotes around @cite{linker_name} if @cite{linker_name} contains spaces
7383 or other separator characters.
7384 As an example @code{--GNATLINK="lan -x -y"}
7385 will instruct @emph{gnatmake} to use @code{lan -x -y} as your
7386 linker. Linker switches that are normally appended by @code{gnatmake} to
7387 @code{gnatlink} are now appended to the end of @code{lan -x -y}.
7388 A limitation of this syntax is that the name and path name of the executable
7389 itself must not include any embedded spaces.
7391 @item @code{--create-map-file}
7393 When linking an executable, create a map file. The name of the map file
7394 has the same name as the executable with extension ".map".
7396 @item @code{--create-map-file=@emph{mapfile}}
7398 When linking an executable, create a map file with the specified name.
7401 @geindex --create-missing-dirs (gnatmake)
7406 @item @code{--create-missing-dirs}
7408 When using project files (@code{-P@emph{project}}), automatically create
7409 missing object directories, library directories and exec
7412 @item @code{--single-compile-per-obj-dir}
7414 Disallow simultaneous compilations in the same object directory when
7415 project files are used.
7417 @item @code{--subdirs=@emph{subdir}}
7419 Actual object directory of each project file is the subdirectory subdir of the
7420 object directory specified or defaulted in the project file.
7422 @item @code{--unchecked-shared-lib-imports}
7424 By default, shared library projects are not allowed to import static library
7425 projects. When this switch is used on the command line, this restriction is
7428 @item @code{--source-info=@emph{source info file}}
7430 Specify a source info file. This switch is active only when project files
7431 are used. If the source info file is specified as a relative path, then it is
7432 relative to the object directory of the main project. If the source info file
7433 does not exist, then after the Project Manager has successfully parsed and
7434 processed the project files and found the sources, it creates the source info
7435 file. If the source info file already exists and can be read successfully,
7436 then the Project Manager will get all the needed information about the sources
7437 from the source info file and will not look for them. This reduces the time
7438 to process the project files, especially when looking for sources that take a
7439 long time. If the source info file exists but cannot be parsed successfully,
7440 the Project Manager will attempt to recreate it. If the Project Manager fails
7441 to create the source info file, a message is issued, but gnatmake does not
7442 fail. @emph{gnatmake} "trusts" the source info file. This means that
7443 if the source files have changed (addition, deletion, moving to a different
7444 source directory), then the source info file need to be deleted and recreated.
7447 @geindex -a (gnatmake)
7454 Consider all files in the make process, even the GNAT internal system
7455 files (for example, the predefined Ada library files), as well as any
7456 locked files. Locked files are files whose ALI file is write-protected.
7458 @emph{gnatmake} does not check these files,
7459 because the assumption is that the GNAT internal files are properly up
7460 to date, and also that any write protected ALI files have been properly
7461 installed. Note that if there is an installation problem, such that one
7462 of these files is not up to date, it will be properly caught by the
7464 You may have to specify this switch if you are working on GNAT
7465 itself. The switch @code{-a} is also useful
7466 in conjunction with @code{-f}
7467 if you need to recompile an entire application,
7468 including run-time files, using special configuration pragmas,
7469 such as a @cite{Normalize_Scalars} pragma.
7472 @code{gnatmake -a} compiles all GNAT
7474 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
7477 @geindex -b (gnatmake)
7484 Bind only. Can be combined with @emph{-c} to do
7485 compilation and binding, but no link.
7486 Can be combined with @emph{-l}
7487 to do binding and linking. When not combined with
7489 all the units in the closure of the main program must have been previously
7490 compiled and must be up to date. The root unit specified by @cite{file_name}
7491 may be given without extension, with the source extension or, if no GNAT
7492 Project File is specified, with the ALI file extension.
7495 @geindex -c (gnatmake)
7502 Compile only. Do not perform binding, except when @emph{-b}
7503 is also specified. Do not perform linking, except if both
7505 @emph{-l} are also specified.
7506 If the root unit specified by @cite{file_name} is not a main unit, this is the
7507 default. Otherwise @emph{gnatmake} will attempt binding and linking
7508 unless all objects are up to date and the executable is more recent than
7512 @geindex -C (gnatmake)
7519 Use a temporary mapping file. A mapping file is a way to communicate
7520 to the compiler two mappings: from unit names to file names (without
7521 any directory information) and from file names to path names (with
7522 full directory information). A mapping file can make the compiler's
7523 file searches faster, especially if there are many source directories,
7524 or the sources are read over a slow network connection. If
7525 @emph{-P} is used, a mapping file is always used, so
7526 @emph{-C} is unnecessary; in this case the mapping file
7527 is initially populated based on the project file. If
7528 @emph{-C} is used without
7530 the mapping file is initially empty. Each invocation of the compiler
7531 will add any newly accessed sources to the mapping file.
7534 @geindex -C= (gnatmake)
7539 @item @code{-C=@emph{file}}
7541 Use a specific mapping file. The file, specified as a path name (absolute or
7542 relative) by this switch, should already exist, otherwise the switch is
7543 ineffective. The specified mapping file will be communicated to the compiler.
7544 This switch is not compatible with a project file
7545 (-P`file`) or with multiple compiling processes
7546 (-jnnn, when nnn is greater than 1).
7549 @geindex -d (gnatmake)
7556 Display progress for each source, up to date or not, as a single line:
7559 completed x out of y (zz%)
7562 If the file needs to be compiled this is displayed after the invocation of
7563 the compiler. These lines are displayed even in quiet output mode.
7566 @geindex -D (gnatmake)
7571 @item @code{-D @emph{dir}}
7573 Put all object files and ALI file in directory @cite{dir}.
7574 If the @emph{-D} switch is not used, all object files
7575 and ALI files go in the current working directory.
7577 This switch cannot be used when using a project file.
7580 @geindex -eI (gnatmake)
7585 @item @code{-eI@emph{nnn}}
7587 Indicates that the main source is a multi-unit source and the rank of the unit
7588 in the source file is nnn. nnn needs to be a positive number and a valid
7589 index in the source. This switch cannot be used when @emph{gnatmake} is
7590 invoked for several mains.
7593 @geindex -eL (gnatmake)
7595 @geindex symbolic links
7602 Follow all symbolic links when processing project files.
7603 This should be used if your project uses symbolic links for files or
7604 directories, but is not needed in other cases.
7606 @geindex naming scheme
7608 This also assumes that no directory matches the naming scheme for files (for
7609 instance that you do not have a directory called "sources.ads" when using the
7610 default GNAT naming scheme).
7612 When you do not have to use this switch (i.e., by default), gnatmake is able to
7613 save a lot of system calls (several per source file and object file), which
7614 can result in a significant speed up to load and manipulate a project file,
7615 especially when using source files from a remote system.
7618 @geindex -eS (gnatmake)
7625 Output the commands for the compiler, the binder and the linker
7627 instead of standard error.
7630 @geindex -f (gnatmake)
7637 Force recompilations. Recompile all sources, even though some object
7638 files may be up to date, but don't recompile predefined or GNAT internal
7639 files or locked files (files with a write-protected ALI file),
7640 unless the @emph{-a} switch is also specified.
7643 @geindex -F (gnatmake)
7650 When using project files, if some errors or warnings are detected during
7651 parsing and verbose mode is not in effect (no use of switch
7652 -v), then error lines start with the full path name of the project
7653 file, rather than its simple file name.
7656 @geindex -g (gnatmake)
7663 Enable debugging. This switch is simply passed to the compiler and to the
7667 @geindex -i (gnatmake)
7674 In normal mode, @emph{gnatmake} compiles all object files and ALI files
7675 into the current directory. If the @emph{-i} switch is used,
7676 then instead object files and ALI files that already exist are overwritten
7677 in place. This means that once a large project is organized into separate
7678 directories in the desired manner, then @emph{gnatmake} will automatically
7679 maintain and update this organization. If no ALI files are found on the
7680 Ada object path (see @ref{8e,,Search Paths and the Run-Time Library (RTL)}),
7681 the new object and ALI files are created in the
7682 directory containing the source being compiled. If another organization
7683 is desired, where objects and sources are kept in different directories,
7684 a useful technique is to create dummy ALI files in the desired directories.
7685 When detecting such a dummy file, @emph{gnatmake} will be forced to
7686 recompile the corresponding source file, and it will be put the resulting
7687 object and ALI files in the directory where it found the dummy file.
7690 @geindex -j (gnatmake)
7692 @geindex Parallel make
7697 @item @code{-j@emph{n}}
7699 Use @cite{n} processes to carry out the (re)compilations. On a multiprocessor
7700 machine compilations will occur in parallel. If @cite{n} is 0, then the
7701 maximum number of parallel compilations is the number of core processors
7702 on the platform. In the event of compilation errors, messages from various
7703 compilations might get interspersed (but @emph{gnatmake} will give you the
7704 full ordered list of failing compiles at the end). If this is problematic,
7705 rerun the make process with n set to 1 to get a clean list of messages.
7708 @geindex -k (gnatmake)
7715 Keep going. Continue as much as possible after a compilation error. To
7716 ease the programmer's task in case of compilation errors, the list of
7717 sources for which the compile fails is given when @emph{gnatmake}
7720 If @emph{gnatmake} is invoked with several @code{file_names} and with this
7721 switch, if there are compilation errors when building an executable,
7722 @emph{gnatmake} will not attempt to build the following executables.
7725 @geindex -l (gnatmake)
7732 Link only. Can be combined with @emph{-b} to binding
7733 and linking. Linking will not be performed if combined with
7735 but not with @emph{-b}.
7736 When not combined with @emph{-b}
7737 all the units in the closure of the main program must have been previously
7738 compiled and must be up to date, and the main program needs to have been bound.
7739 The root unit specified by @cite{file_name}
7740 may be given without extension, with the source extension or, if no GNAT
7741 Project File is specified, with the ALI file extension.
7744 @geindex -m (gnatmake)
7751 Specify that the minimum necessary amount of recompilations
7752 be performed. In this mode @emph{gnatmake} ignores time
7753 stamp differences when the only
7754 modifications to a source file consist in adding/removing comments,
7755 empty lines, spaces or tabs. This means that if you have changed the
7756 comments in a source file or have simply reformatted it, using this
7757 switch will tell @emph{gnatmake} not to recompile files that depend on it
7758 (provided other sources on which these files depend have undergone no
7759 semantic modifications). Note that the debugging information may be
7760 out of date with respect to the sources if the @emph{-m} switch causes
7761 a compilation to be switched, so the use of this switch represents a
7762 trade-off between compilation time and accurate debugging information.
7765 @geindex Dependencies
7766 @geindex producing list
7768 @geindex -M (gnatmake)
7775 Check if all objects are up to date. If they are, output the object
7776 dependences to @code{stdout} in a form that can be directly exploited in
7777 a @code{Makefile}. By default, each source file is prefixed with its
7778 (relative or absolute) directory name. This name is whatever you
7779 specified in the various @emph{-aI}
7780 and @emph{-I} switches. If you use
7781 @cite{gnatmake -M} @emph{-q}
7782 (see below), only the source file names,
7783 without relative paths, are output. If you just specify the @emph{-M}
7784 switch, dependencies of the GNAT internal system files are omitted. This
7785 is typically what you want. If you also specify
7786 the @emph{-a} switch,
7787 dependencies of the GNAT internal files are also listed. Note that
7788 dependencies of the objects in external Ada libraries (see
7789 switch @code{-aL@emph{dir}} in the following list)
7793 @geindex -n (gnatmake)
7800 Don't compile, bind, or link. Checks if all objects are up to date.
7801 If they are not, the full name of the first file that needs to be
7802 recompiled is printed.
7803 Repeated use of this option, followed by compiling the indicated source
7804 file, will eventually result in recompiling all required units.
7807 @geindex -o (gnatmake)
7812 @item @code{-o @emph{exec_name}}
7814 Output executable name. The name of the final executable program will be
7815 @cite{exec_name}. If the @emph{-o} switch is omitted the default
7816 name for the executable will be the name of the input file in appropriate form
7817 for an executable file on the host system.
7819 This switch cannot be used when invoking @emph{gnatmake} with several
7823 @geindex -p (gnatmake)
7830 Same as @code{--create-missing-dirs}
7833 @geindex -P (gnatmake)
7838 @item @code{-P@emph{project}}
7840 Use project file @cite{project}. Only one such switch can be used.
7841 @ref{e4,,gnatmake and Project Files}.
7844 @geindex -q (gnatmake)
7851 Quiet. When this flag is not set, the commands carried out by
7852 @emph{gnatmake} are displayed.
7855 @geindex -s (gnatmake)
7862 Recompile if compiler switches have changed since last compilation.
7863 All compiler switches but -I and -o are taken into account in the
7865 orders between different 'first letter' switches are ignored, but
7866 orders between same switches are taken into account. For example,
7867 @emph{-O -O2} is different than @emph{-O2 -O}, but @emph{-g -O}
7868 is equivalent to @emph{-O -g}.
7870 This switch is recommended when Integrated Preprocessing is used.
7873 @geindex -u (gnatmake)
7880 Unique. Recompile at most the main files. It implies -c. Combined with
7881 -f, it is equivalent to calling the compiler directly. Note that using
7882 -u with a project file and no main has a special meaning
7883 (@ref{e5,,Project Files and Main Subprograms}).
7886 @geindex -U (gnatmake)
7893 When used without a project file or with one or several mains on the command
7894 line, is equivalent to -u. When used with a project file and no main
7895 on the command line, all sources of all project files are checked and compiled
7896 if not up to date, and libraries are rebuilt, if necessary.
7899 @geindex -v (gnatmake)
7906 Verbose. Display the reason for all recompilations @emph{gnatmake}
7907 decides are necessary, with the highest verbosity level.
7910 @geindex -vl (gnatmake)
7917 Verbosity level Low. Display fewer lines than in verbosity Medium.
7920 @geindex -vm (gnatmake)
7927 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7930 @geindex -vm (gnatmake)
7937 Verbosity level High. Equivalent to -v.
7939 @item @code{-vP@emph{x}}
7941 Indicate the verbosity of the parsing of GNAT project files.
7942 See @ref{e6,,Switches Related to Project Files}.
7945 @geindex -x (gnatmake)
7952 Indicate that sources that are not part of any Project File may be compiled.
7953 Normally, when using Project Files, only sources that are part of a Project
7954 File may be compile. When this switch is used, a source outside of all Project
7955 Files may be compiled. The ALI file and the object file will be put in the
7956 object directory of the main Project. The compilation switches used will only
7957 be those specified on the command line. Even when
7958 @emph{-x} is used, mains specified on the
7959 command line need to be sources of a project file.
7961 @item @code{-X@emph{name}=@emph{value}}
7963 Indicate that external variable @cite{name} has the value @cite{value}.
7964 The Project Manager will use this value for occurrences of
7965 @cite{external(name)} when parsing the project file.
7966 @ref{e6,,Switches Related to Project Files}.
7969 @geindex -z (gnatmake)
7976 No main subprogram. Bind and link the program even if the unit name
7977 given on the command line is a package name. The resulting executable
7978 will execute the elaboration routines of the package and its closure,
7979 then the finalization routines.
7982 @subsubheading GCC switches
7985 Any uppercase or multi-character switch that is not a @emph{gnatmake} switch
7986 is passed to @emph{gcc} (e.g., @emph{-O}, @emph{-gnato,} etc.)
7988 @subsubheading Source and library search path switches
7991 @geindex -aI (gnatmake)
7996 @item @code{-aI@emph{dir}}
7998 When looking for source files also look in directory @cite{dir}.
7999 The order in which source files search is undertaken is
8000 described in @ref{8e,,Search Paths and the Run-Time Library (RTL)}.
8003 @geindex -aL (gnatmake)
8008 @item @code{-aL@emph{dir}}
8010 Consider @cite{dir} as being an externally provided Ada library.
8011 Instructs @emph{gnatmake} to skip compilation units whose @code{.ALI}
8012 files have been located in directory @cite{dir}. This allows you to have
8013 missing bodies for the units in @cite{dir} and to ignore out of date bodies
8014 for the same units. You still need to specify
8015 the location of the specs for these units by using the switches
8016 @code{-aI@emph{dir}} or @code{-I@emph{dir}}.
8017 Note: this switch is provided for compatibility with previous versions
8018 of @emph{gnatmake}. The easier method of causing standard libraries
8019 to be excluded from consideration is to write-protect the corresponding
8023 @geindex -aO (gnatmake)
8028 @item @code{-aO@emph{dir}}
8030 When searching for library and object files, look in directory
8031 @cite{dir}. The order in which library files are searched is described in
8032 @ref{91,,Search Paths for gnatbind}.
8035 @geindex Search paths
8036 @geindex for gnatmake
8038 @geindex -A (gnatmake)
8043 @item @code{-A@emph{dir}}
8045 Equivalent to @code{-aL@emph{dir}} @code{-aI@emph{dir}}.
8047 @geindex -I (gnatmake)
8049 @item @code{-I@emph{dir}}
8051 Equivalent to @code{-aO@emph{dir} -aI@emph{dir}}.
8054 @geindex -I- (gnatmake)
8056 @geindex Source files
8057 @geindex suppressing search
8064 Do not look for source files in the directory containing the source
8065 file named in the command line.
8066 Do not look for ALI or object files in the directory
8067 where @emph{gnatmake} was invoked.
8070 @geindex -L (gnatmake)
8072 @geindex Linker libraries
8077 @item @code{-L@emph{dir}}
8079 Add directory @cite{dir} to the list of directories in which the linker
8080 will search for libraries. This is equivalent to
8081 @code{-largs} @code{-L@emph{dir}}.
8082 Furthermore, under Windows, the sources pointed to by the libraries path
8083 set in the registry are not searched for.
8086 @geindex -nostdinc (gnatmake)
8091 @item @code{-nostdinc}
8093 Do not look for source files in the system default directory.
8096 @geindex -nostdlib (gnatmake)
8101 @item @code{-nostdlib}
8103 Do not look for library files in the system default directory.
8106 @geindex --RTS (gnatmake)
8111 @item @code{--RTS=@emph{rts-path}}
8113 Specifies the default location of the runtime library. GNAT looks for the
8115 in the following directories, and stops as soon as a valid runtime is found
8116 (@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
8117 @code{ada_object_path} present):
8123 @emph{<current directory>/$rts_path}
8126 @emph{<default-search-dir>/$rts_path}
8129 @emph{<default-search-dir>/rts-$rts_path}
8132 The selected path is handled like a normal RTS path.
8136 @node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
8137 @anchor{gnat_ugn/building_executable_programs_with_gnat id4}@anchor{e7}@anchor{gnat_ugn/building_executable_programs_with_gnat mode-switches-for-gnatmake}@anchor{e8}
8138 @subsection Mode Switches for @emph{gnatmake}
8141 The mode switches (referred to as @cite{mode_switches}) allow the
8142 inclusion of switches that are to be passed to the compiler itself, the
8143 binder or the linker. The effect of a mode switch is to cause all
8144 subsequent switches up to the end of the switch list, or up to the next
8145 mode switch, to be interpreted as switches to be passed on to the
8146 designated component of GNAT.
8148 @geindex -cargs (gnatmake)
8153 @item @code{-cargs @emph{switches}}
8155 Compiler switches. Here @cite{switches} is a list of switches
8156 that are valid switches for @emph{gcc}. They will be passed on to
8157 all compile steps performed by @emph{gnatmake}.
8160 @geindex -bargs (gnatmake)
8165 @item @code{-bargs @emph{switches}}
8167 Binder switches. Here @cite{switches} is a list of switches
8168 that are valid switches for @cite{gnatbind}. They will be passed on to
8169 all bind steps performed by @emph{gnatmake}.
8172 @geindex -largs (gnatmake)
8177 @item @code{-largs @emph{switches}}
8179 Linker switches. Here @cite{switches} is a list of switches
8180 that are valid switches for @emph{gnatlink}. They will be passed on to
8181 all link steps performed by @emph{gnatmake}.
8184 @geindex -margs (gnatmake)
8189 @item @code{-margs @emph{switches}}
8191 Make switches. The switches are directly interpreted by @emph{gnatmake},
8192 regardless of any previous occurrence of @emph{-cargs}, @emph{-bargs}
8196 @node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8197 @anchor{gnat_ugn/building_executable_programs_with_gnat id5}@anchor{e9}@anchor{gnat_ugn/building_executable_programs_with_gnat notes-on-the-command-line}@anchor{ea}
8198 @subsection Notes on the Command Line
8201 This section contains some additional useful notes on the operation
8202 of the @emph{gnatmake} command.
8204 @geindex Recompilation (by gnatmake)
8210 If @emph{gnatmake} finds no ALI files, it recompiles the main program
8211 and all other units required by the main program.
8212 This means that @emph{gnatmake}
8213 can be used for the initial compile, as well as during subsequent steps of
8214 the development cycle.
8217 If you enter @code{gnatmake foo.adb}, where @code{foo}
8218 is a subunit or body of a generic unit, @emph{gnatmake} recompiles
8219 @code{foo.adb} (because it finds no ALI) and stops, issuing a
8223 In @emph{gnatmake} the switch @emph{-I}
8224 is used to specify both source and
8225 library file paths. Use @emph{-aI}
8226 instead if you just want to specify
8227 source paths only and @emph{-aO}
8228 if you want to specify library paths
8232 @emph{gnatmake} will ignore any files whose ALI file is write-protected.
8233 This may conveniently be used to exclude standard libraries from
8234 consideration and in particular it means that the use of the
8235 @emph{-f} switch will not recompile these files
8236 unless @emph{-a} is also specified.
8239 @emph{gnatmake} has been designed to make the use of Ada libraries
8240 particularly convenient. Assume you have an Ada library organized
8241 as follows: @emph{obj-dir} contains the objects and ALI files for
8242 of your Ada compilation units,
8243 whereas @emph{include-dir} contains the
8244 specs of these units, but no bodies. Then to compile a unit
8245 stored in @cite{main.adb}, which uses this Ada library you would just type:
8248 $ gnatmake -aI`include-dir` -aL`obj-dir` main
8252 Using @emph{gnatmake} along with the @emph{-m (minimal recompilation)}
8253 switch provides a mechanism for avoiding unnecessary recompilations. Using
8255 you can update the comments/format of your
8256 source files without having to recompile everything. Note, however, that
8257 adding or deleting lines in a source files may render its debugging
8258 info obsolete. If the file in question is a spec, the impact is rather
8259 limited, as that debugging info will only be useful during the
8260 elaboration phase of your program. For bodies the impact can be more
8261 significant. In all events, your debugger will warn you if a source file
8262 is more recent than the corresponding object, and alert you to the fact
8263 that the debugging information may be out of date.
8266 @node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8267 @anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{eb}@anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{ec}
8268 @subsection How @emph{gnatmake} Works
8271 Generally @emph{gnatmake} automatically performs all necessary
8272 recompilations and you don't need to worry about how it works. However,
8273 it may be useful to have some basic understanding of the @emph{gnatmake}
8274 approach and in particular to understand how it uses the results of
8275 previous compilations without incorrectly depending on them.
8277 First a definition: an object file is considered @emph{up to date} if the
8278 corresponding ALI file exists and if all the source files listed in the
8279 dependency section of this ALI file have time stamps matching those in
8280 the ALI file. This means that neither the source file itself nor any
8281 files that it depends on have been modified, and hence there is no need
8282 to recompile this file.
8284 @emph{gnatmake} works by first checking if the specified main unit is up
8285 to date. If so, no compilations are required for the main unit. If not,
8286 @emph{gnatmake} compiles the main program to build a new ALI file that
8287 reflects the latest sources. Then the ALI file of the main unit is
8288 examined to find all the source files on which the main program depends,
8289 and @emph{gnatmake} recursively applies the above procedure on all these
8292 This process ensures that @emph{gnatmake} only trusts the dependencies
8293 in an existing ALI file if they are known to be correct. Otherwise it
8294 always recompiles to determine a new, guaranteed accurate set of
8295 dependencies. As a result the program is compiled 'upside down' from what may
8296 be more familiar as the required order of compilation in some other Ada
8297 systems. In particular, clients are compiled before the units on which
8298 they depend. The ability of GNAT to compile in any order is critical in
8299 allowing an order of compilation to be chosen that guarantees that
8300 @emph{gnatmake} will recompute a correct set of new dependencies if
8303 When invoking @emph{gnatmake} with several @cite{file_names}, if a unit is
8304 imported by several of the executables, it will be recompiled at most once.
8306 Note: when using non-standard naming conventions
8307 (@ref{37,,Using Other File Names}), changing through a configuration pragmas
8308 file the version of a source and invoking @emph{gnatmake} to recompile may
8309 have no effect, if the previous version of the source is still accessible
8310 by @emph{gnatmake}. It may be necessary to use the switch
8313 @node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8314 @anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatmake-usage}@anchor{ed}@anchor{gnat_ugn/building_executable_programs_with_gnat id7}@anchor{ee}
8315 @subsection Examples of @emph{gnatmake} Usage
8321 @item @emph{gnatmake hello.adb}
8323 Compile all files necessary to bind and link the main program
8324 @code{hello.adb} (containing unit @cite{Hello}) and bind and link the
8325 resulting object files to generate an executable file @code{hello}.
8327 @item @emph{gnatmake main1 main2 main3}
8329 Compile all files necessary to bind and link the main programs
8330 @code{main1.adb} (containing unit @cite{Main1}), @code{main2.adb}
8331 (containing unit @cite{Main2}) and @code{main3.adb}
8332 (containing unit @cite{Main3}) and bind and link the resulting object files
8333 to generate three executable files @code{main1},
8334 @code{main2} and @code{main3}.
8336 @item @emph{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8338 Compile all files necessary to bind and link the main program unit
8339 @cite{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8340 be done with optimization level 2 and the order of elaboration will be
8341 listed by the binder. @emph{gnatmake} will operate in quiet mode, not
8342 displaying commands it is executing.
8345 @node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8346 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{1e}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{ef}
8347 @section Compiling with @emph{gcc}
8350 This section discusses how to compile Ada programs using the @emph{gcc}
8351 command. It also describes the set of switches
8352 that can be used to control the behavior of the compiler.
8355 * Compiling Programs::
8356 * Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL.
8357 * Order of Compilation Issues::
8362 @node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8363 @anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{f0}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{f1}
8364 @subsection Compiling Programs
8367 The first step in creating an executable program is to compile the units
8368 of the program using the @emph{gcc} command. You must compile the
8375 the body file (@code{.adb}) for a library level subprogram or generic
8379 the spec file (@code{.ads}) for a library level package or generic
8380 package that has no body
8383 the body file (@code{.adb}) for a library level package
8384 or generic package that has a body
8387 You need @emph{not} compile the following files
8393 the spec of a library unit which has a body
8399 because they are compiled as part of compiling related units. GNAT
8401 when the corresponding body is compiled, and subunits when the parent is
8404 @geindex cannot generate code
8406 If you attempt to compile any of these files, you will get one of the
8407 following error messages (where @cite{fff} is the name of the file you
8413 cannot generate code for file `fff` (package spec)
8414 to check package spec, use -gnatc
8416 cannot generate code for file `fff` (missing subunits)
8417 to check parent unit, use -gnatc
8419 cannot generate code for file `fff` (subprogram spec)
8420 to check subprogram spec, use -gnatc
8422 cannot generate code for file `fff` (subunit)
8423 to check subunit, use -gnatc
8427 As indicated by the above error messages, if you want to submit
8428 one of these files to the compiler to check for correct semantics
8429 without generating code, then use the @emph{-gnatc} switch.
8431 The basic command for compiling a file containing an Ada unit is:
8434 $ gcc -c [switches] <file name>
8437 where @cite{file name} is the name of the Ada file (usually
8438 having an extension @code{.ads} for a spec or @code{.adb} for a body).
8440 @code{-c} switch to tell @emph{gcc} to compile, but not link, the file.
8441 The result of a successful compilation is an object file, which has the
8442 same name as the source file but an extension of @code{.o} and an Ada
8443 Library Information (ALI) file, which also has the same name as the
8444 source file, but with @code{.ali} as the extension. GNAT creates these
8445 two output files in the current directory, but you may specify a source
8446 file in any directory using an absolute or relative path specification
8447 containing the directory information.
8451 @emph{gcc} is actually a driver program that looks at the extensions of
8452 the file arguments and loads the appropriate compiler. For example, the
8453 GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8454 These programs are in directories known to the driver program (in some
8455 configurations via environment variables you set), but need not be in
8456 your path. The @emph{gcc} driver also calls the assembler and any other
8457 utilities needed to complete the generation of the required object
8460 It is possible to supply several file names on the same @emph{gcc}
8461 command. This causes @emph{gcc} to call the appropriate compiler for
8462 each file. For example, the following command lists two separate
8463 files to be compiled:
8466 $ gcc -c x.adb y.adb
8469 calls @cite{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8471 The compiler generates two object files @code{x.o} and @code{y.o}
8472 and the two ALI files @code{x.ali} and @code{y.ali}.
8474 Any switches apply to all the files listed, see @ref{f2,,Compiler Switches} for a
8475 list of available @emph{gcc} switches.
8477 @node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8478 @anchor{gnat_ugn/building_executable_programs_with_gnat id10}@anchor{f3}@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-and-the-run-time-library-rtl}@anchor{8e}
8479 @subsection Search Paths and the Run-Time Library (RTL)
8482 With the GNAT source-based library system, the compiler must be able to
8483 find source files for units that are needed by the unit being compiled.
8484 Search paths are used to guide this process.
8486 The compiler compiles one source file whose name must be given
8487 explicitly on the command line. In other words, no searching is done
8488 for this file. To find all other source files that are needed (the most
8489 common being the specs of units), the compiler examines the following
8490 directories, in the following order:
8496 The directory containing the source file of the main unit being compiled
8497 (the file name on the command line).
8500 Each directory named by an @emph{-I} switch given on the @emph{gcc}
8501 command line, in the order given.
8503 @geindex ADA_PRJ_INCLUDE_FILE
8506 Each of the directories listed in the text file whose name is given
8508 @geindex ADA_PRJ_INCLUDE_FILE
8509 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8510 @code{ADA_PRJ_INCLUDE_FILE} environment variable.
8511 @geindex ADA_PRJ_INCLUDE_FILE
8512 @geindex environment variable; ADA_PRJ_INCLUDE_FILE
8513 @code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8514 driver when project files are used. It should not normally be set
8517 @geindex ADA_INCLUDE_PATH
8520 Each of the directories listed in the value of the
8521 @geindex ADA_INCLUDE_PATH
8522 @geindex environment variable; ADA_INCLUDE_PATH
8523 @code{ADA_INCLUDE_PATH} environment variable.
8524 Construct this value
8527 @geindex environment variable; PATH
8528 @code{PATH} environment variable: a list of directory
8529 names separated by colons (semicolons when working with the NT version).
8532 The content of the @code{ada_source_path} file which is part of the GNAT
8533 installation tree and is used to store standard libraries such as the
8534 GNAT Run Time Library (RTL) source files.
8535 @ref{8b,,Installing a library}
8538 Specifying the switch @emph{-I-}
8539 inhibits the use of the directory
8540 containing the source file named in the command line. You can still
8541 have this directory on your search path, but in this case it must be
8542 explicitly requested with a @emph{-I} switch.
8544 Specifying the switch @emph{-nostdinc}
8545 inhibits the search of the default location for the GNAT Run Time
8546 Library (RTL) source files.
8548 The compiler outputs its object files and ALI files in the current
8550 Caution: The object file can be redirected with the @emph{-o} switch;
8551 however, @emph{gcc} and @cite{gnat1} have not been coordinated on this
8552 so the @code{ALI} file will not go to the right place. Therefore, you should
8553 avoid using the @emph{-o} switch.
8557 The packages @cite{Ada}, @cite{System}, and @cite{Interfaces} and their
8558 children make up the GNAT RTL, together with the simple @cite{System.IO}
8559 package used in the @cite{"Hello World"} example. The sources for these units
8560 are needed by the compiler and are kept together in one directory. Not
8561 all of the bodies are needed, but all of the sources are kept together
8562 anyway. In a normal installation, you need not specify these directory
8563 names when compiling or binding. Either the environment variables or
8564 the built-in defaults cause these files to be found.
8566 In addition to the language-defined hierarchies (@cite{System}, @cite{Ada} and
8567 @cite{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8568 consisting of child units of @cite{GNAT}. This is a collection of generally
8569 useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8570 for further details.
8572 Besides simplifying access to the RTL, a major use of search paths is
8573 in compiling sources from multiple directories. This can make
8574 development environments much more flexible.
8576 @node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8577 @anchor{gnat_ugn/building_executable_programs_with_gnat id11}@anchor{f4}@anchor{gnat_ugn/building_executable_programs_with_gnat order-of-compilation-issues}@anchor{f5}
8578 @subsection Order of Compilation Issues
8581 If, in our earlier example, there was a spec for the @cite{hello}
8582 procedure, it would be contained in the file @code{hello.ads}; yet this
8583 file would not have to be explicitly compiled. This is the result of the
8584 model we chose to implement library management. Some of the consequences
8585 of this model are as follows:
8591 There is no point in compiling specs (except for package
8592 specs with no bodies) because these are compiled as needed by clients. If
8593 you attempt a useless compilation, you will receive an error message.
8594 It is also useless to compile subunits because they are compiled as needed
8598 There are no order of compilation requirements: performing a
8599 compilation never obsoletes anything. The only way you can obsolete
8600 something and require recompilations is to modify one of the
8601 source files on which it depends.
8604 There is no library as such, apart from the ALI files
8605 (@ref{44,,The Ada Library Information Files}, for information on the format
8606 of these files). For now we find it convenient to create separate ALI files,
8607 but eventually the information therein may be incorporated into the object
8611 When you compile a unit, the source files for the specs of all units
8612 that it @emph{with}s, all its subunits, and the bodies of any generics it
8613 instantiates must be available (reachable by the search-paths mechanism
8614 described above), or you will receive a fatal error message.
8617 @node Examples,,Order of Compilation Issues,Compiling with gcc
8618 @anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{f7}
8619 @subsection Examples
8622 The following are some typical Ada compilation command line examples:
8628 Compile body in file @code{xyz.adb} with all default options.
8631 $ gcc -c -O2 -gnata xyz-def.adb
8634 Compile the child unit package in file @code{xyz-def.adb} with extensive
8635 optimizations, and pragma @cite{Assert}/@cite{Debug} statements
8639 $ gcc -c -gnatc abc-def.adb
8642 Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8645 @node Compiler Switches,Binding with gnatbind,Compiling with gcc,Building Executable Programs with GNAT
8646 @anchor{gnat_ugn/building_executable_programs_with_gnat compiler-switches}@anchor{f8}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gcc}@anchor{f2}
8647 @section Compiler Switches
8650 The @emph{gcc} command accepts switches that control the
8651 compilation process. These switches are fully described in this section:
8652 first an alphabetical listing of all switches with a brief description,
8653 and then functionally grouped sets of switches with more detailed
8656 More switches exist for GCC than those documented here, especially
8657 for specific targets. However, their use is not recommended as
8658 they may change code generation in ways that are incompatible with
8659 the Ada run-time library, or can cause inconsistencies between
8663 * Alphabetical List of All Switches::
8664 * Output and Error Message Control::
8665 * Warning Message Control::
8666 * Debugging and Assertion Control::
8667 * Validity Checking::
8670 * Using gcc for Syntax Checking::
8671 * Using gcc for Semantic Checking::
8672 * Compiling Different Versions of Ada::
8673 * Character Set Control::
8674 * File Naming Control::
8675 * Subprogram Inlining Control::
8676 * Auxiliary Output Control::
8677 * Debugging Control::
8678 * Exception Handling Control::
8679 * Units to Sources Mapping Files::
8680 * Code Generation Control::
8684 @node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8685 @anchor{gnat_ugn/building_executable_programs_with_gnat id13}@anchor{f9}@anchor{gnat_ugn/building_executable_programs_with_gnat alphabetical-list-of-all-switches}@anchor{fa}
8686 @subsection Alphabetical List of All Switches
8694 @item @code{-b @emph{target}}
8696 Compile your program to run on @cite{target}, which is the name of a
8697 system configuration. You must have a GNAT cross-compiler built if
8698 @cite{target} is not the same as your host system.
8706 @item @code{-B@emph{dir}}
8708 Load compiler executables (for example, @cite{gnat1}, the Ada compiler)
8709 from @cite{dir} instead of the default location. Only use this switch
8710 when multiple versions of the GNAT compiler are available.
8711 See the "Options for Directory Search" section in the
8712 @cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8713 You would normally use the @emph{-b} or @emph{-V} switch instead.
8723 Compile. Always use this switch when compiling Ada programs.
8725 Note: for some other languages when using @emph{gcc}, notably in
8726 the case of C and C++, it is possible to use
8727 use @emph{gcc} without a @emph{-c} switch to
8728 compile and link in one step. In the case of GNAT, you
8729 cannot use this approach, because the binder must be run
8730 and @emph{gcc} cannot be used to run the GNAT binder.
8733 @geindex -fcallgraph-info (gcc)
8738 @item @code{-fcallgraph-info[=su,da]}
8740 Makes the compiler output callgraph information for the program, on a
8741 per-file basis. The information is generated in the VCG format. It can
8742 be decorated with additional, per-node and/or per-edge information, if a
8743 list of comma-separated markers is additionally specified. When the
8744 @cite{su} marker is specified, the callgraph is decorated with stack usage
8745 information; it is equivalent to @emph{-fstack-usage}. When the @cite{da}
8746 marker is specified, the callgraph is decorated with information about
8747 dynamically allocated objects.
8750 @geindex -fdump-scos (gcc)
8755 @item @code{-fdump-scos}
8757 Generates SCO (Source Coverage Obligation) information in the ALI file.
8758 This information is used by advanced coverage tools. See unit @code{SCOs}
8759 in the compiler sources for details in files @code{scos.ads} and
8763 @geindex -fdump-xref (gcc)
8768 @item @code{-fdump-xref}
8770 Generates cross reference information in GLI files for C and C++ sources.
8771 The GLI files have the same syntax as the ALI files for Ada, and can be used
8772 for source navigation in IDEs and on the command line using e.g. gnatxref
8773 and the @emph{--ext=gli} switch.
8776 @geindex -flto (gcc)
8781 @item @code{-flto[=@emph{n}]}
8783 Enables Link Time Optimization. This switch must be used in conjunction
8784 with the traditional @emph{-Ox} switches and instructs the compiler to
8785 defer most optimizations until the link stage. The advantage of this
8786 approach is that the compiler can do a whole-program analysis and choose
8787 the best interprocedural optimization strategy based on a complete view
8788 of the program, instead of a fragmentary view with the usual approach.
8789 This can also speed up the compilation of big programs and reduce the
8790 size of the executable, compared with a traditional per-unit compilation
8791 with inlining across modules enabled by the @emph{-gnatn} switch.
8792 The drawback of this approach is that it may require more memory and that
8793 the debugging information generated by -g with it might be hardly usable.
8794 The switch, as well as the accompanying @emph{-Ox} switches, must be
8795 specified both for the compilation and the link phases.
8796 If the @cite{n} parameter is specified, the optimization and final code
8797 generation at link time are executed using @cite{n} parallel jobs by
8798 means of an installed @emph{make} program.
8801 @geindex -fno-inline (gcc)
8806 @item @code{-fno-inline}
8808 Suppresses all inlining, unless requested with pragma @cite{Inline_Always}. The
8809 effect is enforced regardless of other optimization or inlining switches.
8810 Note that inlining can also be suppressed on a finer-grained basis with
8811 pragma @cite{No_Inline}.
8814 @geindex -fno-inline-functions (gcc)
8819 @item @code{-fno-inline-functions}
8821 Suppresses automatic inlining of subprograms, which is enabled
8822 if @emph{-O3} is used.
8825 @geindex -fno-inline-small-functions (gcc)
8830 @item @code{-fno-inline-small-functions}
8832 Suppresses automatic inlining of small subprograms, which is enabled
8833 if @emph{-O2} is used.
8836 @geindex -fno-inline-functions-called-once (gcc)
8841 @item @code{-fno-inline-functions-called-once}
8843 Suppresses inlining of subprograms local to the unit and called once
8844 from within it, which is enabled if @emph{-O1} is used.
8847 @geindex -fno-ivopts (gcc)
8852 @item @code{-fno-ivopts}
8854 Suppresses high-level loop induction variable optimizations, which are
8855 enabled if @emph{-O1} is used. These optimizations are generally
8856 profitable but, for some specific cases of loops with numerous uses
8857 of the iteration variable that follow a common pattern, they may end
8858 up destroying the regularity that could be exploited at a lower level
8859 and thus producing inferior code.
8862 @geindex -fno-strict-aliasing (gcc)
8867 @item @code{-fno-strict-aliasing}
8869 Causes the compiler to avoid assumptions regarding non-aliasing
8870 of objects of different types. See
8871 @ref{fb,,Optimization and Strict Aliasing} for details.
8874 @geindex -fno-strict-overflow (gcc)
8879 @item @code{-fno-strict-overflow}
8881 Causes the compiler to avoid assumptions regarding the rules of signed
8882 integer overflow. These rules specify that signed integer overflow will
8883 result in a Constraint_Error exception at run time and are enforced in
8884 default mode by the compiler, so this switch should not be necessary in
8885 normal operating mode. It might be useful in conjunction with @emph{-gnato0}
8886 for very peculiar cases of low-level programming.
8889 @geindex -fstack-check (gcc)
8894 @item @code{-fstack-check}
8896 Activates stack checking.
8897 See @ref{fc,,Stack Overflow Checking} for details.
8900 @geindex -fstack-usage (gcc)
8905 @item @code{-fstack-usage}
8907 Makes the compiler output stack usage information for the program, on a
8908 per-subprogram basis. See @ref{fd,,Static Stack Usage Analysis} for details.
8918 Generate debugging information. This information is stored in the object
8919 file and copied from there to the final executable file by the linker,
8920 where it can be read by the debugger. You must use the
8921 @emph{-g} switch if you plan on using the debugger.
8924 @geindex -gnat05 (gcc)
8929 @item @code{-gnat05}
8931 Allow full Ada 2005 features.
8934 @geindex -gnat12 (gcc)
8939 @item @code{-gnat12}
8941 Allow full Ada 2012 features.
8944 @geindex -gnat83 (gcc)
8946 @geindex -gnat2005 (gcc)
8951 @item @code{-gnat2005}
8953 Allow full Ada 2005 features (same as @emph{-gnat05})
8956 @geindex -gnat2012 (gcc)
8961 @item @code{-gnat2012}
8963 Allow full Ada 2012 features (same as @emph{-gnat12})
8965 @item @code{-gnat83}
8967 Enforce Ada 83 restrictions.
8970 @geindex -gnat95 (gcc)
8975 @item @code{-gnat95}
8977 Enforce Ada 95 restrictions.
8979 Note: for compatibility with some Ada 95 compilers which support only
8980 the @cite{overriding} keyword of Ada 2005, the @emph{-gnatd.D} switch can
8981 be used along with @emph{-gnat95} to achieve a similar effect with GNAT.
8983 @emph{-gnatd.D} instructs GNAT to consider @cite{overriding} as a keyword
8984 and handle its associated semantic checks, even in Ada 95 mode.
8987 @geindex -gnata (gcc)
8994 Assertions enabled. @cite{Pragma Assert} and @cite{pragma Debug} to be
8995 activated. Note that these pragmas can also be controlled using the
8996 configuration pragmas @cite{Assertion_Policy} and @cite{Debug_Policy}.
8997 It also activates pragmas @cite{Check}, @cite{Precondition}, and
8998 @cite{Postcondition}. Note that these pragmas can also be controlled
8999 using the configuration pragma @cite{Check_Policy}. In Ada 2012, it
9000 also activates all assertions defined in the RM as aspects: preconditions,
9001 postconditions, type invariants and (sub)type predicates. In all Ada modes,
9002 corresponding pragmas for type invariants and (sub)type predicates are
9003 also activated. The default is that all these assertions are disabled,
9004 and have no effect, other than being checked for syntactic validity, and
9005 in the case of subtype predicates, constructions such as membership tests
9006 still test predicates even if assertions are turned off.
9009 @geindex -gnatA (gcc)
9016 Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
9020 @geindex -gnatb (gcc)
9027 Generate brief messages to @code{stderr} even if verbose mode set.
9030 @geindex -gnatB (gcc)
9037 Assume no invalid (bad) values except for 'Valid attribute use
9038 (@ref{fe,,Validity Checking}).
9041 @geindex -gnatc (gcc)
9048 Check syntax and semantics only (no code generation attempted). When the
9049 compiler is invoked by @emph{gnatmake}, if the switch @emph{-gnatc} is
9050 only given to the compiler (after @emph{-cargs} or in package Compiler of
9051 the project file, @emph{gnatmake} will fail because it will not find the
9052 object file after compilation. If @emph{gnatmake} is called with
9053 @emph{-gnatc} as a builder switch (before @emph{-cargs} or in package
9054 Builder of the project file) then @emph{gnatmake} will not fail because
9055 it will not look for the object files after compilation, and it will not try
9056 to build and link. This switch may not be given if a previous @cite{-gnatR}
9057 switch has been given, since @cite{-gnatR} requires that the code generator
9058 be called to complete determination of representation information.
9061 @geindex -gnatC (gcc)
9068 Generate CodePeer intermediate format (no code generation attempted).
9069 This switch will generate an intermediate representation suitable for
9070 use by CodePeer (@code{.scil} files). This switch is not compatible with
9071 code generation (it will, among other things, disable some switches such
9072 as -gnatn, and enable others such as -gnata).
9075 @geindex -gnatd (gcc)
9082 Specify debug options for the compiler. The string of characters after
9083 the @emph{-gnatd} specify the specific debug options. The possible
9084 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
9085 compiler source file @code{debug.adb} for details of the implemented
9086 debug options. Certain debug options are relevant to applications
9087 programmers, and these are documented at appropriate points in this
9091 @geindex -gnatD[nn] (gcc)
9098 Create expanded source files for source level debugging. This switch
9099 also suppress generation of cross-reference information
9100 (see @emph{-gnatx}). Note that this switch is not allowed if a previous
9101 -gnatR switch has been given, since these two switches are not compatible.
9104 @geindex -gnateA (gcc)
9109 @item @code{-gnateA}
9111 Check that the actual parameters of a subprogram call are not aliases of one
9112 another. To qualify as aliasing, the actuals must denote objects of a composite
9113 type, their memory locations must be identical or overlapping, and at least one
9114 of the corresponding formal parameters must be of mode OUT or IN OUT.
9117 type Rec_Typ is record
9118 Data : Integer := 0;
9121 function Self (Val : Rec_Typ) return Rec_Typ is
9126 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
9129 end Detect_Aliasing;
9133 Detect_Aliasing (Obj, Obj);
9134 Detect_Aliasing (Obj, Self (Obj));
9137 In the example above, the first call to @cite{Detect_Aliasing} fails with a
9138 @cite{Program_Error} at runtime because the actuals for @cite{Val_1} and
9139 @cite{Val_2} denote the same object. The second call executes without raising
9140 an exception because @cite{Self(Obj)} produces an anonymous object which does
9141 not share the memory location of @cite{Obj}.
9144 @geindex -gnatec (gcc)
9149 @item @code{-gnatec=@emph{path}}
9151 Specify a configuration pragma file
9152 (the equal sign is optional)
9153 (@ref{7b,,The Configuration Pragmas Files}).
9156 @geindex -gnateC (gcc)
9161 @item @code{-gnateC}
9163 Generate CodePeer messages in a compiler-like format. This switch is only
9164 effective if @emph{-gnatcC} is also specified and requires an installation
9168 @geindex -gnated (gcc)
9173 @item @code{-gnated}
9175 Disable atomic synchronization
9178 @geindex -gnateD (gcc)
9183 @item @code{-gnateDsymbol[=@emph{value}]}
9185 Defines a symbol, associated with @cite{value}, for preprocessing.
9186 (@ref{1a,,Integrated Preprocessing}).
9189 @geindex -gnateE (gcc)
9194 @item @code{-gnateE}
9196 Generate extra information in exception messages. In particular, display
9197 extra column information and the value and range associated with index and
9198 range check failures, and extra column information for access checks.
9199 In cases where the compiler is able to determine at compile time that
9200 a check will fail, it gives a warning, and the extra information is not
9201 produced at run time.
9204 @geindex -gnatef (gcc)
9209 @item @code{-gnatef}
9211 Display full source path name in brief error messages.
9214 @geindex -gnateF (gcc)
9219 @item @code{-gnateF}
9221 Check for overflow on all floating-point operations, including those
9222 for unconstrained predefined types. See description of pragma
9223 @cite{Check_Float_Overflow} in GNAT RM.
9226 @geindex -gnateg (gcc)
9233 The @cite{-gnatc} switch must always be specified before this switch, e.g.
9234 @cite{-gnatceg}. Generate a C header from the Ada input file. See
9235 @ref{d0,,Generating C Headers for Ada Specifications} for more
9239 @geindex -gnateG (gcc)
9244 @item @code{-gnateG}
9246 Save result of preprocessing in a text file.
9249 @geindex -gnatei (gcc)
9254 @item @code{-gnatei@emph{nnn}}
9256 Set maximum number of instantiations during compilation of a single unit to
9257 @cite{nnn}. This may be useful in increasing the default maximum of 8000 for
9258 the rare case when a single unit legitimately exceeds this limit.
9261 @geindex -gnateI (gcc)
9266 @item @code{-gnateI@emph{nnn}}
9268 Indicates that the source is a multi-unit source and that the index of the
9269 unit to compile is @cite{nnn}. @cite{nnn} needs to be a positive number and need
9270 to be a valid index in the multi-unit source.
9273 @geindex -gnatel (gcc)
9278 @item @code{-gnatel}
9280 This switch can be used with the static elaboration model to issue info
9282 where implicit @cite{pragma Elaborate} and @cite{pragma Elaborate_All}
9283 are generated. This is useful in diagnosing elaboration circularities
9284 caused by these implicit pragmas when using the static elaboration
9285 model. See See the section in this guide on elaboration checking for
9286 further details. These messages are not generated by default, and are
9287 intended only for temporary use when debugging circularity problems.
9290 @geindex -gnatel (gcc)
9295 @item @code{-gnateL}
9297 This switch turns off the info messages about implicit elaboration pragmas.
9300 @geindex -gnatem (gcc)
9305 @item @code{-gnatem=@emph{path}}
9307 Specify a mapping file
9308 (the equal sign is optional)
9309 (@ref{ff,,Units to Sources Mapping Files}).
9312 @geindex -gnatep (gcc)
9317 @item @code{-gnatep=@emph{file}}
9319 Specify a preprocessing data file
9320 (the equal sign is optional)
9321 (@ref{1a,,Integrated Preprocessing}).
9324 @geindex -gnateP (gcc)
9329 @item @code{-gnateP}
9331 Turn categorization dependency errors into warnings.
9332 Ada requires that units that WITH one another have compatible categories, for
9333 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9334 these errors become warnings (which can be ignored, or suppressed in the usual
9335 manner). This can be useful in some specialized circumstances such as the
9336 temporary use of special test software.
9339 @geindex -gnateS (gcc)
9344 @item @code{-gnateS}
9346 Synonym of @emph{-fdump-scos}, kept for backwards compatibility.
9349 @geindex -gnatet=file (gcc)
9354 @item @code{-gnatet=@emph{path}}
9356 Generate target dependent information. The format of the output file is
9357 described in the section about switch @emph{-gnateT}.
9360 @geindex -gnateT (gcc)
9365 @item @code{-gnateT=@emph{path}}
9367 Read target dependent information, such as endianness or sizes and alignments
9368 of base type. If this switch is passed, the default target dependent
9369 information of the compiler is replaced by the one read from the input file.
9370 This is used by tools other than the compiler, e.g. to do
9371 semantic analysis of programs that will run on some other target than
9372 the machine on which the tool is run.
9374 The following target dependent values should be defined,
9375 where @cite{Nat} denotes a natural integer value, @cite{Pos} denotes a
9376 positive integer value, and fields marked with a question mark are
9377 boolean fields, where a value of 0 is False, and a value of 1 is True:
9380 Bits_BE : Nat; -- Bits stored big-endian?
9381 Bits_Per_Unit : Pos; -- Bits in a storage unit
9382 Bits_Per_Word : Pos; -- Bits in a word
9383 Bytes_BE : Nat; -- Bytes stored big-endian?
9384 Char_Size : Pos; -- Standard.Character'Size
9385 Double_Float_Alignment : Nat; -- Alignment of double float
9386 Double_Scalar_Alignment : Nat; -- Alignment of double length scalar
9387 Double_Size : Pos; -- Standard.Long_Float'Size
9388 Float_Size : Pos; -- Standard.Float'Size
9389 Float_Words_BE : Nat; -- Float words stored big-endian?
9390 Int_Size : Pos; -- Standard.Integer'Size
9391 Long_Double_Size : Pos; -- Standard.Long_Long_Float'Size
9392 Long_Long_Size : Pos; -- Standard.Long_Long_Integer'Size
9393 Long_Size : Pos; -- Standard.Long_Integer'Size
9394 Maximum_Alignment : Pos; -- Maximum permitted alignment
9395 Max_Unaligned_Field : Pos; -- Maximum size for unaligned bit field
9396 Pointer_Size : Pos; -- System.Address'Size
9397 Short_Enums : Nat; -- Short foreign convention enums?
9398 Short_Size : Pos; -- Standard.Short_Integer'Size
9399 Strict_Alignment : Nat; -- Strict alignment?
9400 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9401 Wchar_T_Size : Pos; -- Interfaces.C.wchar_t'Size
9402 Words_BE : Nat; -- Words stored big-endian?
9405 The format of the input file is as follows. First come the values of
9406 the variables defined above, with one line per value:
9412 where @cite{name} is the name of the parameter, spelled out in full,
9413 and cased as in the above list, and @cite{value} is an unsigned decimal
9414 integer. Two or more blanks separates the name from the value.
9416 All the variables must be present, in alphabetical order (i.e. the
9417 same order as the list above).
9419 Then there is a blank line to separate the two parts of the file. Then
9420 come the lines showing the floating-point types to be registered, with
9421 one line per registered mode:
9424 name digs float_rep size alignment
9427 where @cite{name} is the string name of the type (which can have
9428 single spaces embedded in the name (e.g. long double), @cite{digs} is
9429 the number of digits for the floating-point type, @cite{float_rep} is
9430 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
9431 AAMP), @cite{size} is the size in bits, @cite{alignment} is the
9432 alignment in bits. The name is followed by at least two blanks, fields
9433 are separated by at least one blank, and a LF character immediately
9434 follows the alignment field.
9436 Here is an example of a target parameterization file:
9444 Double_Float_Alignment 0
9445 Double_Scalar_Alignment 0
9450 Long_Double_Size 128
9453 Maximum_Alignment 16
9454 Max_Unaligned_Field 64
9458 System_Allocator_Alignment 16
9464 long double 18 I 80 128
9469 @geindex -gnateu (gcc)
9474 @item @code{-gnateu}
9476 Ignore unrecognized validity, warning, and style switches that
9477 appear after this switch is given. This may be useful when
9478 compiling sources developed on a later version of the compiler
9479 with an earlier version. Of course the earlier version must
9480 support this switch.
9483 @geindex -gnateV (gcc)
9488 @item @code{-gnateV}
9490 Check that all actual parameters of a subprogram call are valid according to
9491 the rules of validity checking (@ref{fe,,Validity Checking}).
9494 @geindex -gnateY (gcc)
9499 @item @code{-gnateY}
9501 Ignore all STYLE_CHECKS pragmas. Full legality checks
9502 are still carried out, but the pragmas have no effect
9503 on what style checks are active. This allows all style
9504 checking options to be controlled from the command line.
9507 @geindex -gnatE (gcc)
9514 Full dynamic elaboration checks.
9517 @geindex -gnatf (gcc)
9524 Full errors. Multiple errors per line, all undefined references, do not
9525 attempt to suppress cascaded errors.
9528 @geindex -gnatF (gcc)
9535 Externals names are folded to all uppercase.
9538 @geindex -gnatg (gcc)
9545 Internal GNAT implementation mode. This should not be used for
9546 applications programs, it is intended only for use by the compiler
9547 and its run-time library. For documentation, see the GNAT sources.
9548 Note that @emph{-gnatg} implies
9549 @emph{-gnatw.ge} and
9551 so that all standard warnings and all standard style options are turned on.
9552 All warnings and style messages are treated as errors.
9555 @geindex -gnatG[nn] (gcc)
9560 @item @code{-gnatG=nn}
9562 List generated expanded code in source form.
9565 @geindex -gnath (gcc)
9572 Output usage information. The output is written to @code{stdout}.
9575 @geindex -gnati (gcc)
9580 @item @code{-gnati@emph{c}}
9582 Identifier character set (@cite{c} = 1/2/3/4/8/9/p/f/n/w).
9583 For details of the possible selections for @cite{c},
9584 see @ref{4a,,Character Set Control}.
9587 @geindex -gnatI (gcc)
9594 Ignore representation clauses. When this switch is used,
9595 representation clauses are treated as comments. This is useful
9596 when initially porting code where you want to ignore rep clause
9597 problems, and also for compiling foreign code (particularly
9598 for use with ASIS). The representation clauses that are ignored
9599 are: enumeration_representation_clause, record_representation_clause,
9600 and attribute_definition_clause for the following attributes:
9601 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9602 Object_Size, Size, Small, Stream_Size, and Value_Size.
9603 Note that this option should be used only for compiling -- the
9604 code is likely to malfunction at run time.
9606 Note that when @cite{-gnatct} is used to generate trees for input
9607 into @cite{ASIS} tools, these representation clauses are removed
9608 from the tree and ignored. This means that the tool will not see them.
9611 @geindex -gnatjnn (gcc)
9616 @item @code{-gnatj@emph{nn}}
9618 Reformat error messages to fit on @cite{nn} character lines
9621 @geindex -gnatk (gcc)
9626 @item @code{-gnatk=@emph{n}}
9628 Limit file names to @cite{n} (1-999) characters (@cite{k} = krunch).
9631 @geindex -gnatl (gcc)
9638 Output full source listing with embedded error messages.
9641 @geindex -gnatL (gcc)
9648 Used in conjunction with -gnatG or -gnatD to intersperse original
9649 source lines (as comment lines with line numbers) in the expanded
9653 @geindex -gnatm (gcc)
9658 @item @code{-gnatm=@emph{n}}
9660 Limit number of detected error or warning messages to @cite{n}
9661 where @cite{n} is in the range 1..999999. The default setting if
9662 no switch is given is 9999. If the number of warnings reaches this
9663 limit, then a message is output and further warnings are suppressed,
9664 but the compilation is continued. If the number of error messages
9665 reaches this limit, then a message is output and the compilation
9666 is abandoned. The equal sign here is optional. A value of zero
9667 means that no limit applies.
9670 @geindex -gnatn (gcc)
9675 @item @code{-gnatn[12]}
9677 Activate inlining for subprograms for which pragma @cite{Inline} is
9678 specified. This inlining is performed by the GCC back-end. An optional
9679 digit sets the inlining level: 1 for moderate inlining across modules
9680 or 2 for full inlining across modules. If no inlining level is specified,
9681 the compiler will pick it based on the optimization level.
9684 @geindex -gnatN (gcc)
9691 Activate front end inlining for subprograms for which
9692 pragma @cite{Inline} is specified. This inlining is performed
9693 by the front end and will be visible in the
9694 @emph{-gnatG} output.
9696 When using a gcc-based back end (in practice this means using any version
9697 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
9698 @emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
9699 Historically front end inlining was more extensive than the gcc back end
9700 inlining, but that is no longer the case.
9703 @geindex -gnato0 (gcc)
9708 @item @code{-gnato0}
9710 Suppresses overflow checking. This causes the behavior of the compiler to
9711 match the default for older versions where overflow checking was suppressed
9712 by default. This is equivalent to having
9713 @cite{pragma Suppress (Overflow_Mode)} in a configuration pragma file.
9716 @geindex -gnato?? (gcc)
9721 @item @code{-gnato??}
9723 Set default mode for handling generation of code to avoid intermediate
9724 arithmetic overflow. Here @cite{??} is two digits, a
9725 single digit, or nothing. Each digit is one of the digits @cite{1}
9729 @multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
9744 All intermediate overflows checked against base type (@cite{STRICT})
9752 Minimize intermediate overflows (@cite{MINIMIZED})
9760 Eliminate intermediate overflows (@cite{ELIMINATED})
9765 If only one digit appears, then it applies to all
9766 cases; if two digits are given, then the first applies outside
9767 assertions, pre/postconditions, and type invariants, and the second
9768 applies within assertions, pre/postconditions, and type invariants.
9770 If no digits follow the @emph{-gnato}, then it is equivalent to
9772 causing all intermediate overflows to be handled in strict
9775 This switch also causes arithmetic overflow checking to be performed
9776 (as though @cite{pragma Unsuppress (Overflow_Mode)} had been specified).
9778 The default if no option @emph{-gnato} is given is that overflow handling
9779 is in @cite{STRICT} mode (computations done using the base type), and that
9780 overflow checking is enabled.
9782 Note that division by zero is a separate check that is not
9783 controlled by this switch (divide-by-zero checking is on by default).
9785 See also @ref{100,,Specifying the Desired Mode}.
9788 @geindex -gnatp (gcc)
9795 Suppress all checks. See @ref{101,,Run-Time Checks} for details. This switch
9796 has no effect if cancelled by a subsequent @emph{-gnat-p} switch.
9799 @geindex -gnat-p (gcc)
9804 @item @code{-gnat-p}
9806 Cancel effect of previous @emph{-gnatp} switch.
9809 @geindex -gnatP (gcc)
9816 Enable polling. This is required on some systems (notably Windows NT) to
9817 obtain asynchronous abort and asynchronous transfer of control capability.
9818 See @cite{Pragma_Polling} in the @cite{GNAT_Reference_Manual} for full
9822 @geindex -gnatq (gcc)
9829 Don't quit. Try semantics, even if parse errors.
9832 @geindex -gnatQ (gcc)
9839 Don't quit. Generate @code{ALI} and tree files even if illegalities.
9840 Note that code generation is still suppressed in the presence of any
9841 errors, so even with @emph{-gnatQ} no object file is generated.
9844 @geindex -gnatr (gcc)
9851 Treat pragma Restrictions as Restriction_Warnings.
9854 @geindex -gnatR (gcc)
9859 @item @code{-gnatR[0/1/2/3[s]]}
9861 Output representation information for declared types and objects.
9862 Note that this switch is not allowed if a previous @cite{-gnatD} switch has
9863 been given, since these two switches are not compatible.
9865 @item @code{-gnatRm[s]}
9867 Output convention and parameter passing mechanisms for all subprograms.
9870 @geindex -gnats (gcc)
9880 @geindex -gnatS (gcc)
9887 Print package Standard.
9890 @geindex -gnatt (gcc)
9897 Generate tree output file.
9900 @geindex -gnatT (gcc)
9905 @item @code{-gnatT@emph{nnn}}
9907 All compiler tables start at @cite{nnn} times usual starting size.
9910 @geindex -gnatu (gcc)
9917 List units for this compilation.
9920 @geindex -gnatU (gcc)
9927 Tag all error messages with the unique string 'error:'
9930 @geindex -gnatv (gcc)
9937 Verbose mode. Full error output with source lines to @code{stdout}.
9940 @geindex -gnatV (gcc)
9947 Control level of validity checking (@ref{fe,,Validity Checking}).
9950 @geindex -gnatw (gcc)
9955 @item @code{-gnatw@emph{xxx}}
9958 @cite{xxx} is a string of option letters that denotes
9959 the exact warnings that
9960 are enabled or disabled (@ref{102,,Warning Message Control}).
9963 @geindex -gnatW (gcc)
9968 @item @code{-gnatW@emph{e}}
9970 Wide character encoding method
9971 (@cite{e}=n/h/u/s/e/8).
9974 @geindex -gnatx (gcc)
9981 Suppress generation of cross-reference information.
9984 @geindex -gnatX (gcc)
9991 Enable GNAT implementation extensions and latest Ada version.
9994 @geindex -gnaty (gcc)
10001 Enable built-in style checks (@ref{103,,Style Checking}).
10004 @geindex -gnatz (gcc)
10009 @item @code{-gnatz@emph{m}}
10011 Distribution stub generation and compilation
10012 (@cite{m}=r/c for receiver/caller stubs).
10020 @item @code{-I@emph{dir}}
10024 Direct GNAT to search the @cite{dir} directory for source files needed by
10025 the current compilation
10026 (see @ref{8e,,Search Paths and the Run-Time Library (RTL)}).
10038 Except for the source file named in the command line, do not look for source
10039 files in the directory containing the source file named in the command line
10040 (see @ref{8e,,Search Paths and the Run-Time Library (RTL)}).
10048 @item @code{-o @emph{file}}
10050 This switch is used in @emph{gcc} to redirect the generated object file
10051 and its associated ALI file. Beware of this switch with GNAT, because it may
10052 cause the object file and ALI file to have different names which in turn
10053 may confuse the binder and the linker.
10056 @geindex -nostdinc (gcc)
10061 @item @code{-nostdinc}
10063 Inhibit the search of the default location for the GNAT Run Time
10064 Library (RTL) source files.
10067 @geindex -nostdlib (gcc)
10072 @item @code{-nostdlib}
10074 Inhibit the search of the default location for the GNAT Run Time
10075 Library (RTL) ALI files.
10083 @item @code{-O[@emph{n}]}
10085 @cite{n} controls the optimization level:
10088 @multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
10103 No optimization, the default setting if no @emph{-O} appears
10111 Normal optimization, the default if you specify @emph{-O} without an
10112 operand. A good compromise between code quality and compilation
10121 Extensive optimization, may improve execution time, possibly at
10122 the cost of substantially increased compilation time.
10130 Same as @emph{-O2}, and also includes inline expansion for small
10131 subprograms in the same unit.
10139 Optimize space usage
10144 See also @ref{104,,Optimization Levels}.
10147 @geindex -pass-exit-codes (gcc)
10152 @item @code{-pass-exit-codes}
10154 Catch exit codes from the compiler and use the most meaningful as
10158 @geindex --RTS (gcc)
10163 @item @code{--RTS=@emph{rts-path}}
10165 Specifies the default location of the runtime library. Same meaning as the
10166 equivalent @emph{gnatmake} flag (@ref{e2,,Switches for gnatmake}).
10176 Used in place of @emph{-c} to
10177 cause the assembler source file to be
10178 generated, using @code{.s} as the extension,
10179 instead of the object file.
10180 This may be useful if you need to examine the generated assembly code.
10183 @geindex -fverbose-asm (gcc)
10188 @item @code{-fverbose-asm}
10190 Used in conjunction with @emph{-S}
10191 to cause the generated assembly code file to be annotated with variable
10192 names, making it significantly easier to follow.
10202 Show commands generated by the @emph{gcc} driver. Normally used only for
10203 debugging purposes or if you need to be sure what version of the
10204 compiler you are executing.
10212 @item @code{-V @emph{ver}}
10214 Execute @cite{ver} version of the compiler. This is the @emph{gcc}
10215 version, not the GNAT version.
10225 Turn off warnings generated by the back end of the compiler. Use of
10226 this switch also causes the default for front end warnings to be set
10227 to suppress (as though @emph{-gnatws} had appeared at the start of
10231 @geindex Combining GNAT switches
10233 You may combine a sequence of GNAT switches into a single switch. For
10234 example, the combined switch
10243 is equivalent to specifying the following sequence of switches:
10248 -gnato -gnatf -gnati3
10252 The following restrictions apply to the combination of switches
10259 The switch @emph{-gnatc} if combined with other switches must come
10260 first in the string.
10263 The switch @emph{-gnats} if combined with other switches must come
10264 first in the string.
10268 @emph{-gnatzc} and @emph{-gnatzr} may not be combined with any other
10269 switches, and only one of them may appear in the command line.
10272 The switch @emph{-gnat-p} may not be combined with any other switch.
10275 Once a 'y' appears in the string (that is a use of the @emph{-gnaty}
10276 switch), then all further characters in the switch are interpreted
10277 as style modifiers (see description of @emph{-gnaty}).
10280 Once a 'd' appears in the string (that is a use of the @emph{-gnatd}
10281 switch), then all further characters in the switch are interpreted
10282 as debug flags (see description of @emph{-gnatd}).
10285 Once a 'w' appears in the string (that is a use of the @emph{-gnatw}
10286 switch), then all further characters in the switch are interpreted
10287 as warning mode modifiers (see description of @emph{-gnatw}).
10290 Once a 'V' appears in the string (that is a use of the @emph{-gnatV}
10291 switch), then all further characters in the switch are interpreted
10292 as validity checking options (@ref{fe,,Validity Checking}).
10295 Option 'em', 'ec', 'ep', 'l=' and 'R' must be the last options in
10296 a combined list of options.
10299 @node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10300 @anchor{gnat_ugn/building_executable_programs_with_gnat id14}@anchor{105}@anchor{gnat_ugn/building_executable_programs_with_gnat output-and-error-message-control}@anchor{106}
10301 @subsection Output and Error Message Control
10306 The standard default format for error messages is called 'brief format'.
10307 Brief format messages are written to @code{stderr} (the standard error
10308 file) and have the following form:
10311 e.adb:3:04: Incorrect spelling of keyword "function"
10312 e.adb:4:20: ";" should be "is"
10315 The first integer after the file name is the line number in the file,
10316 and the second integer is the column number within the line.
10317 @cite{GPS} can parse the error messages
10318 and point to the referenced character.
10319 The following switches provide control over the error message
10322 @geindex -gnatv (gcc)
10327 @item @code{-gnatv}
10329 The @cite{v} stands for verbose.
10330 The effect of this setting is to write long-format error
10331 messages to @code{stdout} (the standard output file.
10332 The same program compiled with the
10333 @emph{-gnatv} switch would generate:
10336 3. funcion X (Q : Integer)
10338 >>> Incorrect spelling of keyword "function"
10341 >>> ";" should be "is"
10344 The vertical bar indicates the location of the error, and the @code{>>>}
10345 prefix can be used to search for error messages. When this switch is
10346 used the only source lines output are those with errors.
10349 @geindex -gnatl (gcc)
10354 @item @code{-gnatl}
10356 The @cite{l} stands for list.
10357 This switch causes a full listing of
10358 the file to be generated. In the case where a body is
10359 compiled, the corresponding spec is also listed, along
10360 with any subunits. Typical output from compiling a package
10361 body @code{p.adb} might look like:
10366 1. package body p is
10368 3. procedure a is separate;
10379 2. pragma Elaborate_Body
10400 When you specify the @emph{-gnatv} or @emph{-gnatl} switches and
10401 standard output is redirected, a brief summary is written to
10402 @code{stderr} (standard error) giving the number of error messages and
10403 warning messages generated.
10406 @geindex -gnatl=fname (gcc)
10411 @item @code{-gnatl=@emph{fname}}
10413 This has the same effect as @emph{-gnatl} except that the output is
10414 written to a file instead of to standard output. If the given name
10415 @code{fname} does not start with a period, then it is the full name
10416 of the file to be written. If @code{fname} is an extension, it is
10417 appended to the name of the file being compiled. For example, if
10418 file @code{xyz.adb} is compiled with @emph{-gnatl=.lst},
10419 then the output is written to file xyz.adb.lst.
10422 @geindex -gnatU (gcc)
10427 @item @code{-gnatU}
10429 This switch forces all error messages to be preceded by the unique
10430 string 'error:'. This means that error messages take a few more
10431 characters in space, but allows easy searching for and identification
10435 @geindex -gnatb (gcc)
10440 @item @code{-gnatb}
10442 The @cite{b} stands for brief.
10443 This switch causes GNAT to generate the
10444 brief format error messages to @code{stderr} (the standard error
10445 file) as well as the verbose
10446 format message or full listing (which as usual is written to
10447 @code{stdout} (the standard output file).
10450 @geindex -gnatm (gcc)
10455 @item @code{-gnatm=@emph{n}}
10457 The @cite{m} stands for maximum.
10458 @cite{n} is a decimal integer in the
10459 range of 1 to 999999 and limits the number of error or warning
10460 messages to be generated. For example, using
10461 @emph{-gnatm2} might yield
10464 e.adb:3:04: Incorrect spelling of keyword "function"
10465 e.adb:5:35: missing ".."
10466 fatal error: maximum number of errors detected
10467 compilation abandoned
10470 The default setting if
10471 no switch is given is 9999. If the number of warnings reaches this
10472 limit, then a message is output and further warnings are suppressed,
10473 but the compilation is continued. If the number of error messages
10474 reaches this limit, then a message is output and the compilation
10475 is abandoned. A value of zero means that no limit applies.
10477 Note that the equal sign is optional, so the switches
10478 @emph{-gnatm2} and @emph{-gnatm=2} are equivalent.
10481 @geindex -gnatf (gcc)
10486 @item @code{-gnatf}
10488 @geindex Error messages
10489 @geindex suppressing
10491 The @cite{f} stands for full.
10492 Normally, the compiler suppresses error messages that are likely to be
10493 redundant. This switch causes all error
10494 messages to be generated. In particular, in the case of
10495 references to undefined variables. If a given variable is referenced
10496 several times, the normal format of messages is
10499 e.adb:7:07: "V" is undefined (more references follow)
10502 where the parenthetical comment warns that there are additional
10503 references to the variable @cite{V}. Compiling the same program with the
10504 @emph{-gnatf} switch yields
10507 e.adb:7:07: "V" is undefined
10508 e.adb:8:07: "V" is undefined
10509 e.adb:8:12: "V" is undefined
10510 e.adb:8:16: "V" is undefined
10511 e.adb:9:07: "V" is undefined
10512 e.adb:9:12: "V" is undefined
10515 The @emph{-gnatf} switch also generates additional information for
10516 some error messages. Some examples are:
10522 Details on possibly non-portable unchecked conversion
10525 List possible interpretations for ambiguous calls
10528 Additional details on incorrect parameters
10532 @geindex -gnatjnn (gcc)
10537 @item @code{-gnatjnn}
10539 In normal operation mode (or if @emph{-gnatj0} is used), then error messages
10540 with continuation lines are treated as though the continuation lines were
10541 separate messages (and so a warning with two continuation lines counts as
10542 three warnings, and is listed as three separate messages).
10544 If the @emph{-gnatjnn} switch is used with a positive value for nn, then
10545 messages are output in a different manner. A message and all its continuation
10546 lines are treated as a unit, and count as only one warning or message in the
10547 statistics totals. Furthermore, the message is reformatted so that no line
10548 is longer than nn characters.
10551 @geindex -gnatq (gcc)
10556 @item @code{-gnatq}
10558 The @cite{q} stands for quit (really 'don't quit').
10559 In normal operation mode, the compiler first parses the program and
10560 determines if there are any syntax errors. If there are, appropriate
10561 error messages are generated and compilation is immediately terminated.
10563 GNAT to continue with semantic analysis even if syntax errors have been
10564 found. This may enable the detection of more errors in a single run. On
10565 the other hand, the semantic analyzer is more likely to encounter some
10566 internal fatal error when given a syntactically invalid tree.
10569 @geindex -gnatQ (gcc)
10574 @item @code{-gnatQ}
10576 In normal operation mode, the @code{ALI} file is not generated if any
10577 illegalities are detected in the program. The use of @emph{-gnatQ} forces
10578 generation of the @code{ALI} file. This file is marked as being in
10579 error, so it cannot be used for binding purposes, but it does contain
10580 reasonably complete cross-reference information, and thus may be useful
10581 for use by tools (e.g., semantic browsing tools or integrated development
10582 environments) that are driven from the @code{ALI} file. This switch
10583 implies @emph{-gnatq}, since the semantic phase must be run to get a
10584 meaningful ALI file.
10586 In addition, if @emph{-gnatt} is also specified, then the tree file is
10587 generated even if there are illegalities. It may be useful in this case
10588 to also specify @emph{-gnatq} to ensure that full semantic processing
10589 occurs. The resulting tree file can be processed by ASIS, for the purpose
10590 of providing partial information about illegal units, but if the error
10591 causes the tree to be badly malformed, then ASIS may crash during the
10594 When @emph{-gnatQ} is used and the generated @code{ALI} file is marked as
10595 being in error, @emph{gnatmake} will attempt to recompile the source when it
10596 finds such an @code{ALI} file, including with switch @emph{-gnatc}.
10598 Note that @emph{-gnatQ} has no effect if @emph{-gnats} is specified,
10599 since ALI files are never generated if @emph{-gnats} is set.
10602 @node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10603 @anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{102}@anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{107}
10604 @subsection Warning Message Control
10607 @geindex Warning messages
10609 In addition to error messages, which correspond to illegalities as defined
10610 in the Ada Reference Manual, the compiler detects two kinds of warning
10613 First, the compiler considers some constructs suspicious and generates a
10614 warning message to alert you to a possible error. Second, if the
10615 compiler detects a situation that is sure to raise an exception at
10616 run time, it generates a warning message. The following shows an example
10617 of warning messages:
10620 e.adb:4:24: warning: creation of object may raise Storage_Error
10621 e.adb:10:17: warning: static value out of range
10622 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10625 GNAT considers a large number of situations as appropriate
10626 for the generation of warning messages. As always, warnings are not
10627 definite indications of errors. For example, if you do an out-of-range
10628 assignment with the deliberate intention of raising a
10629 @cite{Constraint_Error} exception, then the warning that may be
10630 issued does not indicate an error. Some of the situations for which GNAT
10631 issues warnings (at least some of the time) are given in the following
10632 list. This list is not complete, and new warnings are often added to
10633 subsequent versions of GNAT. The list is intended to give a general idea
10634 of the kinds of warnings that are generated.
10640 Possible infinitely recursive calls
10643 Out-of-range values being assigned
10646 Possible order of elaboration problems
10649 Size not a multiple of alignment for a record type
10652 Assertions (pragma Assert) that are sure to fail
10658 Address clauses with possibly unaligned values, or where an attempt is
10659 made to overlay a smaller variable with a larger one.
10662 Fixed-point type declarations with a null range
10665 Direct_IO or Sequential_IO instantiated with a type that has access values
10668 Variables that are never assigned a value
10671 Variables that are referenced before being initialized
10674 Task entries with no corresponding @cite{accept} statement
10677 Duplicate accepts for the same task entry in a @cite{select}
10680 Objects that take too much storage
10683 Unchecked conversion between types of differing sizes
10686 Missing @cite{return} statement along some execution path in a function
10689 Incorrect (unrecognized) pragmas
10692 Incorrect external names
10695 Allocation from empty storage pool
10698 Potentially blocking operation in protected type
10701 Suspicious parenthesization of expressions
10704 Mismatching bounds in an aggregate
10707 Attempt to return local value by reference
10710 Premature instantiation of a generic body
10713 Attempt to pack aliased components
10716 Out of bounds array subscripts
10719 Wrong length on string assignment
10722 Violations of style rules if style checking is enabled
10725 Unused @emph{with} clauses
10728 @cite{Bit_Order} usage that does not have any effect
10731 @cite{Standard.Duration} used to resolve universal fixed expression
10734 Dereference of possibly null value
10737 Declaration that is likely to cause storage error
10740 Internal GNAT unit @emph{with}ed by application unit
10743 Values known to be out of range at compile time
10746 Unreferenced or unmodified variables. Note that a special
10747 exemption applies to variables which contain any of the substrings
10748 @cite{DISCARD@comma{} DUMMY@comma{} IGNORE@comma{} JUNK@comma{} UNUSED}, in any casing. Such variables
10749 are considered likely to be intentionally used in a situation where
10750 otherwise a warning would be given, so warnings of this kind are
10751 always suppressed for such variables.
10754 Address overlays that could clobber memory
10757 Unexpected initialization when address clause present
10760 Bad alignment for address clause
10763 Useless type conversions
10766 Redundant assignment statements and other redundant constructs
10769 Useless exception handlers
10772 Accidental hiding of name by child unit
10775 Access before elaboration detected at compile time
10778 A range in a @cite{for} loop that is known to be null or might be null
10781 The following section lists compiler switches that are available
10782 to control the handling of warning messages. It is also possible
10783 to exercise much finer control over what warnings are issued and
10784 suppressed using the GNAT pragma Warnings (see the description
10785 of the pragma in the @cite{GNAT_Reference_manual}).
10787 @geindex -gnatwa (gcc)
10792 @item @code{-gnatwa}
10794 @emph{Activate most optional warnings.}
10796 This switch activates most optional warning messages. See the remaining list
10797 in this section for details on optional warning messages that can be
10798 individually controlled. The warnings that are not turned on by this
10805 @code{-gnatwd} (implicit dereferencing)
10808 @code{-gnatw.d} (tag warnings with -gnatw switch)
10811 @code{-gnatwh} (hiding)
10814 @code{-gnatw.h} (holes in record layouts)
10817 @code{-gnatw.k} (redefinition of names in standard)
10820 @code{-gnatwl} (elaboration warnings)
10823 @code{-gnatw.l} (inherited aspects)
10826 @code{-gnatw.n} (atomic synchronization)
10829 @code{-gnatwo} (address clause overlay)
10832 @code{-gnatw.o} (values set by out parameters ignored)
10835 @code{-gnatw.s} (overridden size clause)
10838 @code{-gnatwt} (tracking of deleted conditional code)
10841 @code{-gnatw.u} (unordered enumeration)
10844 @code{-gnatw.w} (use of Warnings Off)
10847 @code{-gnatw.y} (reasons for package needing body)
10850 All other optional warnings are turned on.
10853 @geindex -gnatwA (gcc)
10858 @item @code{-gnatwA}
10860 @emph{Suppress all optional errors.}
10862 This switch suppresses all optional warning messages, see remaining list
10863 in this section for details on optional warning messages that can be
10864 individually controlled. Note that unlike switch @emph{-gnatws}, the
10865 use of switch @emph{-gnatwA} does not suppress warnings that are
10866 normally given unconditionally and cannot be individually controlled
10867 (for example, the warning about a missing exit path in a function).
10868 Also, again unlike switch @emph{-gnatws}, warnings suppressed by
10869 the use of switch @emph{-gnatwA} can be individually turned back
10870 on. For example the use of switch @emph{-gnatwA} followed by
10871 switch @emph{-gnatwd} will suppress all optional warnings except
10872 the warnings for implicit dereferencing.
10875 @geindex -gnatw.a (gcc)
10880 @item @code{-gnatw.a}
10882 @emph{Activate warnings on failing assertions.}
10884 @geindex Assert failures
10886 This switch activates warnings for assertions where the compiler can tell at
10887 compile time that the assertion will fail. Note that this warning is given
10888 even if assertions are disabled. The default is that such warnings are
10892 @geindex -gnatw.A (gcc)
10897 @item @code{-gnatw.A}
10899 @emph{Suppress warnings on failing assertions.}
10901 @geindex Assert failures
10903 This switch suppresses warnings for assertions where the compiler can tell at
10904 compile time that the assertion will fail.
10907 @geindex -gnatwb (gcc)
10912 @item @code{-gnatwb}
10914 @emph{Activate warnings on bad fixed values.}
10916 @geindex Bad fixed values
10918 @geindex Fixed-point Small value
10920 @geindex Small value
10922 This switch activates warnings for static fixed-point expressions whose
10923 value is not an exact multiple of Small. Such values are implementation
10924 dependent, since an implementation is free to choose either of the multiples
10925 that surround the value. GNAT always chooses the closer one, but this is not
10926 required behavior, and it is better to specify a value that is an exact
10927 multiple, ensuring predictable execution. The default is that such warnings
10931 @geindex -gnatwB (gcc)
10936 @item @code{-gnatwB}
10938 @emph{Suppress warnings on bad fixed values.}
10940 This switch suppresses warnings for static fixed-point expressions whose
10941 value is not an exact multiple of Small.
10944 @geindex -gnatw.b (gcc)
10949 @item @code{-gnatw.b}
10951 @emph{Activate warnings on biased representation.}
10953 @geindex Biased representation
10955 This switch activates warnings when a size clause, value size clause, component
10956 clause, or component size clause forces the use of biased representation for an
10957 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
10958 to represent 10/11). The default is that such warnings are generated.
10961 @geindex -gnatwB (gcc)
10966 @item @code{-gnatw.B}
10968 @emph{Suppress warnings on biased representation.}
10970 This switch suppresses warnings for representation clauses that force the use
10971 of biased representation.
10974 @geindex -gnatwc (gcc)
10979 @item @code{-gnatwc}
10981 @emph{Activate warnings on conditionals.}
10983 @geindex Conditionals
10986 This switch activates warnings for conditional expressions used in
10987 tests that are known to be True or False at compile time. The default
10988 is that such warnings are not generated.
10989 Note that this warning does
10990 not get issued for the use of boolean variables or constants whose
10991 values are known at compile time, since this is a standard technique
10992 for conditional compilation in Ada, and this would generate too many
10993 false positive warnings.
10995 This warning option also activates a special test for comparisons using
10996 the operators '>=' and' <='.
10997 If the compiler can tell that only the equality condition is possible,
10998 then it will warn that the '>' or '<' part of the test
10999 is useless and that the operator could be replaced by '='.
11000 An example would be comparing a @cite{Natural} variable <= 0.
11002 This warning option also generates warnings if
11003 one or both tests is optimized away in a membership test for integer
11004 values if the result can be determined at compile time. Range tests on
11005 enumeration types are not included, since it is common for such tests
11006 to include an end point.
11008 This warning can also be turned on using @emph{-gnatwa}.
11011 @geindex -gnatwC (gcc)
11016 @item @code{-gnatwC}
11018 @emph{Suppress warnings on conditionals.}
11020 This switch suppresses warnings for conditional expressions used in
11021 tests that are known to be True or False at compile time.
11024 @geindex -gnatw.c (gcc)
11029 @item @code{-gnatw.c}
11031 @emph{Activate warnings on missing component clauses.}
11033 @geindex Component clause
11036 This switch activates warnings for record components where a record
11037 representation clause is present and has component clauses for the
11038 majority, but not all, of the components. A warning is given for each
11039 component for which no component clause is present.
11042 @geindex -gnatwC (gcc)
11047 @item @code{-gnatw.C}
11049 @emph{Suppress warnings on missing component clauses.}
11051 This switch suppresses warnings for record components that are
11052 missing a component clause in the situation described above.
11055 @geindex -gnatwd (gcc)
11060 @item @code{-gnatwd}
11062 @emph{Activate warnings on implicit dereferencing.}
11064 If this switch is set, then the use of a prefix of an access type
11065 in an indexed component, slice, or selected component without an
11066 explicit @cite{.all} will generate a warning. With this warning
11067 enabled, access checks occur only at points where an explicit
11068 @cite{.all} appears in the source code (assuming no warnings are
11069 generated as a result of this switch). The default is that such
11070 warnings are not generated.
11073 @geindex -gnatwD (gcc)
11078 @item @code{-gnatwD}
11080 @emph{Suppress warnings on implicit dereferencing.}
11082 @geindex Implicit dereferencing
11084 @geindex Dereferencing
11087 This switch suppresses warnings for implicit dereferences in
11088 indexed components, slices, and selected components.
11091 @geindex -gnatw.d (gcc)
11096 @item @code{-gnatw.d}
11098 @emph{Activate tagging of warning and info messages.}
11100 If this switch is set, then warning messages are tagged, with one of the
11110 Used to tag warnings controlled by the switch @emph{-gnatwx} where x
11115 Used to tag warnings controlled by the switch @emph{-gnatw.x} where x
11120 Used to tag elaboration information (info) messages generated when the
11121 static model of elaboration is used and the @emph{-gnatel} switch is set.
11124 @emph{[restriction warning]}
11125 Used to tag warning messages for restriction violations, activated by use
11126 of the pragma @emph{Restriction_Warnings}.
11129 @emph{[warning-as-error]}
11130 Used to tag warning messages that have been converted to error messages by
11131 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11132 the string "error: " rather than "warning: ".
11135 @emph{[enabled by default]}
11136 Used to tag all other warnings that are always given by default, unless
11137 warnings are completely suppressed using pragma @emph{Warnings(Off)} or
11138 the switch @emph{-gnatws}.
11143 @geindex -gnatw.d (gcc)
11148 @item @code{-gnatw.D}
11150 @emph{Deactivate tagging of warning and info messages messages.}
11152 If this switch is set, then warning messages return to the default
11153 mode in which warnings and info messages are not tagged as described above for
11157 @geindex -gnatwe (gcc)
11160 @geindex treat as error
11165 @item @code{-gnatwe}
11167 @emph{Treat warnings and style checks as errors.}
11169 This switch causes warning messages and style check messages to be
11171 The warning string still appears, but the warning messages are counted
11172 as errors, and prevent the generation of an object file. Note that this
11173 is the only -gnatw switch that affects the handling of style check messages.
11174 Note also that this switch has no effect on info (information) messages, which
11175 are not treated as errors if this switch is present.
11178 @geindex -gnatw.e (gcc)
11183 @item @code{-gnatw.e}
11185 @emph{Activate every optional warning.}
11188 @geindex activate every optional warning
11190 This switch activates all optional warnings, including those which
11191 are not activated by @cite{-gnatwa}. The use of this switch is not
11192 recommended for normal use. If you turn this switch on, it is almost
11193 certain that you will get large numbers of useless warnings. The
11194 warnings that are excluded from @cite{-gnatwa} are typically highly
11195 specialized warnings that are suitable for use only in code that has
11196 been specifically designed according to specialized coding rules.
11199 @geindex -gnatwf (gcc)
11204 @item @code{-gnatwf}
11206 @emph{Activate warnings on unreferenced formals.}
11209 @geindex unreferenced
11211 This switch causes a warning to be generated if a formal parameter
11212 is not referenced in the body of the subprogram. This warning can
11213 also be turned on using @emph{-gnatwu}. The
11214 default is that these warnings are not generated.
11217 @geindex -gnatwF (gcc)
11222 @item @code{-gnatwF}
11224 @emph{Suppress warnings on unreferenced formals.}
11226 This switch suppresses warnings for unreferenced formal
11227 parameters. Note that the
11228 combination @emph{-gnatwu} followed by @emph{-gnatwF} has the
11229 effect of warning on unreferenced entities other than subprogram
11233 @geindex -gnatwg (gcc)
11238 @item @code{-gnatwg}
11240 @emph{Activate warnings on unrecognized pragmas.}
11243 @geindex unrecognized
11245 This switch causes a warning to be generated if an unrecognized
11246 pragma is encountered. Apart from issuing this warning, the
11247 pragma is ignored and has no effect. The default
11248 is that such warnings are issued (satisfying the Ada Reference
11249 Manual requirement that such warnings appear).
11252 @geindex -gnatwG (gcc)
11257 @item @code{-gnatwG}
11259 @emph{Suppress warnings on unrecognized pragmas.}
11261 This switch suppresses warnings for unrecognized pragmas.
11264 @geindex -gnatw.g (gcc)
11269 @item @code{-gnatw.g}
11271 @emph{Warnings used for GNAT sources.}
11273 This switch sets the warning categories that are used by the standard
11274 GNAT style. Currently this is equivalent to
11275 @emph{-gnatwAao.sI.C.V.X}
11276 but more warnings may be added in the future without advanced notice.
11279 @geindex -gnatwh (gcc)
11284 @item @code{-gnatwh}
11286 @emph{Activate warnings on hiding.}
11288 @geindex Hiding of Declarations
11290 This switch activates warnings on hiding declarations.
11291 A declaration is considered hiding
11292 if it is for a non-overloadable entity, and it declares an entity with the
11293 same name as some other entity that is directly or use-visible. The default
11294 is that such warnings are not generated.
11297 @geindex -gnatwH (gcc)
11302 @item @code{-gnatwH}
11304 @emph{Suppress warnings on hiding.}
11306 This switch suppresses warnings on hiding declarations.
11309 @geindex -gnatw.h (gcc)
11314 @item @code{-gnatw.h}
11316 @emph{Activate warnings on holes/gaps in records.}
11318 @geindex Record Representation (gaps)
11320 This switch activates warnings on component clauses in record
11321 representation clauses that leave holes (gaps) in the record layout.
11322 If this warning option is active, then record representation clauses
11323 should specify a contiguous layout, adding unused fill fields if needed.
11326 @geindex -gnatw.H (gcc)
11331 @item @code{-gnatw.H}
11333 @emph{Suppress warnings on holes/gaps in records.}
11335 This switch suppresses warnings on component clauses in record
11336 representation clauses that leave holes (haps) in the record layout.
11339 @geindex -gnatwi (gcc)
11344 @item @code{-gnatwi}
11346 @emph{Activate warnings on implementation units.}
11348 This switch activates warnings for a @emph{with} of an internal GNAT
11349 implementation unit, defined as any unit from the @cite{Ada},
11350 @cite{Interfaces}, @cite{GNAT},
11352 hierarchies that is not
11353 documented in either the Ada Reference Manual or the GNAT
11354 Programmer's Reference Manual. Such units are intended only
11355 for internal implementation purposes and should not be @emph{with}ed
11356 by user programs. The default is that such warnings are generated
11359 @geindex -gnatwI (gcc)
11364 @item @code{-gnatwI}
11366 @emph{Disable warnings on implementation units.}
11368 This switch disables warnings for a @emph{with} of an internal GNAT
11369 implementation unit.
11372 @geindex -gnatw.i (gcc)
11377 @item @code{-gnatw.i}
11379 @emph{Activate warnings on overlapping actuals.}
11381 This switch enables a warning on statically detectable overlapping actuals in
11382 a subprogram call, when one of the actuals is an in-out parameter, and the
11383 types of the actuals are not by-copy types. This warning is off by default.
11386 @geindex -gnatw.I (gcc)
11391 @item @code{-gnatw.I}
11393 @emph{Disable warnings on overlapping actuals.}
11395 This switch disables warnings on overlapping actuals in a call..
11398 @geindex -gnatwj (gcc)
11403 @item @code{-gnatwj}
11405 @emph{Activate warnings on obsolescent features (Annex J).}
11408 @geindex obsolescent
11410 @geindex Obsolescent features
11412 If this warning option is activated, then warnings are generated for
11413 calls to subprograms marked with @cite{pragma Obsolescent} and
11414 for use of features in Annex J of the Ada Reference Manual. In the
11415 case of Annex J, not all features are flagged. In particular use
11416 of the renamed packages (like @cite{Text_IO}) and use of package
11417 @cite{ASCII} are not flagged, since these are very common and
11418 would generate many annoying positive warnings. The default is that
11419 such warnings are not generated.
11421 In addition to the above cases, warnings are also generated for
11422 GNAT features that have been provided in past versions but which
11423 have been superseded (typically by features in the new Ada standard).
11424 For example, @cite{pragma Ravenscar} will be flagged since its
11425 function is replaced by @cite{pragma Profile(Ravenscar)}, and
11426 @cite{pragma Interface_Name} will be flagged since its function
11427 is replaced by @cite{pragma Import}.
11429 Note that this warning option functions differently from the
11430 restriction @cite{No_Obsolescent_Features} in two respects.
11431 First, the restriction applies only to annex J features.
11432 Second, the restriction does flag uses of package @cite{ASCII}.
11435 @geindex -gnatwJ (gcc)
11440 @item @code{-gnatwJ}
11442 @emph{Suppress warnings on obsolescent features (Annex J).}
11444 This switch disables warnings on use of obsolescent features.
11447 @geindex -gnatwk (gcc)
11452 @item @code{-gnatwk}
11454 @emph{Activate warnings on variables that could be constants.}
11456 This switch activates warnings for variables that are initialized but
11457 never modified, and then could be declared constants. The default is that
11458 such warnings are not given.
11461 @geindex -gnatwK (gcc)
11466 @item @code{-gnatwK}
11468 @emph{Suppress warnings on variables that could be constants.}
11470 This switch disables warnings on variables that could be declared constants.
11473 @geindex -gnatw.k (gcc)
11478 @item @code{-gnatw.k}
11480 @emph{Activate warnings on redefinition of names in standard.}
11482 This switch activates warnings for declarations that declare a name that
11483 is defined in package Standard. Such declarations can be confusing,
11484 especially since the names in package Standard continue to be directly
11485 visible, meaning that use visibiliy on such redeclared names does not
11486 work as expected. Names of discriminants and components in records are
11487 not included in this check.
11490 @geindex -gnatwK (gcc)
11495 @item @code{-gnatw.K}
11497 @emph{Suppress warnings on redefinition of names in standard.}
11499 This switch activates warnings for declarations that declare a name that
11500 is defined in package Standard.
11503 @geindex -gnatwl (gcc)
11508 @item @code{-gnatwl}
11510 @emph{Activate warnings for elaboration pragmas.}
11512 @geindex Elaboration
11515 This switch activates warnings for possible elaboration problems,
11516 including suspicious use
11517 of @cite{Elaborate} pragmas, when using the static elaboration model, and
11518 possible situations that may raise @cite{Program_Error} when using the
11519 dynamic elaboration model.
11520 See the section in this guide on elaboration checking for further details.
11521 The default is that such warnings
11525 @geindex -gnatwL (gcc)
11530 @item @code{-gnatwL}
11532 @emph{Suppress warnings for elaboration pragmas.}
11534 This switch suppresses warnings for possible elaboration problems.
11537 @geindex -gnatw.l (gcc)
11542 @item @code{-gnatw.l}
11544 @emph{List inherited aspects.}
11546 This switch causes the compiler to list inherited invariants,
11547 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
11548 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
11551 @geindex -gnatw.L (gcc)
11556 @item @code{-gnatw.L}
11558 @emph{Suppress listing of inherited aspects.}
11560 This switch suppresses listing of inherited aspects.
11563 @geindex -gnatwm (gcc)
11568 @item @code{-gnatwm}
11570 @emph{Activate warnings on modified but unreferenced variables.}
11572 This switch activates warnings for variables that are assigned (using
11573 an initialization value or with one or more assignment statements) but
11574 whose value is never read. The warning is suppressed for volatile
11575 variables and also for variables that are renamings of other variables
11576 or for which an address clause is given.
11577 The default is that these warnings are not given.
11580 @geindex -gnatwM (gcc)
11585 @item @code{-gnatwM}
11587 @emph{Disable warnings on modified but unreferenced variables.}
11589 This switch disables warnings for variables that are assigned or
11590 initialized, but never read.
11593 @geindex -gnatw.m (gcc)
11598 @item @code{-gnatw.m}
11600 @emph{Activate warnings on suspicious modulus values.}
11602 This switch activates warnings for modulus values that seem suspicious.
11603 The cases caught are where the size is the same as the modulus (e.g.
11604 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11605 with no size clause. The guess in both cases is that 2**x was intended
11606 rather than x. In addition expressions of the form 2*x for small x
11607 generate a warning (the almost certainly accurate guess being that
11608 2**x was intended). The default is that these warnings are given.
11611 @geindex -gnatw.M (gcc)
11616 @item @code{-gnatw.M}
11618 @emph{Disable warnings on suspicious modulus values.}
11620 This switch disables warnings for suspicious modulus values.
11623 @geindex -gnatwn (gcc)
11628 @item @code{-gnatwn}
11630 @emph{Set normal warnings mode.}
11632 This switch sets normal warning mode, in which enabled warnings are
11633 issued and treated as warnings rather than errors. This is the default
11634 mode. the switch @emph{-gnatwn} can be used to cancel the effect of
11635 an explicit @emph{-gnatws} or
11636 @emph{-gnatwe}. It also cancels the effect of the
11637 implicit @emph{-gnatwe} that is activated by the
11638 use of @emph{-gnatg}.
11641 @geindex -gnatw.n (gcc)
11643 @geindex Atomic Synchronization
11649 @item @code{-gnatw.n}
11651 @emph{Activate warnings on atomic synchronization.}
11653 This switch actives warnings when an access to an atomic variable
11654 requires the generation of atomic synchronization code. These
11655 warnings are off by default.
11658 @geindex -gnatw.N (gcc)
11663 @item @code{-gnatw.N}
11665 @emph{Suppress warnings on atomic synchronization.}
11667 @geindex Atomic Synchronization
11670 This switch suppresses warnings when an access to an atomic variable
11671 requires the generation of atomic synchronization code.
11674 @geindex -gnatwo (gcc)
11676 @geindex Address Clauses
11682 @item @code{-gnatwo}
11684 @emph{Activate warnings on address clause overlays.}
11686 This switch activates warnings for possibly unintended initialization
11687 effects of defining address clauses that cause one variable to overlap
11688 another. The default is that such warnings are generated.
11691 @geindex -gnatwO (gcc)
11696 @item @code{-gnatwO}
11698 @emph{Suppress warnings on address clause overlays.}
11700 This switch suppresses warnings on possibly unintended initialization
11701 effects of defining address clauses that cause one variable to overlap
11705 @geindex -gnatw.o (gcc)
11710 @item @code{-gnatw.o}
11712 @emph{Activate warnings on modified but unreferenced out parameters.}
11714 This switch activates warnings for variables that are modified by using
11715 them as actuals for a call to a procedure with an out mode formal, where
11716 the resulting assigned value is never read. It is applicable in the case
11717 where there is more than one out mode formal. If there is only one out
11718 mode formal, the warning is issued by default (controlled by -gnatwu).
11719 The warning is suppressed for volatile
11720 variables and also for variables that are renamings of other variables
11721 or for which an address clause is given.
11722 The default is that these warnings are not given.
11725 @geindex -gnatw.O (gcc)
11730 @item @code{-gnatw.O}
11732 @emph{Disable warnings on modified but unreferenced out parameters.}
11734 This switch suppresses warnings for variables that are modified by using
11735 them as actuals for a call to a procedure with an out mode formal, where
11736 the resulting assigned value is never read.
11739 @geindex -gnatwp (gcc)
11747 @item @code{-gnatwp}
11749 @emph{Activate warnings on ineffective pragma Inlines.}
11751 This switch activates warnings for failure of front end inlining
11752 (activated by @emph{-gnatN}) to inline a particular call. There are
11753 many reasons for not being able to inline a call, including most
11754 commonly that the call is too complex to inline. The default is
11755 that such warnings are not given.
11756 Warnings on ineffective inlining by the gcc back-end can be activated
11757 separately, using the gcc switch -Winline.
11760 @geindex -gnatwP (gcc)
11765 @item @code{-gnatwP}
11767 @emph{Suppress warnings on ineffective pragma Inlines.}
11769 This switch suppresses warnings on ineffective pragma Inlines. If the
11770 inlining mechanism cannot inline a call, it will simply ignore the
11774 @geindex -gnatw.p (gcc)
11776 @geindex Parameter order
11782 @item @code{-gnatw.p}
11784 @emph{Activate warnings on parameter ordering.}
11786 This switch activates warnings for cases of suspicious parameter
11787 ordering when the list of arguments are all simple identifiers that
11788 match the names of the formals, but are in a different order. The
11789 warning is suppressed if any use of named parameter notation is used,
11790 so this is the appropriate way to suppress a false positive (and
11791 serves to emphasize that the "misordering" is deliberate). The
11792 default is that such warnings are not given.
11795 @geindex -gnatw.P (gcc)
11800 @item @code{-gnatw.P}
11802 @emph{Suppress warnings on parameter ordering.}
11804 This switch suppresses warnings on cases of suspicious parameter
11808 @geindex -gnatwq (gcc)
11810 @geindex Parentheses
11816 @item @code{-gnatwq}
11818 @emph{Activate warnings on questionable missing parentheses.}
11820 This switch activates warnings for cases where parentheses are not used and
11821 the result is potential ambiguity from a readers point of view. For example
11822 (not a > b) when a and b are modular means ((not a) > b) and very likely the
11823 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11824 quite likely ((-x) mod 5) was intended. In such situations it seems best to
11825 follow the rule of always parenthesizing to make the association clear, and
11826 this warning switch warns if such parentheses are not present. The default
11827 is that these warnings are given.
11830 @geindex -gnatwQ (gcc)
11835 @item @code{-gnatwQ}
11837 @emph{Suppress warnings on questionable missing parentheses.}
11839 This switch suppresses warnings for cases where the association is not
11840 clear and the use of parentheses is preferred.
11843 @geindex -gnatwr (gcc)
11848 @item @code{-gnatwr}
11850 @emph{Activate warnings on redundant constructs.}
11852 This switch activates warnings for redundant constructs. The following
11853 is the current list of constructs regarded as redundant:
11859 Assignment of an item to itself.
11862 Type conversion that converts an expression to its own type.
11865 Use of the attribute @cite{Base} where @cite{typ'Base} is the same
11869 Use of pragma @cite{Pack} when all components are placed by a record
11870 representation clause.
11873 Exception handler containing only a reraise statement (raise with no
11874 operand) which has no effect.
11877 Use of the operator abs on an operand that is known at compile time
11881 Comparison of boolean expressions to an explicit True value.
11884 The default is that warnings for redundant constructs are not given.
11887 @geindex -gnatwR (gcc)
11892 @item @code{-gnatwR}
11894 @emph{Suppress warnings on redundant constructs.}
11896 This switch suppresses warnings for redundant constructs.
11899 @geindex -gnatw.r (gcc)
11904 @item @code{-gnatw.r}
11906 @emph{Activate warnings for object renaming function.}
11908 This switch activates warnings for an object renaming that renames a
11909 function call, which is equivalent to a constant declaration (as
11910 opposed to renaming the function itself). The default is that these
11911 warnings are given.
11914 @geindex -gnatwT (gcc)
11919 @item @code{-gnatw.R}
11921 @emph{Suppress warnings for object renaming function.}
11923 This switch suppresses warnings for object renaming function.
11926 @geindex -gnatws (gcc)
11931 @item @code{-gnatws}
11933 @emph{Suppress all warnings.}
11935 This switch completely suppresses the
11936 output of all warning messages from the GNAT front end, including
11937 both warnings that can be controlled by switches described in this
11938 section, and those that are normally given unconditionally. The
11939 effect of this suppress action can only be cancelled by a subsequent
11940 use of the switch @emph{-gnatwn}.
11942 Note that switch @emph{-gnatws} does not suppress
11943 warnings from the @emph{gcc} back end.
11944 To suppress these back end warnings as well, use the switch @emph{-w}
11945 in addition to @emph{-gnatws}. Also this switch has no effect on the
11946 handling of style check messages.
11949 @geindex -gnatw.s (gcc)
11951 @geindex Record Representation (component sizes)
11956 @item @code{-gnatw.s}
11958 @emph{Activate warnings on overridden size clauses.}
11960 This switch activates warnings on component clauses in record
11961 representation clauses where the length given overrides that
11962 specified by an explicit size clause for the component type. A
11963 warning is similarly given in the array case if a specified
11964 component size overrides an explicit size clause for the array
11968 @geindex -gnatw.S (gcc)
11973 @item @code{-gnatw.S}
11975 @emph{Suppress warnings on overridden size clauses.}
11977 This switch suppresses warnings on component clauses in record
11978 representation clauses that override size clauses, and similar
11979 warnings when an array component size overrides a size clause.
11982 @geindex -gnatwt (gcc)
11984 @geindex Deactivated code
11987 @geindex Deleted code
11993 @item @code{-gnatwt}
11995 @emph{Activate warnings for tracking of deleted conditional code.}
11997 This switch activates warnings for tracking of code in conditionals (IF and
11998 CASE statements) that is detected to be dead code which cannot be executed, and
11999 which is removed by the front end. This warning is off by default. This may be
12000 useful for detecting deactivated code in certified applications.
12003 @geindex -gnatwT (gcc)
12008 @item @code{-gnatwT}
12010 @emph{Suppress warnings for tracking of deleted conditional code.}
12012 This switch suppresses warnings for tracking of deleted conditional code.
12015 @geindex -gnatw.t (gcc)
12020 @item @code{-gnatw.t}
12022 @emph{Activate warnings on suspicious contracts.}
12024 This switch activates warnings on suspicious contracts. This includes
12025 warnings on suspicious postconditions (whether a pragma @cite{Postcondition} or a
12026 @cite{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
12027 @cite{Contract_Cases}). A function postcondition or contract case is suspicious
12028 when no postcondition or contract case for this function mentions the result
12029 of the function. A procedure postcondition or contract case is suspicious
12030 when it only refers to the pre-state of the procedure, because in that case
12031 it should rather be expressed as a precondition. This switch also controls
12032 warnings on suspicious cases of expressions typically found in contracts like
12033 quantified expressions and uses of Update attribute. The default is that such
12034 warnings are generated.
12037 @geindex -gnatw.T (gcc)
12042 @item @code{-gnatw.T}
12044 @emph{Suppress warnings on suspicious contracts.}
12046 This switch suppresses warnings on suspicious contracts.
12049 @geindex -gnatwu (gcc)
12054 @item @code{-gnatwu}
12056 @emph{Activate warnings on unused entities.}
12058 This switch activates warnings to be generated for entities that
12059 are declared but not referenced, and for units that are @emph{with}ed
12061 referenced. In the case of packages, a warning is also generated if
12062 no entities in the package are referenced. This means that if a with'ed
12063 package is referenced but the only references are in @cite{use}
12064 clauses or @cite{renames}
12065 declarations, a warning is still generated. A warning is also generated
12066 for a generic package that is @emph{with}ed but never instantiated.
12067 In the case where a package or subprogram body is compiled, and there
12068 is a @emph{with} on the corresponding spec
12069 that is only referenced in the body,
12070 a warning is also generated, noting that the
12071 @emph{with} can be moved to the body. The default is that
12072 such warnings are not generated.
12073 This switch also activates warnings on unreferenced formals
12074 (it includes the effect of @emph{-gnatwf}).
12077 @geindex -gnatwU (gcc)
12082 @item @code{-gnatwU}
12084 @emph{Suppress warnings on unused entities.}
12086 This switch suppresses warnings for unused entities and packages.
12087 It also turns off warnings on unreferenced formals (and thus includes
12088 the effect of @emph{-gnatwF}).
12091 @geindex -gnatw.u (gcc)
12096 @item @code{-gnatw.u}
12098 @emph{Activate warnings on unordered enumeration types.}
12100 This switch causes enumeration types to be considered as conceptually
12101 unordered, unless an explicit pragma @cite{Ordered} is given for the type.
12102 The effect is to generate warnings in clients that use explicit comparisons
12103 or subranges, since these constructs both treat objects of the type as
12104 ordered. (A @emph{client} is defined as a unit that is other than the unit in
12105 which the type is declared, or its body or subunits.) Please refer to
12106 the description of pragma @cite{Ordered} in the
12107 @cite{GNAT Reference Manual} for further details.
12108 The default is that such warnings are not generated.
12111 @geindex -gnatw.U (gcc)
12116 @item @code{-gnatw.U}
12118 @emph{Deactivate warnings on unordered enumeration types.}
12120 This switch causes all enumeration types to be considered as ordered, so
12121 that no warnings are given for comparisons or subranges for any type.
12124 @geindex -gnatwv (gcc)
12126 @geindex Unassigned variable warnings
12131 @item @code{-gnatwv}
12133 @emph{Activate warnings on unassigned variables.}
12135 This switch activates warnings for access to variables which
12136 may not be properly initialized. The default is that
12137 such warnings are generated.
12140 @geindex -gnatwV (gcc)
12145 @item @code{-gnatwV}
12147 @emph{Suppress warnings on unassigned variables.}
12149 This switch suppresses warnings for access to variables which
12150 may not be properly initialized.
12151 For variables of a composite type, the warning can also be suppressed in
12152 Ada 2005 by using a default initialization with a box. For example, if
12153 Table is an array of records whose components are only partially uninitialized,
12154 then the following code:
12157 Tab : Table := (others => <>);
12160 will suppress warnings on subsequent statements that access components
12164 @geindex -gnatw.v (gcc)
12166 @geindex bit order warnings
12171 @item @code{-gnatw.v}
12173 @emph{Activate info messages for non-default bit order.}
12175 This switch activates messages (labeled "info", they are not warnings,
12176 just informational messages) about the effects of non-default bit-order
12177 on records to which a component clause is applied. The effect of specifying
12178 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12179 these messages, which are given by default, are useful in understanding the
12180 exact consequences of using this feature.
12183 @geindex -gnatw.V (gcc)
12188 @item @code{-gnatw.V}
12190 @emph{Suppress info messages for non-default bit order.}
12192 This switch suppresses information messages for the effects of specifying
12193 non-default bit order on record components with component clauses.
12196 @geindex -gnatww (gcc)
12198 @geindex String indexing warnings
12203 @item @code{-gnatww}
12205 @emph{Activate warnings on wrong low bound assumption.}
12207 This switch activates warnings for indexing an unconstrained string parameter
12208 with a literal or S'Length. This is a case where the code is assuming that the
12209 low bound is one, which is in general not true (for example when a slice is
12210 passed). The default is that such warnings are generated.
12213 @geindex -gnatwW (gcc)
12218 @item @code{-gnatwW}
12220 @emph{Suppress warnings on wrong low bound assumption.}
12222 This switch suppresses warnings for indexing an unconstrained string parameter
12223 with a literal or S'Length. Note that this warning can also be suppressed
12224 in a particular case by adding an assertion that the lower bound is 1,
12225 as shown in the following example:
12228 procedure K (S : String) is
12229 pragma Assert (S'First = 1);
12234 @geindex -gnatw.w (gcc)
12236 @geindex Warnings Off control
12241 @item @code{-gnatw.w}
12243 @emph{Activate warnings on Warnings Off pragmas.}
12245 This switch activates warnings for use of @cite{pragma Warnings (Off@comma{} entity)}
12246 where either the pragma is entirely useless (because it suppresses no
12247 warnings), or it could be replaced by @cite{pragma Unreferenced} or
12248 @cite{pragma Unmodified}.
12249 Also activates warnings for the case of
12250 Warnings (Off, String), where either there is no matching
12251 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12252 The default is that these warnings are not given.
12255 @geindex -gnatw.W (gcc)
12260 @item @code{-gnatw.W}
12262 @emph{Suppress warnings on unnecessary Warnings Off pragmas.}
12264 This switch suppresses warnings for use of @cite{pragma Warnings (Off@comma{} ...)}.
12267 @geindex -gnatwx (gcc)
12269 @geindex Export/Import pragma warnings
12274 @item @code{-gnatwx}
12276 @emph{Activate warnings on Export/Import pragmas.}
12278 This switch activates warnings on Export/Import pragmas when
12279 the compiler detects a possible conflict between the Ada and
12280 foreign language calling sequences. For example, the use of
12281 default parameters in a convention C procedure is dubious
12282 because the C compiler cannot supply the proper default, so
12283 a warning is issued. The default is that such warnings are
12287 @geindex -gnatwX (gcc)
12292 @item @code{-gnatwX}
12294 @emph{Suppress warnings on Export/Import pragmas.}
12296 This switch suppresses warnings on Export/Import pragmas.
12297 The sense of this is that you are telling the compiler that
12298 you know what you are doing in writing the pragma, and it
12299 should not complain at you.
12302 @geindex -gnatwm (gcc)
12307 @item @code{-gnatw.x}
12309 @emph{Activate warnings for No_Exception_Propagation mode.}
12311 This switch activates warnings for exception usage when pragma Restrictions
12312 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
12313 explicit exception raises which are not covered by a local handler, and for
12314 exception handlers which do not cover a local raise. The default is that these
12315 warnings are not given.
12317 @item @code{-gnatw.X}
12319 @emph{Disable warnings for No_Exception_Propagation mode.}
12321 This switch disables warnings for exception usage when pragma Restrictions
12322 (No_Exception_Propagation) is in effect.
12325 @geindex -gnatwy (gcc)
12327 @geindex Ada compatibility issues warnings
12332 @item @code{-gnatwy}
12334 @emph{Activate warnings for Ada compatibility issues.}
12336 For the most part, newer versions of Ada are upwards compatible
12337 with older versions. For example, Ada 2005 programs will almost
12338 always work when compiled as Ada 2012.
12339 However there are some exceptions (for example the fact that
12340 @cite{some} is now a reserved word in Ada 2012). This
12341 switch activates several warnings to help in identifying
12342 and correcting such incompatibilities. The default is that
12343 these warnings are generated. Note that at one point Ada 2005
12344 was called Ada 0Y, hence the choice of character.
12347 @geindex -gnatwY (gcc)
12349 @geindex Ada compatibility issues warnings
12354 @item @code{-gnatwY}
12356 @emph{Disable warnings for Ada compatibility issues.}
12358 This switch suppresses the warnings intended to help in identifying
12359 incompatibilities between Ada language versions.
12362 @geindex -gnatw.y (gcc)
12364 @geindex Package spec needing body
12369 @item @code{-gnatw.y}
12371 @emph{Activate information messages for why package spec needs body.}
12373 There are a number of cases in which a package spec needs a body.
12374 For example, the use of pragma Elaborate_Body, or the declaration
12375 of a procedure specification requiring a completion. This switch
12376 causes information messages to be output showing why a package
12377 specification requires a body. This can be useful in the case of
12378 a large package specification which is unexpectedly requiring a
12379 body. The default is that such information messages are not output.
12382 @geindex -gnatw.Y (gcc)
12384 @geindex No information messages for why package spec needs body
12389 @item @code{-gnatw.Y}
12391 @emph{Disable information messages for why package spec needs body.}
12393 This switch suppresses the output of information messages showing why
12394 a package specification needs a body.
12397 @geindex -gnatwz (gcc)
12399 @geindex Unchecked_Conversion warnings
12404 @item @code{-gnatwz}
12406 @emph{Activate warnings on unchecked conversions.}
12408 This switch activates warnings for unchecked conversions
12409 where the types are known at compile time to have different
12410 sizes. The default is that such warnings are generated. Warnings are also
12411 generated for subprogram pointers with different conventions.
12414 @geindex -gnatwZ (gcc)
12419 @item @code{-gnatwZ}
12421 @emph{Suppress warnings on unchecked conversions.}
12423 This switch suppresses warnings for unchecked conversions
12424 where the types are known at compile time to have different
12425 sizes or conventions.
12428 @geindex -gnatw.z (gcc)
12430 @geindex Size/Alignment warnings
12435 @item @code{-gnatw.z}
12437 @emph{Activate warnings for size not a multiple of alignment.}
12439 This switch activates warnings for cases of record types with
12440 specified @cite{Size} and @cite{Alignment} attributes where the
12441 size is not a multiple of the alignment, resulting in an object
12442 size that is greater than the specified size. The default
12443 is that such warnings are generated.
12446 @geindex -gnatw.Z (gcc)
12448 @geindex Size/Alignment warnings
12453 @item @code{-gnatw.Z}
12455 @emph{Suppress warnings for size not a multiple of alignment.}
12457 This switch suppresses warnings for cases of record types with
12458 specified @cite{Size} and @cite{Alignment} attributes where the
12459 size is not a multiple of the alignment, resulting in an object
12460 size that is greater than the specified size.
12461 The warning can also be
12462 suppressed by giving an explicit @cite{Object_Size} value.
12465 @geindex -Wunused (gcc)
12470 @item @code{-Wunused}
12472 The warnings controlled by the @emph{-gnatw} switch are generated by
12473 the front end of the compiler. The @emph{GCC} back end can provide
12474 additional warnings and they are controlled by the @emph{-W} switch.
12475 For example, @emph{-Wunused} activates back end
12476 warnings for entities that are declared but not referenced.
12479 @geindex -Wuninitialized (gcc)
12484 @item @code{-Wuninitialized}
12486 Similarly, @emph{-Wuninitialized} activates
12487 the back end warning for uninitialized variables. This switch must be
12488 used in conjunction with an optimization level greater than zero.
12491 @geindex -Wstack-usage (gcc)
12496 @item @code{-Wstack-usage=@emph{len}}
12498 Warn if the stack usage of a subprogram might be larger than @cite{len} bytes.
12499 See @ref{fd,,Static Stack Usage Analysis} for details.
12502 @geindex -Wall (gcc)
12509 This switch enables most warnings from the @emph{GCC} back end.
12510 The code generator detects a number of warning situations that are missed
12511 by the @emph{GNAT} front end, and this switch can be used to activate them.
12512 The use of this switch also sets the default front end warning mode to
12513 @emph{-gnatwa}, that is, most front end warnings activated as well.
12523 Conversely, this switch suppresses warnings from the @emph{GCC} back end.
12524 The use of this switch also sets the default front end warning mode to
12525 @emph{-gnatws}, that is, front end warnings suppressed as well.
12528 @geindex -Werror (gcc)
12533 @item @code{-Werror}
12535 This switch causes warnings from the @emph{GCC} back end to be treated as
12536 errors. The warning string still appears, but the warning messages are
12537 counted as errors, and prevent the generation of an object file.
12540 A string of warning parameters can be used in the same parameter. For example:
12546 will turn on all optional warnings except for unrecognized pragma warnings,
12547 and also specify that warnings should be treated as errors.
12549 When no switch @emph{-gnatw} is used, this is equivalent to:
12666 @node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12667 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-and-assertion-control}@anchor{108}@anchor{gnat_ugn/building_executable_programs_with_gnat id16}@anchor{109}
12668 @subsection Debugging and Assertion Control
12671 @geindex -gnata (gcc)
12676 @item @code{-gnata}
12682 @geindex Assertions
12684 @geindex Precondition
12686 @geindex Postcondition
12688 @geindex Type invariants
12690 @geindex Subtype predicates
12692 The @cite{-gnata} option is equivalent to the following Assertion_Policy pragma:
12695 pragma Assertion_Policy (Check);
12698 Which is a shorthand for:
12701 pragma Assertion_Policy
12703 Static_Predicate => Check,
12704 Dynamic_Predicate => Check,
12706 Pre'Class => Check,
12708 Post'Class => Check,
12709 Type_Invariant => Check,
12710 Type_Invariant'Class => Check);
12713 The pragmas @cite{Assert} and @cite{Debug} normally have no effect and
12714 are ignored. This switch, where @code{a} stands for assert, causes
12715 pragmas @cite{Assert} and @cite{Debug} to be activated. This switch also
12716 causes preconditions, postconditions, subtype predicates, and
12717 type invariants to be activated.
12719 The pragmas have the form:
12722 pragma Assert (<Boolean-expression> [, <static-string-expression>])
12723 pragma Debug (<procedure call>)
12724 pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
12725 pragma Predicate (<type-local-name>, <Boolean-expression>)
12726 pragma Precondition (<Boolean-expression>, <string-expression>)
12727 pragma Postcondition (<Boolean-expression>, <string-expression>)
12730 The aspects have the form:
12733 with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
12734 => <Boolean-expression>;
12737 The @cite{Assert} pragma causes @cite{Boolean-expression} to be tested.
12738 If the result is @cite{True}, the pragma has no effect (other than
12739 possible side effects from evaluating the expression). If the result is
12740 @cite{False}, the exception @cite{Assert_Failure} declared in the package
12741 @cite{System.Assertions} is raised (passing @cite{static-string-expression}, if
12742 present, as the message associated with the exception). If no string
12743 expression is given, the default is a string containing the file name and
12744 line number of the pragma.
12746 The @cite{Debug} pragma causes @cite{procedure} to be called. Note that
12747 @cite{pragma Debug} may appear within a declaration sequence, allowing
12748 debugging procedures to be called between declarations.
12750 For the aspect specification, the @cite{<Boolean-expression>} is evaluated.
12751 If the result is @cite{True}, the aspect has no effect. If the result
12752 is @cite{False}, the exception @cite{Assert_Failure} is raised.
12755 @node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
12756 @anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{fe}@anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{10a}
12757 @subsection Validity Checking
12760 @geindex Validity Checking
12762 The Ada Reference Manual defines the concept of invalid values (see
12763 RM 13.9.1). The primary source of invalid values is uninitialized
12764 variables. A scalar variable that is left uninitialized may contain
12765 an invalid value; the concept of invalid does not apply to access or
12768 It is an error to read an invalid value, but the RM does not require
12769 run-time checks to detect such errors, except for some minimal
12770 checking to prevent erroneous execution (i.e. unpredictable
12771 behavior). This corresponds to the @emph{-gnatVd} switch below,
12772 which is the default. For example, by default, if the expression of a
12773 case statement is invalid, it will raise Constraint_Error rather than
12774 causing a wild jump, and if an array index on the left-hand side of an
12775 assignment is invalid, it will raise Constraint_Error rather than
12776 overwriting an arbitrary memory location.
12778 The @emph{-gnatVa} may be used to enable additional validity checks,
12779 which are not required by the RM. These checks are often very
12780 expensive (which is why the RM does not require them). These checks
12781 are useful in tracking down uninitialized variables, but they are
12782 not usually recommended for production builds, and in particular
12783 we do not recommend using these extra validity checking options in
12784 combination with optimization, since this can confuse the optimizer.
12785 If performance is a consideration, leading to the need to optimize,
12786 then the validity checking options should not be used.
12788 The other @emph{-gnatV}@code{x} switches below allow finer-grained
12789 control; you can enable whichever validity checks you desire. However,
12790 for most debugging purposes, @emph{-gnatVa} is sufficient, and the
12791 default @emph{-gnatVd} (i.e. standard Ada behavior) is usually
12792 sufficient for non-debugging use.
12794 The @emph{-gnatB} switch tells the compiler to assume that all
12795 values are valid (that is, within their declared subtype range)
12796 except in the context of a use of the Valid attribute. This means
12797 the compiler can generate more efficient code, since the range
12798 of values is better known at compile time. However, an uninitialized
12799 variable can cause wild jumps and memory corruption in this mode.
12801 The @emph{-gnatV}@code{x} switch allows control over the validity
12802 checking mode as described below.
12803 The @code{x} argument is a string of letters that
12804 indicate validity checks that are performed or not performed in addition
12805 to the default checks required by Ada as described above.
12807 @geindex -gnatVa (gcc)
12812 @item @code{-gnatVa}
12814 @emph{All validity checks.}
12816 All validity checks are turned on.
12817 That is, @emph{-gnatVa} is
12818 equivalent to @emph{gnatVcdfimorst}.
12821 @geindex -gnatVc (gcc)
12826 @item @code{-gnatVc}
12828 @emph{Validity checks for copies.}
12830 The right hand side of assignments, and the initializing values of
12831 object declarations are validity checked.
12834 @geindex -gnatVd (gcc)
12839 @item @code{-gnatVd}
12841 @emph{Default (RM) validity checks.}
12843 Some validity checks are done by default following normal Ada semantics
12844 (RM 13.9.1 (9-11)).
12845 A check is done in case statements that the expression is within the range
12846 of the subtype. If it is not, Constraint_Error is raised.
12847 For assignments to array components, a check is done that the expression used
12848 as index is within the range. If it is not, Constraint_Error is raised.
12849 Both these validity checks may be turned off using switch @emph{-gnatVD}.
12850 They are turned on by default. If @emph{-gnatVD} is specified, a subsequent
12851 switch @emph{-gnatVd} will leave the checks turned on.
12852 Switch @emph{-gnatVD} should be used only if you are sure that all such
12853 expressions have valid values. If you use this switch and invalid values
12854 are present, then the program is erroneous, and wild jumps or memory
12855 overwriting may occur.
12858 @geindex -gnatVe (gcc)
12863 @item @code{-gnatVe}
12865 @emph{Validity checks for elementary components.}
12867 In the absence of this switch, assignments to record or array components are
12868 not validity checked, even if validity checks for assignments generally
12869 (@emph{-gnatVc}) are turned on. In Ada, assignment of composite values do not
12870 require valid data, but assignment of individual components does. So for
12871 example, there is a difference between copying the elements of an array with a
12872 slice assignment, compared to assigning element by element in a loop. This
12873 switch allows you to turn off validity checking for components, even when they
12874 are assigned component by component.
12877 @geindex -gnatVf (gcc)
12882 @item @code{-gnatVf}
12884 @emph{Validity checks for floating-point values.}
12886 In the absence of this switch, validity checking occurs only for discrete
12887 values. If @emph{-gnatVf} is specified, then validity checking also applies
12888 for floating-point values, and NaNs and infinities are considered invalid,
12889 as well as out of range values for constrained types. Note that this means
12890 that standard IEEE infinity mode is not allowed. The exact contexts
12891 in which floating-point values are checked depends on the setting of other
12892 options. For example, @emph{-gnatVif} or @emph{-gnatVfi}
12893 (the order does not matter) specifies that floating-point parameters of mode
12894 @cite{in} should be validity checked.
12897 @geindex -gnatVi (gcc)
12902 @item @code{-gnatVi}
12904 @emph{Validity checks for `in` mode parameters.}
12906 Arguments for parameters of mode @cite{in} are validity checked in function
12907 and procedure calls at the point of call.
12910 @geindex -gnatVm (gcc)
12915 @item @code{-gnatVm}
12917 @emph{Validity checks for `in out` mode parameters.}
12919 Arguments for parameters of mode @cite{in out} are validity checked in
12920 procedure calls at the point of call. The @cite{'m'} here stands for
12921 modify, since this concerns parameters that can be modified by the call.
12922 Note that there is no specific option to test @cite{out} parameters,
12923 but any reference within the subprogram will be tested in the usual
12924 manner, and if an invalid value is copied back, any reference to it
12925 will be subject to validity checking.
12928 @geindex -gnatVn (gcc)
12933 @item @code{-gnatVn}
12935 @emph{No validity checks.}
12937 This switch turns off all validity checking, including the default checking
12938 for case statements and left hand side subscripts. Note that the use of
12939 the switch @emph{-gnatp} suppresses all run-time checks, including
12940 validity checks, and thus implies @emph{-gnatVn}. When this switch
12941 is used, it cancels any other @emph{-gnatV} previously issued.
12944 @geindex -gnatVo (gcc)
12949 @item @code{-gnatVo}
12951 @emph{Validity checks for operator and attribute operands.}
12953 Arguments for predefined operators and attributes are validity checked.
12954 This includes all operators in package @cite{Standard},
12955 the shift operators defined as intrinsic in package @cite{Interfaces}
12956 and operands for attributes such as @cite{Pos}. Checks are also made
12957 on individual component values for composite comparisons, and on the
12958 expressions in type conversions and qualified expressions. Checks are
12959 also made on explicit ranges using @code{..} (e.g., slices, loops etc).
12962 @geindex -gnatVp (gcc)
12967 @item @code{-gnatVp}
12969 @emph{Validity checks for parameters.}
12971 This controls the treatment of parameters within a subprogram (as opposed
12972 to @emph{-gnatVi} and @emph{-gnatVm} which control validity testing
12973 of parameters on a call. If either of these call options is used, then
12974 normally an assumption is made within a subprogram that the input arguments
12975 have been validity checking at the point of call, and do not need checking
12976 again within a subprogram). If @emph{-gnatVp} is set, then this assumption
12977 is not made, and parameters are not assumed to be valid, so their validity
12978 will be checked (or rechecked) within the subprogram.
12981 @geindex -gnatVr (gcc)
12986 @item @code{-gnatVr}
12988 @emph{Validity checks for function returns.}
12990 The expression in @cite{return} statements in functions is validity
12994 @geindex -gnatVs (gcc)
12999 @item @code{-gnatVs}
13001 @emph{Validity checks for subscripts.}
13003 All subscripts expressions are checked for validity, whether they appear
13004 on the right side or left side (in default mode only left side subscripts
13005 are validity checked).
13008 @geindex -gnatVt (gcc)
13013 @item @code{-gnatVt}
13015 @emph{Validity checks for tests.}
13017 Expressions used as conditions in @cite{if}, @cite{while} or @cite{exit}
13018 statements are checked, as well as guard expressions in entry calls.
13021 The @emph{-gnatV} switch may be followed by a string of letters
13022 to turn on a series of validity checking options.
13023 For example, @code{-gnatVcr}
13024 specifies that in addition to the default validity checking, copies and
13025 function return expressions are to be validity checked.
13026 In order to make it easier to specify the desired combination of effects,
13027 the upper case letters @cite{CDFIMORST} may
13028 be used to turn off the corresponding lower case option.
13029 Thus @code{-gnatVaM} turns on all validity checking options except for
13030 checking of @cite{**in out**} procedure arguments.
13032 The specification of additional validity checking generates extra code (and
13033 in the case of @emph{-gnatVa} the code expansion can be substantial).
13034 However, these additional checks can be very useful in detecting
13035 uninitialized variables, incorrect use of unchecked conversion, and other
13036 errors leading to invalid values. The use of pragma @cite{Initialize_Scalars}
13037 is useful in conjunction with the extra validity checking, since this
13038 ensures that wherever possible uninitialized variables have invalid values.
13040 See also the pragma @cite{Validity_Checks} which allows modification of
13041 the validity checking mode at the program source level, and also allows for
13042 temporary disabling of validity checks.
13044 @node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
13045 @anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{10b}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{103}
13046 @subsection Style Checking
13049 @geindex Style checking
13051 @geindex -gnaty (gcc)
13053 The @emph{-gnatyx} switch causes the compiler to
13054 enforce specified style rules. A limited set of style rules has been used
13055 in writing the GNAT sources themselves. This switch allows user programs
13056 to activate all or some of these checks. If the source program fails a
13057 specified style check, an appropriate message is given, preceded by
13058 the character sequence '(style)'. This message does not prevent
13059 successful compilation (unless the @emph{-gnatwe} switch is used).
13061 Note that this is by no means intended to be a general facility for
13062 checking arbitrary coding standards. It is simply an embedding of the
13063 style rules we have chosen for the GNAT sources. If you are starting
13064 a project which does not have established style standards, you may
13065 find it useful to adopt the entire set of GNAT coding standards, or
13066 some subset of them.
13069 The string @cite{x} is a sequence of letters or digits
13070 indicating the particular style
13071 checks to be performed. The following checks are defined:
13073 @geindex -gnaty[0-9] (gcc)
13078 @item @code{-gnaty0}
13080 @emph{Specify indentation level.}
13082 If a digit from 1-9 appears
13083 in the string after @emph{-gnaty}
13084 then proper indentation is checked, with the digit indicating the
13085 indentation level required. A value of zero turns off this style check.
13086 The general style of required indentation is as specified by
13087 the examples in the Ada Reference Manual. Full line comments must be
13088 aligned with the @cite{--} starting on a column that is a multiple of
13089 the alignment level, or they may be aligned the same way as the following
13090 non-blank line (this is useful when full line comments appear in the middle
13091 of a statement, or they may be aligned with the source line on the previous
13095 @geindex -gnatya (gcc)
13100 @item @code{-gnatya}
13102 @emph{Check attribute casing.}
13104 Attribute names, including the case of keywords such as @cite{digits}
13105 used as attributes names, must be written in mixed case, that is, the
13106 initial letter and any letter following an underscore must be uppercase.
13107 All other letters must be lowercase.
13110 @geindex -gnatyA (gcc)
13115 @item @code{-gnatyA}
13117 @emph{Use of array index numbers in array attributes.}
13119 When using the array attributes First, Last, Range,
13120 or Length, the index number must be omitted for one-dimensional arrays
13121 and is required for multi-dimensional arrays.
13124 @geindex -gnatyb (gcc)
13129 @item @code{-gnatyb}
13131 @emph{Blanks not allowed at statement end.}
13133 Trailing blanks are not allowed at the end of statements. The purpose of this
13134 rule, together with h (no horizontal tabs), is to enforce a canonical format
13135 for the use of blanks to separate source tokens.
13138 @geindex -gnatyB (gcc)
13143 @item @code{-gnatyB}
13145 @emph{Check Boolean operators.}
13147 The use of AND/OR operators is not permitted except in the cases of modular
13148 operands, array operands, and simple stand-alone boolean variables or
13149 boolean constants. In all other cases @cite{and then}/@cite{or else} are
13153 @geindex -gnatyc (gcc)
13158 @item @code{-gnatyc}
13160 @emph{Check comments, double space.}
13162 Comments must meet the following set of rules:
13168 The '@cite{--}' that starts the column must either start in column one,
13169 or else at least one blank must precede this sequence.
13172 Comments that follow other tokens on a line must have at least one blank
13173 following the '@cite{--}' at the start of the comment.
13176 Full line comments must have at least two blanks following the
13177 '@cite{--}' that starts the comment, with the following exceptions.
13180 A line consisting only of the '@cite{--}' characters, possibly preceded
13181 by blanks is permitted.
13184 A comment starting with '@cite{--x}' where @cite{x} is a special character
13186 This allows proper processing of the output generated by specialized tools
13187 including @emph{gnatprep} (where '@cite{--!}' is used) and the SPARK
13189 language (where '@cite{--#}' is used). For the purposes of this rule, a
13190 special character is defined as being in one of the ASCII ranges
13191 @cite{16#21#...16#2F#} or @cite{16#3A#...16#3F#}.
13192 Note that this usage is not permitted
13193 in GNAT implementation units (i.e., when @emph{-gnatg} is used).
13196 A line consisting entirely of minus signs, possibly preceded by blanks, is
13197 permitted. This allows the construction of box comments where lines of minus
13198 signs are used to form the top and bottom of the box.
13201 A comment that starts and ends with '@cite{--}' is permitted as long as at
13202 least one blank follows the initial '@cite{--}'. Together with the preceding
13203 rule, this allows the construction of box comments, as shown in the following
13207 ---------------------------
13208 -- This is a box comment --
13209 -- with two text lines. --
13210 ---------------------------
13215 @geindex -gnatyC (gcc)
13220 @item @code{-gnatyC}
13222 @emph{Check comments, single space.}
13224 This is identical to @cite{c} except that only one space
13225 is required following the @cite{--} of a comment instead of two.
13228 @geindex -gnatyd (gcc)
13233 @item @code{-gnatyd}
13235 @emph{Check no DOS line terminators present.}
13237 All lines must be terminated by a single ASCII.LF
13238 character (in particular the DOS line terminator sequence CR/LF is not
13242 @geindex -gnatye (gcc)
13247 @item @code{-gnatye}
13249 @emph{Check end/exit labels.}
13251 Optional labels on @cite{end} statements ending subprograms and on
13252 @cite{exit} statements exiting named loops, are required to be present.
13255 @geindex -gnatyf (gcc)
13260 @item @code{-gnatyf}
13262 @emph{No form feeds or vertical tabs.}
13264 Neither form feeds nor vertical tab characters are permitted
13265 in the source text.
13268 @geindex -gnatyg (gcc)
13273 @item @code{-gnatyg}
13275 @emph{GNAT style mode.}
13277 The set of style check switches is set to match that used by the GNAT sources.
13278 This may be useful when developing code that is eventually intended to be
13279 incorporated into GNAT. Currently this is equivalent to @emph{-gnatwydISux})
13280 but additional style switches may be added to this set in the future without
13284 @geindex -gnatyh (gcc)
13289 @item @code{-gnatyh}
13291 @emph{No horizontal tabs.}
13293 Horizontal tab characters are not permitted in the source text.
13294 Together with the b (no blanks at end of line) check, this
13295 enforces a canonical form for the use of blanks to separate
13299 @geindex -gnatyi (gcc)
13304 @item @code{-gnatyi}
13306 @emph{Check if-then layout.}
13308 The keyword @cite{then} must appear either on the same
13309 line as corresponding @cite{if}, or on a line on its own, lined
13310 up under the @cite{if}.
13313 @geindex -gnatyI (gcc)
13318 @item @code{-gnatyI}
13320 @emph{check mode IN keywords.}
13322 Mode @cite{in} (the default mode) is not
13323 allowed to be given explicitly. @cite{in out} is fine,
13324 but not @cite{in} on its own.
13327 @geindex -gnatyk (gcc)
13332 @item @code{-gnatyk}
13334 @emph{Check keyword casing.}
13336 All keywords must be in lower case (with the exception of keywords
13337 such as @cite{digits} used as attribute names to which this check
13341 @geindex -gnatyl (gcc)
13346 @item @code{-gnatyl}
13348 @emph{Check layout.}
13350 Layout of statement and declaration constructs must follow the
13351 recommendations in the Ada Reference Manual, as indicated by the
13352 form of the syntax rules. For example an @cite{else} keyword must
13353 be lined up with the corresponding @cite{if} keyword.
13355 There are two respects in which the style rule enforced by this check
13356 option are more liberal than those in the Ada Reference Manual. First
13357 in the case of record declarations, it is permissible to put the
13358 @cite{record} keyword on the same line as the @cite{type} keyword, and
13359 then the @cite{end} in @cite{end record} must line up under @cite{type}.
13360 This is also permitted when the type declaration is split on two lines.
13361 For example, any of the following three layouts is acceptable:
13382 Second, in the case of a block statement, a permitted alternative
13383 is to put the block label on the same line as the @cite{declare} or
13384 @cite{begin} keyword, and then line the @cite{end} keyword up under
13385 the block label. For example both the following are permitted:
13402 The same alternative format is allowed for loops. For example, both of
13403 the following are permitted:
13406 Clear : while J < 10 loop
13417 @geindex -gnatyLnnn (gcc)
13422 @item @code{-gnatyL}
13424 @emph{Set maximum nesting level.}
13426 The maximum level of nesting of constructs (including subprograms, loops,
13427 blocks, packages, and conditionals) may not exceed the given value
13428 @emph{nnn}. A value of zero disconnects this style check.
13431 @geindex -gnatym (gcc)
13436 @item @code{-gnatym}
13438 @emph{Check maximum line length.}
13440 The length of source lines must not exceed 79 characters, including
13441 any trailing blanks. The value of 79 allows convenient display on an
13442 80 character wide device or window, allowing for possible special
13443 treatment of 80 character lines. Note that this count is of
13444 characters in the source text. This means that a tab character counts
13445 as one character in this count and a wide character sequence counts as
13446 a single character (however many bytes are needed in the encoding).
13449 @geindex -gnatyMnnn (gcc)
13454 @item @code{-gnatyM}
13456 @emph{Set maximum line length.}
13458 The length of lines must not exceed the
13459 given value @emph{nnn}. The maximum value that can be specified is 32767.
13460 If neither style option for setting the line length is used, then the
13461 default is 255. This also controls the maximum length of lexical elements,
13462 where the only restriction is that they must fit on a single line.
13465 @geindex -gnatyn (gcc)
13470 @item @code{-gnatyn}
13472 @emph{Check casing of entities in Standard.}
13474 Any identifier from Standard must be cased
13475 to match the presentation in the Ada Reference Manual (for example,
13476 @cite{Integer} and @cite{ASCII.NUL}).
13479 @geindex -gnatyN (gcc)
13484 @item @code{-gnatyN}
13486 @emph{Turn off all style checks.}
13488 All style check options are turned off.
13491 @geindex -gnatyo (gcc)
13496 @item @code{-gnatyo}
13498 @emph{Check order of subprogram bodies.}
13500 All subprogram bodies in a given scope
13501 (e.g., a package body) must be in alphabetical order. The ordering
13502 rule uses normal Ada rules for comparing strings, ignoring casing
13503 of letters, except that if there is a trailing numeric suffix, then
13504 the value of this suffix is used in the ordering (e.g., Junk2 comes
13508 @geindex -gnatyO (gcc)
13513 @item @code{-gnatyO}
13515 @emph{Check that overriding subprograms are explicitly marked as such.}
13517 This applies to all subprograms of a derived type that override a primitive
13518 operation of the type, for both tagged and untagged types. In particular,
13519 the declaration of a primitive operation of a type extension that overrides
13520 an inherited operation must carry an overriding indicator. Another case is
13521 the declaration of a function that overrides a predefined operator (such
13522 as an equality operator).
13525 @geindex -gnatyp (gcc)
13530 @item @code{-gnatyp}
13532 @emph{Check pragma casing.}
13534 Pragma names must be written in mixed case, that is, the
13535 initial letter and any letter following an underscore must be uppercase.
13536 All other letters must be lowercase. An exception is that SPARK_Mode is
13537 allowed as an alternative for Spark_Mode.
13540 @geindex -gnatyr (gcc)
13545 @item @code{-gnatyr}
13547 @emph{Check references.}
13549 All identifier references must be cased in the same way as the
13550 corresponding declaration. No specific casing style is imposed on
13551 identifiers. The only requirement is for consistency of references
13555 @geindex -gnatys (gcc)
13560 @item @code{-gnatys}
13562 @emph{Check separate specs.}
13564 Separate declarations ('specs') are required for subprograms (a
13565 body is not allowed to serve as its own declaration). The only
13566 exception is that parameterless library level procedures are
13567 not required to have a separate declaration. This exception covers
13568 the most frequent form of main program procedures.
13571 @geindex -gnatyS (gcc)
13576 @item @code{-gnatyS}
13578 @emph{Check no statements after then/else.}
13580 No statements are allowed
13581 on the same line as a @cite{then} or @cite{else} keyword following the
13582 keyword in an @cite{if} statement. @cite{or else} and @cite{and then} are not
13583 affected, and a special exception allows a pragma to appear after @cite{else}.
13586 @geindex -gnatyt (gcc)
13591 @item @code{-gnatyt}
13593 @emph{Check token spacing.}
13595 The following token spacing rules are enforced:
13601 The keywords @cite{abs} and @cite{not} must be followed by a space.
13604 The token @cite{=>} must be surrounded by spaces.
13607 The token @cite{<>} must be preceded by a space or a left parenthesis.
13610 Binary operators other than @cite{**} must be surrounded by spaces.
13611 There is no restriction on the layout of the @cite{**} binary operator.
13614 Colon must be surrounded by spaces.
13617 Colon-equal (assignment, initialization) must be surrounded by spaces.
13620 Comma must be the first non-blank character on the line, or be
13621 immediately preceded by a non-blank character, and must be followed
13625 If the token preceding a left parenthesis ends with a letter or digit, then
13626 a space must separate the two tokens.
13629 If the token following a right parenthesis starts with a letter or digit, then
13630 a space must separate the two tokens.
13633 A right parenthesis must either be the first non-blank character on
13634 a line, or it must be preceded by a non-blank character.
13637 A semicolon must not be preceded by a space, and must not be followed by
13638 a non-blank character.
13641 A unary plus or minus may not be followed by a space.
13644 A vertical bar must be surrounded by spaces.
13647 Exactly one blank (and no other white space) must appear between
13648 a @cite{not} token and a following @cite{in} token.
13651 @geindex -gnatyu (gcc)
13656 @item @code{-gnatyu}
13658 @emph{Check unnecessary blank lines.}
13660 Unnecessary blank lines are not allowed. A blank line is considered
13661 unnecessary if it appears at the end of the file, or if more than
13662 one blank line occurs in sequence.
13665 @geindex -gnatyx (gcc)
13670 @item @code{-gnatyx}
13672 @emph{Check extra parentheses.}
13674 Unnecessary extra level of parentheses (C-style) are not allowed
13675 around conditions in @cite{if} statements, @cite{while} statements and
13676 @cite{exit} statements.
13679 @geindex -gnatyy (gcc)
13684 @item @code{-gnatyy}
13686 @emph{Set all standard style check options.}
13688 This is equivalent to @cite{gnaty3aAbcefhiklmnprst}, that is all checking
13689 options enabled with the exception of @emph{-gnatyB}, @emph{-gnatyd},
13690 @emph{-gnatyI}, @emph{-gnatyLnnn}, @emph{-gnatyo}, @emph{-gnatyO},
13691 @emph{-gnatyS}, @emph{-gnatyu}, and @emph{-gnatyx}.
13694 @geindex -gnaty- (gcc)
13699 @item @code{-gnaty-}
13701 @emph{Remove style check options.}
13703 This causes any subsequent options in the string to act as canceling the
13704 corresponding style check option. To cancel maximum nesting level control,
13705 use @emph{L} parameter witout any integer value after that, because any
13706 digit following @emph{-} in the parameter string of the @emph{-gnaty}
13707 option will be threated as canceling indentation check. The same is true
13708 for @emph{M} parameter. @emph{y} and @emph{N} parameters are not
13709 allowed after @emph{-}.
13712 @geindex -gnaty+ (gcc)
13717 @item @code{-gnaty+}
13719 @emph{Enable style check options.}
13721 This causes any subsequent options in the string to enable the corresponding
13722 style check option. That is, it cancels the effect of a previous -,
13726 @c end of switch description (leave this comment to ease automatic parsing for
13730 In the above rules, appearing in column one is always permitted, that is,
13731 counts as meeting either a requirement for a required preceding space,
13732 or as meeting a requirement for no preceding space.
13734 Appearing at the end of a line is also always permitted, that is, counts
13735 as meeting either a requirement for a following space, or as meeting
13736 a requirement for no following space.
13738 If any of these style rules is violated, a message is generated giving
13739 details on the violation. The initial characters of such messages are
13740 always '@cite{(style)}'. Note that these messages are treated as warning
13741 messages, so they normally do not prevent the generation of an object
13742 file. The @emph{-gnatwe} switch can be used to treat warning messages,
13743 including style messages, as fatal errors.
13745 The switch @code{-gnaty} on its own (that is not
13746 followed by any letters or digits) is equivalent
13747 to the use of @emph{-gnatyy} as described above, that is all
13748 built-in standard style check options are enabled.
13750 The switch @code{-gnatyN} clears any previously set style checks.
13752 @node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
13753 @anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{101}@anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{10c}
13754 @subsection Run-Time Checks
13757 @geindex Division by zero
13759 @geindex Access before elaboration
13762 @geindex division by zero
13765 @geindex access before elaboration
13768 @geindex stack overflow checking
13770 By default, the following checks are suppressed: stack overflow
13771 checks, and checks for access before elaboration on subprogram
13772 calls. All other checks, including overflow checks, range checks and
13773 array bounds checks, are turned on by default. The following @emph{gcc}
13774 switches refine this default behavior.
13776 @geindex -gnatp (gcc)
13781 @item @code{-gnatp}
13783 @geindex Suppressing checks
13786 @geindex suppressing
13788 This switch causes the unit to be compiled
13789 as though @cite{pragma Suppress (All_checks)}
13790 had been present in the source. Validity checks are also eliminated (in
13791 other words @emph{-gnatp} also implies @emph{-gnatVn}.
13792 Use this switch to improve the performance
13793 of the code at the expense of safety in the presence of invalid data or
13796 Note that when checks are suppressed, the compiler is allowed, but not
13797 required, to omit the checking code. If the run-time cost of the
13798 checking code is zero or near-zero, the compiler will generate it even
13799 if checks are suppressed. In particular, if the compiler can prove
13800 that a certain check will necessarily fail, it will generate code to
13801 do an unconditional 'raise', even if checks are suppressed. The
13802 compiler warns in this case. Another case in which checks may not be
13803 eliminated is when they are embedded in certain run time routines such
13804 as math library routines.
13806 Of course, run-time checks are omitted whenever the compiler can prove
13807 that they will not fail, whether or not checks are suppressed.
13809 Note that if you suppress a check that would have failed, program
13810 execution is erroneous, which means the behavior is totally
13811 unpredictable. The program might crash, or print wrong answers, or
13812 do anything else. It might even do exactly what you wanted it to do
13813 (and then it might start failing mysteriously next week or next
13814 year). The compiler will generate code based on the assumption that
13815 the condition being checked is true, which can result in erroneous
13816 execution if that assumption is wrong.
13818 The checks subject to suppression include all the checks defined by the Ada
13819 standard, the additional implementation defined checks @cite{Alignment_Check},
13820 @cite{Duplicated_Tag_Check}, @cite{Predicate_Check}, Container_Checks, Tampering_Check,
13821 and @cite{Validity_Check}, as well as any checks introduced using @cite{pragma Check_Name}. Note that @cite{Atomic_Synchronization} is not automatically
13822 suppressed by use of this option.
13824 If the code depends on certain checks being active, you can use
13825 pragma @cite{Unsuppress} either as a configuration pragma or as
13826 a local pragma to make sure that a specified check is performed
13827 even if @emph{gnatp} is specified.
13829 The @emph{-gnatp} switch has no effect if a subsequent
13830 @emph{-gnat-p} switch appears.
13833 @geindex -gnat-p (gcc)
13835 @geindex Suppressing checks
13838 @geindex suppressing
13845 @item @code{-gnat-p}
13847 This switch cancels the effect of a previous @emph{gnatp} switch.
13850 @geindex -gnato?? (gcc)
13852 @geindex Overflow checks
13854 @geindex Overflow mode
13862 @item @code{-gnato??}
13864 This switch controls the mode used for computing intermediate
13865 arithmetic integer operations, and also enables overflow checking.
13866 For a full description of overflow mode and checking control, see
13867 the 'Overflow Check Handling in GNAT' appendix in this
13870 Overflow checks are always enabled by this switch. The argument
13871 controls the mode, using the codes
13876 @item @emph{1 = STRICT}
13878 In STRICT mode, intermediate operations are always done using the
13879 base type, and overflow checking ensures that the result is within
13880 the base type range.
13882 @item @emph{2 = MINIMIZED}
13884 In MINIMIZED mode, overflows in intermediate operations are avoided
13885 where possible by using a larger integer type for the computation
13886 (typically @cite{Long_Long_Integer}). Overflow checking ensures that
13887 the result fits in this larger integer type.
13889 @item @emph{3 = ELIMINATED}
13891 In ELIMINATED mode, overflows in intermediate operations are avoided
13892 by using multi-precision arithmetic. In this case, overflow checking
13893 has no effect on intermediate operations (since overflow is impossible).
13896 If two digits are present after @emph{-gnato} then the first digit
13897 sets the mode for expressions outside assertions, and the second digit
13898 sets the mode for expressions within assertions. Here assertions is used
13899 in the technical sense (which includes for example precondition and
13900 postcondition expressions).
13902 If one digit is present, the corresponding mode is applicable to both
13903 expressions within and outside assertion expressions.
13905 If no digits are present, the default is to enable overflow checks
13906 and set STRICT mode for both kinds of expressions. This is compatible
13907 with the use of @emph{-gnato} in previous versions of GNAT.
13909 @geindex Machine_Overflows
13911 Note that the @emph{-gnato??} switch does not affect the code generated
13912 for any floating-point operations; it applies only to integer semantics.
13913 For floating-point, GNAT has the @cite{Machine_Overflows}
13914 attribute set to @cite{False} and the normal mode of operation is to
13915 generate IEEE NaN and infinite values on overflow or invalid operations
13916 (such as dividing 0.0 by 0.0).
13918 The reason that we distinguish overflow checking from other kinds of
13919 range constraint checking is that a failure of an overflow check, unlike
13920 for example the failure of a range check, can result in an incorrect
13921 value, but cannot cause random memory destruction (like an out of range
13922 subscript), or a wild jump (from an out of range case value). Overflow
13923 checking is also quite expensive in time and space, since in general it
13924 requires the use of double length arithmetic.
13926 Note again that the default is @emph{-gnato11} (equivalent to @emph{-gnato1}),
13927 so overflow checking is performed in STRICT mode by default.
13930 @geindex -gnatE (gcc)
13932 @geindex Elaboration checks
13935 @geindex elaboration
13940 @item @code{-gnatE}
13942 Enables dynamic checks for access-before-elaboration
13943 on subprogram calls and generic instantiations.
13944 Note that @emph{-gnatE} is not necessary for safety, because in the
13945 default mode, GNAT ensures statically that the checks would not fail.
13946 For full details of the effect and use of this switch,
13947 @ref{1e,,Compiling with gcc}.
13950 @geindex -fstack-check (gcc)
13952 @geindex Stack Overflow Checking
13955 @geindex stack overflow checking
13960 @item @code{-fstack-check}
13962 Activates stack overflow checking. For full details of the effect and use of
13963 this switch see @ref{fc,,Stack Overflow Checking}.
13966 @geindex Unsuppress
13968 The setting of these switches only controls the default setting of the
13969 checks. You may modify them using either @cite{Suppress} (to remove
13970 checks) or @cite{Unsuppress} (to add back suppressed checks) pragmas in
13971 the program source.
13973 @node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
13974 @anchor{gnat_ugn/building_executable_programs_with_gnat id20}@anchor{10d}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-syntax-checking}@anchor{10e}
13975 @subsection Using @emph{gcc} for Syntax Checking
13978 @geindex -gnats (gcc)
13983 @item @code{-gnats}
13985 The @cite{s} stands for 'syntax'.
13987 Run GNAT in syntax checking only mode. For
13988 example, the command
13991 $ gcc -c -gnats x.adb
13994 compiles file @code{x.adb} in syntax-check-only mode. You can check a
13995 series of files in a single command
13996 , and can use wild cards to specify such a group of files.
13997 Note that you must specify the @emph{-c} (compile
13998 only) flag in addition to the @emph{-gnats} flag.
14000 You may use other switches in conjunction with @emph{-gnats}. In
14001 particular, @emph{-gnatl} and @emph{-gnatv} are useful to control the
14002 format of any generated error messages.
14004 When the source file is empty or contains only empty lines and/or comments,
14005 the output is a warning:
14008 $ gcc -c -gnats -x ada toto.txt
14009 toto.txt:1:01: warning: empty file, contains no compilation units
14013 Otherwise, the output is simply the error messages, if any. No object file or
14014 ALI file is generated by a syntax-only compilation. Also, no units other
14015 than the one specified are accessed. For example, if a unit @cite{X}
14016 @emph{with}s a unit @cite{Y}, compiling unit @cite{X} in syntax
14017 check only mode does not access the source file containing unit
14020 @geindex Multiple units
14021 @geindex syntax checking
14023 Normally, GNAT allows only a single unit in a source file. However, this
14024 restriction does not apply in syntax-check-only mode, and it is possible
14025 to check a file containing multiple compilation units concatenated
14026 together. This is primarily used by the @cite{gnatchop} utility
14027 (@ref{38,,Renaming Files with gnatchop}).
14030 @node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
14031 @anchor{gnat_ugn/building_executable_programs_with_gnat id21}@anchor{10f}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-semantic-checking}@anchor{110}
14032 @subsection Using @emph{gcc} for Semantic Checking
14035 @geindex -gnatc (gcc)
14040 @item @code{-gnatc}
14042 The @cite{c} stands for 'check'.
14043 Causes the compiler to operate in semantic check mode,
14044 with full checking for all illegalities specified in the
14045 Ada Reference Manual, but without generation of any object code
14046 (no object file is generated).
14048 Because dependent files must be accessed, you must follow the GNAT
14049 semantic restrictions on file structuring to operate in this mode:
14055 The needed source files must be accessible
14056 (see @ref{8e,,Search Paths and the Run-Time Library (RTL)}).
14059 Each file must contain only one compilation unit.
14062 The file name and unit name must match (@ref{54,,File Naming Rules}).
14065 The output consists of error messages as appropriate. No object file is
14066 generated. An @code{ALI} file is generated for use in the context of
14067 cross-reference tools, but this file is marked as not being suitable
14068 for binding (since no object file is generated).
14069 The checking corresponds exactly to the notion of
14070 legality in the Ada Reference Manual.
14072 Any unit can be compiled in semantics-checking-only mode, including
14073 units that would not normally be compiled (subunits,
14074 and specifications where a separate body is present).
14077 @node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14078 @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{111}
14079 @subsection Compiling Different Versions of Ada
14082 The switches described in this section allow you to explicitly specify
14083 the version of the Ada language that your programs are written in.
14084 The default mode is Ada 2012,
14085 but you can also specify Ada 95, Ada 2005 mode, or
14086 indicate Ada 83 compatibility mode.
14088 @geindex Compatibility with Ada 83
14090 @geindex -gnat83 (gcc)
14093 @geindex Ada 83 tests
14095 @geindex Ada 83 mode
14100 @item @code{-gnat83} (Ada 83 Compatibility Mode)
14102 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14103 specifies that the program is to be compiled in Ada 83 mode. With
14104 @emph{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14105 semantics where this can be done easily.
14106 It is not possible to guarantee this switch does a perfect
14107 job; some subtle tests, such as are
14108 found in earlier ACVC tests (and that have been removed from the ACATS suite
14109 for Ada 95), might not compile correctly.
14110 Nevertheless, this switch may be useful in some circumstances, for example
14111 where, due to contractual reasons, existing code needs to be maintained
14112 using only Ada 83 features.
14114 With few exceptions (most notably the need to use @cite{<>} on
14116 @geindex Generic formal parameters
14117 generic formal parameters,
14118 the use of the new Ada 95 / Ada 2005
14119 reserved words, and the use of packages
14120 with optional bodies), it is not necessary to specify the
14121 @emph{-gnat83} switch when compiling Ada 83 programs, because, with rare
14122 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14123 a correct Ada 83 program is usually also a correct program
14124 in these later versions of the language standard. For further information
14125 please refer to the @cite{Compatibility_and_Porting_Guide} chapter in the
14126 @cite{GNAT Reference Manual}.
14129 @geindex -gnat95 (gcc)
14131 @geindex Ada 95 mode
14136 @item @code{-gnat95} (Ada 95 mode)
14138 This switch directs the compiler to implement the Ada 95 version of the
14140 Since Ada 95 is almost completely upwards
14141 compatible with Ada 83, Ada 83 programs may generally be compiled using
14142 this switch (see the description of the @emph{-gnat83} switch for further
14143 information about Ada 83 mode).
14144 If an Ada 2005 program is compiled in Ada 95 mode,
14145 uses of the new Ada 2005 features will cause error
14146 messages or warnings.
14148 This switch also can be used to cancel the effect of a previous
14149 @emph{-gnat83}, @emph{-gnat05/2005}, or @emph{-gnat12/2012}
14150 switch earlier in the command line.
14153 @geindex -gnat05 (gcc)
14155 @geindex -gnat2005 (gcc)
14157 @geindex Ada 2005 mode
14162 @item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14164 This switch directs the compiler to implement the Ada 2005 version of the
14165 language, as documented in the official Ada standards document.
14166 Since Ada 2005 is almost completely upwards
14167 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14168 may generally be compiled using this switch (see the description of the
14169 @emph{-gnat83} and @emph{-gnat95} switches for further
14173 @geindex -gnat12 (gcc)
14175 @geindex -gnat2012 (gcc)
14177 @geindex Ada 2012 mode
14182 @item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14184 This switch directs the compiler to implement the Ada 2012 version of the
14185 language (also the default).
14186 Since Ada 2012 is almost completely upwards
14187 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14188 Ada 83 and Ada 95 programs
14189 may generally be compiled using this switch (see the description of the
14190 @emph{-gnat83}, @emph{-gnat95}, and @emph{-gnat05/2005} switches
14191 for further information).
14194 @geindex -gnatX (gcc)
14196 @geindex Ada language extensions
14198 @geindex GNAT extensions
14203 @item @code{-gnatX} (Enable GNAT Extensions)
14205 This switch directs the compiler to implement the latest version of the
14206 language (currently Ada 2012) and also to enable certain GNAT implementation
14207 extensions that are not part of any Ada standard. For a full list of these
14208 extensions, see the GNAT reference manual.
14211 @node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14212 @anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{112}@anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{4a}
14213 @subsection Character Set Control
14216 @geindex -gnati (gcc)
14221 @item @code{-gnati@emph{c}}
14223 Normally GNAT recognizes the Latin-1 character set in source program
14224 identifiers, as described in the Ada Reference Manual.
14226 GNAT to recognize alternate character sets in identifiers. @cite{c} is a
14227 single character indicating the character set, as follows:
14230 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14237 ISO 8859-1 (Latin-1) identifiers
14245 ISO 8859-2 (Latin-2) letters allowed in identifiers
14253 ISO 8859-3 (Latin-3) letters allowed in identifiers
14261 ISO 8859-4 (Latin-4) letters allowed in identifiers
14269 ISO 8859-5 (Cyrillic) letters allowed in identifiers
14277 ISO 8859-15 (Latin-9) letters allowed in identifiers
14285 IBM PC letters (code page 437) allowed in identifiers
14293 IBM PC letters (code page 850) allowed in identifiers
14301 Full upper-half codes allowed in identifiers
14309 No upper-half codes allowed in identifiers
14317 Wide-character codes (that is, codes greater than 255)
14318 allowed in identifiers
14323 See @ref{40,,Foreign Language Representation} for full details on the
14324 implementation of these character sets.
14327 @geindex -gnatW (gcc)
14332 @item @code{-gnatW@emph{e}}
14334 Specify the method of encoding for wide characters.
14335 @cite{e} is one of the following:
14338 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14345 Hex encoding (brackets coding also recognized)
14353 Upper half encoding (brackets encoding also recognized)
14361 Shift/JIS encoding (brackets encoding also recognized)
14369 EUC encoding (brackets encoding also recognized)
14377 UTF-8 encoding (brackets encoding also recognized)
14385 Brackets encoding only (default value)
14390 For full details on these encoding
14391 methods see @ref{50,,Wide_Character Encodings}.
14392 Note that brackets coding is always accepted, even if one of the other
14393 options is specified, so for example @emph{-gnatW8} specifies that both
14394 brackets and UTF-8 encodings will be recognized. The units that are
14395 with'ed directly or indirectly will be scanned using the specified
14396 representation scheme, and so if one of the non-brackets scheme is
14397 used, it must be used consistently throughout the program. However,
14398 since brackets encoding is always recognized, it may be conveniently
14399 used in standard libraries, allowing these libraries to be used with
14400 any of the available coding schemes.
14402 Note that brackets encoding only applies to program text. Within comments,
14403 brackets are considered to be normal graphic characters, and bracket sequences
14404 are never recognized as wide characters.
14406 If no @emph{-gnatW?} parameter is present, then the default
14407 representation is normally Brackets encoding only. However, if the
14408 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14409 byte order mark or BOM for UTF-8), then these three characters are
14410 skipped and the default representation for the file is set to UTF-8.
14412 Note that the wide character representation that is specified (explicitly
14413 or by default) for the main program also acts as the default encoding used
14414 for Wide_Text_IO files if not specifically overridden by a WCEM form
14418 When no @emph{-gnatW?} is specified, then characters (other than wide
14419 characters represented using brackets notation) are treated as 8-bit
14420 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14421 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14422 characters in the range 16#00#..16#1F# are not accepted in program text
14423 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14424 in program text, but allowed and ignored in comments. Note in particular
14425 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14426 as an end of line in this default mode. If your source program contains
14427 instances of the NEL character used as a line terminator,
14428 you must use UTF-8 encoding for the whole
14429 source program. In default mode, all lines must be ended by a standard
14430 end of line sequence (CR, CR/LF, or LF).
14432 Note that the convention of simply accepting all upper half characters in
14433 comments means that programs that use standard ASCII for program text, but
14434 UTF-8 encoding for comments are accepted in default mode, providing that the
14435 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14436 This is a common mode for many programs with foreign language comments.
14438 @node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14439 @anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{113}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{114}
14440 @subsection File Naming Control
14443 @geindex -gnatk (gcc)
14448 @item @code{-gnatk@emph{n}}
14450 Activates file name 'krunching'. @cite{n}, a decimal integer in the range
14451 1-999, indicates the maximum allowable length of a file name (not
14452 including the @code{.ads} or @code{.adb} extension). The default is not
14453 to enable file name krunching.
14455 For the source file naming rules, @ref{54,,File Naming Rules}.
14458 @node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14459 @anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{115}@anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{116}
14460 @subsection Subprogram Inlining Control
14463 @geindex -gnatn (gcc)
14468 @item @code{-gnatn[12]}
14470 The @cite{n} here is intended to suggest the first syllable of the
14472 GNAT recognizes and processes @cite{Inline} pragmas. However, for the
14473 inlining to actually occur, optimization must be enabled and, in order
14474 to enable inlining of subprograms specified by pragma @cite{Inline},
14475 you must also specify this switch.
14476 In the absence of this switch, GNAT does not attempt
14477 inlining and does not need to access the bodies of
14478 subprograms for which @cite{pragma Inline} is specified if they are not
14479 in the current unit.
14481 You can optionally specify the inlining level: 1 for moderate inlining across
14482 modules, which is a good compromise between compilation times and performances
14483 at run time, or 2 for full inlining across modules, which may bring about
14484 longer compilation times. If no inlining level is specified, the compiler will
14485 pick it based on the optimization level: 1 for @emph{-O1}, @emph{-O2} or
14486 @emph{-Os} and 2 for @emph{-O3}.
14488 If you specify this switch the compiler will access these bodies,
14489 creating an extra source dependency for the resulting object file, and
14490 where possible, the call will be inlined.
14491 For further details on when inlining is possible
14492 see @ref{117,,Inlining of Subprograms}.
14495 @geindex -gnatN (gcc)
14500 @item @code{-gnatN}
14502 This switch activates front-end inlining which also
14503 generates additional dependencies.
14505 When using a gcc-based back end (in practice this means using any version
14506 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
14507 @emph{-gnatN} is deprecated, and the use of @emph{-gnatn} is preferred.
14508 Historically front end inlining was more extensive than the gcc back end
14509 inlining, but that is no longer the case.
14512 @node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14513 @anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{118}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{119}
14514 @subsection Auxiliary Output Control
14517 @geindex -gnatt (gcc)
14519 @geindex Writing internal trees
14521 @geindex Internal trees
14522 @geindex writing to file
14527 @item @code{-gnatt}
14529 Causes GNAT to write the internal tree for a unit to a file (with the
14530 extension @code{.adt}.
14531 This not normally required, but is used by separate analysis tools.
14533 these tools do the necessary compilations automatically, so you should
14534 not have to specify this switch in normal operation.
14535 Note that the combination of switches @emph{-gnatct}
14536 generates a tree in the form required by ASIS applications.
14539 @geindex -gnatu (gcc)
14544 @item @code{-gnatu}
14546 Print a list of units required by this compilation on @code{stdout}.
14547 The listing includes all units on which the unit being compiled depends
14548 either directly or indirectly.
14551 @geindex -pass-exit-codes (gcc)
14556 @item @code{-pass-exit-codes}
14558 If this switch is not used, the exit code returned by @emph{gcc} when
14559 compiling multiple files indicates whether all source files have
14560 been successfully used to generate object files or not.
14562 When @emph{-pass-exit-codes} is used, @emph{gcc} exits with an extended
14563 exit status and allows an integrated development environment to better
14564 react to a compilation failure. Those exit status are:
14567 @multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14574 There was an error in at least one source file.
14582 At least one source file did not generate an object file.
14590 The compiler died unexpectedly (internal error for example).
14598 An object file has been generated for every source file.
14604 @node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
14605 @anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{11a}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{11b}
14606 @subsection Debugging Control
14611 @geindex Debugging options
14614 @geindex -gnatd (gcc)
14619 @item @code{-gnatd@emph{x}}
14621 Activate internal debugging switches. @cite{x} is a letter or digit, or
14622 string of letters or digits, which specifies the type of debugging
14623 outputs desired. Normally these are used only for internal development
14624 or system debugging purposes. You can find full documentation for these
14625 switches in the body of the @cite{Debug} unit in the compiler source
14626 file @code{debug.adb}.
14629 @geindex -gnatG (gcc)
14634 @item @code{-gnatG[=@emph{nn}]}
14636 This switch causes the compiler to generate auxiliary output containing
14637 a pseudo-source listing of the generated expanded code. Like most Ada
14638 compilers, GNAT works by first transforming the high level Ada code into
14639 lower level constructs. For example, tasking operations are transformed
14640 into calls to the tasking run-time routines. A unique capability of GNAT
14641 is to list this expanded code in a form very close to normal Ada source.
14642 This is very useful in understanding the implications of various Ada
14643 usage on the efficiency of the generated code. There are many cases in
14644 Ada (e.g., the use of controlled types), where simple Ada statements can
14645 generate a lot of run-time code. By using @emph{-gnatG} you can identify
14646 these cases, and consider whether it may be desirable to modify the coding
14647 approach to improve efficiency.
14649 The optional parameter @cite{nn} if present after -gnatG specifies an
14650 alternative maximum line length that overrides the normal default of 72.
14651 This value is in the range 40-999999, values less than 40 being silently
14652 reset to 40. The equal sign is optional.
14654 The format of the output is very similar to standard Ada source, and is
14655 easily understood by an Ada programmer. The following special syntactic
14656 additions correspond to low level features used in the generated code that
14657 do not have any exact analogies in pure Ada source form. The following
14658 is a partial list of these special constructions. See the spec
14659 of package @cite{Sprint} in file @code{sprint.ads} for a full list.
14661 @geindex -gnatL (gcc)
14663 If the switch @emph{-gnatL} is used in conjunction with
14664 @emph{-gnatG}, then the original source lines are interspersed
14665 in the expanded source (as comment lines with the original line number).
14670 @item @code{new @emph{xxx} [storage_pool = @emph{yyy}]}
14672 Shows the storage pool being used for an allocator.
14674 @item @code{at end @emph{procedure-name};}
14676 Shows the finalization (cleanup) procedure for a scope.
14678 @item @code{(if @emph{expr} then @emph{expr} else @emph{expr})}
14680 Conditional expression equivalent to the @cite{x?y:z} construction in C.
14682 @item @code{@emph{target}^(@emph{source})}
14684 A conversion with floating-point truncation instead of rounding.
14686 @item @code{@emph{target}?(@emph{source})}
14688 A conversion that bypasses normal Ada semantic checking. In particular
14689 enumeration types and fixed-point types are treated simply as integers.
14691 @item @code{@emph{target}?^(@emph{source})}
14693 Combines the above two cases.
14696 @code{@emph{x} #/ @emph{y}}
14698 @code{@emph{x} #mod @emph{y}}
14700 @code{@emph{x} # @emph{y}}
14705 @item @code{@emph{x} #rem @emph{y}}
14707 A division or multiplication of fixed-point values which are treated as
14708 integers without any kind of scaling.
14710 @item @code{free @emph{expr} [storage_pool = @emph{xxx}]}
14712 Shows the storage pool associated with a @cite{free} statement.
14714 @item @code{[subtype or type declaration]}
14716 Used to list an equivalent declaration for an internally generated
14717 type that is referenced elsewhere in the listing.
14719 @item @code{freeze @emph{type-name} [@emph{actions}]}
14721 Shows the point at which @cite{type-name} is frozen, with possible
14722 associated actions to be performed at the freeze point.
14724 @item @code{reference @emph{itype}}
14726 Reference (and hence definition) to internal type @cite{itype}.
14728 @item @code{@emph{function-name}! (@emph{arg}, @emph{arg}, @emph{arg})}
14730 Intrinsic function call.
14732 @item @code{@emph{label-name} : label}
14734 Declaration of label @cite{labelname}.
14736 @item @code{#$ @emph{subprogram-name}}
14738 An implicit call to a run-time support routine
14739 (to meet the requirement of H.3.1(9) in a
14740 convenient manner).
14742 @item @code{@emph{expr} && @emph{expr} && @emph{expr} ... && @emph{expr}}
14744 A multiple concatenation (same effect as @cite{expr} & @cite{expr} &
14745 @cite{expr}, but handled more efficiently).
14747 @item @code{[constraint_error]}
14749 Raise the @cite{Constraint_Error} exception.
14751 @item @code{@emph{expression}'reference}
14753 A pointer to the result of evaluating @{expression@}.
14755 @item @code{@emph{target-type}!(@emph{source-expression})}
14757 An unchecked conversion of @cite{source-expression} to @cite{target-type}.
14759 @item @code{[@emph{numerator}/@emph{denominator}]}
14761 Used to represent internal real literals (that) have no exact
14762 representation in base 2-16 (for example, the result of compile time
14763 evaluation of the expression 1.0/27.0).
14767 @geindex -gnatD (gcc)
14772 @item @code{-gnatD[=nn]}
14774 When used in conjunction with @emph{-gnatG}, this switch causes
14775 the expanded source, as described above for
14776 @emph{-gnatG} to be written to files with names
14777 @code{xxx.dg}, where @code{xxx} is the normal file name,
14778 instead of to the standard output file. For
14779 example, if the source file name is @code{hello.adb}, then a file
14780 @code{hello.adb.dg} will be written. The debugging
14781 information generated by the @emph{gcc} @emph{-g} switch
14782 will refer to the generated @code{xxx.dg} file. This allows
14783 you to do source level debugging using the generated code which is
14784 sometimes useful for complex code, for example to find out exactly
14785 which part of a complex construction raised an exception. This switch
14786 also suppress generation of cross-reference information (see
14787 @emph{-gnatx}) since otherwise the cross-reference information
14788 would refer to the @code{.dg} file, which would cause
14789 confusion since this is not the original source file.
14791 Note that @emph{-gnatD} actually implies @emph{-gnatG}
14792 automatically, so it is not necessary to give both options.
14793 In other words @emph{-gnatD} is equivalent to @emph{-gnatDG}).
14795 @geindex -gnatL (gcc)
14797 If the switch @emph{-gnatL} is used in conjunction with
14798 @emph{-gnatDG}, then the original source lines are interspersed
14799 in the expanded source (as comment lines with the original line number).
14801 The optional parameter @cite{nn} if present after -gnatD specifies an
14802 alternative maximum line length that overrides the normal default of 72.
14803 This value is in the range 40-999999, values less than 40 being silently
14804 reset to 40. The equal sign is optional.
14807 @geindex -gnatr (gcc)
14809 @geindex pragma Restrictions
14814 @item @code{-gnatr}
14816 This switch causes pragma Restrictions to be treated as Restriction_Warnings
14817 so that violation of restrictions causes warnings rather than illegalities.
14818 This is useful during the development process when new restrictions are added
14819 or investigated. The switch also causes pragma Profile to be treated as
14820 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
14821 restriction warnings rather than restrictions.
14824 @geindex -gnatR (gcc)
14829 @item @code{-gnatR[0|1|2|3[s]]}
14831 This switch controls output from the compiler of a listing showing
14832 representation information for declared types and objects. For
14833 @emph{-gnatR0}, no information is output (equivalent to omitting
14834 the @emph{-gnatR} switch). For @emph{-gnatR1} (which is the default,
14835 so @emph{-gnatR} with no parameter has the same effect), size and alignment
14836 information is listed for declared array and record types. For
14837 @emph{-gnatR2}, size and alignment information is listed for all
14838 declared types and objects. The @cite{Linker_Section} is also listed for any
14839 entity for which the @cite{Linker_Section} is set explicitly or implicitly (the
14840 latter case occurs for objects of a type for which a @cite{Linker_Section}
14843 Finally @emph{-gnatR3} includes symbolic
14844 expressions for values that are computed at run time for
14845 variant records. These symbolic expressions have a mostly obvious
14846 format with #n being used to represent the value of the n'th
14847 discriminant. See source files @code{repinfo.ads/adb} in the
14848 @cite{GNAT} sources for full details on the format of @emph{-gnatR3}
14849 output. If the switch is followed by an s (e.g., @emph{-gnatR2s}), then
14850 the output is to a file with the name @code{file.rep} where
14851 file is the name of the corresponding source file.
14853 @item @code{-gnatRm[s]}
14855 This form of the switch controls output of subprogram conventions
14856 and parameter passing mechanisms for all subprograms. A following
14857 @cite{s} means output to a file as described above.
14859 Note that it is possible for record components to have zero size. In
14860 this case, the component clause uses an obvious extension of permitted
14861 Ada syntax, for example @cite{at 0 range 0 .. -1}.
14863 Representation information requires that code be generated (since it is the
14864 code generator that lays out complex data structures). If an attempt is made
14865 to output representation information when no code is generated, for example
14866 when a subunit is compiled on its own, then no information can be generated
14867 and the compiler outputs a message to this effect.
14870 @geindex -gnatS (gcc)
14875 @item @code{-gnatS}
14877 The use of the switch @emph{-gnatS} for an
14878 Ada compilation will cause the compiler to output a
14879 representation of package Standard in a form very
14880 close to standard Ada. It is not quite possible to
14881 do this entirely in standard Ada (since new
14882 numeric base types cannot be created in standard
14883 Ada), but the output is easily
14884 readable to any Ada programmer, and is useful to
14885 determine the characteristics of target dependent
14886 types in package Standard.
14889 @geindex -gnatx (gcc)
14894 @item @code{-gnatx}
14896 Normally the compiler generates full cross-referencing information in
14897 the @code{ALI} file. This information is used by a number of tools,
14898 including @cite{gnatfind} and @cite{gnatxref}. The @emph{-gnatx} switch
14899 suppresses this information. This saves some space and may slightly
14900 speed up compilation, but means that these tools cannot be used.
14903 @node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
14904 @anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{11c}@anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{11d}
14905 @subsection Exception Handling Control
14908 GNAT uses two methods for handling exceptions at run-time. The
14909 @cite{setjmp/longjmp} method saves the context when entering
14910 a frame with an exception handler. Then when an exception is
14911 raised, the context can be restored immediately, without the
14912 need for tracing stack frames. This method provides very fast
14913 exception propagation, but introduces significant overhead for
14914 the use of exception handlers, even if no exception is raised.
14916 The other approach is called 'zero cost' exception handling.
14917 With this method, the compiler builds static tables to describe
14918 the exception ranges. No dynamic code is required when entering
14919 a frame containing an exception handler. When an exception is
14920 raised, the tables are used to control a back trace of the
14921 subprogram invocation stack to locate the required exception
14922 handler. This method has considerably poorer performance for
14923 the propagation of exceptions, but there is no overhead for
14924 exception handlers if no exception is raised. Note that in this
14925 mode and in the context of mixed Ada and C/C++ programming,
14926 to propagate an exception through a C/C++ code, the C/C++ code
14927 must be compiled with the @emph{-funwind-tables} GCC's
14930 The following switches may be used to control which of the
14931 two exception handling methods is used.
14933 @geindex --RTS=sjlj (gnatmake)
14938 @item @code{--RTS=sjlj}
14940 This switch causes the setjmp/longjmp run-time (when available) to be used
14941 for exception handling. If the default
14942 mechanism for the target is zero cost exceptions, then
14943 this switch can be used to modify this default, and must be
14944 used for all units in the partition.
14945 This option is rarely used. One case in which it may be
14946 advantageous is if you have an application where exception
14947 raising is common and the overall performance of the
14948 application is improved by favoring exception propagation.
14951 @geindex --RTS=zcx (gnatmake)
14953 @geindex Zero Cost Exceptions
14958 @item @code{--RTS=zcx}
14960 This switch causes the zero cost approach to be used
14961 for exception handling. If this is the default mechanism for the
14962 target (see below), then this switch is unneeded. If the default
14963 mechanism for the target is setjmp/longjmp exceptions, then
14964 this switch can be used to modify this default, and must be
14965 used for all units in the partition.
14966 This option can only be used if the zero cost approach
14967 is available for the target in use, otherwise it will generate an error.
14970 The same option @emph{--RTS} must be used both for @emph{gcc}
14971 and @emph{gnatbind}. Passing this option to @emph{gnatmake}
14972 (@ref{e2,,Switches for gnatmake}) will ensure the required consistency
14973 through the compilation and binding steps.
14975 @node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
14976 @anchor{gnat_ugn/building_executable_programs_with_gnat id29}@anchor{11e}@anchor{gnat_ugn/building_executable_programs_with_gnat units-to-sources-mapping-files}@anchor{ff}
14977 @subsection Units to Sources Mapping Files
14980 @geindex -gnatem (gcc)
14985 @item @code{-gnatem=@emph{path}}
14987 A mapping file is a way to communicate to the compiler two mappings:
14988 from unit names to file names (without any directory information) and from
14989 file names to path names (with full directory information). These mappings
14990 are used by the compiler to short-circuit the path search.
14992 The use of mapping files is not required for correct operation of the
14993 compiler, but mapping files can improve efficiency, particularly when
14994 sources are read over a slow network connection. In normal operation,
14995 you need not be concerned with the format or use of mapping files,
14996 and the @emph{-gnatem} switch is not a switch that you would use
14997 explicitly. It is intended primarily for use by automatic tools such as
14998 @emph{gnatmake} running under the project file facility. The
14999 description here of the format of mapping files is provided
15000 for completeness and for possible use by other tools.
15002 A mapping file is a sequence of sets of three lines. In each set, the
15003 first line is the unit name, in lower case, with @cite{%s} appended
15004 for specs and @cite{%b} appended for bodies; the second line is the
15005 file name; and the third line is the path name.
15012 /gnat/project1/sources/main.2.ada
15015 When the switch @emph{-gnatem} is specified, the compiler will
15016 create in memory the two mappings from the specified file. If there is
15017 any problem (nonexistent file, truncated file or duplicate entries),
15018 no mapping will be created.
15020 Several @emph{-gnatem} switches may be specified; however, only the
15021 last one on the command line will be taken into account.
15023 When using a project file, @emph{gnatmake} creates a temporary
15024 mapping file and communicates it to the compiler using this switch.
15027 @node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
15028 @anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{11f}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{120}
15029 @subsection Code Generation Control
15032 The GCC technology provides a wide range of target dependent
15033 @code{-m} switches for controlling
15034 details of code generation with respect to different versions of
15035 architectures. This includes variations in instruction sets (e.g.,
15036 different members of the power pc family), and different requirements
15037 for optimal arrangement of instructions (e.g., different members of
15038 the x86 family). The list of available @emph{-m} switches may be
15039 found in the GCC documentation.
15041 Use of these @emph{-m} switches may in some cases result in improved
15044 The GNAT technology is tested and qualified without any
15045 @code{-m} switches,
15046 so generally the most reliable approach is to avoid the use of these
15047 switches. However, we generally expect most of these switches to work
15048 successfully with GNAT, and many customers have reported successful
15049 use of these options.
15051 Our general advice is to avoid the use of @emph{-m} switches unless
15052 special needs lead to requirements in this area. In particular,
15053 there is no point in using @emph{-m} switches to improve performance
15054 unless you actually see a performance improvement.
15056 @node Binding with gnatbind,Linking with gnatlink,Compiler Switches,Building Executable Programs with GNAT
15057 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{1f}@anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{121}
15058 @section Binding with @cite{gnatbind}
15063 This chapter describes the GNAT binder, @cite{gnatbind}, which is used
15064 to bind compiled GNAT objects.
15066 Note: to invoke @cite{gnatbind} with a project file, use the @cite{gnat}
15067 driver (see @ref{122,,The GNAT Driver and Project Files}).
15069 The @cite{gnatbind} program performs four separate functions:
15075 Checks that a program is consistent, in accordance with the rules in
15076 Chapter 10 of the Ada Reference Manual. In particular, error
15077 messages are generated if a program uses inconsistent versions of a
15081 Checks that an acceptable order of elaboration exists for the program
15082 and issues an error message if it cannot find an order of elaboration
15083 that satisfies the rules in Chapter 10 of the Ada Language Manual.
15086 Generates a main program incorporating the given elaboration order.
15087 This program is a small Ada package (body and spec) that
15088 must be subsequently compiled
15089 using the GNAT compiler. The necessary compilation step is usually
15090 performed automatically by @emph{gnatlink}. The two most important
15091 functions of this program
15092 are to call the elaboration routines of units in an appropriate order
15093 and to call the main program.
15096 Determines the set of object files required by the given main program.
15097 This information is output in the forms of comments in the generated program,
15098 to be read by the @emph{gnatlink} utility used to link the Ada application.
15102 * Running gnatbind::
15103 * Switches for gnatbind::
15104 * Command-Line Access::
15105 * Search Paths for gnatbind::
15106 * Examples of gnatbind Usage::
15110 @node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15111 @anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{123}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{124}
15112 @subsection Running @cite{gnatbind}
15115 The form of the @cite{gnatbind} command is
15118 $ gnatbind [`switches`] `mainprog`[.ali] [`switches`]
15121 where @code{mainprog.adb} is the Ada file containing the main program
15122 unit body. @cite{gnatbind} constructs an Ada
15123 package in two files whose names are
15124 @code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15125 For example, if given the
15126 parameter @code{hello.ali}, for a main program contained in file
15127 @code{hello.adb}, the binder output files would be @code{b~hello.ads}
15128 and @code{b~hello.adb}.
15130 When doing consistency checking, the binder takes into consideration
15131 any source files it can locate. For example, if the binder determines
15132 that the given main program requires the package @cite{Pack}, whose
15134 file is @code{pack.ali} and whose corresponding source spec file is
15135 @code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15136 (using the same search path conventions as previously described for the
15137 @emph{gcc} command). If it can locate this source file, it checks that
15139 or source checksums of the source and its references to in @code{ALI} files
15140 match. In other words, any @code{ALI} files that mentions this spec must have
15141 resulted from compiling this version of the source file (or in the case
15142 where the source checksums match, a version close enough that the
15143 difference does not matter).
15145 @geindex Source files
15146 @geindex use by binder
15148 The effect of this consistency checking, which includes source files, is
15149 that the binder ensures that the program is consistent with the latest
15150 version of the source files that can be located at bind time. Editing a
15151 source file without compiling files that depend on the source file cause
15152 error messages to be generated by the binder.
15154 For example, suppose you have a main program @code{hello.adb} and a
15155 package @cite{P}, from file @code{p.ads} and you perform the following
15162 Enter @cite{gcc -c hello.adb} to compile the main program.
15165 Enter @cite{gcc -c p.ads} to compile package @cite{P}.
15168 Edit file @code{p.ads}.
15171 Enter @cite{gnatbind hello}.
15174 At this point, the file @code{p.ali} contains an out-of-date time stamp
15175 because the file @code{p.ads} has been edited. The attempt at binding
15176 fails, and the binder generates the following error messages:
15179 error: "hello.adb" must be recompiled ("p.ads" has been modified)
15180 error: "p.ads" has been modified and must be recompiled
15183 Now both files must be recompiled as indicated, and then the bind can
15184 succeed, generating a main program. You need not normally be concerned
15185 with the contents of this file, but for reference purposes a sample
15186 binder output file is given in @ref{10,,Example of Binder Output File}.
15188 In most normal usage, the default mode of @emph{gnatbind} which is to
15189 generate the main package in Ada, as described in the previous section.
15190 In particular, this means that any Ada programmer can read and understand
15191 the generated main program. It can also be debugged just like any other
15192 Ada code provided the @emph{-g} switch is used for
15193 @emph{gnatbind} and @emph{gnatlink}.
15195 @node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15196 @anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{125}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{126}
15197 @subsection Switches for @emph{gnatbind}
15200 The following switches are available with @cite{gnatbind}; details will
15201 be presented in subsequent sections.
15203 @geindex --version (gnatbind)
15208 @item @code{--version}
15210 Display Copyright and version, then exit disregarding all other options.
15213 @geindex --help (gnatbind)
15218 @item @code{--help}
15220 If @emph{--version} was not used, display usage, then exit disregarding
15224 @geindex -a (gnatbind)
15231 Indicates that, if supported by the platform, the adainit procedure should
15232 be treated as an initialisation routine by the linker (a constructor). This
15233 is intended to be used by the Project Manager to automatically initialize
15234 shared Stand-Alone Libraries.
15237 @geindex -aO (gnatbind)
15244 Specify directory to be searched for ALI files.
15247 @geindex -aI (gnatbind)
15254 Specify directory to be searched for source file.
15257 @geindex -A (gnatbind)
15262 @item @code{-A[=@emph{filename}]}
15264 Output ALI list (to standard output or to the named file).
15267 @geindex -b (gnatbind)
15274 Generate brief messages to @code{stderr} even if verbose mode set.
15277 @geindex -c (gnatbind)
15284 Check only, no generation of binder output file.
15287 @geindex -dnn[k|m] (gnatbind)
15292 @item @code{-d@emph{nn}[k|m]}
15294 This switch can be used to change the default task stack size value
15295 to a specified size @cite{nn}, which is expressed in bytes by default, or
15296 in kilobytes when suffixed with @cite{k} or in megabytes when suffixed
15298 In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15299 in effect, to completing all task specs with
15302 pragma Storage_Size (nn);
15305 When they do not already have such a pragma.
15308 @geindex -D (gnatbind)
15313 @item @code{-D@emph{nn}[k|m]}
15315 This switch can be used to change the default secondary stack size value
15316 to a specified size @cite{nn}, which is expressed in bytes by default, or
15317 in kilobytes when suffixed with @cite{k} or in megabytes when suffixed
15320 The secondary stack is used to deal with functions that return a variable
15321 sized result, for example a function returning an unconstrained
15322 String. There are two ways in which this secondary stack is allocated.
15324 For most targets, the secondary stack is growing on demand and is allocated
15325 as a chain of blocks in the heap. The -D option is not very
15326 relevant. It only give some control over the size of the allocated
15327 blocks (whose size is the minimum of the default secondary stack size value,
15328 and the actual size needed for the current allocation request).
15330 For certain targets, notably VxWorks 653,
15331 the secondary stack is allocated by carving off a fixed ratio chunk of the
15332 primary task stack. The -D option is used to define the
15333 size of the environment task's secondary stack.
15336 @geindex -e (gnatbind)
15343 Output complete list of elaboration-order dependencies.
15346 @geindex -Ea (gnatbind)
15353 Store tracebacks in exception occurrences when the target supports it.
15354 The "a" is for "address"; tracebacks will contain hexadecimal addresses,
15355 unless symbolic tracebacks are enabled.
15357 See also the packages @cite{GNAT.Traceback} and
15358 @cite{GNAT.Traceback.Symbolic} for more information.
15359 Note that on x86 ports, you must not use @emph{-fomit-frame-pointer}
15363 @geindex -Es (gnatbind)
15370 Store tracebacks in exception occurrences when the target supports it.
15371 The "s" is for "symbolic"; symbolic tracebacks are enabled.
15374 @geindex -E (gnatbind)
15381 Currently the same as @cite{-Ea}.
15384 @geindex -F (gnatbind)
15391 Force the checks of elaboration flags. @emph{gnatbind} does not normally
15392 generate checks of elaboration flags for the main executable, except when
15393 a Stand-Alone Library is used. However, there are cases when this cannot be
15394 detected by gnatbind. An example is importing an interface of a Stand-Alone
15395 Library through a pragma Import and only specifying through a linker switch
15396 this Stand-Alone Library. This switch is used to guarantee that elaboration
15397 flag checks are generated.
15400 @geindex -h (gnatbind)
15407 Output usage (help) information.
15409 @geindex -H32 (gnatbind)
15413 Use 32-bit allocations for @cite{__gnat_malloc} (and thus for access types).
15414 For further details see @ref{127,,Dynamic Allocation Control}.
15416 @geindex -H64 (gnatbind)
15418 @geindex __gnat_malloc
15422 Use 64-bit allocations for @cite{__gnat_malloc} (and thus for access types).
15423 For further details see @ref{127,,Dynamic Allocation Control}.
15425 @geindex -I (gnatbind)
15429 Specify directory to be searched for source and ALI files.
15431 @geindex -I- (gnatbind)
15435 Do not look for sources in the current directory where @cite{gnatbind} was
15436 invoked, and do not look for ALI files in the directory containing the
15437 ALI file named in the @cite{gnatbind} command line.
15439 @geindex -l (gnatbind)
15443 Output chosen elaboration order.
15445 @geindex -L (gnatbind)
15447 @item @code{-L@emph{xxx}}
15449 Bind the units for library building. In this case the adainit and
15450 adafinal procedures (@ref{ba,,Binding with Non-Ada Main Programs})
15451 are renamed to @cite{xxx`init and `xxx`final. Implies -n. (:ref:`GNAT_and_Libraries}, for more details.)
15453 @geindex -M (gnatbind)
15455 @item @code{-M@emph{xyz}}
15457 Rename generated main program from main to xyz. This option is
15458 supported on cross environments only.
15460 @geindex -m (gnatbind)
15462 @item @code{-m@emph{n}}
15464 Limit number of detected errors or warnings to @cite{n}, where @cite{n} is
15465 in the range 1..999999. The default value if no switch is
15466 given is 9999. If the number of warnings reaches this limit, then a
15467 message is output and further warnings are suppressed, the bind
15468 continues in this case. If the number of errors reaches this
15469 limit, then a message is output and the bind is abandoned.
15470 A value of zero means that no limit is enforced. The equal
15473 @geindex -n (gnatbind)
15479 @geindex -nostdinc (gnatbind)
15481 @item @code{-nostdinc}
15483 Do not look for sources in the system default directory.
15485 @geindex -nostdlib (gnatbind)
15487 @item @code{-nostdlib}
15489 Do not look for library files in the system default directory.
15491 @geindex --RTS (gnatbind)
15493 @item @code{--RTS=@emph{rts-path}}
15495 Specifies the default location of the runtime library. Same meaning as the
15496 equivalent @emph{gnatmake} flag (@ref{e2,,Switches for gnatmake}).
15498 @geindex -o (gnatbind)
15500 @item @code{-o @emph{file}}
15502 Name the output file @cite{file} (default is @code{b~`xxx}.adb`).
15503 Note that if this option is used, then linking must be done manually,
15504 gnatlink cannot be used.
15506 @geindex -O (gnatbind)
15508 @item @code{-O[=@emph{filename}]}
15510 Output object list (to standard output or to the named file).
15512 @geindex -p (gnatbind)
15516 Pessimistic (worst-case) elaboration order.
15518 @geindex -P (gnatbind)
15522 Generate binder file suitable for CodePeer.
15524 @geindex -R (gnatbind)
15528 Output closure source list, which includes all non-run-time units that are
15529 included in the bind.
15531 @geindex -Ra (gnatbind)
15535 Like @emph{-R} but the list includes run-time units.
15537 @geindex -s (gnatbind)
15541 Require all source files to be present.
15543 @geindex -S (gnatbind)
15545 @item @code{-S@emph{xxx}}
15547 Specifies the value to be used when detecting uninitialized scalar
15548 objects with pragma Initialize_Scalars.
15549 The @cite{xxx} string specified with the switch is one of:
15555 @code{in} for an invalid value.
15557 If zero is invalid for the discrete type in question,
15558 then the scalar value is set to all zero bits.
15559 For signed discrete types, the largest possible negative value of
15560 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15561 For unsigned discrete types, the underlying scalar value is set to all
15562 one bits. For floating-point types, a NaN value is set
15563 (see body of package System.Scalar_Values for exact values).
15566 @code{lo} for low value.
15568 If zero is invalid for the discrete type in question,
15569 then the scalar value is set to all zero bits.
15570 For signed discrete types, the largest possible negative value of
15571 the underlying scalar is set (i.e. a one bit followed by all zero bits).
15572 For unsigned discrete types, the underlying scalar value is set to all
15573 zero bits. For floating-point, a small value is set
15574 (see body of package System.Scalar_Values for exact values).
15577 @code{hi} for high value.
15579 If zero is invalid for the discrete type in question,
15580 then the scalar value is set to all one bits.
15581 For signed discrete types, the largest possible positive value of
15582 the underlying scalar is set (i.e. a zero bit followed by all one bits).
15583 For unsigned discrete types, the underlying scalar value is set to all
15584 one bits. For floating-point, a large value is set
15585 (see body of package System.Scalar_Values for exact values).
15588 @cite{xx} for hex value (two hex digits).
15590 The underlying scalar is set to a value consisting of repeated bytes, whose
15591 value corresponds to the given value. For example if @code{BF} is given,
15592 then a 32-bit scalar value will be set to the bit patterm @code{16#BFBFBFBF#}.
15595 @geindex GNAT_INIT_SCALARS
15597 In addition, you can specify @emph{-Sev} to indicate that the value is
15598 to be set at run time. In this case, the program will look for an environment
15599 variable of the form @code{GNAT_INIT_SCALARS=@emph{yy}}, where @cite{yy} is one
15600 of @emph{in/lo/hi/`xx*` with the same meanings as above.
15601 If no environment variable is found, or if it does not have a valid value,
15602 then the default is *in} (invalid values).
15605 @geindex -static (gnatbind)
15610 @item @code{-static}
15612 Link against a static GNAT run time.
15614 @geindex -shared (gnatbind)
15616 @item @code{-shared}
15618 Link against a shared GNAT run time when available.
15620 @geindex -t (gnatbind)
15624 Tolerate time stamp and other consistency errors.
15626 @geindex -T (gnatbind)
15628 @item @code{-T@emph{n}}
15630 Set the time slice value to @cite{n} milliseconds. If the system supports
15631 the specification of a specific time slice value, then the indicated value
15632 is used. If the system does not support specific time slice values, but
15633 does support some general notion of round-robin scheduling, then any
15634 nonzero value will activate round-robin scheduling.
15636 A value of zero is treated specially. It turns off time
15637 slicing, and in addition, indicates to the tasking run time that the
15638 semantics should match as closely as possible the Annex D
15639 requirements of the Ada RM, and in particular sets the default
15640 scheduling policy to @cite{FIFO_Within_Priorities}.
15642 @geindex -u (gnatbind)
15644 @item @code{-u@emph{n}}
15646 Enable dynamic stack usage, with @cite{n} results stored and displayed
15647 at program termination. A result is generated when a task
15648 terminates. Results that can't be stored are displayed on the fly, at
15649 task termination. This option is currently not supported on Itanium
15650 platforms. (See @ref{128,,Dynamic Stack Usage Analysis} for details.)
15652 @geindex -v (gnatbind)
15656 Verbose mode. Write error messages, header, summary output to
15659 @geindex -V (gnatbind)
15661 @item @code{-V@emph{key}=@emph{value}}
15663 Store the given association of @cite{key} to @cite{value} in the bind environment.
15664 Values stored this way can be retrieved at run time using
15665 @cite{GNAT.Bind_Environment}.
15667 @geindex -w (gnatbind)
15669 @item @code{-w@emph{x}}
15671 Warning mode; @cite{x} = s/e for suppress/treat as error.
15673 @geindex -Wx (gnatbind)
15675 @item @code{-Wx@emph{e}}
15677 Override default wide character encoding for standard Text_IO files.
15679 @geindex -x (gnatbind)
15683 Exclude source files (check object consistency only).
15685 @geindex -Xnnn (gnatbind)
15687 @item @code{-X@emph{nnn}}
15689 Set default exit status value, normally 0 for POSIX compliance.
15691 @geindex -y (gnatbind)
15695 Enable leap seconds support in @cite{Ada.Calendar} and its children.
15697 @geindex -z (gnatbind)
15701 No main subprogram.
15704 You may obtain this listing of switches by running @cite{gnatbind} with
15708 * Consistency-Checking Modes::
15709 * Binder Error Message Control::
15710 * Elaboration Control::
15712 * Dynamic Allocation Control::
15713 * Binding with Non-Ada Main Programs::
15714 * Binding Programs with No Main Subprogram::
15718 @node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
15719 @anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{129}@anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{12a}
15720 @subsubsection Consistency-Checking Modes
15723 As described earlier, by default @cite{gnatbind} checks
15724 that object files are consistent with one another and are consistent
15725 with any source files it can locate. The following switches control binder
15730 @geindex -s (gnatbind)
15738 Require source files to be present. In this mode, the binder must be
15739 able to locate all source files that are referenced, in order to check
15740 their consistency. In normal mode, if a source file cannot be located it
15741 is simply ignored. If you specify this switch, a missing source
15744 @geindex -Wx (gnatbind)
15746 @item @code{-Wx@emph{e}}
15748 Override default wide character encoding for standard Text_IO files.
15749 Normally the default wide character encoding method used for standard
15750 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
15751 the main source input (see description of switch
15752 @emph{-gnatWx} for the compiler). The
15753 use of this switch for the binder (which has the same set of
15754 possible arguments) overrides this default as specified.
15756 @geindex -x (gnatbind)
15760 Exclude source files. In this mode, the binder only checks that ALI
15761 files are consistent with one another. Source files are not accessed.
15762 The binder runs faster in this mode, and there is still a guarantee that
15763 the resulting program is self-consistent.
15764 If a source file has been edited since it was last compiled, and you
15765 specify this switch, the binder will not detect that the object
15766 file is out of date with respect to the source file. Note that this is the
15767 mode that is automatically used by @emph{gnatmake} because in this
15768 case the checking against sources has already been performed by
15769 @emph{gnatmake} in the course of compilation (i.e., before binding).
15772 @node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
15773 @anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{12b}@anchor{gnat_ugn/building_executable_programs_with_gnat binder-error-message-control}@anchor{12c}
15774 @subsubsection Binder Error Message Control
15777 The following switches provide control over the generation of error
15778 messages from the binder:
15782 @geindex -v (gnatbind)
15790 Verbose mode. In the normal mode, brief error messages are generated to
15791 @code{stderr}. If this switch is present, a header is written
15792 to @code{stdout} and any error messages are directed to @code{stdout}.
15793 All that is written to @code{stderr} is a brief summary message.
15795 @geindex -b (gnatbind)
15799 Generate brief error messages to @code{stderr} even if verbose mode is
15800 specified. This is relevant only when used with the
15803 @geindex -m (gnatbind)
15805 @item @code{-m@emph{n}}
15807 Limits the number of error messages to @cite{n}, a decimal integer in the
15808 range 1-999. The binder terminates immediately if this limit is reached.
15810 @geindex -M (gnatbind)
15812 @item @code{-M@emph{xxx}}
15814 Renames the generated main program from @cite{main} to @cite{xxx}.
15815 This is useful in the case of some cross-building environments, where
15816 the actual main program is separate from the one generated
15817 by @cite{gnatbind}.
15819 @geindex -ws (gnatbind)
15825 Suppress all warning messages.
15827 @geindex -we (gnatbind)
15831 Treat any warning messages as fatal errors.
15833 @geindex -t (gnatbind)
15835 @geindex Time stamp checks
15838 @geindex Binder consistency checks
15840 @geindex Consistency checks
15845 The binder performs a number of consistency checks including:
15851 Check that time stamps of a given source unit are consistent
15854 Check that checksums of a given source unit are consistent
15857 Check that consistent versions of @cite{GNAT} were used for compilation
15860 Check consistency of configuration pragmas as required
15863 Normally failure of such checks, in accordance with the consistency
15864 requirements of the Ada Reference Manual, causes error messages to be
15865 generated which abort the binder and prevent the output of a binder
15866 file and subsequent link to obtain an executable.
15868 The @emph{-t} switch converts these error messages
15869 into warnings, so that
15870 binding and linking can continue to completion even in the presence of such
15871 errors. The result may be a failed link (due to missing symbols), or a
15872 non-functional executable which has undefined semantics.
15876 This means that @emph{-t} should be used only in unusual situations,
15882 @node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
15883 @anchor{gnat_ugn/building_executable_programs_with_gnat id36}@anchor{12d}@anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{12e}
15884 @subsubsection Elaboration Control
15887 The following switches provide additional control over the elaboration
15888 order. For full details see @ref{11,,Elaboration Order Handling in GNAT}.
15892 @geindex -p (gnatbind)
15900 Normally the binder attempts to choose an elaboration order that is
15901 likely to minimize the likelihood of an elaboration order error resulting
15902 in raising a @cite{Program_Error} exception. This switch reverses the
15903 action of the binder, and requests that it deliberately choose an order
15904 that is likely to maximize the likelihood of an elaboration error.
15905 This is useful in ensuring portability and avoiding dependence on
15906 accidental fortuitous elaboration ordering.
15908 Normally it only makes sense to use the @emph{-p}
15910 elaboration checking is used (@emph{-gnatE} switch used for compilation).
15911 This is because in the default static elaboration mode, all necessary
15912 @cite{Elaborate} and @cite{Elaborate_All} pragmas are implicitly inserted.
15913 These implicit pragmas are still respected by the binder in
15914 @emph{-p} mode, so a
15915 safe elaboration order is assured.
15917 Note that @emph{-p} is not intended for
15918 production use; it is more for debugging/experimental use.
15921 @node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
15922 @anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{12f}@anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{130}
15923 @subsubsection Output Control
15926 The following switches allow additional control over the output
15927 generated by the binder.
15931 @geindex -c (gnatbind)
15939 Check only. Do not generate the binder output file. In this mode the
15940 binder performs all error checks but does not generate an output file.
15942 @geindex -e (gnatbind)
15946 Output complete list of elaboration-order dependencies, showing the
15947 reason for each dependency. This output can be rather extensive but may
15948 be useful in diagnosing problems with elaboration order. The output is
15949 written to @code{stdout}.
15951 @geindex -h (gnatbind)
15955 Output usage information. The output is written to @code{stdout}.
15957 @geindex -K (gnatbind)
15961 Output linker options to @code{stdout}. Includes library search paths,
15962 contents of pragmas Ident and Linker_Options, and libraries added
15963 by @cite{gnatbind}.
15965 @geindex -l (gnatbind)
15969 Output chosen elaboration order. The output is written to @code{stdout}.
15971 @geindex -O (gnatbind)
15975 Output full names of all the object files that must be linked to provide
15976 the Ada component of the program. The output is written to @code{stdout}.
15977 This list includes the files explicitly supplied and referenced by the user
15978 as well as implicitly referenced run-time unit files. The latter are
15979 omitted if the corresponding units reside in shared libraries. The
15980 directory names for the run-time units depend on the system configuration.
15982 @geindex -o (gnatbind)
15984 @item @code{-o @emph{file}}
15986 Set name of output file to @cite{file} instead of the normal
15987 @code{b~`mainprog}.adb` default. Note that @cite{file} denote the Ada
15988 binder generated body filename.
15989 Note that if this option is used, then linking must be done manually.
15990 It is not possible to use gnatlink in this case, since it cannot locate
15993 @geindex -r (gnatbind)
15997 Generate list of @cite{pragma Restrictions} that could be applied to
15998 the current unit. This is useful for code audit purposes, and also may
15999 be used to improve code generation in some cases.
16002 @node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
16003 @anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{127}@anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{131}
16004 @subsubsection Dynamic Allocation Control
16007 The heap control switches -- @emph{-H32} and @emph{-H64} --
16008 determine whether dynamic allocation uses 32-bit or 64-bit memory.
16009 They only affect compiler-generated allocations via @cite{__gnat_malloc};
16010 explicit calls to @cite{malloc} and related functions from the C
16011 run-time library are unaffected.
16018 Allocate memory on 32-bit heap
16022 Allocate memory on 64-bit heap. This is the default
16023 unless explicitly overridden by a @cite{'Size} clause on the access type.
16026 These switches are only effective on VMS platforms.
16028 @node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
16029 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-non-ada-main-programs}@anchor{ba}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{132}
16030 @subsubsection Binding with Non-Ada Main Programs
16033 The description so far has assumed that the main
16034 program is in Ada, and that the task of the binder is to generate a
16035 corresponding function @cite{main} that invokes this Ada main
16036 program. GNAT also supports the building of executable programs where
16037 the main program is not in Ada, but some of the called routines are
16038 written in Ada and compiled using GNAT (@ref{46,,Mixed Language Programming}).
16039 The following switch is used in this situation:
16043 @geindex -n (gnatbind)
16051 No main program. The main program is not in Ada.
16054 In this case, most of the functions of the binder are still required,
16055 but instead of generating a main program, the binder generates a file
16056 containing the following callable routines:
16065 @item @emph{adainit}
16067 You must call this routine to initialize the Ada part of the program by
16068 calling the necessary elaboration routines. A call to @cite{adainit} is
16069 required before the first call to an Ada subprogram.
16071 Note that it is assumed that the basic execution environment must be setup
16072 to be appropriate for Ada execution at the point where the first Ada
16073 subprogram is called. In particular, if the Ada code will do any
16074 floating-point operations, then the FPU must be setup in an appropriate
16075 manner. For the case of the x86, for example, full precision mode is
16076 required. The procedure GNAT.Float_Control.Reset may be used to ensure
16077 that the FPU is in the right state.
16085 @item @emph{adafinal}
16087 You must call this routine to perform any library-level finalization
16088 required by the Ada subprograms. A call to @cite{adafinal} is required
16089 after the last call to an Ada subprogram, and before the program
16094 @geindex -n (gnatbind)
16097 @geindex multiple input files
16099 If the @emph{-n} switch
16100 is given, more than one ALI file may appear on
16101 the command line for @cite{gnatbind}. The normal @emph{closure}
16102 calculation is performed for each of the specified units. Calculating
16103 the closure means finding out the set of units involved by tracing
16104 @emph{with} references. The reason it is necessary to be able to
16105 specify more than one ALI file is that a given program may invoke two or
16106 more quite separate groups of Ada units.
16108 The binder takes the name of its output file from the last specified ALI
16109 file, unless overridden by the use of the @emph{-o file}.
16111 @geindex -o (gnatbind)
16113 The output is an Ada unit in source form that can be compiled with GNAT.
16114 This compilation occurs automatically as part of the @emph{gnatlink}
16117 Currently the GNAT run time requires a FPU using 80 bits mode
16118 precision. Under targets where this is not the default it is required to
16119 call GNAT.Float_Control.Reset before using floating point numbers (this
16120 include float computation, float input and output) in the Ada code. A
16121 side effect is that this could be the wrong mode for the foreign code
16122 where floating point computation could be broken after this call.
16124 @node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16125 @anchor{gnat_ugn/building_executable_programs_with_gnat binding-programs-with-no-main-subprogram}@anchor{133}@anchor{gnat_ugn/building_executable_programs_with_gnat id40}@anchor{134}
16126 @subsubsection Binding Programs with No Main Subprogram
16129 It is possible to have an Ada program which does not have a main
16130 subprogram. This program will call the elaboration routines of all the
16131 packages, then the finalization routines.
16133 The following switch is used to bind programs organized in this manner:
16137 @geindex -z (gnatbind)
16145 Normally the binder checks that the unit name given on the command line
16146 corresponds to a suitable main subprogram. When this switch is used,
16147 a list of ALI files can be given, and the execution of the program
16148 consists of elaboration of these units in an appropriate order. Note
16149 that the default wide character encoding method for standard Text_IO
16150 files is always set to Brackets if this switch is set (you can use
16152 @emph{-Wx} to override this default).
16155 @node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16156 @anchor{gnat_ugn/building_executable_programs_with_gnat id41}@anchor{135}@anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{136}
16157 @subsection Command-Line Access
16160 The package @cite{Ada.Command_Line} provides access to the command-line
16161 arguments and program name. In order for this interface to operate
16162 correctly, the two variables
16173 are declared in one of the GNAT library routines. These variables must
16174 be set from the actual @cite{argc} and @cite{argv} values passed to the
16175 main program. With no @emph{n} present, @cite{gnatbind}
16176 generates the C main program to automatically set these variables.
16177 If the @emph{n} switch is used, there is no automatic way to
16178 set these variables. If they are not set, the procedures in
16179 @cite{Ada.Command_Line} will not be available, and any attempt to use
16180 them will raise @cite{Constraint_Error}. If command line access is
16181 required, your main program must set @cite{gnat_argc} and
16182 @cite{gnat_argv} from the @cite{argc} and @cite{argv} values passed to
16185 @node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16186 @anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-for-gnatbind}@anchor{91}@anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{137}
16187 @subsection Search Paths for @cite{gnatbind}
16190 The binder takes the name of an ALI file as its argument and needs to
16191 locate source files as well as other ALI files to verify object consistency.
16193 For source files, it follows exactly the same search rules as @emph{gcc}
16194 (see @ref{8e,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16195 directories searched are:
16201 The directory containing the ALI file named in the command line, unless
16202 the switch @emph{-I-} is specified.
16205 All directories specified by @emph{-I}
16206 switches on the @cite{gnatbind}
16207 command line, in the order given.
16209 @geindex ADA_PRJ_OBJECTS_FILE
16212 Each of the directories listed in the text file whose name is given
16214 @geindex ADA_PRJ_OBJECTS_FILE
16215 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16216 @code{ADA_PRJ_OBJECTS_FILE} environment variable.
16218 @geindex ADA_PRJ_OBJECTS_FILE
16219 @geindex environment variable; ADA_PRJ_OBJECTS_FILE
16220 @code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16221 driver when project files are used. It should not normally be set
16224 @geindex ADA_OBJECTS_PATH
16227 Each of the directories listed in the value of the
16228 @geindex ADA_OBJECTS_PATH
16229 @geindex environment variable; ADA_OBJECTS_PATH
16230 @code{ADA_OBJECTS_PATH} environment variable.
16231 Construct this value
16234 @geindex environment variable; PATH
16235 @code{PATH} environment variable: a list of directory
16236 names separated by colons (semicolons when working with the NT version
16240 The content of the @code{ada_object_path} file which is part of the GNAT
16241 installation tree and is used to store standard libraries such as the
16242 GNAT Run Time Library (RTL) unless the switch @emph{-nostdlib} is
16243 specified. See @ref{8b,,Installing a library}
16246 @geindex -I (gnatbind)
16248 @geindex -aI (gnatbind)
16250 @geindex -aO (gnatbind)
16252 In the binder the switch @emph{-I}
16253 is used to specify both source and
16254 library file paths. Use @emph{-aI}
16255 instead if you want to specify
16256 source paths only, and @emph{-aO}
16257 if you want to specify library paths
16258 only. This means that for the binder
16259 @code{-I@emph{dir}} is equivalent to
16260 @code{-aI@emph{dir}}
16261 @code{-aO`@emph{dir}}.
16262 The binder generates the bind file (a C language source file) in the
16263 current working directory.
16269 @geindex Interfaces
16273 The packages @cite{Ada}, @cite{System}, and @cite{Interfaces} and their
16274 children make up the GNAT Run-Time Library, together with the package
16275 GNAT and its children, which contain a set of useful additional
16276 library functions provided by GNAT. The sources for these units are
16277 needed by the compiler and are kept together in one directory. The ALI
16278 files and object files generated by compiling the RTL are needed by the
16279 binder and the linker and are kept together in one directory, typically
16280 different from the directory containing the sources. In a normal
16281 installation, you need not specify these directory names when compiling
16282 or binding. Either the environment variables or the built-in defaults
16283 cause these files to be found.
16285 Besides simplifying access to the RTL, a major use of search paths is
16286 in compiling sources from multiple directories. This can make
16287 development environments much more flexible.
16289 @node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16290 @anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatbind-usage}@anchor{138}@anchor{gnat_ugn/building_executable_programs_with_gnat id43}@anchor{139}
16291 @subsection Examples of @cite{gnatbind} Usage
16294 Here are some examples of @cite{gnatbind} invovations:
16302 The main program @cite{Hello} (source program in @code{hello.adb}) is
16303 bound using the standard switch settings. The generated main program is
16304 @code{b~hello.adb}. This is the normal, default use of the binder.
16307 gnatbind hello -o mainprog.adb
16310 The main program @cite{Hello} (source program in @code{hello.adb}) is
16311 bound using the standard switch settings. The generated main program is
16312 @code{mainprog.adb} with the associated spec in
16313 @code{mainprog.ads}. Note that you must specify the body here not the
16314 spec. Note that if this option is used, then linking must be done manually,
16315 since gnatlink will not be able to find the generated file.
16318 @node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16319 @anchor{gnat_ugn/building_executable_programs_with_gnat id44}@anchor{13a}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{20}
16320 @section Linking with @emph{gnatlink}
16325 This chapter discusses @emph{gnatlink}, a tool that links
16326 an Ada program and builds an executable file. This utility
16327 invokes the system linker (via the @emph{gcc} command)
16328 with a correct list of object files and library references.
16329 @emph{gnatlink} automatically determines the list of files and
16330 references for the Ada part of a program. It uses the binder file
16331 generated by the @emph{gnatbind} to determine this list.
16333 Note: to invoke @cite{gnatlink} with a project file, use the @cite{gnat}
16334 driver (see @ref{122,,The GNAT Driver and Project Files}).
16337 * Running gnatlink::
16338 * Switches for gnatlink::
16342 @node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16343 @anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{13b}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{13c}
16344 @subsection Running @emph{gnatlink}
16347 The form of the @emph{gnatlink} command is
16350 $ gnatlink [`switches`] `mainprog`[.ali]
16351 [`non-Ada objects`] [`linker options`]
16354 The arguments of @emph{gnatlink} (switches, main @code{ALI} file,
16356 or linker options) may be in any order, provided that no non-Ada object may
16357 be mistaken for a main @code{ALI} file.
16358 Any file name @code{F} without the @code{.ali}
16359 extension will be taken as the main @code{ALI} file if a file exists
16360 whose name is the concatenation of @code{F} and @code{.ali}.
16362 @code{mainprog.ali} references the ALI file of the main program.
16363 The @code{.ali} extension of this file can be omitted. From this
16364 reference, @emph{gnatlink} locates the corresponding binder file
16365 @code{b~mainprog.adb} and, using the information in this file along
16366 with the list of non-Ada objects and linker options, constructs a
16367 linker command file to create the executable.
16369 The arguments other than the @emph{gnatlink} switches and the main
16370 @code{ALI} file are passed to the linker uninterpreted.
16371 They typically include the names of
16372 object files for units written in other languages than Ada and any library
16373 references required to resolve references in any of these foreign language
16374 units, or in @cite{Import} pragmas in any Ada units.
16376 @cite{linker options} is an optional list of linker specific
16378 The default linker called by gnatlink is @emph{gcc} which in
16379 turn calls the appropriate system linker.
16381 One useful option for the linker is @emph{-s}: it reduces the size of the
16382 executable by removing all symbol table and relocation information from the
16385 Standard options for the linker such as @emph{-lmy_lib} or
16386 @emph{-Ldir} can be added as is.
16387 For options that are not recognized by
16388 @emph{gcc} as linker options, use the @emph{gcc} switches
16389 @emph{-Xlinker} or @emph{-Wl,}.
16391 Refer to the GCC documentation for
16394 Here is an example showing how to generate a linker map:
16397 $ gnatlink my_prog -Wl,-Map,MAPFILE
16400 Using @cite{linker options} it is possible to set the program stack and
16402 See @ref{13d,,Setting Stack Size from gnatlink} and
16403 @ref{13e,,Setting Heap Size from gnatlink}.
16405 @emph{gnatlink} determines the list of objects required by the Ada
16406 program and prepends them to the list of objects passed to the linker.
16407 @emph{gnatlink} also gathers any arguments set by the use of
16408 @cite{pragma Linker_Options} and adds them to the list of arguments
16409 presented to the linker.
16411 @node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
16412 @anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{13f}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{140}
16413 @subsection Switches for @emph{gnatlink}
16416 The following switches are available with the @emph{gnatlink} utility:
16418 @geindex --version (gnatlink)
16423 @item @code{--version}
16425 Display Copyright and version, then exit disregarding all other options.
16428 @geindex --help (gnatlink)
16433 @item @code{--help}
16435 If @emph{--version} was not used, display usage, then exit disregarding
16439 @geindex Command line length
16441 @geindex -f (gnatlink)
16448 On some targets, the command line length is limited, and @emph{gnatlink}
16449 will generate a separate file for the linker if the list of object files
16451 The @emph{-f} switch forces this file
16452 to be generated even if
16453 the limit is not exceeded. This is useful in some cases to deal with
16454 special situations where the command line length is exceeded.
16457 @geindex Debugging information
16460 @geindex -g (gnatlink)
16467 The option to include debugging information causes the Ada bind file (in
16468 other words, @code{b~mainprog.adb}) to be compiled with @emph{-g}.
16469 In addition, the binder does not delete the @code{b~mainprog.adb},
16470 @code{b~mainprog.o} and @code{b~mainprog.ali} files.
16471 Without @emph{-g}, the binder removes these files by default.
16474 @geindex -n (gnatlink)
16481 Do not compile the file generated by the binder. This may be used when
16482 a link is rerun with different options, but there is no need to recompile
16486 @geindex -v (gnatlink)
16493 Verbose mode. Causes additional information to be output, including a full
16494 list of the included object files.
16495 This switch option is most useful when you want
16496 to see what set of object files are being used in the link step.
16499 @geindex -v -v (gnatlink)
16506 Very verbose mode. Requests that the compiler operate in verbose mode when
16507 it compiles the binder file, and that the system linker run in verbose mode.
16510 @geindex -o (gnatlink)
16515 @item @code{-o @emph{exec-name}}
16517 @cite{exec-name} specifies an alternate name for the generated
16518 executable program. If this switch is omitted, the executable has the same
16519 name as the main unit. For example, @cite{gnatlink try.ali} creates
16520 an executable called @code{try}.
16523 @geindex -b (gnatlink)
16528 @item @code{-b @emph{target}}
16530 Compile your program to run on @cite{target}, which is the name of a
16531 system configuration. You must have a GNAT cross-compiler built if
16532 @cite{target} is not the same as your host system.
16535 @geindex -B (gnatlink)
16540 @item @code{-B@emph{dir}}
16542 Load compiler executables (for example, @cite{gnat1}, the Ada compiler)
16543 from @cite{dir} instead of the default location. Only use this switch
16544 when multiple versions of the GNAT compiler are available.
16545 See the @cite{Directory Options} section in @cite{The_GNU_Compiler_Collection}
16546 for further details. You would normally use the @emph{-b} or
16547 @emph{-V} switch instead.
16550 @geindex -M (gnatlink)
16557 When linking an executable, create a map file. The name of the map file
16558 has the same name as the executable with extension ".map".
16561 @geindex -M= (gnatlink)
16566 @item @code{-M=@emph{mapfile}}
16568 When linking an executable, create a map file. The name of the map file is
16572 @geindex --GCC=compiler_name (gnatlink)
16577 @item @code{--GCC=@emph{compiler_name}}
16579 Program used for compiling the binder file. The default is
16580 @code{gcc}. You need to use quotes around @cite{compiler_name} if
16581 @cite{compiler_name} contains spaces or other separator characters.
16582 As an example @code{--GCC="foo -x -y"} will instruct @emph{gnatlink} to
16583 use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
16584 inserted after your command name. Thus in the above example the compiler
16585 command that will be used by @emph{gnatlink} will be @code{foo -c -x -y}.
16586 A limitation of this syntax is that the name and path name of the executable
16587 itself must not include any embedded spaces. If the compiler executable is
16588 different from the default one (gcc or <prefix>-gcc), then the back-end
16589 switches in the ALI file are not used to compile the binder generated source.
16590 For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
16591 switches will be used for @code{--GCC="gcc -gnatv"}. If several
16592 @code{--GCC=compiler_name} are used, only the last @cite{compiler_name}
16593 is taken into account. However, all the additional switches are also taken
16594 into account. Thus,
16595 @code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
16596 @code{--GCC="bar -x -y -z -t"}.
16599 @geindex --LINK= (gnatlink)
16604 @item @code{--LINK=@emph{name}}
16606 @cite{name} is the name of the linker to be invoked. This is especially
16607 useful in mixed language programs since languages such as C++ require
16608 their own linker to be used. When this switch is omitted, the default
16609 name for the linker is @emph{gcc}. When this switch is used, the
16610 specified linker is called instead of @emph{gcc} with exactly the same
16611 parameters that would have been passed to @emph{gcc} so if the desired
16612 linker requires different parameters it is necessary to use a wrapper
16613 script that massages the parameters before invoking the real linker. It
16614 may be useful to control the exact invocation by using the verbose
16618 @node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
16619 @anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{141}@anchor{gnat_ugn/building_executable_programs_with_gnat using-the-gnu-make-utility}@anchor{21}
16620 @section Using the GNU @cite{make} Utility
16623 @geindex make (GNU)
16626 This chapter offers some examples of makefiles that solve specific
16627 problems. It does not explain how to write a makefile, nor does it try to replace the
16628 @emph{gnatmake} utility (@ref{1d,,Building with gnatmake}).
16630 All the examples in this section are specific to the GNU version of
16631 make. Although @emph{make} is a standard utility, and the basic language
16632 is the same, these examples use some advanced features found only in
16636 * Using gnatmake in a Makefile::
16637 * Automatically Creating a List of Directories::
16638 * Generating the Command Line Switches::
16639 * Overcoming Command Line Length Limits::
16643 @node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
16644 @anchor{gnat_ugn/building_executable_programs_with_gnat using-gnatmake-in-a-makefile}@anchor{142}@anchor{gnat_ugn/building_executable_programs_with_gnat id48}@anchor{143}
16645 @subsection Using gnatmake in a Makefile
16648 @c index makefile (GNU make)
16650 Complex project organizations can be handled in a very powerful way by
16651 using GNU make combined with gnatmake. For instance, here is a Makefile
16652 which allows you to build each subsystem of a big project into a separate
16653 shared library. Such a makefile allows you to significantly reduce the link
16654 time of very big applications while maintaining full coherence at
16655 each step of the build process.
16657 The list of dependencies are handled automatically by
16658 @emph{gnatmake}. The Makefile is simply used to call gnatmake in each of
16659 the appropriate directories.
16661 Note that you should also read the example on how to automatically
16662 create the list of directories
16663 (@ref{144,,Automatically Creating a List of Directories})
16664 which might help you in case your project has a lot of subdirectories.
16667 ## This Makefile is intended to be used with the following directory
16669 ## - The sources are split into a series of csc (computer software components)
16670 ## Each of these csc is put in its own directory.
16671 ## Their name are referenced by the directory names.
16672 ## They will be compiled into shared library (although this would also work
16673 ## with static libraries
16674 ## - The main program (and possibly other packages that do not belong to any
16675 ## csc is put in the top level directory (where the Makefile is).
16676 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
16677 ## \\_ second_csc (sources) __ lib (will contain the library)
16679 ## Although this Makefile is build for shared library, it is easy to modify
16680 ## to build partial link objects instead (modify the lines with -shared and
16683 ## With this makefile, you can change any file in the system or add any new
16684 ## file, and everything will be recompiled correctly (only the relevant shared
16685 ## objects will be recompiled, and the main program will be re-linked).
16687 # The list of computer software component for your project. This might be
16688 # generated automatically.
16691 # Name of the main program (no extension)
16694 # If we need to build objects with -fPIC, uncomment the following line
16697 # The following variable should give the directory containing libgnat.so
16698 # You can get this directory through 'gnatls -v'. This is usually the last
16699 # directory in the Object_Path.
16702 # The directories for the libraries
16703 # (This macro expands the list of CSC to the list of shared libraries, you
16704 # could simply use the expanded form:
16705 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16706 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16708 $@{MAIN@}: objects $@{LIB_DIR@}
16709 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16710 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16713 # recompile the sources
16714 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16716 # Note: In a future version of GNAT, the following commands will be simplified
16717 # by a new tool, gnatmlib
16719 mkdir -p $@{dir $@@ @}
16720 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16721 cd $@{dir $@@ @} && cp -f ../*.ali .
16723 # The dependencies for the modules
16724 # Note that we have to force the expansion of *.o, since in some cases
16725 # make won't be able to do it itself.
16726 aa/lib/libaa.so: $@{wildcard aa/*.o@}
16727 bb/lib/libbb.so: $@{wildcard bb/*.o@}
16728 cc/lib/libcc.so: $@{wildcard cc/*.o@}
16730 # Make sure all of the shared libraries are in the path before starting the
16733 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16736 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16737 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16738 $@{RM@} $@{CSC_LIST:%=%/*.o@}
16739 $@{RM@} *.o *.ali $@{MAIN@}
16742 @node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
16743 @anchor{gnat_ugn/building_executable_programs_with_gnat automatically-creating-a-list-of-directories}@anchor{144}@anchor{gnat_ugn/building_executable_programs_with_gnat id49}@anchor{145}
16744 @subsection Automatically Creating a List of Directories
16747 In most makefiles, you will have to specify a list of directories, and
16748 store it in a variable. For small projects, it is often easier to
16749 specify each of them by hand, since you then have full control over what
16750 is the proper order for these directories, which ones should be
16753 However, in larger projects, which might involve hundreds of
16754 subdirectories, it might be more convenient to generate this list
16757 The example below presents two methods. The first one, although less
16758 general, gives you more control over the list. It involves wildcard
16759 characters, that are automatically expanded by @emph{make}. Its
16760 shortcoming is that you need to explicitly specify some of the
16761 organization of your project, such as for instance the directory tree
16762 depth, whether some directories are found in a separate tree, etc.
16764 The second method is the most general one. It requires an external
16765 program, called @emph{find}, which is standard on all Unix systems. All
16766 the directories found under a given root directory will be added to the
16770 # The examples below are based on the following directory hierarchy:
16771 # All the directories can contain any number of files
16772 # ROOT_DIRECTORY -> a -> aa -> aaa
16775 # -> b -> ba -> baa
16778 # This Makefile creates a variable called DIRS, that can be reused any time
16779 # you need this list (see the other examples in this section)
16781 # The root of your project's directory hierarchy
16785 # First method: specify explicitly the list of directories
16786 # This allows you to specify any subset of all the directories you need.
16789 DIRS := a/aa/ a/ab/ b/ba/
16792 # Second method: use wildcards
16793 # Note that the argument(s) to wildcard below should end with a '/'.
16794 # Since wildcards also return file names, we have to filter them out
16795 # to avoid duplicate directory names.
16796 # We thus use make's `dir` and `sort` functions.
16797 # It sets DIRs to the following value (note that the directories aaa and baa
16798 # are not given, unless you change the arguments to wildcard).
16799 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
16802 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
16803 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
16806 # Third method: use an external program
16807 # This command is much faster if run on local disks, avoiding NFS slowdowns.
16808 # This is the most complete command: it sets DIRs to the following value:
16809 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
16812 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
16815 @node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
16816 @anchor{gnat_ugn/building_executable_programs_with_gnat id50}@anchor{146}@anchor{gnat_ugn/building_executable_programs_with_gnat generating-the-command-line-switches}@anchor{147}
16817 @subsection Generating the Command Line Switches
16820 Once you have created the list of directories as explained in the
16821 previous section (@ref{144,,Automatically Creating a List of Directories}),
16822 you can easily generate the command line arguments to pass to gnatmake.
16824 For the sake of completeness, this example assumes that the source path
16825 is not the same as the object path, and that you have two separate lists
16829 # see "Automatically creating a list of directories" to create
16834 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
16835 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
16838 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
16841 @node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
16842 @anchor{gnat_ugn/building_executable_programs_with_gnat overcoming-command-line-length-limits}@anchor{148}@anchor{gnat_ugn/building_executable_programs_with_gnat id51}@anchor{149}
16843 @subsection Overcoming Command Line Length Limits
16846 One problem that might be encountered on big projects is that many
16847 operating systems limit the length of the command line. It is thus hard to give
16848 gnatmake the list of source and object directories.
16850 This example shows how you can set up environment variables, which will
16851 make @emph{gnatmake} behave exactly as if the directories had been
16852 specified on the command line, but have a much higher length limit (or
16853 even none on most systems).
16855 It assumes that you have created a list of directories in your Makefile,
16856 using one of the methods presented in
16857 @ref{144,,Automatically Creating a List of Directories}.
16858 For the sake of completeness, we assume that the object
16859 path (where the ALI files are found) is different from the sources patch.
16861 Note a small trick in the Makefile below: for efficiency reasons, we
16862 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
16863 expanded immediately by @cite{make}. This way we overcome the standard
16864 make behavior which is to expand the variables only when they are
16867 On Windows, if you are using the standard Windows command shell, you must
16868 replace colons with semicolons in the assignments to these variables.
16871 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
16872 # This is the same thing as putting the -I arguments on the command line.
16873 # (the equivalent of using -aI on the command line would be to define
16874 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
16875 # You can of course have different values for these variables.
16877 # Note also that we need to keep the previous values of these variables, since
16878 # they might have been set before running 'make' to specify where the GNAT
16879 # library is installed.
16881 # see "Automatically creating a list of directories" to create these
16887 space:=$@{empty@} $@{empty@}
16888 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
16889 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
16890 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
16891 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
16892 export ADA_INCLUDE_PATH
16893 export ADA_OBJECTS_PATH
16899 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
16901 @node GNAT Project Manager,Tools Supporting Project Files,Building Executable Programs with GNAT,Top
16902 @anchor{gnat_ugn/gnat_project_manager doc}@anchor{14a}@anchor{gnat_ugn/gnat_project_manager gnat-project-manager}@anchor{b}@anchor{gnat_ugn/gnat_project_manager id1}@anchor{14b}
16903 @chapter GNAT Project Manager
16908 * Building With Projects::
16909 * Organizing Projects into Subsystems::
16910 * Scenarios in Projects::
16911 * Library Projects::
16912 * Project Extension::
16913 * Aggregate Projects::
16914 * Aggregate Library Projects::
16915 * Project File Reference::
16919 @node Introduction,Building With Projects,,GNAT Project Manager
16920 @anchor{gnat_ugn/gnat_project_manager introduction}@anchor{14c}@anchor{gnat_ugn/gnat_project_manager gnat-project-manager-introduction}@anchor{14d}
16921 @section Introduction
16924 This chapter describes GNAT's @emph{Project Manager}, a facility that allows
16925 you to manage complex builds involving a number of source files, directories,
16926 and options for different system configurations. In particular,
16927 project files allow you to specify:
16933 The directory or set of directories containing the source files, and/or the
16934 names of the specific source files themselves
16937 The directory in which the compiler's output
16938 (@code{ALI} files, object files, tree files, etc.) is to be placed
16941 The directory in which the executable programs are to be placed
16944 Switch settings for any of the project-enabled tools;
16945 you can apply these settings either globally or to individual compilation units.
16948 The source files containing the main subprogram(s) to be built
16951 The source programming language(s)
16954 Source file naming conventions; you can specify these either globally or for
16955 individual compilation units (see @ref{14e,,Naming Schemes}).
16958 Change any of the above settings depending on external values, thus enabling
16959 the reuse of the projects in various @strong{scenarios} (see @ref{14f,,Scenarios in Projects}).
16962 Automatically build libraries as part of the build process
16963 (see @ref{8a,,Library Projects}).
16966 Project files are written in a syntax close to that of Ada, using familiar
16967 notions such as packages, context clauses, declarations, default values,
16968 assignments, and inheritance (see @ref{150,,Project File Reference}).
16970 Project files can be built hierarchically from other project files, simplifying
16971 complex system integration and project reuse (see @ref{151,,Organizing Projects into Subsystems}).
16977 One project can import other projects containing needed source files.
16978 More generally, the Project Manager lets you structure large development
16979 efforts into hierarchical subsystems, where build decisions are delegated
16980 to the subsystem level, and thus different compilation environments
16981 (switch settings) used for different subsystems.
16984 You can organize GNAT projects in a hierarchy: a child project
16985 can extend a parent project, inheriting the parent's source files and
16986 optionally overriding any of them with alternative versions
16987 (see @ref{152,,Project Extension}).
16990 Several tools support project files, generally in addition to specifying
16991 the information on the command line itself). They share common switches
16992 to control the loading of the project (in particular
16993 @code{-P@emph{projectfile}} and
16994 @code{-X@emph{vbl}=@emph{value}}).
16996 The Project Manager supports a wide range of development strategies,
16997 for systems of all sizes. Here are some typical practices that are
17004 Using a common set of source files and generating object files in different
17005 directories via different switch settings. It can be used for instance, for
17006 generating separate sets of object files for debugging and for production.
17009 Using a mostly-shared set of source files with different versions of
17010 some units or subunits. It can be used for instance, for grouping and hiding
17011 all OS dependencies in a small number of implementation units.
17014 Project files can be used to achieve some of the effects of a source
17015 versioning system (for example, defining separate projects for
17016 the different sets of sources that comprise different releases) but the
17017 Project Manager is independent of any source configuration management tool
17018 that might be used by the developers.
17020 The various sections below introduce the different concepts related to
17021 projects. Each section starts with examples and use cases, and then goes into
17022 the details of related project file capabilities.
17024 @node Building With Projects,Organizing Projects into Subsystems,Introduction,GNAT Project Manager
17025 @anchor{gnat_ugn/gnat_project_manager building-with-projects}@anchor{153}@anchor{gnat_ugn/gnat_project_manager id2}@anchor{154}
17026 @section Building With Projects
17029 In its simplest form, a unique project is used to build a single executable.
17030 This section concentrates on such a simple setup. Later sections will extend
17031 this basic model to more complex setups.
17033 The following concepts are the foundation of project files, and will be further
17034 detailed later in this documentation. They are summarized here as a reference.
17039 @item @strong{Project file}:
17041 A text file using an Ada-like syntax, generally using the @code{.gpr}
17042 extension. It defines build-related characteristics of an application.
17043 The characteristics include the list of sources, the location of those
17044 sources, the location for the generated object files, the name of
17045 the main program, and the options for the various tools involved in the
17048 @item @strong{Project attribute}:
17050 A specific project characteristic is defined by an attribute clause. Its
17051 value is a string or a sequence of strings. All settings in a project
17052 are defined through a list of predefined attributes with precise
17053 semantics. See @ref{155,,Attributes}.
17055 @item @strong{Package in a project}:
17057 Global attributes are defined at the top level of a project.
17058 Attributes affecting specific tools are grouped in a
17059 package whose name is related to tool's function. The most common
17060 packages are @cite{Builder}, @cite{Compiler}, @cite{Binder},
17061 and @cite{Linker}. See @ref{156,,Packages}.
17063 @item @strong{Project variables}:
17065 In addition to attributes, a project can use variables to store intermediate
17066 values and avoid duplication in complex expressions. It can be initialized
17067 with a value coming from the environment.
17068 A frequent use of variables is to define scenarios.
17069 See @ref{157,,External Values}, @ref{14f,,Scenarios in Projects}, and @ref{158,,Variables}.
17071 @item @strong{Source files} and @strong{source directories}:
17073 A source file is associated with a language through a naming convention. For
17074 instance, @cite{foo.c} is typically the name of a C source file;
17075 @cite{bar.ads} or @cite{bar.1.ada} are two common naming conventions for a
17076 file containing an Ada spec. A compilation unit is often composed of a main
17077 source file and potentially several auxiliary ones, such as header files in C.
17078 The naming conventions can be user defined @ref{14e,,Naming Schemes}, and will
17079 drive the builder to call the appropriate compiler for the given source file.
17080 Source files are searched for in the source directories associated with the
17081 project through the @strong{Source_Dirs} attribute. By default, all the files (in
17082 these source directories) following the naming conventions associated with the
17083 declared languages are considered to be part of the project. It is also
17084 possible to limit the list of source files using the @strong{Source_Files} or
17085 @strong{Source_List_File} attributes. Note that those last two attributes only
17086 accept basenames with no directory information.
17088 @item @strong{Object files} and @strong{object directory}:
17090 An object file is an intermediate file produced by the compiler from a
17091 compilation unit. It is used by post-compilation tools to produce
17092 final executables or libraries. Object files produced in the context of
17093 a given project are stored in a single directory that can be specified by the
17094 @strong{Object_Dir} attribute. In order to store objects in
17095 two or more object directories, the system must be split into
17096 distinct subsystems with their own project file.
17099 The following subsections introduce gradually all the attributes of interest
17100 for simple build needs. Here is the simple setup that will be used in the
17101 following examples.
17103 The Ada source files @code{pack.ads}, @code{pack.adb}, and @code{proc.adb} are in
17104 the @code{common/} directory. The file @code{proc.adb} contains an Ada main
17105 subprogram @cite{Proc} that @emph{with}s package @cite{Pack}. We want to compile
17106 these source files with the switch
17107 @emph{-O2}, and put the resulting files in
17108 the directory @code{obj/}.
17116 proc.ali, proc.o pack.ali, pack.o
17119 Our project is to be called @emph{Build}. The name of the
17120 file is the name of the project (case-insensitive) with the
17121 @code{.gpr} extension, therefore the project file name is @code{build.gpr}. This
17122 is not mandatory, but a warning is issued when this convention is not followed.
17124 This is a very simple example, and as stated above, a single project
17125 file is enough for it. We will thus create a new file, that for now
17126 should contain the following code:
17134 * Source Files and Directories::
17135 * Duplicate Sources in Projects::
17136 * Object and Exec Directory::
17137 * Main Subprograms::
17138 * Tools Options in Project Files::
17139 * Compiling with Project Files::
17140 * Executable File Names::
17141 * Avoid Duplication With Variables::
17144 * Distributed support::
17148 @node Source Files and Directories,Duplicate Sources in Projects,,Building With Projects
17149 @anchor{gnat_ugn/gnat_project_manager id3}@anchor{159}@anchor{gnat_ugn/gnat_project_manager source-files-and-directories}@anchor{15a}
17150 @subsection Source Files and Directories
17153 When you create a new project, the first thing to describe is how to find the
17154 corresponding source files. These are the only settings that are needed by all
17155 the tools that will use this project (builder, compiler, binder and linker for
17156 the compilation, IDEs to edit the source files,...).
17158 @geindex Source directories (GNAT Project Manager)
17160 The first step is to declare the source directories, which are the directories
17161 to be searched to find source files. In the case of the example,
17162 the @code{common} directory is the only source directory.
17164 @geindex Source_Dirs (GNAT Project Manager)
17166 There are several ways of defining source directories:
17172 When the attribute @strong{Source_Dirs} is not used, a project contains a
17173 single source directory which is the one where the project file itself
17174 resides. In our example, if @code{build.gpr} is placed in the @code{common}
17175 directory, the project has the needed implicit source directory.
17178 The attribute @strong{Source_Dirs} can be set to a list of path names, one
17179 for each of the source directories. Such paths can either be absolute
17180 names (for instance @code{"/usr/local/common/"} on UNIX), or relative to the
17181 directory in which the project file resides (for instance "." if
17182 @code{build.gpr} is inside @code{common/}, or "common" if it is one level up).
17183 Each of the source directories must exist and be readable.
17185 @geindex portability of path names (GNAT Project Manager)
17187 The syntax for directories is platform specific. For portability, however,
17188 the project manager will always properly translate UNIX-like path names to
17189 the native format of the specific platform. For instance, when the same
17190 project file is to be used both on Unix and Windows, "/" should be used as
17191 the directory separator rather than "\".
17194 The attribute @strong{Source_Dirs} can automatically include subdirectories
17195 using a special syntax inspired by some UNIX shells. If any of the paths in
17196 the list ends with "@code{**}", then that path and all its subdirectories
17197 (recursively) are included in the list of source directories. For instance,
17198 @code{**} and @code{./**} represent the complete directory tree rooted at
17199 the directory in which the project file resides.
17201 @geindex Source directories (GNAT Project Manager)
17203 @geindex Excluded_Source_Dirs (GNAT Project Manager)
17205 When using that construct, it can sometimes be convenient to also use the
17206 attribute @strong{Excluded_Source_Dirs}, which is also a list of paths. Each entry
17207 specifies a directory whose immediate content, not including subdirs, is to
17208 be excluded. It is also possible to exclude a complete directory subtree
17209 using the "**" notation.
17211 @geindex Ignore_Source_Sub_Dirs (GNAT Project Manager)
17213 It is often desirable to remove, from the source directories, directory
17214 subtrees rooted at some subdirectories. An example is the subdirectories
17215 created by a Version Control System such as Subversion that creates directory
17216 subtrees rooted at subdirectories ".svn". To do that, attribute
17217 @strong{Ignore_Source_Sub_Dirs} can be used. It specifies the list of simple
17218 file names for the roots of these undesirable directory subtrees.
17221 for Source_Dirs use ("./**");
17222 for Ignore_Source_Sub_Dirs use (".svn");
17226 When applied to the simple example, and because we generally prefer to have
17227 the project file at the toplevel directory rather than mixed with the sources,
17228 we will create the following file
17233 for Source_Dirs use ("common"); -- <<<<
17237 Once source directories have been specified, one may need to indicate
17238 source files of interest. By default, all source files present in the source
17239 directories are considered by the project manager. When this is not desired,
17240 it is possible to specify the list of sources to consider explicitly.
17241 In such a case, only source file base names are indicated and not
17242 their absolute or relative path names. The project manager is in charge of
17243 locating the specified source files in the specified source directories.
17249 By default, the project manager searches for all source files of all
17250 specified languages in all the source directories.
17252 Since the project manager was initially developed for Ada environments, the
17253 default language is usually Ada and the above project file is complete: it
17254 defines without ambiguity the sources composing the project: that is to say,
17255 all the sources in subdirectory "common" for the default language (Ada) using
17256 the default naming convention.
17258 @geindex Languages (GNAT Project Manager)
17260 However, when compiling a multi-language application, or a pure C
17261 application, the project manager must be told which languages are of
17262 interest, which is done by setting the @strong{Languages} attribute to a list of
17263 strings, each of which is the name of a language.
17265 @geindex Naming scheme (GNAT Project Manager)
17267 Even when using only Ada, the default naming might not be suitable. Indeed,
17268 how does the project manager recognizes an "Ada file" from any other
17269 file? Project files can describe the naming scheme used for source files,
17270 and override the default (see @ref{14e,,Naming Schemes}). The default is the
17271 standard GNAT extension (@code{.adb} for bodies and @code{.ads} for
17272 specs), which is what is used in our example, explaining why no naming scheme
17273 is explicitly specified.
17274 See @ref{14e,,Naming Schemes}.
17276 @geindex Source_Files (GNAT Project Manager)
17279 @cite{Source_Files}.
17280 In some cases, source directories might contain files that should not be
17281 included in a project. One can specify the explicit list of file names to
17282 be considered through the @strong{Source_Files} attribute.
17283 When this attribute is defined, instead of looking at every file in the
17284 source directories, the project manager takes only those names into
17285 consideration reports errors if they cannot be found in the source
17286 directories or does not correspond to the naming scheme.
17289 For various reasons, it is sometimes useful to have a project with no
17290 sources (most of the time because the attributes defined in the project
17291 file will be reused in other projects, as explained in
17292 @ref{151,,Organizing Projects into Subsystems}. To do this, the attribute
17293 @emph{Source_Files} is set to the empty list, i.e. @cite{()}. Alternatively,
17294 @emph{Source_Dirs} can be set to the empty list, with the same
17297 @geindex Source_List_File (GNAT Project Manager)
17300 @cite{Source_List_File}.
17301 If there is a great number of files, it might be more convenient to use
17302 the attribute @strong{Source_List_File}, which specifies the full path of a file.
17303 This file must contain a list of source file names (one per line, no
17304 directory information) that are searched as if they had been defined
17305 through @emph{Source_Files}. Such a file can easily be created through
17308 A warning is issued if both attributes @cite{Source_Files} and
17309 @cite{Source_List_File} are given explicit values. In this case, the
17310 attribute @cite{Source_Files} prevails.
17312 @geindex Excluded_Source_Files (GNAT Project Manager)
17314 @geindex Locally_Removed_Files (GNAT Project Manager)
17316 @geindex Excluded_Source_List_File (GNAT Project Manager)
17319 @cite{Excluded_Source_Files}.
17320 Specifying an explicit list of files is not always convenient.It might be
17321 more convenient to use the default search rules with specific exceptions.
17322 This can be done thanks to the attribute @strong{Excluded_Source_Files}
17323 (or its synonym @strong{Locally_Removed_Files}).
17324 Its value is the list of file names that should not be taken into account.
17325 This attribute is often used when extending a project,
17326 see @ref{152,,Project Extension}. A similar attribute
17327 @strong{Excluded_Source_List_File} plays the same
17328 role but takes the name of file containing file names similarly to
17329 @cite{Source_List_File}.
17332 In most simple cases, such as the above example, the default source file search
17333 behavior provides the expected result, and we do not need to add anything after
17334 setting @cite{Source_Dirs}. The project manager automatically finds
17335 @code{pack.ads}, @code{pack.adb}, and @code{proc.adb} as source files of the
17338 Note that by default a warning is issued when a project has no sources attached
17339 to it and this is not explicitly indicated in the project file.
17341 @node Duplicate Sources in Projects,Object and Exec Directory,Source Files and Directories,Building With Projects
17342 @anchor{gnat_ugn/gnat_project_manager duplicate-sources-in-projects}@anchor{15b}@anchor{gnat_ugn/gnat_project_manager id4}@anchor{15c}
17343 @subsection Duplicate Sources in Projects
17346 If the order of the source directories is known statically, that is if
17347 @cite{"/**"} is not used in the string list @cite{Source_Dirs}, then there may
17348 be several files with the same name sitting in different directories of the
17349 project. In this case, only the file in the first directory is considered as a
17350 source of the project and the others are hidden. If @cite{"/**"} is used in the
17351 string list @cite{Source_Dirs}, it is an error to have several files with the
17352 same name in the same directory @cite{"/**"} subtree, since there would be an
17353 ambiguity as to which one should be used. However, two files with the same name
17354 may exist in two single directories or directory subtrees. In this case, the
17355 one in the first directory or directory subtree is a source of the project.
17357 If there are two sources in different directories of the same @cite{"/**"}
17358 subtree, one way to resolve the problem is to exclude the directory of the
17359 file that should not be used as a source of the project.
17361 @node Object and Exec Directory,Main Subprograms,Duplicate Sources in Projects,Building With Projects
17362 @anchor{gnat_ugn/gnat_project_manager object-and-exec-directory}@anchor{15d}@anchor{gnat_ugn/gnat_project_manager id5}@anchor{15e}
17363 @subsection Object and Exec Directory
17366 The next step when writing a project is to indicate where the compiler should
17367 put the object files. In fact, the compiler and other tools might create
17368 several different kind of files (for GNAT, there is the object file and the ALI
17369 file for instance). One of the important concepts in projects is that most
17370 tools may consider source directories as read-only and do not attempt to create
17371 new or temporary files there. Instead, all files are created in the object
17372 directory. It is of course not true for project-aware IDEs, whose purpose it is
17373 to create the source files.
17375 @geindex Object_Dir (GNAT Project Manager)
17377 The object directory is specified through the @strong{Object_Dir} attribute.
17378 Its value is the path to the object directory, either absolute or
17379 relative to the directory containing the project file. This
17380 directory must already exist and be readable and writable, although
17381 some tools have a switch to create the directory if needed (See
17382 the switch @cite{-p} for @emph{gprbuild}).
17384 If the attribute @cite{Object_Dir} is not specified, it defaults to
17385 the project directory, that is the directory containing the project file.
17387 For our example, we can specify the object dir in this way:
17391 for Source_Dirs use ("common");
17392 for Object_Dir use "obj"; -- <<<<
17396 As mentioned earlier, there is a single object directory per project. As a
17397 result, if you have an existing system where the object files are spread across
17398 several directories, you can either move all of them into the same directory if
17399 you want to build it with a single project file, or study the section on
17400 subsystems (see @ref{151,,Organizing Projects into Subsystems}) to see how each
17401 separate object directory can be associated with one of the subsystems
17402 constituting the application.
17404 When the @emph{linker} is called, it usually creates an executable. By
17405 default, this executable is placed in the object directory of the project. It
17406 might be convenient to store it in its own directory.
17408 @geindex Exec_Dir (GNAT Project Manager)
17410 This can be done through the @cite{Exec_Dir} attribute, which, like
17411 @emph{Object_Dir} contains a single absolute or relative path and must point to
17412 an existing and writable directory, unless you ask the tool to create it on
17413 your behalf. When not specified, It defaults to the object directory and
17414 therefore to the project file's directory if neither @emph{Object_Dir} nor
17415 @emph{Exec_Dir} was specified.
17417 In the case of the example, let's place the executable in the root
17418 of the hierarchy, ie the same directory as @code{build.gpr}. Hence
17419 the project file is now
17423 for Source_Dirs use ("common");
17424 for Object_Dir use "obj";
17425 for Exec_Dir use "."; -- <<<<
17429 @node Main Subprograms,Tools Options in Project Files,Object and Exec Directory,Building With Projects
17430 @anchor{gnat_ugn/gnat_project_manager id6}@anchor{15f}@anchor{gnat_ugn/gnat_project_manager main-subprograms}@anchor{160}
17431 @subsection Main Subprograms
17434 In the previous section, executables were mentioned. The project manager needs
17435 to be taught what they are. In a project file, an executable is indicated by
17436 pointing to the source file of a main subprogram. In C this is the file that
17437 contains the @cite{main} function, and in Ada the file that contains the main
17440 There can be any number of such main files within a given project, and thus
17441 several executables can be built in the context of a single project file. Of
17442 course, one given executable might not (and in fact will not) need all the
17443 source files referenced by the project. As opposed to other build environments
17444 such as @emph{makefile}, one does not need to specify the list of
17445 dependencies of each executable, the project-aware builder knows enough of the
17446 semantics of the languages to build and link only the necessary elements.
17448 @geindex Main (GNAT Project Manager)
17450 The list of main files is specified via the @strong{Main} attribute. It contains
17451 a list of file names (no directories). If a project defines this
17452 attribute, it is not necessary to identify main files on the
17453 command line when invoking a builder, and editors like
17454 @emph{GPS} will be able to create extra menus to spawn or debug the
17455 corresponding executables.
17459 for Source_Dirs use ("common");
17460 for Object_Dir use "obj";
17461 for Exec_Dir use ".";
17462 for Main use ("proc.adb"); -- <<<<
17466 If this attribute is defined in the project, then spawning the builder
17467 with a command such as
17473 automatically builds all the executables corresponding to the files
17474 listed in the @emph{Main} attribute. It is possible to specify one
17475 or more executables on the command line to build a subset of them.
17477 @node Tools Options in Project Files,Compiling with Project Files,Main Subprograms,Building With Projects
17478 @anchor{gnat_ugn/gnat_project_manager tools-options-in-project-files}@anchor{161}@anchor{gnat_ugn/gnat_project_manager id7}@anchor{162}
17479 @subsection Tools Options in Project Files
17482 We now have a project file that fully describes our environment, and can be
17483 used to build the application with a simple @emph{gprbuild} command as seen
17484 in the previous section. In fact, the empty project we showed immediately at
17485 the beginning (with no attribute at all) could already fulfill that need if it
17486 was put in the @code{common} directory.
17488 Of course, we might want more control. This section shows you how to specify
17489 the compilation switches that the various tools involved in the building of the
17490 executable should use.
17492 @geindex command line length (GNAT Project Manager)
17494 Since source names and locations are described in the project file, it is not
17495 necessary to use switches on the command line for this purpose (switches such
17496 as -I for gcc). This removes a major source of command line length overflow.
17497 Clearly, the builders will have to communicate this information one way or
17498 another to the underlying compilers and tools they call but they usually use
17499 response files for this and thus are not subject to command line overflows.
17501 Several tools participate to the creation of an executable: the compiler
17502 produces object files from the source files; the binder (in the Ada case)
17503 creates a "source" file that takes care, among other things, of elaboration
17504 issues and global variable initialization; and the linker gathers everything
17505 into a single executable that users can execute. All these tools are known to
17506 the project manager and will be called with user defined switches from the
17507 project files. However, we need to introduce a new project file concept to
17508 express the switches to be used for any of the tools involved in the build.
17510 @geindex project file packages (GNAT Project Manager)
17512 A project file is subdivided into zero or more @strong{packages}, each of which
17513 contains the attributes specific to one tool (or one set of tools). Project
17514 files use an Ada-like syntax for packages. Package names permitted in project
17515 files are restricted to a predefined set (see @ref{156,,Packages}), and the contents
17516 of packages are limited to a small set of constructs and attributes
17517 (see @ref{155,,Attributes}).
17519 Our example project file can be extended with the following empty packages. At
17520 this stage, they could all be omitted since they are empty, but they show which
17521 packages would be involved in the build process.
17525 for Source_Dirs use ("common");
17526 for Object_Dir use "obj";
17527 for Exec_Dir use ".";
17528 for Main use ("proc.adb");
17530 package Builder is --<<< for gprbuild
17533 package Compiler is --<<< for the compiler
17536 package Binder is --<<< for the binder
17539 package Linker is --<<< for the linker
17544 Let's first examine the compiler switches. As stated in the initial description
17545 of the example, we want to compile all files with @emph{-O2}. This is a
17546 compiler switch, although it is usual, on the command line, to pass it to the
17547 builder which then passes it to the compiler. It is recommended to use directly
17548 the right package, which will make the setup easier to understand for other
17551 Several attributes can be used to specify the switches:
17553 @geindex Default_Switches (GNAT Project Manager)
17555 @strong{Default_Switches}:
17559 This is the first mention in this manual of an @strong{indexed attribute}. When
17560 this attribute is defined, one must supply an @emph{index} in the form of a
17562 In the case of @emph{Default_Switches}, the index is the name of the
17563 language to which the switches apply (since a different compiler will
17564 likely be used for each language, and each compiler has its own set of
17565 switches). The value of the attribute is a list of switches.
17567 In this example, we want to compile all Ada source files with the switch
17568 @emph{-O2}, and the resulting project file is as follows
17569 (only the @cite{Compiler} package is shown):
17572 package Compiler is
17573 for Default_Switches ("Ada") use ("-O2");
17578 @geindex Switches (GNAT Project Manager)
17584 In some cases, we might want to use specific switches
17585 for one or more files. For instance, compiling @code{proc.adb} might not be
17586 possible at high level of optimization because of a compiler issue.
17587 In such a case, the @emph{Switches}
17588 attribute (indexed on the file name) can be used and will override the
17589 switches defined by @emph{Default_Switches}. Our project file would
17593 package Compiler is
17594 for Default_Switches ("Ada")
17596 for Switches ("proc.adb")
17601 @cite{Switches} may take a pattern as an index, such as in:
17604 package Compiler is
17605 for Default_Switches ("Ada")
17607 for Switches ("pkg*")
17612 Sources @code{pkg.adb} and @code{pkg-child.adb} would be compiled with -O0,
17615 @cite{Switches} can also be given a language name as index instead of a file
17616 name in which case it has the same semantics as @emph{Default_Switches}.
17617 However, indexes with wild cards are never valid for language name.
17620 @geindex Local_Configuration_Pragmas (GNAT Project Manager)
17622 @strong{Local_Configuration_Pragmas}:
17626 This attribute may specify the path
17627 of a file containing configuration pragmas for use by the Ada compiler,
17628 such as @cite{pragma Restrictions (No_Tasking)}. These pragmas will be
17629 used for all the sources of the project.
17632 The switches for the other tools are defined in a similar manner through the
17633 @strong{Default_Switches} and @strong{Switches} attributes, respectively in the
17634 @emph{Builder} package (for @emph{gprbuild}),
17635 the @emph{Binder} package (binding Ada executables) and the @emph{Linker}
17636 package (for linking executables).
17638 @node Compiling with Project Files,Executable File Names,Tools Options in Project Files,Building With Projects
17639 @anchor{gnat_ugn/gnat_project_manager compiling-with-project-files}@anchor{163}@anchor{gnat_ugn/gnat_project_manager id8}@anchor{164}
17640 @subsection Compiling with Project Files
17643 Now that our project files are written, let's build our executable.
17644 Here is the command we would use from the command line:
17650 This will automatically build the executables specified through the
17651 @emph{Main} attribute: for each, it will compile or recompile the
17652 sources for which the object file does not exist or is not up-to-date; it
17653 will then run the binder; and finally run the linker to create the
17656 The @emph{gprbuild} builder, can automatically manage C files the
17657 same way: create the file @code{utils.c} in the @code{common} directory,
17658 set the attribute @emph{Languages} to @cite{"(Ada@comma{} C)"}, and re-run
17664 Gprbuild knows how to recompile the C files and will
17665 recompile them only if one of their dependencies has changed. No direct
17666 indication on how to build the various elements is given in the
17667 project file, which describes the project properties rather than a
17668 set of actions to be executed. Here is the invocation of
17669 @emph{gprbuild} when building a multi-language program:
17681 Notice the three steps described earlier:
17687 The first three gcc commands correspond to the compilation phase.
17690 The gprbind command corresponds to the post-compilation phase.
17693 The last gcc command corresponds to the final link.
17696 @geindex -v option (for GPRbuild)
17698 The default output of GPRbuild's execution is kept reasonably simple and easy
17699 to understand. In particular, some of the less frequently used commands are not
17700 shown, and some parameters are abbreviated. So it is not possible to rerun the
17701 effect of the @emph{gprbuild} command by cut-and-pasting its output.
17702 GPRbuild's option @cite{-v} provides a much more verbose output which includes,
17703 among other information, more complete compilation, post-compilation and link
17706 @node Executable File Names,Avoid Duplication With Variables,Compiling with Project Files,Building With Projects
17707 @anchor{gnat_ugn/gnat_project_manager executable-file-names}@anchor{165}@anchor{gnat_ugn/gnat_project_manager id9}@anchor{166}
17708 @subsection Executable File Names
17711 @geindex Executable (GNAT Project Manager)
17713 By default, the executable name corresponding to a main file is
17714 computed from the main source file name. Through the attribute
17715 @strong{Builder.Executable}, it is possible to change this default.
17717 For instance, instead of building @emph{proc} (or @emph{proc.exe}
17718 on Windows), we could configure our project file to build "proc1"
17719 (resp proc1.exe) with the following addition:
17723 ... -- same as before
17725 for Executable ("proc.adb") use "proc1";
17730 @geindex Executable_Suffix (GNAT Project Manager)
17732 Attribute @strong{Executable_Suffix}, when specified, may change the suffix
17733 of the executable files, when no attribute @cite{Executable} applies:
17734 its value replaces the platform-specific executable suffix.
17735 The default executable suffix is empty on UNIX and ".exe" on Windows.
17737 It is also possible to change the name of the produced executable by using the
17738 command line switch @emph{-o}. When several mains are defined in the project,
17739 it is not possible to use the @emph{-o} switch and the only way to change the
17740 names of the executable is provided by Attributes @cite{Executable} and
17741 @cite{Executable_Suffix}.
17743 @node Avoid Duplication With Variables,Naming Schemes,Executable File Names,Building With Projects
17744 @anchor{gnat_ugn/gnat_project_manager id10}@anchor{167}@anchor{gnat_ugn/gnat_project_manager avoid-duplication-with-variables}@anchor{168}
17745 @subsection Avoid Duplication With Variables
17748 To illustrate some other project capabilities, here is a slightly more complex
17749 project using similar sources and a main program in C:
17753 for Languages use ("Ada", "C");
17754 for Source_Dirs use ("common");
17755 for Object_Dir use "obj";
17756 for Main use ("main.c");
17757 package Compiler is
17758 C_Switches := ("-pedantic");
17759 for Default_Switches ("C") use C_Switches;
17760 for Default_Switches ("Ada") use ("-gnaty");
17761 for Switches ("main.c") use C_Switches & ("-g");
17766 This project has many similarities with the previous one.
17767 As expected, its @cite{Main} attribute now refers to a C source.
17768 The attribute @emph{Exec_Dir} is now omitted, thus the resulting
17769 executable will be put in the directory @code{obj}.
17771 The most noticeable difference is the use of a variable in the
17772 @emph{Compiler} package to store settings used in several attributes.
17773 This avoids text duplication, and eases maintenance (a single place to
17774 modify if we want to add new switches for C files). We will revisit
17775 the use of variables in the context of scenarios (see @ref{14f,,Scenarios in Projects}).
17777 In this example, we see how the file @code{main.c} can be compiled with
17778 the switches used for all the other C files, plus @emph{-g}.
17779 In this specific situation the use of a variable could have been
17780 replaced by a reference to the @cite{Default_Switches} attribute:
17783 for Switches ("c_main.c") use Compiler'Default_Switches ("C") & ("-g");
17786 Note the tick (@emph{'}) used to refer to attributes defined in a package.
17788 Here is the output of the GPRbuild command using this project:
17791 $ gprbuild -Pc_main
17792 gcc -c -pedantic -g main.c
17793 gcc -c -gnaty proc.adb
17794 gcc -c -gnaty pack.adb
17795 gcc -c -pedantic utils.c
17801 The default switches for Ada sources,
17802 the default switches for C sources (in the compilation of @code{lib.c}),
17803 and the specific switches for @code{main.c} have all been taken into
17806 @node Naming Schemes,Installation,Avoid Duplication With Variables,Building With Projects
17807 @anchor{gnat_ugn/gnat_project_manager id11}@anchor{169}@anchor{gnat_ugn/gnat_project_manager naming-schemes}@anchor{14e}
17808 @subsection Naming Schemes
17811 Sometimes an Ada software system is ported from one compilation environment to
17812 another (say GNAT), and the file are not named using the default GNAT
17813 conventions. Instead of changing all the file names, which for a variety of
17814 reasons might not be possible, you can define the relevant file naming scheme
17815 in the @strong{Naming} package of your project file.
17817 The naming scheme has two distinct goals for the project manager: it
17818 allows finding of source files when searching in the source
17819 directories, and given a source file name it makes it possible to guess
17820 the associated language, and thus the compiler to use.
17822 Note that the use by the Ada compiler of pragmas Source_File_Name is not
17823 supported when using project files. You must use the features described in this
17824 paragraph. You can however specify other configuration pragmas.
17826 The following attributes can be defined in package @cite{Naming}:
17828 @geindex Casing (GNAT Project Manager)
17834 Its value must be one of @cite{"lowercase"} (the default if
17835 unspecified), @cite{"uppercase"} or @cite{"mixedcase"}. It describes the
17836 casing of file names with regards to the Ada unit name. Given an Ada unit
17837 My_Unit, the file name will respectively be @code{my_unit.adb} (lowercase),
17838 @code{MY_UNIT.ADB} (uppercase) or @code{My_Unit.adb} (mixedcase).
17839 On Windows, file names are case insensitive, so this attribute is
17843 @geindex Dot_Replacement (GNAT Project Manager)
17845 @strong{Dot_Replacement}:
17849 This attribute specifies the string that should replace the "." in unit
17850 names. Its default value is @cite{"-"} so that a unit
17851 @cite{Parent.Child} is expected to be found in the file
17852 @code{parent-child.adb}. The replacement string must satisfy the following
17853 requirements to avoid ambiguities in the naming scheme:
17859 It must not be empty
17862 It cannot start or end with an alphanumeric character
17865 It cannot be a single underscore
17868 It cannot start with an underscore followed by an alphanumeric
17871 It cannot contain a dot @cite{'.'} except if the entire string is @cite{"."}
17875 @geindex Spec_Suffix (GNAT Project Manager)
17877 @geindex Specification_Suffix (GNAT Project Manager)
17879 @strong{Spec_Suffix} and @strong{Specification_Suffix}:
17883 For Ada, these attributes give the suffix used in file names that contain
17884 specifications. For other languages, they give the extension for files
17885 that contain declaration (header files in C for instance). The attribute
17886 is indexed on the language.
17887 The two attributes are equivalent, but the latter is obsolescent.
17889 If the value of the attribute is the empty string, it indicates to the
17890 Project Manager that the only specifications/header files for the language
17891 are those specified with attributes @cite{Spec} or
17892 @cite{Specification_Exceptions}.
17894 If @cite{Spec_Suffix ("Ada")} is not specified, then the default is
17897 A non empty value must satisfy the following requirements:
17903 It must include at least one dot
17906 If @cite{Dot_Replacement} is a single dot, then it cannot include
17911 @geindex Body_Suffix (GNAT Project Manager)
17913 @geindex Implementation_Suffix (GNAT Project Manager)
17915 @strong{Body_Suffix} and @strong{Implementation_Suffix}:
17919 These attributes give the extension used for file names that contain
17920 code (bodies in Ada). They are indexed on the language. The second
17921 version is obsolescent and fully replaced by the first attribute.
17923 For each language of a project, one of these two attributes need to be
17924 specified, either in the project itself or in the configuration project file.
17926 If the value of the attribute is the empty string, it indicates to the
17927 Project Manager that the only source files for the language
17928 are those specified with attributes @cite{Body} or
17929 @cite{Implementation_Exceptions}.
17931 These attributes must satisfy the same requirements as @cite{Spec_Suffix}.
17932 In addition, they must be different from any of the values in
17933 @cite{Spec_Suffix}.
17934 If @cite{Body_Suffix ("Ada")} is not specified, then the default is
17937 If @cite{Body_Suffix ("Ada")} and @cite{Spec_Suffix ("Ada")} end with the
17938 same string, then a file name that ends with the longest of these two
17939 suffixes will be a body if the longest suffix is @cite{Body_Suffix ("Ada")}
17940 or a spec if the longest suffix is @cite{Spec_Suffix ("Ada")}.
17942 If the suffix does not start with a '.', a file with a name exactly equal to
17943 the suffix will also be part of the project (for instance if you define the
17944 suffix as @cite{Makefile.in}, a file called @code{Makefile.in} will be part
17945 of the project. This capability is usually not interesting when building.
17946 However, it might become useful when a project is also used to
17947 find the list of source files in an editor, like the GNAT Programming System
17951 @geindex Separate_Suffix (GNAT Project Manager)
17953 @strong{Separate_Suffix}:
17957 This attribute is specific to Ada. It denotes the suffix used in file names
17958 that contain separate bodies. If it is not specified, then it defaults to
17959 same value as @cite{Body_Suffix ("Ada")}.
17961 The value of this attribute cannot be the empty string.
17963 Otherwise, the same rules apply as for the
17964 @cite{Body_Suffix} attribute. The only accepted index is "Ada".
17967 @strong{Spec} or @strong{Specification}:
17971 @geindex Spec (GNAT Project Manager)
17973 @geindex Specification (GNAT Project Manager)
17975 This attribute @cite{Spec} can be used to define the source file name for a
17976 given Ada compilation unit's spec. The index is the literal name of the Ada
17977 unit (case insensitive). The value is the literal base name of the file that
17978 contains this unit's spec (case sensitive or insensitive depending on the
17979 operating system). This attribute allows the definition of exceptions to the
17980 general naming scheme, in case some files do not follow the usual
17983 When a source file contains several units, the relative position of the unit
17984 can be indicated. The first unit in the file is at position 1
17987 for Spec ("MyPack.MyChild") use "mypack.mychild.spec";
17988 for Spec ("top") use "foo.a" at 1;
17989 for Spec ("foo") use "foo.a" at 2;
17993 @geindex Body (GNAT Project Manager)
17995 @geindex Implementation (GNAT Project Manager)
17997 @strong{Body} or @strong{Implementation}:
18001 These attribute play the same role as @emph{Spec} for Ada bodies.
18004 @geindex Specification_Exceptions (GNAT Project Manager)
18006 @geindex Implementation_Exceptions (GNAT Project Manager)
18008 @strong{Specification_Exceptions} and @strong{Implementation_Exceptions}:
18012 These attributes define exceptions to the naming scheme for languages
18013 other than Ada. They are indexed on the language name, and contain
18014 a list of file names respectively for headers and source code.
18017 For example, the following package models the Apex file naming rules:
18021 for Casing use "lowercase";
18022 for Dot_Replacement use ".";
18023 for Spec_Suffix ("Ada") use ".1.ada";
18024 for Body_Suffix ("Ada") use ".2.ada";
18028 @node Installation,Distributed support,Naming Schemes,Building With Projects
18029 @anchor{gnat_ugn/gnat_project_manager id12}@anchor{16a}@anchor{gnat_ugn/gnat_project_manager installation}@anchor{16b}
18030 @subsection Installation
18033 After building an application or a library it is often required to
18034 install it into the development environment. For instance this step is
18035 required if the library is to be used by another application.
18036 The @emph{gprinstall} tool provides an easy way to install
18037 libraries, executable or object code generated during the build. The
18038 @strong{Install} package can be used to change the default locations.
18040 The following attributes can be defined in package @cite{Install}:
18042 @geindex Active (GNAT Project Manager)
18047 @item @strong{Active}
18049 Whether the project is to be installed, values are @cite{true}
18050 (default) or @cite{false}.
18053 @geindex Artifacts (GNAT Project Manager)
18059 An array attribute to declare a set of files not part of the sources
18060 to be installed. The array discriminant is the directory where the
18061 file is to be installed. If a relative directory then Prefix (see
18062 below) is prepended. Note also that if the same file name occurs
18063 multiple time in the attribute list, the last one will be the one
18067 @geindex Prefix (GNAT Project Manager)
18073 Root directory for the installation.
18076 @strong{Exec_Subdir}
18080 Subdirectory of @strong{Prefix} where executables are to be
18081 installed. Default is @strong{bin}.
18084 @strong{Lib_Subdir}
18088 Subdirectory of @strong{Prefix} where directory with the library or object
18089 files is to be installed. Default is @strong{lib}.
18092 @strong{Sources_Subdir}
18096 Subdirectory of @strong{Prefix} where directory with sources is to be
18097 installed. Default is @strong{include}.
18100 @strong{Project_Subdir}
18104 Subdirectory of @strong{Prefix} where the generated project file is to be
18105 installed. Default is @strong{share/gpr}.
18112 The installation mode, it is either @strong{dev} (default) or @strong{usage}.
18113 See @strong{gprbuild} user's guide for details.
18116 @strong{Install_Name}
18120 Specify the name to use for recording the installation. The default is
18121 the project name without the extension.
18124 @node Distributed support,,Installation,Building With Projects
18125 @anchor{gnat_ugn/gnat_project_manager id13}@anchor{16c}@anchor{gnat_ugn/gnat_project_manager distributed-support}@anchor{16d}
18126 @subsection Distributed support
18129 For large projects the compilation time can become a limitation in
18130 the development cycle. To cope with that, GPRbuild supports
18131 distributed compilation.
18133 The following attributes can be defined in package @cite{Remote}:
18135 @geindex Root_Dir (GNAT Project Manager)
18141 Root directory of the project's sources. The default value is the
18142 project's directory.
18145 @node Organizing Projects into Subsystems,Scenarios in Projects,Building With Projects,GNAT Project Manager
18146 @anchor{gnat_ugn/gnat_project_manager organizing-projects-into-subsystems}@anchor{151}@anchor{gnat_ugn/gnat_project_manager id14}@anchor{16e}
18147 @section Organizing Projects into Subsystems
18150 A @strong{subsystem} is a coherent part of the complete system to be built. It is
18151 represented by a set of sources and one single object directory. A system can
18152 be composed of a single subsystem when it is simple as we have seen in the
18153 first section. Complex systems are usually composed of several interdependent
18154 subsystems. A subsystem is dependent on another subsystem if knowledge of the
18155 other one is required to build it, and in particular if visibility on some of
18156 the sources of this other subsystem is required. Each subsystem is usually
18157 represented by its own project file.
18159 In this section, the previous example is being extended. Let's assume some
18160 sources of our @cite{Build} project depend on other sources.
18161 For instance, when building a graphical interface, it is usual to depend upon
18162 a graphical library toolkit such as GtkAda. Furthermore, we also need
18163 sources from a logging module we had previously written.
18166 * Project Dependencies::
18167 * Cyclic Project Dependencies::
18168 * Sharing Between Projects::
18169 * Global Attributes::
18173 @node Project Dependencies,Cyclic Project Dependencies,,Organizing Projects into Subsystems
18174 @anchor{gnat_ugn/gnat_project_manager project-dependencies}@anchor{16f}@anchor{gnat_ugn/gnat_project_manager id15}@anchor{170}
18175 @subsection Project Dependencies
18178 GtkAda comes with its own project file (appropriately called
18179 @code{gtkada.gpr}), and we will assume we have already built a project
18180 called @code{logging.gpr} for the logging module. With the information provided
18181 so far in @code{build.gpr}, building the application would fail with an error
18182 indicating that the gtkada and logging units that are relied upon by the sources
18183 of this project cannot be found.
18185 This is solved by adding the following @strong{with} clauses at the beginning of our
18190 with "a/b/logging.gpr";
18196 @geindex Externally_Built (GNAT Project Manager)
18198 When such a project is compiled, @emph{gprbuild} will automatically check
18199 the other projects and recompile their sources when needed. It will also
18200 recompile the sources from @cite{Build} when needed, and finally create the
18201 executable. In some cases, the implementation units needed to recompile a
18202 project are not available, or come from some third party and you do not want to
18203 recompile it yourself. In this case, set the attribute @strong{Externally_Built} to
18204 "true", indicating to the builder that this project can be assumed to be
18205 up-to-date, and should not be considered for recompilation. In Ada, if the
18206 sources of this externally built project were compiled with another version of
18207 the compiler or with incompatible options, the binder will issue an error.
18209 The project's @emph{with} clause has several effects. It provides source
18210 visibility between projects during the compilation process. It also guarantees
18211 that the necessary object files from @cite{Logging} and @cite{GtkAda} are
18212 available when linking @cite{Build}.
18214 As can be seen in this example, the syntax for importing projects is similar
18215 to the syntax for importing compilation units in Ada. However, project files
18216 use literal strings instead of names, and the @emph{with} clause identifies
18217 project files rather than packages.
18219 Each literal string after @emph{with} is the path
18220 (absolute or relative) to a project file. The @cite{.gpr} extension is
18221 optional, although we recommend adding it. If no extension is specified,
18222 and no project file with the @code{.gpr} extension is found, then
18223 the file is searched for exactly as written in the @emph{with} clause,
18224 that is with no extension.
18226 As mentioned above, the path after a @emph{with} has to be a literal
18227 string, and you cannot use concatenation, or lookup the value of external
18228 variables to change the directories from which a project is loaded.
18229 A solution if you need something like this is to use aggregate projects
18230 (see @ref{171,,Aggregate Projects}).
18232 @geindex project path (GNAT Project Manager)
18234 When a relative path or a base name is used, the
18235 project files are searched relative to each of the directories in the
18236 @strong{project path}. This path includes all the directories found with the
18237 following algorithm, in this order; the first matching file is used:
18243 First, the file is searched relative to the directory that contains the
18244 current project file.
18246 @geindex GPR_PROJECT_PATH_FILE (GNAT Project Manager)
18248 @geindex GPR_PROJECT_PATH (GNAT Project Manager)
18250 @geindex ADA_PROJECT_PATH (GNAT Project Manager)
18253 Then it is searched relative to all the directories specified in the
18254 environment variables @strong{GPR_PROJECT_PATH_FILE},
18255 @strong{GPR_PROJECT_PATH} and @strong{ADA_PROJECT_PATH} (in that order) if they exist.
18256 The value of @strong{GPR_PROJECT_PATH_FILE}, when defined, is the path name of
18257 a text file that contains project directory path names, one per line.
18258 @strong{GPR_PROJECT_PATH} and @strong{ADA_PROJECT_PATH}, when defined, contain
18259 project directory path names separated by directory separators.
18260 @strong{ADA_PROJECT_PATH} is used for compatibility, it is recommended to
18261 use @strong{GPR_PROJECT_PATH_FILE} or @strong{GPR_PROJECT_PATH}.
18264 Finally, it is searched relative to the default project directories.
18265 Such directories depend on the tool used. The locations searched in the
18266 specified order are:
18272 @code{<prefix>/<target>/lib/gnat} if option @emph{--target} is specified
18275 @code{<prefix>/<target>/share/gpr} if option @emph{--target} is specified
18278 @code{<prefix>/share/gpr/}
18281 @code{<prefix>/lib/gnat/}
18284 In our example, @code{gtkada.gpr} is found in the predefined directory if
18285 it was installed at the same root as GNAT.
18288 Some tools also support extending the project path from the command line,
18289 generally through the @emph{-aP}. You can see the value of the project
18290 path by using the @emph{gnatls -v} command.
18292 Any symbolic link will be fully resolved in the directory of the
18293 importing project file before the imported project file is examined.
18295 Any source file in the imported project can be used by the sources of the
18296 importing project, transitively.
18297 Thus if @cite{A} imports @cite{B}, which imports @cite{C}, the sources of
18298 @cite{A} may depend on the sources of @cite{C}, even if @cite{A} does not
18299 import @cite{C} explicitly. However, this is not recommended, because if
18300 and when @cite{B} ceases to import @cite{C}, some sources in @cite{A} will
18301 no longer compile. @emph{gprbuild} has a switch @emph{--no-indirect-imports}
18302 that will report such indirect dependencies.
18306 One very important aspect of a project hierarchy is that
18307 @strong{a given source can only belong to one project} (otherwise the project manager
18308 would not know which settings apply to it and when to recompile it). It means
18309 that different project files do not usually share source directories or
18310 when they do, they need to specify precisely which project owns which sources
18311 using attribute @cite{Source_Files} or equivalent. By contrast, 2 projects
18312 can each own a source with the same base file name as long as they live in
18313 different directories. The latter is not true for Ada Sources because of the
18314 correlation between source files and Ada units.
18318 @node Cyclic Project Dependencies,Sharing Between Projects,Project Dependencies,Organizing Projects into Subsystems
18319 @anchor{gnat_ugn/gnat_project_manager id16}@anchor{172}@anchor{gnat_ugn/gnat_project_manager cyclic-project-dependencies}@anchor{173}
18320 @subsection Cyclic Project Dependencies
18323 Cyclic dependencies are mostly forbidden:
18324 if @cite{A} imports @cite{B} (directly or indirectly) then @cite{B}
18325 is not allowed to import @cite{A}. However, there are cases when cyclic
18326 dependencies would be beneficial. For these cases, another form of import
18327 between projects exists: the @strong{limited with}. A project @cite{A} that
18328 imports a project @cite{B} with a straight @emph{with} may also be imported,
18329 directly or indirectly, by @cite{B} through a @cite{limited with}.
18331 The difference between straight @emph{with} and @cite{limited with} is that
18332 the name of a project imported with a @cite{limited with} cannot be used in the
18333 project importing it. In particular, its packages cannot be renamed and
18334 its variables cannot be referred to.
18340 for Exec_Dir use B'Exec_Dir; -- ok
18343 limited with "a.gpr"; -- Cyclic dependency: A -> B -> A
18345 for Exec_Dir use A'Exec_Dir; -- not ok
18352 limited with "a.gpr"; -- Cyclic dependency: A -> C -> D -> A
18354 for Exec_Dir use A'Exec_Dir; -- not ok
18358 @node Sharing Between Projects,Global Attributes,Cyclic Project Dependencies,Organizing Projects into Subsystems
18359 @anchor{gnat_ugn/gnat_project_manager sharing-between-projects}@anchor{174}@anchor{gnat_ugn/gnat_project_manager id17}@anchor{175}
18360 @subsection Sharing Between Projects
18363 When building an application, it is common to have similar needs in several of
18364 the projects corresponding to the subsystems under construction. For instance,
18365 they will all have the same compilation switches.
18367 As seen before (see @ref{161,,Tools Options in Project Files}), setting compilation
18368 switches for all sources of a subsystem is simple: it is just a matter of
18369 adding a @cite{Compiler.Default_Switches} attribute to each project files with
18370 the same value. Of course, that means duplication of data, and both places need
18371 to be changed in order to recompile the whole application with different
18372 switches. It can become a real problem if there are many subsystems and thus
18373 many project files to edit.
18375 There are two main approaches to avoiding this duplication:
18381 Since @code{build.gpr} imports @code{logging.gpr}, we could change it
18382 to reference the attribute in Logging, either through a package renaming,
18383 or by referencing the attribute. The following example shows both cases:
18387 package Compiler is
18388 for Switches ("Ada")
18392 for Switches ("Ada")
18397 with "logging.gpr";
18399 package Compiler renames Logging.Compiler;
18401 for Switches ("Ada") use Logging.Binder'Switches ("Ada");
18406 The solution used for @cite{Compiler} gets the same value for all
18407 attributes of the package, but you cannot modify anything from the
18408 package (adding extra switches or some exceptions). The second
18409 version is more flexible, but more verbose.
18411 If you need to refer to the value of a variable in an imported
18412 project, rather than an attribute, the syntax is similar but uses
18413 a "." rather than an apostrophe. For instance:
18418 Var1 := Imported.Var;
18423 The second approach is to define the switches in a third project.
18424 That project is set up without any sources (so that, as opposed to
18425 the first example, none of the project plays a special role), and
18426 will only be used to define the attributes. Such a project is
18427 typically called @code{shared.gpr}.
18430 abstract project Shared is
18431 for Source_Files use (); -- no sources
18432 package Compiler is
18433 for Switches ("Ada")
18440 package Compiler renames Shared.Compiler;
18445 package Compiler renames Shared.Compiler;
18449 As for the first example, we could have chosen to set the attributes
18450 one by one rather than to rename a package. The reason we explicitly
18451 indicate that @cite{Shared} has no sources is so that it can be created
18452 in any directory and we are sure it shares no sources with @cite{Build}
18453 or @cite{Logging}, which of course would be invalid.
18455 @geindex project qualifier (GNAT Project Manager)
18457 Note the additional use of the @strong{abstract} qualifier in @code{shared.gpr}.
18458 This qualifier is optional, but helps convey the message that we do not
18459 intend this project to have sources (see @ref{176,,Qualified Projects} for
18463 @node Global Attributes,,Sharing Between Projects,Organizing Projects into Subsystems
18464 @anchor{gnat_ugn/gnat_project_manager global-attributes}@anchor{177}@anchor{gnat_ugn/gnat_project_manager id18}@anchor{178}
18465 @subsection Global Attributes
18468 We have already seen many examples of attributes used to specify a special
18469 option of one of the tools involved in the build process. Most of those
18470 attributes are project specific. That it to say, they only affect the invocation
18471 of tools on the sources of the project where they are defined.
18473 There are a few additional attributes that apply to all projects in a
18474 hierarchy as long as they are defined on the "main" project.
18475 The main project is the project explicitly mentioned on the command-line.
18476 The project hierarchy is the "with"-closure of the main project.
18478 Here is a list of commonly used global attributes:
18480 @geindex Global_Configuration_Pragmas (GNAT Project Manager)
18482 @strong{Builder.Global_Configuration_Pragmas}:
18486 This attribute points to a file that contains configuration pragmas
18487 to use when building executables. These pragmas apply for all
18488 executables built from this project hierarchy. As we have seen before,
18489 additional pragmas can be specified on a per-project basis by setting the
18490 @cite{Compiler.Local_Configuration_Pragmas} attribute.
18493 @geindex Global_Compilation_Switches (GNAT Project Manager)
18495 @strong{Builder.Global_Compilation_Switches}:
18499 This attribute is a list of compiler switches to use when compiling any
18500 source file in the project hierarchy. These switches are used in addition
18501 to the ones defined in the @cite{Compiler} package, which only apply to
18502 the sources of the corresponding project. This attribute is indexed on
18503 the name of the language.
18506 Using such global capabilities is convenient. It can also lead to unexpected
18507 behavior. Especially when several subsystems are shared among different main
18508 projects and the different global attributes are not
18509 compatible. Note that using aggregate projects can be a safer and more powerful
18510 replacement to global attributes.
18512 @node Scenarios in Projects,Library Projects,Organizing Projects into Subsystems,GNAT Project Manager
18513 @anchor{gnat_ugn/gnat_project_manager id19}@anchor{179}@anchor{gnat_ugn/gnat_project_manager scenarios-in-projects}@anchor{14f}
18514 @section Scenarios in Projects
18517 Various aspects of the projects can be modified based on @strong{scenarios}. These
18518 are user-defined modes that change the behavior of a project. Typical
18519 examples are the setup of platform-specific compiler options, or the use of
18520 a debug and a release mode (the former would activate the generation of debug
18521 information, while the second will focus on improving code optimization).
18523 Let's enhance our example to support debug and release modes. The issue is to
18524 let the user choose what kind of system he is building: use @emph{-g} as
18525 compiler switches in debug mode and @emph{-O2} in release mode. We will also
18526 set up the projects so that we do not share the same object directory in both
18527 modes; otherwise switching from one to the other might trigger more
18528 recompilations than needed or mix objects from the two modes.
18530 One naive approach is to create two different project files, say
18531 @code{build_debug.gpr} and @code{build_release.gpr}, that set the appropriate
18532 attributes as explained in previous sections. This solution does not scale
18533 well, because in the presence of multiple projects depending on each other, you
18534 will also have to duplicate the complete hierarchy and adapt the project files
18535 to point to the right copies.
18537 @geindex scenarios (GNAT Project Manager)
18539 Instead, project files support the notion of scenarios controlled
18540 by external values. Such values can come from several sources (in decreasing
18541 order of priority):
18543 @geindex -X (usage with GNAT Project Manager)
18548 @item @strong{Command line}:
18550 When launching @emph{gprbuild}, the user can pass
18551 extra @emph{-X} switches to define the external value. In
18552 our case, the command line might look like
18555 gprbuild -Pbuild.gpr -Xmode=release
18558 @item @strong{Environment variables}:
18560 When the external value does not come from the command line, it can come from
18561 the value of environment variables of the appropriate name.
18562 In our case, if an environment variable called "mode"
18563 exists, its value will be taken into account.
18566 @geindex external (GNAT Project Manager)
18568 @strong{External function second parameter}.
18570 We now need to get that value in the project. The general form is to use
18571 the predefined function @strong{external} which returns the current value of
18572 the external. For instance, we could set up the object directory to point to
18573 either @code{obj/debug} or @code{obj/release} by changing our project to
18577 for Object_Dir use "obj/" & external ("mode", "debug");
18582 The second parameter to @cite{external} is optional, and is the default
18583 value to use if "mode" is not set from the command line or the environment.
18585 In order to set the switches according to the different scenarios, other
18586 constructs have to be introduced such as typed variables and case constructions.
18588 @geindex typed variable (GNAT Project Manager)
18590 @geindex case construction (GNAT Project Manager)
18592 A @strong{typed variable} is a variable that
18593 can take only a limited number of values, similar to an enumeration in Ada.
18594 Such a variable can then be used in a @strong{case construction} and create conditional
18595 sections in the project. The following example shows how this can be done:
18599 type Mode_Type is ("debug", "release"); -- all possible values
18600 Mode : Mode_Type := external ("mode", "debug"); -- a typed variable
18602 package Compiler is
18605 for Switches ("Ada")
18608 for Switches ("Ada")
18615 The project has suddenly grown in size, but has become much more flexible.
18616 @cite{Mode_Type} defines the only valid values for the @cite{mode} variable. If
18617 any other value is read from the environment, an error is reported and the
18618 project is considered as invalid.
18620 The @cite{Mode} variable is initialized with an external value
18621 defaulting to @cite{"debug"}. This default could be omitted and that would
18622 force the user to define the value. Finally, we can use a case construction to set the
18623 switches depending on the scenario the user has chosen.
18625 Most aspects of the projects can depend on scenarios. The notable exception
18626 are project dependencies (@emph{with} clauses), which cannot depend on a scenario.
18628 Scenarios work the same way with @strong{project hierarchies}: you can either
18629 duplicate a variable similar to @cite{Mode} in each of the project (as long
18630 as the first argument to @cite{external} is always the same and the type is
18631 the same), or simply set the variable in the @code{shared.gpr} project
18632 (see @ref{174,,Sharing Between Projects}).
18634 @node Library Projects,Project Extension,Scenarios in Projects,GNAT Project Manager
18635 @anchor{gnat_ugn/gnat_project_manager library-projects}@anchor{8a}@anchor{gnat_ugn/gnat_project_manager id20}@anchor{17a}
18636 @section Library Projects
18639 So far, we have seen examples of projects that create executables. However,
18640 it is also possible to create libraries instead. A @strong{library} is a specific
18641 type of subsystem where, for convenience, objects are grouped together
18642 using system-specific means such as archives or windows DLLs.
18644 Library projects provide a system- and language-independent way of building
18645 both @strong{static} and @strong{dynamic} libraries. They also support the concept of
18646 @strong{standalone libraries} (SAL) which offer two significant properties: the
18647 elaboration (e.g. initialization) of the library is either automatic or
18648 very simple; a change in the
18649 implementation part of the library implies minimal post-compilation actions on
18650 the complete system and potentially no action at all for the rest of the
18651 system in the case of dynamic SALs.
18653 There is a restriction on shared library projects: by default, they are only
18654 allowed to import other shared library projects. They are not allowed to
18655 import non library projects or static library projects.
18657 The GNAT Project Manager takes complete care of the library build, rebuild and
18658 installation tasks, including recompilation of the source files for which
18659 objects do not exist or are not up to date, assembly of the library archive, and
18660 installation of the library (i.e., copying associated source, object and
18661 @code{ALI} files to the specified location).
18664 * Building Libraries::
18665 * Using Library Projects::
18666 * Stand-alone Library Projects::
18667 * Installing a library with project files::
18671 @node Building Libraries,Using Library Projects,,Library Projects
18672 @anchor{gnat_ugn/gnat_project_manager id21}@anchor{17b}@anchor{gnat_ugn/gnat_project_manager building-libraries}@anchor{17c}
18673 @subsection Building Libraries
18676 Let's enhance our example and transform the @cite{logging} subsystem into a
18677 library. In order to do so, a few changes need to be made to
18678 @code{logging.gpr}. Some attributes need to be defined: at least
18679 @cite{Library_Name} and @cite{Library_Dir}; in addition, some other attributes
18680 can be used to specify specific aspects of the library. For readability, it is
18681 also recommended (although not mandatory), to use the qualifier @cite{library}
18682 in front of the @cite{project} keyword.
18684 @geindex Library_Name (GNAT Project Manager)
18686 @strong{Library_Name}:
18690 This attribute is the name of the library to be built. There is no
18691 restriction on the name of a library imposed by the project manager, except
18692 for stand-alone libraries whose names must follow the syntax of Ada
18693 identifiers; however, there may be system-specific restrictions on the name.
18694 In general, it is recommended to stick to alphanumeric characters (and
18695 possibly single underscores) to help portability.
18698 @geindex Library_Dir (GNAT Project Manager)
18700 @strong{Library_Dir}:
18704 This attribute is the path (absolute or relative) of the directory where
18705 the library is to be installed. In the process of building a library,
18706 the sources are compiled, the object files end up in the explicit or
18707 implicit @cite{Object_Dir} directory. When all sources of a library
18708 are compiled, some of the compilation artifacts, including the library itself,
18709 are copied to the library_dir directory. This directory must exist and be
18710 writable. It must also be different from the object directory so that cleanup
18711 activities in the Library_Dir do not affect recompilation needs.
18714 Here is the new version of @code{logging.gpr} that makes it a library:
18717 library project Logging is -- "library" is optional
18718 for Library_Name use "logging"; -- will create "liblogging.a" on Unix
18719 for Object_Dir use "obj";
18720 for Library_Dir use "lib"; -- different from object_dir
18724 Once the above two attributes are defined, the library project is valid and
18725 is enough for building a library with default characteristics.
18726 Other library-related attributes can be used to change the defaults:
18728 @geindex Library_Kind (GNAT Project Manager)
18730 @strong{Library_Kind}:
18734 The value of this attribute must be either @cite{"static"}, @cite{"dynamic"} or
18735 @cite{"relocatable"} (the latter is a synonym for dynamic). It indicates
18736 which kind of library should be built (the default is to build a
18737 static library, that is an archive of object files that can potentially
18738 be linked into a static executable). When the library is set to be dynamic,
18739 a separate image is created that will be loaded independently, usually
18740 at the start of the main program execution. Support for dynamic libraries is
18741 very platform specific, for instance on Windows it takes the form of a DLL
18742 while on GNU/Linux, it is a dynamic elf image whose suffix is usually
18743 @code{.so}. Library project files, on the other hand, can be written in
18744 a platform independent way so that the same project file can be used to build
18745 a library on different operating systems.
18747 If you need to build both a static and a dynamic library, it is recommended
18748 to use two different object directories, since in some cases some extra code
18749 needs to be generated for the latter. For such cases, one can either define
18750 two different project files, or a single one that uses scenarios to indicate
18751 the various kinds of library to be built and their corresponding object_dir.
18754 @geindex Library_ALI_Dir (GNAT Project Manager)
18756 @strong{Library_ALI_Dir}:
18760 This attribute may be specified to indicate the directory where the ALI
18761 files of the library are installed. By default, they are copied into the
18762 @cite{Library_Dir} directory, but as for the executables where we have a
18763 separate @cite{Exec_Dir} attribute, you might want to put them in a separate
18764 directory since there can be hundreds of them. The same restrictions as for
18765 the @cite{Library_Dir} attribute apply.
18768 @geindex Library_Version (GNAT Project Manager)
18770 @strong{Library_Version}:
18774 This attribute is platform dependent, and has no effect on Windows.
18775 On Unix, it is used only for dynamic libraries as the internal
18776 name of the library (the @cite{"soname"}). If the library file name (built
18777 from the @cite{Library_Name}) is different from the @cite{Library_Version},
18778 then the library file will be a symbolic link to the actual file whose name
18779 will be @cite{Library_Version}. This follows the usual installation schemes
18780 for dynamic libraries on many Unix systems.
18785 for Library_Dir use "lib";
18786 for Library_Name use "logging";
18787 for Library_Kind use "dynamic";
18788 for Library_Version use "liblogging.so." & Version;
18792 After the compilation, the directory @code{lib} will contain both a
18793 @code{libdummy.so.1} library and a symbolic link to it called
18794 @code{libdummy.so}.
18797 @geindex Library_GCC (GNAT Project Manager)
18799 @strong{Library_GCC}:
18803 This attribute is the name of the tool to use instead of "gcc" to link shared
18804 libraries. A common use of this attribute is to define a wrapper script that
18805 accomplishes specific actions before calling gcc (which itself calls the
18806 linker to build the library image).
18809 @geindex Library_Options (GNAT Project Manager)
18811 @strong{Library_Options}:
18815 This attribute may be used to specify additional switches (last switches)
18816 when linking a shared library.
18818 It may also be used to add foreign object files to a static library.
18819 Each string in Library_Options is an absolute or relative path of an object
18820 file. When a relative path, it is relative to the object directory.
18823 @geindex Leading_Library_Options (GNAT Project Manager)
18825 @strong{Leading_Library_Options}:
18829 This attribute, that is taken into account only by @emph{gprbuild}, may be
18830 used to specified leading options (first switches) when linking a shared
18834 @geindex Linker_Options (GNAT Project Manager)
18836 @strong{Linker.Linker_Options}:
18840 This attribute specifies additional switches to be given to the linker when
18841 linking an executable. It is ignored when defined in the main project and
18842 taken into account in all other projects that are imported directly or
18843 indirectly. These switches complement the @cite{Linker.Switches}
18844 defined in the main project. This is useful when a particular subsystem
18845 depends on an external library: adding this dependency as a
18846 @cite{Linker_Options} in the project of the subsystem is more convenient than
18847 adding it to all the @cite{Linker.Switches} of the main projects that depend
18848 upon this subsystem.
18851 @node Using Library Projects,Stand-alone Library Projects,Building Libraries,Library Projects
18852 @anchor{gnat_ugn/gnat_project_manager id22}@anchor{17d}@anchor{gnat_ugn/gnat_project_manager using-library-projects}@anchor{17e}
18853 @subsection Using Library Projects
18856 When the builder detects that a project file is a library project file, it
18857 recompiles all sources of the project that need recompilation and rebuild the
18858 library if any of the sources have been recompiled. It then groups all object
18859 files into a single file, which is a shared or a static library. This library
18860 can later on be linked with multiple executables. Note that the use
18861 of shard libraries reduces the size of the final executable and can also reduce
18862 the memory footprint at execution time when the library is shared among several
18865 @emph{gprbuild also allows to build **multi-language libraries*} when specifying
18866 sources from multiple languages.
18868 A non-library project can import a library project. When the builder is invoked
18869 on the former, the library of the latter is only rebuilt when absolutely
18870 necessary. For instance, if a unit of the library is not up-to-date but none of
18871 the executables need this unit, then the unit is not recompiled and the library
18872 is not reassembled. For instance, let's assume in our example that logging has
18873 the following sources: @code{log1.ads}, @code{log1.adb}, @code{log2.ads} and
18874 @code{log2.adb}. If @code{log1.adb} has been modified, then the library
18875 @code{liblogging} will be rebuilt when compiling all the sources of
18876 @cite{Build} only if @code{proc.ads}, @code{pack.ads} or @code{pack.adb}
18877 include a @cite{"with Log1"}.
18879 To ensure that all the sources in the @cite{Logging} library are
18880 up to date, and that all the sources of @cite{Build} are also up to date,
18881 the following two commands need to be used:
18884 gprbuild -Plogging.gpr
18885 gprbuild -Pbuild.gpr
18888 All @code{ALI} files will also be copied from the object directory to the
18889 library directory. To build executables, @emph{gprbuild} will use the
18890 library rather than the individual object files.
18892 Library projects can also be useful to describe a library that needs to be used
18893 but, for some reason, cannot be rebuilt. For instance, it is the case when some
18894 of the library sources are not available. Such library projects need to use the
18895 @cite{Externally_Built} attribute as in the example below:
18898 library project Extern_Lib is
18899 for Languages use ("Ada", "C");
18900 for Source_Dirs use ("lib_src");
18901 for Library_Dir use "lib2";
18902 for Library_Kind use "dynamic";
18903 for Library_Name use "l2";
18904 for Externally_Built use "true"; -- <<<<
18908 In the case of externally built libraries, the @cite{Object_Dir}
18909 attribute does not need to be specified because it will never be
18912 The main effect of using such an externally built library project is mostly to
18913 affect the linker command in order to reference the desired library. It can
18914 also be achieved by using @cite{Linker.Linker_Options} or @cite{Linker.Switches}
18915 in the project corresponding to the subsystem needing this external library.
18916 This latter method is more straightforward in simple cases but when several
18917 subsystems depend upon the same external library, finding the proper place
18918 for the @cite{Linker.Linker_Options} might not be easy and if it is
18919 not placed properly, the final link command is likely to present ordering issues.
18920 In such a situation, it is better to use the externally built library project
18921 so that all other subsystems depending on it can declare this dependency thanks
18922 to a project @emph{with} clause, which in turn will trigger the builder to find
18923 the proper order of libraries in the final link command.
18925 @node Stand-alone Library Projects,Installing a library with project files,Using Library Projects,Library Projects
18926 @anchor{gnat_ugn/gnat_project_manager id23}@anchor{17f}@anchor{gnat_ugn/gnat_project_manager stand-alone-library-projects}@anchor{97}
18927 @subsection Stand-alone Library Projects
18930 @geindex standalone libraries (usage with GNAT Project Manager)
18932 A @strong{stand-alone library} is a library that contains the necessary code to
18933 elaborate the Ada units that are included in the library. A stand-alone
18934 library is a convenient way to add an Ada subsystem to a more global system
18935 whose main is not in Ada since it makes the elaboration of the Ada part mostly
18936 transparent. However, stand-alone libraries are also useful when the main is in
18937 Ada: they provide a means for minimizing relinking & redeployment of complex
18938 systems when localized changes are made.
18940 The name of a stand-alone library, specified with attribute
18941 @cite{Library_Name}, must have the syntax of an Ada identifier.
18943 The most prominent characteristic of a stand-alone library is that it offers a
18944 distinction between interface units and implementation units. Only the former
18945 are visible to units outside the library. A stand-alone library project is thus
18946 characterised by a third attribute, usually @strong{Library_Interface}, in addition
18947 to the two attributes that make a project a Library Project
18948 (@cite{Library_Name} and @cite{Library_Dir}). This third attribute may also be
18949 @strong{Interfaces}. @strong{Library_Interface} only works when the interface is in Ada
18950 and takes a list of units as parameter. @strong{Interfaces} works for any supported
18951 language and takes a list of sources as parameter.
18953 @geindex Library_Interface (GNAT Project Manager)
18955 @strong{Library_Interface}:
18959 This attribute defines an explicit subset of the units of the project. Units
18960 from projects importing this library project may only "with" units whose
18961 sources are listed in the @cite{Library_Interface}. Other sources are
18962 considered implementation units.
18965 for Library_Dir use "lib";
18966 for Library_Name use "logging";
18967 for Library_Interface use ("lib1", "lib2"); -- unit names
18971 @strong{Interfaces}
18975 This attribute defines an explicit subset of the source files of a project.
18976 Sources from projects importing this project, can only depend on sources from
18977 this subset. This attribute can be used on non library projects. It can also
18978 be used as a replacement for attribute @cite{Library_Interface}, in which
18979 case, units have to be replaced by source files. For multi-language library
18980 projects, it is the only way to make the project a Stand-Alone Library project
18981 whose interface is not purely Ada.
18984 @geindex Library_Standalone (GNAT Project Manager)
18986 @strong{Library_Standalone}:
18990 This attribute defines the kind of standalone library to
18991 build. Values are either @cite{standard} (the default), @cite{no} or
18992 @cite{encapsulated}. When @cite{standard} is used the code to elaborate and
18993 finalize the library is embedded, when @cite{encapsulated} is used the
18994 library can furthermore depend only on static libraries (including
18995 the GNAT runtime). This attribute can be set to @cite{no} to make it clear
18996 that the library should not be standalone in which case the
18997 @cite{Library_Interface} should not defined. Note that this attribute
18998 only applies to shared libraries, so @cite{Library_Kind} must be set
19002 for Library_Dir use "lib";
19003 for Library_Name use "logging";
19004 for Library_Kind use "dynamic";
19005 for Library_Interface use ("lib1", "lib2"); -- unit names
19006 for Library_Standalone use "encapsulated";
19010 In order to include the elaboration code in the stand-alone library, the binder
19011 is invoked on the closure of the library units creating a package whose name
19012 depends on the library name (b~logging.ads/b in the example).
19013 This binder-generated package includes @strong{initialization} and @strong{finalization}
19014 procedures whose names depend on the library name (@cite{logginginit} and
19015 @cite{loggingfinal} in the example). The object corresponding to this package is
19016 included in the library.
19018 @geindex Library_Auto_Init (GNAT Project Manager)
19020 @strong{Library_Auto_Init}:
19024 A dynamic stand-alone Library is automatically initialized
19025 if automatic initialization of Stand-alone Libraries is supported on the
19026 platform and if attribute @strong{Library_Auto_Init} is not specified or
19027 is specified with the value "true". A static Stand-alone Library is never
19028 automatically initialized. Specifying "false" for this attribute
19029 prevents automatic initialization.
19031 When a non-automatically initialized stand-alone library is used in an
19032 executable, its initialization procedure must be called before any service of
19033 the library is used. When the main subprogram is in Ada, it may mean that the
19034 initialization procedure has to be called during elaboration of another
19038 @geindex Library_Dir (GNAT Project Manager)
19040 @strong{Library_Dir}:
19044 For a stand-alone library, only the @code{ALI} files of the interface units
19045 (those that are listed in attribute @cite{Library_Interface}) are copied to
19046 the library directory. As a consequence, only the interface units may be
19047 imported from Ada units outside of the library. If other units are imported,
19048 the binding phase will fail.
19051 @strong{Binder.Default_Switches}:
19055 When a stand-alone library is bound, the switches that are specified in
19056 the attribute @strong{Binder.Default_Switches ("Ada")} are
19057 used in the call to @emph{gnatbind}.
19060 @geindex Library_Src_Dir (GNAT Project Manager)
19062 @strong{Library_Src_Dir}:
19066 This attribute defines the location (absolute or relative to the project
19067 directory) where the sources of the interface units are copied at
19069 These sources includes the specs of the interface units along with the
19070 closure of sources necessary to compile them successfully. That may include
19071 bodies and subunits, when pragmas @cite{Inline} are used, or when there are
19072 generic units in specs. This directory cannot point to the object directory
19073 or one of the source directories, but it can point to the library directory,
19074 which is the default value for this attribute.
19077 @geindex Library_Symbol_Policy (GNAT Project Manager)
19079 @strong{Library_Symbol_Policy}:
19083 This attribute controls the export of symbols and, on some platforms (like
19084 VMS) that have the notions of major and minor IDs built in the library
19085 files, it controls the setting of these IDs. It is not supported on all
19086 platforms (where it will just have no effect). It may have one of the
19093 @cite{"autonomous"} or @cite{"default"}: exported symbols are not controlled
19096 @cite{"compliant"}: if attribute @strong{Library_Reference_Symbol_File}
19097 is not defined, then it is equivalent to policy "autonomous". If there
19098 are exported symbols in the reference symbol file that are not in the
19099 object files of the interfaces, the major ID of the library is increased.
19100 If there are symbols in the object files of the interfaces that are not
19101 in the reference symbol file, these symbols are put at the end of the list
19102 in the newly created symbol file and the minor ID is increased.
19105 @cite{"controlled"}: the attribute @strong{Library_Reference_Symbol_File} must be
19106 defined. The library will fail to build if the exported symbols in the
19107 object files of the interfaces do not match exactly the symbol in the
19111 @cite{"restricted"}: The attribute @strong{Library_Symbol_File} must be defined.
19112 The library will fail to build if there are symbols in the symbol file that
19113 are not in the exported symbols of the object files of the interfaces.
19114 Additional symbols in the object files are not added to the symbol file.
19117 @cite{"direct"}: The attribute @strong{Library_Symbol_File} must be defined and
19118 must designate an existing file in the object directory. This symbol file
19119 is passed directly to the underlying linker without any symbol processing.
19123 @geindex Library_Reference_Symbol_File (GNAT Project Manager)
19125 @strong{Library_Reference_Symbol_File}
19129 This attribute may define the path name of a reference symbol file that is
19130 read when the symbol policy is either "compliant" or "controlled", on
19131 platforms that support symbol control, such as VMS, when building a
19132 stand-alone library. The path may be an absolute path or a path relative
19133 to the project directory.
19136 @geindex Library_Symbol_File (GNAT Project Manager)
19138 @strong{Library_Symbol_File}
19142 This attribute may define the name of the symbol file to be created when
19143 building a stand-alone library when the symbol policy is either "compliant",
19144 "controlled" or "restricted", on platforms that support symbol control,
19145 such as VMS. When symbol policy is "direct", then a file with this name
19146 must exist in the object directory.
19149 @node Installing a library with project files,,Stand-alone Library Projects,Library Projects
19150 @anchor{gnat_ugn/gnat_project_manager installing-a-library-with-project-files}@anchor{8d}@anchor{gnat_ugn/gnat_project_manager id24}@anchor{180}
19151 @subsection Installing a library with project files
19154 When using project files, a usable version of the library is created in the
19155 directory specified by the @cite{Library_Dir} attribute of the library
19156 project file. Thus no further action is needed in order to make use of
19157 the libraries that are built as part of the general application build.
19159 You may want to install a library in a context different from where the library
19160 is built. This situation arises with third party suppliers, who may want
19161 to distribute a library in binary form where the user is not expected to be
19162 able to recompile the library. The simplest option in this case is to provide
19163 a project file slightly different from the one used to build the library, by
19164 using the @cite{externally_built} attribute. See @ref{17e,,Using Library Projects}
19166 Another option is to use @emph{gprinstall} to install the library in a
19167 different context than the build location. @emph{gprinstall} automatically
19168 generates a project to use this library, and also copies the minimum set of
19169 sources needed to use the library to the install location.
19170 @ref{16b,,Installation}
19172 @node Project Extension,Aggregate Projects,Library Projects,GNAT Project Manager
19173 @anchor{gnat_ugn/gnat_project_manager id25}@anchor{181}@anchor{gnat_ugn/gnat_project_manager project-extension}@anchor{152}
19174 @section Project Extension
19177 During development of a large system, it is sometimes necessary to use
19178 modified versions of some of the source files, without changing the original
19179 sources. This can be achieved through the @strong{project extension} facility.
19181 Suppose for instance that our example @cite{Build} project is built every night
19182 for the whole team, in some shared directory. A developer usually needs to work
19183 on a small part of the system, and might not want to have a copy of all the
19184 sources and all the object files (mostly because that would require too much
19185 disk space, time to recompile everything). He prefers to be able to override
19186 some of the source files in his directory, while taking advantage of all the
19187 object files generated at night.
19189 Another example can be taken from large software systems, where it is common to have
19190 multiple implementations of a common interface; in Ada terms, multiple
19191 versions of a package body for the same spec. For example, one implementation
19192 might be safe for use in tasking programs, while another might be used only
19193 in sequential applications. This can be modeled in GNAT using the concept
19194 of @emph{project extension}. If one project (the 'child') @emph{extends}
19195 another project (the 'parent') then by default all source files of the
19196 parent project are inherited by the child, but the child project can
19197 override any of the parent's source files with new versions, and can also
19198 add new files or remove unnecessary ones.
19199 This facility is the project analog of a type extension in
19200 object-oriented programming. Project hierarchies are permitted (an extending
19201 project may itself be extended), and a project that
19202 extends a project can also import other projects.
19204 A third example is that of using project extensions to provide different
19205 versions of the same system. For instance, assume that a @cite{Common}
19206 project is used by two development branches. One of the branches has now
19207 been frozen, and no further change can be done to it or to @cite{Common}.
19208 However, the other development branch still needs evolution of @cite{Common}.
19209 Project extensions provide a flexible solution to create a new version
19210 of a subsystem while sharing and reusing as much as possible from the original
19213 A project extension implicitly inherits all the sources and objects from the
19214 project it extends. It is possible to create a new version of some of the
19215 sources in one of the additional source directories of the extending
19216 project. Those new versions hide the original versions. Adding new sources or
19217 removing existing ones is also possible. Here is an example on how to extend
19218 the project @cite{Build} from previous examples:
19221 project Work extends "../bld/build.gpr" is
19225 The project after @strong{extends} is the one being extended. As usual, it can be
19226 specified using an absolute path, or a path relative to any of the directories
19227 in the project path (see @ref{16f,,Project Dependencies}). This project does not
19228 specify source or object directories, so the default values for these
19229 attributes will be used that is to say the current directory (where project
19230 @cite{Work} is placed). We can compile that project with
19236 If no sources have been placed in the current directory, this command
19237 won't do anything, since this project does not change the
19238 sources it inherited from @cite{Build}, therefore all the object files
19239 in @cite{Build} and its dependencies are still valid and are reused
19242 Suppose we now want to supply an alternate version of @code{pack.adb} but use
19243 the existing versions of @code{pack.ads} and @code{proc.adb}. We can create
19244 the new file in Work's current directory (likely by copying the one from the
19245 @cite{Build} project and making changes to it. If new packages are needed at
19246 the same time, we simply create new files in the source directory of the
19249 When we recompile, @emph{gprbuild} will now automatically recompile
19250 this file (thus creating @code{pack.o} in the current directory) and
19251 any file that depends on it (thus creating @code{proc.o}). Finally, the
19252 executable is also linked locally.
19254 Note that we could have obtained the desired behavior using project import
19255 rather than project inheritance. A @cite{base} project would contain the
19256 sources for @code{pack.ads} and @code{proc.adb}, and @cite{Work} would
19257 import @cite{base} and add @code{pack.adb}. In this scenario, @cite{base}
19258 cannot contain the original version of @code{pack.adb} otherwise there would be
19259 2 versions of the same unit in the closure of the project and this is not
19260 allowed. Generally speaking, it is not recommended to put the spec and the
19261 body of a unit in different projects since this affects their autonomy and
19264 In a project file that extends another project, it is possible to
19265 indicate that an inherited source is @strong{not part} of the sources of the
19266 extending project. This is necessary sometimes when a package spec has
19267 been overridden and no longer requires a body: in this case, it is
19268 necessary to indicate that the inherited body is not part of the sources
19269 of the project, otherwise there will be a compilation error
19270 when compiling the spec.
19272 @geindex Excluded_Source_Files (GNAT Project Manager)
19274 @geindex Excluded_Source_List_File (GNAT Project Manager)
19276 For that purpose, the attribute @strong{Excluded_Source_Files} is used.
19277 Its value is a list of file names.
19278 It is also possible to use attribute @cite{Excluded_Source_List_File}.
19279 Its value is the path of a text file containing one file name per
19283 project Work extends "../bld/build.gpr" is
19284 for Source_Files use ("pack.ads");
19285 -- New spec of Pkg does not need a completion
19286 for Excluded_Source_Files use ("pack.adb");
19290 All packages that are not declared in the extending project are inherited from
19291 the project being extended, with their attributes, with the exception of
19292 @cite{Linker'Linker_Options} which is never inherited. In particular, an
19293 extending project retains all the switches specified in the project being
19296 At the project level, if they are not declared in the extending project, some
19297 attributes are inherited from the project being extended. They are:
19298 @cite{Languages}, @cite{Main} (for a root non library project) and
19299 @cite{Library_Name} (for a project extending a library project).
19302 * Project Hierarchy Extension::
19306 @node Project Hierarchy Extension,,,Project Extension
19307 @anchor{gnat_ugn/gnat_project_manager project-hierarchy-extension}@anchor{182}@anchor{gnat_ugn/gnat_project_manager id26}@anchor{183}
19308 @subsection Project Hierarchy Extension
19311 One of the fundamental restrictions in project extension is the following:
19312 @strong{A project is not allowed to import directly or indirectly at the same time an extending project and one of its ancestors}.
19314 For example, consider the following hierarchy of projects.
19317 a.gpr contains package A1
19318 b.gpr, imports a.gpr and contains B1, which depends on A1
19319 c.gpr, imports b.gpr and contains C1, which depends on B1
19322 If we want to locally extend the packages @cite{A1} and @cite{C1}, we need to
19323 create several extending projects:
19326 a_ext.gpr which extends a.gpr, and overrides A1
19327 b_ext.gpr which extends b.gpr and imports a_ext.gpr
19328 c_ext.gpr which extends c.gpr, imports b_ext.gpr and overrides C1
19332 project A_Ext extends "a.gpr" is
19333 for Source_Files use ("a1.adb", "a1.ads");
19337 project B_Ext extends "b.gpr" is
19341 project C_Ext extends "c.gpr" is
19342 for Source_Files use ("c1.adb");
19346 The extension @code{b_ext.gpr} is required, even though we are not overriding
19347 any of the sources of @code{b.gpr} because otherwise @code{c_expr.gpr} would
19348 import @code{b.gpr} which itself knows nothing about @code{a_ext.gpr}.
19350 @geindex extends all (GNAT Project Manager)
19352 When extending a large system spanning multiple projects, it is often
19353 inconvenient to extend every project in the hierarchy that is impacted by a
19354 small change introduced in a low layer. In such cases, it is possible to create
19355 an @strong{implicit extension} of an entire hierarchy using @strong{extends all}
19358 When the project is extended using @cite{extends all} inheritance, all projects
19359 that are imported by it, both directly and indirectly, are considered virtually
19360 extended. That is, the project manager creates implicit projects
19361 that extend every project in the hierarchy; all these implicit projects do not
19362 control sources on their own and use the object directory of
19363 the "extending all" project.
19365 It is possible to explicitly extend one or more projects in the hierarchy
19366 in order to modify the sources. These extending projects must be imported by
19367 the "extending all" project, which will replace the corresponding virtual
19368 projects with the explicit ones.
19370 When building such a project hierarchy extension, the project manager will
19371 ensure that both modified sources and sources in implicit extending projects
19372 that depend on them are recompiled.
19374 Thus, in our example we could create the following projects instead:
19377 a_ext.gpr, extends a.gpr and overrides A1
19378 c_ext.gpr, "extends all" c.gpr, imports a_ext.gpr and overrides C1
19382 project A_Ext extends "a.gpr" is
19383 for Source_Files use ("a1.adb", "a1.ads");
19387 project C_Ext extends all "c.gpr" is
19388 for Source_Files use ("c1.adb");
19392 When building project @code{c_ext.gpr}, the entire modified project space is
19393 considered for recompilation, including the sources of @code{b.gpr} that are
19394 impacted by the changes in @cite{A1} and @cite{C1}.
19396 @node Aggregate Projects,Aggregate Library Projects,Project Extension,GNAT Project Manager
19397 @anchor{gnat_ugn/gnat_project_manager aggregate-projects}@anchor{171}@anchor{gnat_ugn/gnat_project_manager id27}@anchor{184}
19398 @section Aggregate Projects
19401 Aggregate projects are an extension of the project paradigm, and are
19402 meant to solve a few specific use cases that cannot be solved directly
19403 using standard projects. This section will go over a few of these use
19404 cases to try to explain what you can use aggregate projects for.
19407 * Building all main programs from a single project tree::
19408 * Building a set of projects with a single command::
19409 * Define a build environment::
19410 * Performance improvements in builder::
19411 * Syntax of aggregate projects::
19412 * package Builder in aggregate projects::
19416 @node Building all main programs from a single project tree,Building a set of projects with a single command,,Aggregate Projects
19417 @anchor{gnat_ugn/gnat_project_manager id28}@anchor{185}@anchor{gnat_ugn/gnat_project_manager building-all-main-programs-from-a-single-project-tree}@anchor{186}
19418 @subsection Building all main programs from a single project tree
19421 Most often, an application is organized into modules and submodules,
19422 which are very conveniently represented as a project tree or graph
19423 (the root project A @emph{with}s the projects for each modules (say B and C),
19424 which in turn @emph{with} projects for submodules.
19426 Very often, modules will build their own executables (for testing
19427 purposes for instance), or libraries (for easier reuse in various
19430 However, if you build your project through @emph{gprbuild}, using a syntax similar to
19436 this will only rebuild the main programs of project A, not those of the
19437 imported projects B and C. Therefore you have to spawn several
19438 @emph{gprbuild} commands, one per project, to build all executables.
19439 This is a little inconvenient, but more importantly is inefficient
19440 because @emph{gprbuild} needs to do duplicate work to ensure that sources are
19441 up-to-date, and cannot easily compile things in parallel when using
19444 Also libraries are always rebuilt when building a project.
19446 You could therefore define an aggregate project Agg that groups A, B
19447 and C. Then, when you build with
19453 this will build all mains from A, B and C.
19456 aggregate project Agg is
19457 for Project_Files use ("a.gpr", "b.gpr", "c.gpr");
19461 If B or C do not define any main program (through their Main
19462 attribute), all their sources are built. When you do not group them
19463 in the aggregate project, only those sources that are needed by A
19466 If you add a main to a project P not already explicitly referenced in the
19467 aggregate project, you will need to add "p.gpr" in the list of project
19468 files for the aggregate project, or the main will not be built when
19469 building the aggregate project.
19471 @node Building a set of projects with a single command,Define a build environment,Building all main programs from a single project tree,Aggregate Projects
19472 @anchor{gnat_ugn/gnat_project_manager building-a-set-of-projects-with-a-single-command}@anchor{187}@anchor{gnat_ugn/gnat_project_manager id29}@anchor{188}
19473 @subsection Building a set of projects with a single command
19476 One other case is when you have multiple applications and libraries
19477 that are built independently from each other (but can be built in
19478 parallel). For instance, you have a project tree rooted at A, and
19479 another one (which might share some subprojects) rooted at B.
19481 Using only @emph{gprbuild}, you could do
19488 to build both. But again, @emph{gprbuild} has to do some duplicate work for
19489 those files that are shared between the two, and cannot truly build
19490 things in parallel efficiently.
19492 If the two projects are really independent, share no sources other
19493 than through a common subproject, and have no source files with a
19494 common basename, you could create a project C that imports A and
19495 B. But these restrictions are often too strong, and one has to build
19496 them independently. An aggregate project does not have these
19497 limitations and can aggregate two project trees that have common
19500 This scenario is particularly useful in environments like VxWorks 653
19501 where the applications running in the multiple partitions can be built
19502 in parallel through a single @emph{gprbuild} command. This also works nicely
19505 @node Define a build environment,Performance improvements in builder,Building a set of projects with a single command,Aggregate Projects
19506 @anchor{gnat_ugn/gnat_project_manager id30}@anchor{189}@anchor{gnat_ugn/gnat_project_manager define-a-build-environment}@anchor{18a}
19507 @subsection Define a build environment
19510 The environment variables at the time you launch @emph{gprbuild}
19511 will influence the view these tools have of the project
19512 (PATH to find the compiler, ADA_PROJECT_PATH or GPR_PROJECT_PATH to find the
19513 projects, environment variables that are referenced in project files
19514 through the "external" built-in function, ...). Several command line switches
19515 can be used to override those (-X or -aP), but on some systems and
19516 with some projects, this might make the command line too long, and on
19517 all systems often make it hard to read.
19519 An aggregate project can be used to set the environment for all
19520 projects built through that aggregate. One of the nice aspects is that
19521 you can put the aggregate project under configuration management, and
19522 make sure all your user have a consistent environment when
19523 building. The syntax looks like
19526 aggregate project Agg is
19527 for Project_Files use ("A.gpr", "B.gpr");
19528 for Project_Path use ("../dir1", "../dir1/dir2");
19529 for External ("BUILD") use "PRODUCTION";
19532 for Global_Compilation_Switches ("Ada") use ("-g");
19537 One of the often requested features in projects is to be able to
19538 reference external variables in @emph{with} declarations, as in
19541 with external("SETUP") & "path/prj.gpr"; -- ILLEGAL
19542 project MyProject is
19547 For various reasons, this is not allowed. But using aggregate projects provide
19548 an elegant solution. For instance, you could use a project file like:
19551 aggregate project Agg is
19552 for Project_Path use (external("SETUP") & "path");
19553 for Project_Files use ("myproject.gpr");
19556 with "prj.gpr"; -- searched on Agg'Project_Path
19557 project MyProject is
19562 @node Performance improvements in builder,Syntax of aggregate projects,Define a build environment,Aggregate Projects
19563 @anchor{gnat_ugn/gnat_project_manager performance-improvements-in-builder}@anchor{18b}@anchor{gnat_ugn/gnat_project_manager id31}@anchor{18c}
19564 @subsection Performance improvements in builder
19567 The loading of aggregate projects is optimized in @emph{gprbuild},
19568 so that all files are searched for only once on the disk
19569 (thus reducing the number of system calls and contributing to faster
19570 compilation times, especially on systems with sources on remote
19571 servers). As part of the loading, @emph{gprbuild}
19572 computes how and where a source file should be compiled, and even if it is
19573 found several times in the aggregated projects it will be compiled only
19576 Since there is no ambiguity as to which switches should be used, files
19577 can be compiled in parallel (through the usual -j switch) and this can
19578 be done while maximizing the use of CPUs (compared to launching
19579 multiple @emph{gprbuild} commands in parallel).
19581 @node Syntax of aggregate projects,package Builder in aggregate projects,Performance improvements in builder,Aggregate Projects
19582 @anchor{gnat_ugn/gnat_project_manager id32}@anchor{18d}@anchor{gnat_ugn/gnat_project_manager syntax-of-aggregate-projects}@anchor{18e}
19583 @subsection Syntax of aggregate projects
19586 An aggregate project follows the general syntax of project files. The
19587 recommended extension is still @code{.gpr}. However, a special
19588 @cite{aggregate} qualifier must be put before the keyword
19591 An aggregate project cannot @emph{with} any other project (standard or
19592 aggregate), except an abstract project which can be used to share attribute
19593 values. Also, aggregate projects cannot be extended or imported though a
19594 @emph{with} clause by any other project. Building other aggregate projects from
19595 an aggregate project is done through the Project_Files attribute (see below).
19597 An aggregate project does not have any source files directly (only
19598 through other standard projects). Therefore a number of the standard
19599 attributes and packages are forbidden in an aggregate project. Here is the
19600 (non exhaustive) list:
19609 Source_Files, Source_List_File and other attributes dealing with
19613 Source_Dirs, Exec_Dir and Object_Dir
19616 Library_Dir, Library_Name and other library-related attributes
19628 Inherit_Source_Path
19631 Excluded_Source_Dirs
19634 Locally_Removed_Files
19637 Excluded_Source_Files
19640 Excluded_Source_List_File
19646 The only package that is authorized (albeit optional) is
19647 Builder. Other packages (in particular Compiler, Binder and Linker)
19650 The following three attributes can be used only in an aggregate project:
19652 @geindex Project_Files (GNAT Project Manager)
19654 @strong{Project_Files}:
19658 This attribute is compulsory (or else we are not aggregating any project,
19659 and thus not doing anything). It specifies a list of @code{.gpr} files
19660 that are grouped in the aggregate. The list may be empty. The project
19661 files can be either other aggregate projects, or standard projects. When
19662 grouping standard projects, you can have both the root of a project tree
19663 (and you do not need to specify all its imported projects), and any project
19666 Basically, the idea is to specify all those projects that have
19667 main programs you want to build and link, or libraries you want to
19668 build. You can even specify projects that do not use the Main
19669 attribute nor the @cite{Library_*} attributes, and the result will be to
19670 build all their source files (not just the ones needed by other
19673 The file can include paths (absolute or relative). Paths are relative to
19674 the location of the aggregate project file itself (if you use a base name,
19675 we expect to find the .gpr file in the same directory as the aggregate
19676 project file). The environment variables @cite{ADA_PROJECT_PATH},
19677 @cite{GPR_PROJECT_PATH} and @cite{GPR_PROJECT_PATH_FILE} are not used to find
19678 the project files. The extension @code{.gpr} is mandatory, since this attribute
19679 contains file names, not project names.
19681 Paths can also include the @cite{"*"} and @cite{"**"} globbing patterns. The
19682 latter indicates that any subdirectory (recursively) will be
19683 searched for matching files. The latter (@cite{"**"}) can only occur at the
19684 last position in the directory part (ie @cite{"a/**/*.gpr"} is supported, but
19685 not @cite{"**/a/*.gpr"}). Starting the pattern with @cite{"**"} is equivalent
19686 to starting with @cite{"./**"}.
19688 For now, the pattern @cite{"*"} is only allowed in the filename part, not
19689 in the directory part. This is mostly for efficiency reasons to limit the
19690 number of system calls that are needed.
19692 Here are a few valid examples:
19695 for Project_Files use ("a.gpr", "subdir/b.gpr");
19696 -- two specific projects relative to the directory of agg.gpr
19698 for Project_Files use ("/.gpr");
19699 -- all projects recursively
19703 @geindex Project_Path (GNAT Project Manager)
19705 @strong{Project_Path}:
19709 This attribute can be used to specify a list of directories in
19710 which to look for project files in @emph{with} declarations.
19712 When you specify a project in Project_Files (say @cite{x/y/a.gpr}), and
19713 @cite{a.gpr} imports a project @cite{b.gpr}, only @cite{b.gpr} is searched in
19714 the project path. @cite{a.gpr} must be exactly at
19715 @cite{<dir of the aggregate>/x/y/a.gpr}.
19717 This attribute, however, does not affect the search for the aggregated
19718 project files specified with @cite{Project_Files}.
19720 Each aggregate project has its own @cite{Project_Path} (that is if
19721 @cite{agg1.gpr} includes @cite{agg2.gpr}, they can potentially both have a
19722 different @cite{Project_Path}).
19724 This project path is defined as the concatenation, in that order, of:
19730 the current directory;
19733 followed by the command line -aP switches;
19736 then the directories from the GPR_PROJECT_PATH and ADA_PROJECT_PATH environment
19740 then the directories from the Project_Path attribute;
19743 and finally the predefined directories.
19746 In the example above, agg2.gpr's project path is not influenced by
19747 the attribute agg1'Project_Path, nor is agg1 influenced by
19750 This can potentially lead to errors. Consider the following example:
19754 -- +---------------+ +----------------+
19755 -- | Agg1.gpr |-=--includes--=-->| Agg2.gpr |
19756 -- | 'project_path| | 'project_path |
19758 -- +---------------+ +----------------+
19760 -- includes includes
19763 -- +-------+ +---------+
19764 -- | P.gpr |<---------- withs --------| Q.gpr |
19765 -- +-------+---------\ +---------+
19770 -- +-------+ +---------+
19771 -- | R.gpr | | R'.gpr |
19772 -- +-------+ +---------+
19775 When looking for p.gpr, both aggregates find the same physical file on
19776 the disk. However, it might happen that with their different project
19777 paths, both aggregate projects would in fact find a different r.gpr.
19778 Since we have a common project (p.gpr) "with"ing two different r.gpr,
19779 this will be reported as an error by the builder.
19781 Directories are relative to the location of the aggregate project file.
19786 for Project_Path use ("/usr/local/gpr", "gpr/");
19790 @geindex External (GNAT Project Manager)
19796 This attribute can be used to set the value of environment
19797 variables as retrieved through the @cite{external} function
19798 in projects. It does not affect the environment variables
19799 themselves (so for instance you cannot use it to change the value
19800 of your PATH as seen from the spawned compiler).
19802 This attribute affects the external values as seen in the rest of
19803 the aggregate project, and in the aggregated projects.
19805 The exact value of external a variable comes from one of three
19806 sources (each level overrides the previous levels):
19812 An External attribute in aggregate project, for instance
19813 @cite{for External ("BUILD_MODE") use "DEBUG"};
19816 Environment variables.
19817 These override the value given by the attribute, so that
19818 users can override the value set in the (presumably shared
19819 with others team members) aggregate project.
19822 The -X command line switch to @emph{gprbuild}.
19823 This always takes precedence.
19826 This attribute is only taken into account in the main aggregate
19827 project (i.e. the one specified on the command line to @emph{gprbuild}),
19828 and ignored in other aggregate projects. It is invalid
19829 in standard projects.
19830 The goal is to have a consistent value in all
19831 projects that are built through the aggregate, which would not
19832 be the case in the diamond case: A groups the aggregate
19833 projects B and C, which both (either directly or indirectly)
19834 build the project P. If B and C could set different values for
19835 the environment variables, we would have two different views of
19836 P, which in particular might impact the list of source files in P.
19839 @node package Builder in aggregate projects,,Syntax of aggregate projects,Aggregate Projects
19840 @anchor{gnat_ugn/gnat_project_manager package-builder-in-aggregate-projects}@anchor{18f}@anchor{gnat_ugn/gnat_project_manager id33}@anchor{190}
19841 @subsection package Builder in aggregate projects
19844 As mentioned above, only the package Builder can be specified in
19845 an aggregate project. In this package, only the following attributes
19848 @geindex Switches (GNAT Project Manager)
19854 This attribute gives the list of switches to use for @emph{gprbuild}.
19855 Because no mains can be specified for aggregate projects, the only possible
19856 index for attribute @cite{Switches} is @cite{others}. All other indexes will
19862 for Switches (others) use ("-v", "-k", "-j8");
19865 These switches are only read from the main aggregate project (the
19866 one passed on the command line), and ignored in all other aggregate
19867 projects or projects.
19869 It can only contain builder switches, not compiler switches.
19872 @geindex Global_Compilation_Switches (GNAT Project Manager)
19874 @strong{Global_Compilation_Switches}
19878 This attribute gives the list of compiler switches for the various
19879 languages. For instance,
19882 for Global_Compilation_Switches ("Ada") use ("O1", "-g");
19883 for Global_Compilation_Switches ("C") use ("-O2");
19886 This attribute is only taken into account in the aggregate project
19887 specified on the command line, not in other aggregate projects.
19889 In the projects grouped by that aggregate, the attribute
19890 Builder.Global_Compilation_Switches is also ignored. However, the
19891 attribute Compiler.Default_Switches will be taken into account (but
19892 that of the aggregate have higher priority). The attribute
19893 Compiler.Switches is also taken into account and can be used to
19894 override the switches for a specific file. As a result, it always
19897 The rules are meant to avoid ambiguities when compiling. For
19898 instance, aggregate project Agg groups the projects A and B, that
19899 both depend on C. Here is an extra for all of these projects:
19902 aggregate project Agg is
19903 for Project_Files use ("a.gpr", "b.gpr");
19905 for Global_Compilation_Switches ("Ada") use ("-O2");
19912 for Global_Compilation_Switches ("Ada") use ("-O1");
19916 package Compiler is
19917 for Default_Switches ("Ada")
19919 for Switches ("a_file1.adb")
19926 package Compiler is
19927 for Default_Switches ("Ada") use ("-O0");
19932 package Compiler is
19933 for Default_Switches ("Ada")
19936 for Switches ("c_file1.adb")
19942 then the following switches are used:
19948 all files from project A except a_file1.adb are compiled
19949 with "-O2 -g", since the aggregate project has priority.
19952 the file a_file1.adb is compiled with
19953 "-O0", since the Compiler.Switches has priority
19956 all files from project B are compiled with
19957 "-O2", since the aggregate project has priority
19960 all files from C are compiled with "-O2 -gnatn", except for
19961 c_file1.adb which is compiled with "-O0 -g"
19964 Even though C is seen through two paths (through A and through
19965 B), the switches used by the compiler are unambiguous.
19968 @geindex Global_Configuration_Pragmas (GNAT Project Manager)
19970 @strong{Global_Configuration_Pragmas}
19974 This attribute can be used to specify a file containing
19975 configuration pragmas, to be passed to the Ada compiler. Since we
19976 ignore the package Builder in other aggregate projects and projects,
19977 only those pragmas defined in the main aggregate project will be
19978 taken into account.
19980 Projects can locally add to those by using the
19981 @cite{Compiler.Local_Configuration_Pragmas} attribute if they need.
19984 @geindex Global_Config_File (GNAT Project Manager)
19986 @strong{Global_Config_File}
19990 This attribute, indexed with a language name, can be used to specify a config
19991 when compiling sources of the language. For Ada, these files are configuration
19995 For projects that are built through the aggregate, the package Builder
19996 is ignored, except for the Executable attribute which specifies the
19997 name of the executables resulting from the link of the main programs, and
19998 for the Executable_Suffix.
20000 @node Aggregate Library Projects,Project File Reference,Aggregate Projects,GNAT Project Manager
20001 @anchor{gnat_ugn/gnat_project_manager id34}@anchor{191}@anchor{gnat_ugn/gnat_project_manager aggregate-library-projects}@anchor{192}
20002 @section Aggregate Library Projects
20005 Aggregate library projects make it possible to build a single library
20006 using object files built using other standard or library
20007 projects. This gives the flexibility to describe an application as
20008 having multiple modules (a GUI, database access, ...) using different
20009 project files (so possibly built with different compiler options) and
20010 yet create a single library (static or relocatable) out of the
20011 corresponding object files.
20014 * Building aggregate library projects::
20015 * Syntax of aggregate library projects::
20019 @node Building aggregate library projects,Syntax of aggregate library projects,,Aggregate Library Projects
20020 @anchor{gnat_ugn/gnat_project_manager building-aggregate-library-projects}@anchor{193}@anchor{gnat_ugn/gnat_project_manager id35}@anchor{194}
20021 @subsection Building aggregate library projects
20024 For example, we can define an aggregate project Agg that groups A, B
20028 aggregate library project Agg is
20029 for Project_Files use ("a.gpr", "b.gpr", "c.gpr");
20030 for Library_Name use ("agg");
20031 for Library_Dir use ("lagg");
20035 Then, when you build with:
20041 This will build all units from projects A, B and C and will create a
20042 static library named @code{libagg.a} in the @code{lagg}
20043 directory. An aggregate library project has the same set of
20044 restriction as a standard library project.
20046 Note that a shared aggregate library project cannot aggregate a
20047 static library project. In platforms where a compiler option is
20048 required to create relocatable object files, a Builder package in the
20049 aggregate library project may be used:
20052 aggregate library project Agg is
20053 for Project_Files use ("a.gpr", "b.gpr", "c.gpr");
20054 for Library_Name use ("agg");
20055 for Library_Dir use ("lagg");
20056 for Library_Kind use "relocatable";
20059 for Global_Compilation_Switches ("Ada") use ("-fPIC");
20064 With the above aggregate library Builder package, the @cite{-fPIC}
20065 option will be passed to the compiler when building any source code
20066 from projects @code{a.gpr}, @code{b.gpr} and @code{c.gpr}.
20068 @node Syntax of aggregate library projects,,Building aggregate library projects,Aggregate Library Projects
20069 @anchor{gnat_ugn/gnat_project_manager syntax-of-aggregate-library-projects}@anchor{195}@anchor{gnat_ugn/gnat_project_manager id36}@anchor{196}
20070 @subsection Syntax of aggregate library projects
20073 An aggregate library project follows the general syntax of project
20074 files. The recommended extension is still @code{.gpr}. However, a special
20075 @cite{aggregate library} qualifier must be put before the keyword
20078 An aggregate library project cannot @emph{with} any other project
20079 (standard or aggregate), except an abstract project which can be used
20080 to share attribute values.
20082 An aggregate library project does not have any source files directly (only
20083 through other standard projects). Therefore a number of the standard
20084 attributes and packages are forbidden in an aggregate library
20085 project. Here is the (non exhaustive) list:
20094 Source_Files, Source_List_File and other attributes dealing with
20098 Source_Dirs, Exec_Dir and Object_Dir
20110 Inherit_Source_Path
20113 Excluded_Source_Dirs
20116 Locally_Removed_Files
20119 Excluded_Source_Files
20122 Excluded_Source_List_File
20128 The only package that is authorized (albeit optional) is Builder.
20130 The Project_Files attribute (See @ref{171,,Aggregate Projects}) is used to
20131 described the aggregated projects whose object files have to be
20132 included into the aggregate library. The environment variables
20133 @cite{ADA_PROJECT_PATH}, @cite{GPR_PROJECT_PATH} and
20134 @cite{GPR_PROJECT_PATH_FILE} are not used to find the project files.
20136 @node Project File Reference,,Aggregate Library Projects,GNAT Project Manager
20137 @anchor{gnat_ugn/gnat_project_manager id37}@anchor{197}@anchor{gnat_ugn/gnat_project_manager project-file-reference}@anchor{150}
20138 @section Project File Reference
20141 This section describes the syntactic structure of project files, the various
20142 constructs that can be used. Finally, it ends with a summary of all available
20146 * Project Declaration::
20147 * Qualified Projects::
20151 * External Values::
20152 * Typed String Declaration::
20154 * Case Constructions::
20159 @node Project Declaration,Qualified Projects,,Project File Reference
20160 @anchor{gnat_ugn/gnat_project_manager id38}@anchor{198}@anchor{gnat_ugn/gnat_project_manager project-declaration}@anchor{199}
20161 @subsection Project Declaration
20164 Project files have an Ada-like syntax. The minimal project file is:
20171 The identifier @cite{Empty} is the name of the project.
20172 This project name must be present after the reserved
20173 word @cite{end} at the end of the project file, followed by a semi-colon.
20175 @strong{Identifiers} (i.e., the user-defined names such as project or variable names)
20176 have the same syntax as Ada identifiers: they must start with a letter,
20177 and be followed by zero or more letters, digits or underscore characters;
20178 it is also illegal to have two underscores next to each other. Identifiers
20179 are always case-insensitive ("Name" is the same as "name").
20182 simple_name ::= identifier
20183 name ::= simple_name @{ . simple_name @}
20186 @strong{Strings} are used for values of attributes or as indexes for these
20187 attributes. They are in general case sensitive, except when noted
20188 otherwise (in particular, strings representing file names will be case
20189 insensitive on some systems, so that "file.adb" and "File.adb" both
20190 represent the same file).
20192 @strong{Reserved words} are the same as for standard Ada 95, and cannot
20193 be used for identifiers. In particular, the following words are currently
20194 used in project files, but others could be added later on. In bold are the
20195 extra reserved words in project files:
20196 @code{all}, @code{at}, @code{case}, @code{end}, @code{for}, @code{is}, @code{limited},
20197 @code{null}, @code{others}, @code{package}, @code{renames}, @code{type}, @code{use}, @code{when},
20198 @code{with}, @strong{extends}, @strong{external}, @strong{project}.
20200 @strong{Comments} in project files have the same syntax as in Ada, two consecutive
20201 hyphens through the end of the line.
20203 A project may be an @strong{independent project}, entirely defined by a single
20204 project file. Any source file in an independent project depends only
20205 on the predefined library and other source files in the same project.
20206 But a project may also depend on other projects, either by importing them
20207 through @strong{with clauses}, or by @strong{extending} at most one other project. Both
20208 types of dependency can be used in the same project.
20210 A path name denotes a project file. It can be absolute or relative.
20211 An absolute path name includes a sequence of directories, in the syntax of
20212 the host operating system, that identifies uniquely the project file in the
20213 file system. A relative path name identifies the project file, relative
20214 to the directory that contains the current project, or relative to a
20215 directory listed in the environment variables ADA_PROJECT_PATH and
20216 GPR_PROJECT_PATH. Path names are case sensitive if file names in the host
20217 operating system are case sensitive. As a special case, the directory
20218 separator can always be "/" even on Windows systems, so that project files
20219 can be made portable across architectures.
20220 The syntax of the environment variables ADA_PROJECT_PATH and
20221 GPR_PROJECT_PATH is a list of directory names separated by colons on UNIX and
20222 semicolons on Windows.
20224 A given project name can appear only once in a context clause.
20226 It is illegal for a project imported by a context clause to refer, directly
20227 or indirectly, to the project in which this context clause appears (the
20228 dependency graph cannot contain cycles), except when one of the with clauses
20229 in the cycle is a @strong{limited with}.
20232 with "other_project.gpr";
20233 project My_Project extends "extended.gpr" is
20237 These dependencies form a @strong{directed graph}, potentially cyclic when using
20238 @strong{limited with}. The subgraph reflecting the @strong{extends} relations is a tree.
20240 A project's @strong{immediate sources} are the source files directly defined by
20241 that project, either implicitly by residing in the project source directories,
20242 or explicitly through any of the source-related attributes.
20243 More generally, a project's @strong{sources} are the immediate sources of the
20244 project together with the immediate sources (unless overridden) of any project
20245 on which it depends directly or indirectly.
20247 A @strong{project hierarchy} can be created, where projects are children of
20248 other projects. The name of such a child project must be @cite{Parent.Child},
20249 where @cite{Parent} is the name of the parent project. In particular, this
20250 makes all @emph{with} clauses of the parent project automatically visible
20251 in the child project.
20254 project ::= context_clause project_declaration
20256 context_clause ::= @{with_clause@}
20257 with_clause ::= *with* path_name @{ , path_name @} ;
20258 path_name ::= string_literal
20260 project_declaration ::= simple_project_declaration | project_extension
20261 simple_project_declaration ::=
20262 project <project_>name is
20263 @{declarative_item@}
20264 end <project_>simple_name;
20267 @node Qualified Projects,Declarations,Project Declaration,Project File Reference
20268 @anchor{gnat_ugn/gnat_project_manager qualified-projects}@anchor{176}@anchor{gnat_ugn/gnat_project_manager id39}@anchor{19a}
20269 @subsection Qualified Projects
20272 Before the reserved @cite{project}, there may be one or two @strong{qualifiers}, that
20273 is identifiers or reserved words, to qualify the project.
20274 The current list of qualifiers is:
20279 @item @strong{abstract}:
20281 Qualifies a project with no sources.
20282 Such a project must either have no declaration of attributes @cite{Source_Dirs},
20283 @cite{Source_Files}, @cite{Languages} or @cite{Source_List_File}, or one of
20284 @cite{Source_Dirs}, @cite{Source_Files}, or @cite{Languages} must be declared
20285 as empty. If it extends another project, the project it extends must also be a
20286 qualified abstract project.
20288 @item @strong{standard}:
20290 A standard project is a non library project with sources.
20291 This is the default (implicit) qualifier.
20293 @item @strong{aggregate}:
20295 A project whose sources are aggregated from other project files.
20297 @item @strong{aggregate library}:
20299 A library whose sources are aggregated from other project
20300 or library project files.
20302 @item @strong{library}:
20304 A library project must declare both attributes
20305 Library_Name` and @cite{Library_Dir}.
20307 @item @strong{configuration}:
20309 A configuration project cannot be in a project tree.
20310 It describes compilers and other tools to @emph{gprbuild}.
20313 @node Declarations,Packages,Qualified Projects,Project File Reference
20314 @anchor{gnat_ugn/gnat_project_manager declarations}@anchor{19b}@anchor{gnat_ugn/gnat_project_manager id40}@anchor{19c}
20315 @subsection Declarations
20318 Declarations introduce new entities that denote types, variables, attributes,
20319 and packages. Some declarations can only appear immediately within a project
20320 declaration. Others can appear within a project or within a package.
20323 declarative_item ::= simple_declarative_item
20324 | typed_string_declaration
20325 | package_declaration
20327 simple_declarative_item ::= variable_declaration
20328 | typed_variable_declaration
20329 | attribute_declaration
20330 | case_construction
20331 | empty_declaration
20333 empty_declaration ::= *null* ;
20336 An empty declaration is allowed anywhere a declaration is allowed. It has
20339 @node Packages,Expressions,Declarations,Project File Reference
20340 @anchor{gnat_ugn/gnat_project_manager packages}@anchor{156}@anchor{gnat_ugn/gnat_project_manager id41}@anchor{19d}
20341 @subsection Packages
20344 A project file may contain @strong{packages}, that group attributes (typically
20345 all the attributes that are used by one of the GNAT tools).
20347 A package with a given name may only appear once in a project file.
20348 The following packages are currently supported in project files
20349 (See @ref{155,,Attributes} for the list of attributes that each can contain).
20354 @item @emph{Binder}
20356 This package specifies characteristics useful when invoking the binder either
20357 directly via the @emph{gnat} driver or when using @emph{gprbuild}.
20358 See @ref{160,,Main Subprograms}.
20360 @item @emph{Builder}
20362 This package specifies the compilation options used when building an
20363 executable or a library for a project. Most of the options should be
20364 set in one of @cite{Compiler}, @cite{Binder} or @cite{Linker} packages,
20365 but there are some general options that should be defined in this
20366 package. See @ref{160,,Main Subprograms}, and @ref{165,,Executable File Names} in
20376 This package specifies the options used when cleaning a project or a project
20377 tree using the tools @emph{gnatclean} or @emph{gprclean}.
20379 @item @emph{Compiler}
20381 This package specifies the compilation options used by the compiler for
20382 each languages. See @ref{161,,Tools Options in Project Files}.
20384 @item @emph{Cross_Reference}
20386 This package specifies the options used when calling the library tool
20387 @emph{gnatxref} via the @emph{gnat} driver. Its attributes
20388 @strong{Default_Switches} and @strong{Switches} have the same semantics as for the
20389 package @cite{Builder}.
20396 @item @emph{Finder}
20398 This package specifies the options used when calling the search tool
20399 @emph{gnatfind} via the @emph{gnat} driver. Its attributes
20400 @strong{Default_Switches} and @strong{Switches} have the same semantics as for the
20401 package @cite{Builder}.
20403 @item @emph{Gnatls}
20405 This package specifies the options to use when invoking @emph{gnatls}
20406 via the @emph{gnat} driver.
20415 This package specifies the options used when starting an integrated
20416 development environment, for instance @emph{GPS} or @emph{Gnatbench}.
20418 @item @emph{Install}
20420 This package specifies the options used when installing a project
20421 with @emph{gprinstall}. See @ref{16b,,Installation}.
20423 @item @emph{Linker}
20425 This package specifies the options used by the linker.
20426 See @ref{160,,Main Subprograms}.
20433 @item @emph{Naming}
20437 This package specifies the naming conventions that apply
20438 to the source files in a project. In particular, these conventions are
20439 used to automatically find all source files in the source directories,
20440 or given a file name to find out its language for proper processing.
20441 See @ref{14e,,Naming Schemes}.
20445 @item @emph{Remote}
20447 This package is used by @emph{gprbuild} to describe how distributed
20448 compilation should be done.
20452 This package specifies the options used when calling the tool
20453 @emph{gnatstack} via the @emph{gnat} driver. Its attributes
20454 @strong{Default_Switches} and @strong{Switches} have the same semantics as for the
20455 package @cite{Builder}.
20457 @item @emph{Synchronize}
20459 This package specifies the options used when calling the tool
20460 @emph{gnatsync} via the @emph{gnat} driver.
20463 In its simplest form, a package may be empty:
20472 A package may contain @strong{attribute declarations},
20473 @strong{variable declarations} and @strong{case constructions}, as will be
20476 When there is ambiguity between a project name and a package name,
20477 the name always designates the project. To avoid possible confusion, it is
20478 always a good idea to avoid naming a project with one of the
20479 names allowed for packages or any name that starts with @cite{gnat}.
20481 A package can also be defined by a @strong{renaming declaration}. The new package
20482 renames a package declared in a different project file, and has the same
20483 attributes as the package it renames. The name of the renamed package
20484 must be the same as the name of the renaming package. The project must
20485 contain a package declaration with this name, and the project
20486 must appear in the context clause of the current project, or be its parent
20487 project. It is not possible to add or override attributes to the renaming
20488 project. If you need to do so, you should use an @strong{extending declaration}
20491 Packages that are renamed in other project files often come from project files
20492 that have no sources: they are just used as templates. Any modification in the
20493 template will be reflected automatically in all the project files that rename
20494 a package from the template. This is a very common way to share settings
20497 Finally, a package can also be defined by an @strong{extending declaration}. This is
20498 similar to a @strong{renaming declaration}, except that it is possible to add or
20499 override attributes.
20502 package_declaration ::= package_spec | package_renaming | package_extension
20504 package <package_>simple_name is
20505 @{simple_declarative_item@}
20506 end package_identifier ;
20507 package_renaming ::==
20508 package <package_>simple_name renames <project_>simple_name.package_identifier ;
20509 package_extension ::==
20510 package <package_>simple_name extends <project_>simple_name.package_identifier is
20511 @{simple_declarative_item@}
20512 end package_identifier ;
20515 @node Expressions,External Values,Packages,Project File Reference
20516 @anchor{gnat_ugn/gnat_project_manager expressions}@anchor{19e}@anchor{gnat_ugn/gnat_project_manager id42}@anchor{19f}
20517 @subsection Expressions
20520 An expression is any value that can be assigned to an attribute or a
20521 variable. It is either a literal value, or a construct requiring runtime
20522 computation by the project manager. In a project file, the computed value of
20523 an expression is either a string or a list of strings.
20525 A string value is one of:
20531 A literal string, for instance @cite{"comm/my_proj.gpr"}
20534 The name of a variable that evaluates to a string (see @ref{158,,Variables})
20537 The name of an attribute that evaluates to a string (see @ref{155,,Attributes})
20540 An external reference (see @ref{157,,External Values})
20543 A concatenation of the above, as in @cite{"prefix_" & Var}.
20546 A list of strings is one of the following:
20552 A parenthesized comma-separated list of zero or more string expressions, for
20553 instance @cite{(File_Name@comma{} "gnat.adc"@comma{} File_Name & ".orig")} or @cite{()}.
20556 The name of a variable that evaluates to a list of strings
20559 The name of an attribute that evaluates to a list of strings
20562 A concatenation of a list of strings and a string (as defined above), for
20563 instance @cite{("A"@comma{} "B") & "C"}
20566 A concatenation of two lists of strings
20569 The following is the grammar for expressions
20572 string_literal ::= "@{string_element@}" -- Same as Ada
20573 string_expression ::= string_literal
20576 | attribute_reference
20577 | ( string_expression @{ & string_expression @} )
20578 string_list ::= ( string_expression @{ , string_expression @} )
20579 | *string_variable*_name
20580 | *string_*attribute_reference
20581 term ::= string_expression | string_list
20582 expression ::= term @{ & term @} -- Concatenation
20585 Concatenation involves strings and list of strings. As soon as a list of
20586 strings is involved, the result of the concatenation is a list of strings. The
20587 following Ada declarations show the existing operators:
20590 function "&" (X : String; Y : String) return String;
20591 function "&" (X : String_List; Y : String) return String_List;
20592 function "&" (X : String_List; Y : String_List) return String_List;
20595 Here are some specific examples:
20598 List := () & File_Name; -- One string in this list
20599 List2 := List & (File_Name & ".orig"); -- Two strings
20600 Big_List := List & Lists2; -- Three strings
20601 Illegal := "gnat.adc" & List2; -- Illegal, must start with list
20604 @node External Values,Typed String Declaration,Expressions,Project File Reference
20605 @anchor{gnat_ugn/gnat_project_manager external-values}@anchor{157}@anchor{gnat_ugn/gnat_project_manager id43}@anchor{1a0}
20606 @subsection External Values
20609 An external value is an expression whose value is obtained from the command
20610 that invoked the processing of the current project file (typically a
20611 @emph{gprbuild} command).
20613 There are two kinds of external values, one that returns a single string, and
20614 one that returns a string list.
20616 The syntax of a single string external value is:
20619 external_value ::= *external* ( string_literal [, string_literal] )
20622 The first string_literal is the string to be used on the command line or
20623 in the environment to specify the external value. The second string_literal,
20624 if present, is the default to use if there is no specification for this
20625 external value either on the command line or in the environment.
20627 Typically, the external value will either exist in the
20628 environment variables
20629 or be specified on the command line through the
20630 @code{-X@emph{vbl}=@emph{value}} switch. If both
20631 are specified, then the command line value is used, so that a user can more
20632 easily override the value.
20634 The function @cite{external} always returns a string. It is an error if the
20635 value was not found in the environment and no default was specified in the
20636 call to @cite{external}.
20638 An external reference may be part of a string expression or of a string
20639 list expression, and can therefore appear in a variable declaration or
20640 an attribute declaration.
20642 Most of the time, this construct is used to initialize typed variables, which
20643 are then used in @strong{case} constructions to control the value assigned to
20644 attributes in various scenarios. Thus such variables are often called
20645 @strong{scenario variables}.
20647 The syntax for a string list external value is:
20650 external_value ::= *external_as_list* ( string_literal , string_literal )
20653 The first string_literal is the string to be used on the command line or
20654 in the environment to specify the external value. The second string_literal is
20655 the separator between each component of the string list.
20657 If the external value does not exist in the environment or on the command line,
20658 the result is an empty list. This is also the case, if the separator is an
20659 empty string or if the external value is only one separator.
20661 Any separator at the beginning or at the end of the external value is
20662 discarded. Then, if there is no separator in the external value, the result is
20663 a string list with only one string. Otherwise, any string between the beginning
20664 and the first separator, between two consecutive separators and between the
20665 last separator and the end are components of the string list.
20668 *external_as_list* ("SWITCHES", ",")
20671 If the external value is "-O2,-g",
20672 the result is ("-O2", "-g").
20674 If the external value is ",-O2,-g,",
20675 the result is also ("-O2", "-g").
20677 if the external value is "-gnatv",
20678 the result is ("-gnatv").
20680 If the external value is ",,", the result is ("").
20682 If the external value is ",", the result is (), the empty string list.
20684 @node Typed String Declaration,Variables,External Values,Project File Reference
20685 @anchor{gnat_ugn/gnat_project_manager id44}@anchor{1a1}@anchor{gnat_ugn/gnat_project_manager typed-string-declaration}@anchor{1a2}
20686 @subsection Typed String Declaration
20689 A @strong{type declaration} introduces a discrete set of string literals.
20690 If a string variable is declared to have this type, its value
20691 is restricted to the given set of literals. These are the only named
20692 types in project files. A string type may only be declared at the project
20693 level, not inside a package.
20696 typed_string_declaration ::=
20697 *type* *<typed_string_>*_simple_name *is* ( string_literal @{, string_literal@} );
20700 The string literals in the list are case sensitive and must all be different.
20701 They may include any graphic characters allowed in Ada, including spaces.
20702 Here is an example of a string type declaration:
20705 type OS is ("NT", "nt", "Unix", "GNU/Linux", "other OS");
20708 Variables of a string type are called @strong{typed variables}; all other
20709 variables are called @strong{untyped variables}. Typed variables are
20710 particularly useful in @cite{case} constructions, to support conditional
20711 attribute declarations. (See @ref{1a3,,Case Constructions}).
20713 A string type may be referenced by its name if it has been declared in the same
20714 project file, or by an expanded name whose prefix is the name of the project
20715 in which it is declared.
20717 @node Variables,Case Constructions,Typed String Declaration,Project File Reference
20718 @anchor{gnat_ugn/gnat_project_manager variables}@anchor{158}@anchor{gnat_ugn/gnat_project_manager id45}@anchor{1a4}
20719 @subsection Variables
20722 @strong{Variables} store values (strings or list of strings) and can appear
20723 as part of an expression. The declaration of a variable creates the
20724 variable and assigns the value of the expression to it. The name of the
20725 variable is available immediately after the assignment symbol, if you
20726 need to reuse its old value to compute the new value. Before the completion
20727 of its first declaration, the value of a variable defaults to the empty
20730 A @strong{typed} variable can be used as part of a @strong{case} expression to
20731 compute the value, but it can only be declared once in the project file,
20732 so that all case constructions see the same value for the variable. This
20733 provides more consistency and makes the project easier to understand.
20734 The syntax for its declaration is identical to the Ada syntax for an
20735 object declaration. In effect, a typed variable acts as a constant.
20737 An @strong{untyped} variable can be declared and overridden multiple times
20738 within the same project. It is declared implicitly through an Ada
20739 assignment. The first declaration establishes the kind of the variable
20740 (string or list of strings) and successive declarations must respect
20741 the initial kind. Assignments are executed in the order in which they
20742 appear, so the new value replaces the old one and any subsequent reference
20743 to the variable uses the new value.
20745 A variable may be declared at the project file level, or within a package.
20748 typed_variable_declaration ::=
20749 *<typed_variable_>*simple_name : *<typed_string_>*name := string_expression;
20751 variable_declaration ::= *<variable_>*simple_name := expression;
20754 Here are some examples of variable declarations:
20757 This_OS : OS := external ("OS"); -- a typed variable declaration
20758 That_OS := "GNU/Linux"; -- an untyped variable declaration
20760 Name := "readme.txt";
20761 Save_Name := Name & ".saved";
20764 List_With_One_Element := ("-gnaty");
20765 List_With_Two_Elements := List_With_One_Element & "-gnatg";
20766 Long_List := ("main.ada", "pack1_.ada", "pack1.ada", "pack2_.ada");
20769 A @strong{variable reference} may take several forms:
20775 The simple variable name, for a variable in the current package (if any)
20776 or in the current project
20779 An expanded name, whose prefix is a context name.
20782 A @strong{context} may be one of the following:
20788 The name of an existing package in the current project
20791 The name of an imported project of the current project
20794 The name of an ancestor project (i.e., a project extended by the current
20795 project, either directly or indirectly)
20798 An expanded name whose prefix is an imported/parent project name, and
20799 whose selector is a package name in that project.
20802 @node Case Constructions,Attributes,Variables,Project File Reference
20803 @anchor{gnat_ugn/gnat_project_manager id46}@anchor{1a5}@anchor{gnat_ugn/gnat_project_manager case-constructions}@anchor{1a3}
20804 @subsection Case Constructions
20807 A @strong{case} construction is used in a project file to effect conditional
20808 behavior. Through this construction, you can set the value of attributes
20809 and variables depending on the value previously assigned to a typed
20812 All choices in a choice list must be distinct. Unlike Ada, the choice
20813 lists of all alternatives do not need to include all values of the type.
20814 An @cite{others} choice must appear last in the list of alternatives.
20816 The syntax of a @cite{case} construction is based on the Ada case construction
20817 (although the @cite{null} declaration for empty alternatives is optional).
20819 The case expression must be a string variable, either typed or not, whose value
20820 is often given by an external reference (see @ref{157,,External Values}).
20822 Each alternative starts with the reserved word @cite{when}, either a list of
20823 literal strings separated by the @cite{"|"} character or the reserved word
20824 @cite{others}, and the @cite{"=>"} token.
20825 When the case expression is a typed string variable, each literal string must
20826 belong to the string type that is the type of the case variable.
20827 After each @cite{=>}, there are zero or more declarations. The only
20828 declarations allowed in a case construction are other case constructions,
20829 attribute declarations and variable declarations. String type declarations and
20830 package declarations are not allowed. Variable declarations are restricted to
20831 variables that have already been declared before the case construction.
20834 case_construction ::=
20835 *case* *<variable_>*name *is* @{case_item@} *end case* ;
20838 *when* discrete_choice_list =>
20840 | attribute_declaration
20841 | variable_declaration
20842 | empty_declaration@}
20844 discrete_choice_list ::= string_literal @{| string_literal@} | *others*
20847 Here is a typical example, with a typed string variable:
20851 type OS_Type is ("GNU/Linux", "Unix", "NT", "VMS");
20852 OS : OS_Type := external ("OS", "GNU/Linux");
20854 package Compiler is
20856 when "GNU/Linux" | "Unix" =>
20857 for Switches ("Ada")
20860 for Switches ("Ada")
20869 @node Attributes,,Case Constructions,Project File Reference
20870 @anchor{gnat_ugn/gnat_project_manager id47}@anchor{1a6}@anchor{gnat_ugn/gnat_project_manager attributes}@anchor{155}
20871 @subsection Attributes
20874 A project (and its packages) may have @strong{attributes} that define
20875 the project's properties. Some attributes have values that are strings;
20876 others have values that are string lists.
20879 attribute_declaration ::=
20880 simple_attribute_declaration | indexed_attribute_declaration
20882 simple_attribute_declaration ::= *for* attribute_designator *use* expression ;
20884 indexed_attribute_declaration ::=
20885 *for* *<indexed_attribute_>*simple_name ( string_literal) *use* expression ;
20887 attribute_designator ::=
20888 *<simple_attribute_>*simple_name
20889 | *<indexed_attribute_>*simple_name ( string_literal )
20892 There are two categories of attributes: @strong{simple attributes}
20893 and @strong{indexed attributes}.
20894 Each simple attribute has a default value: the empty string (for string
20895 attributes) and the empty list (for string list attributes).
20896 An attribute declaration defines a new value for an attribute, and overrides
20897 the previous value. The syntax of a simple attribute declaration is similar to
20898 that of an attribute definition clause in Ada.
20900 Some attributes are indexed. These attributes are mappings whose
20901 domain is a set of strings. They are declared one association
20902 at a time, by specifying a point in the domain and the corresponding image
20904 Like untyped variables and simple attributes, indexed attributes
20905 may be declared several times. Each declaration supplies a new value for the
20906 attribute, and replaces the previous setting.
20908 Here are some examples of attribute declarations:
20911 -- simple attributes
20912 for Object_Dir use "objects";
20913 for Source_Dirs use ("units", "test/drivers");
20915 -- indexed attributes
20916 for Body ("main") use "Main.ada";
20917 for Switches ("main.ada")
20918 use ("-v", "-gnatv");
20919 for Switches ("main.ada") use Builder'Switches ("main.ada") & "-g";
20921 -- indexed attributes copy (from package Builder in project Default)
20922 -- The package name must always be specified, even if it is the current
20924 for Default_Switches use Default.Builder'Default_Switches;
20927 Attributes references may appear anywhere in expressions, and are used
20928 to retrieve the value previously assigned to the attribute. If an attribute
20929 has not been set in a given package or project, its value defaults to the
20930 empty string or the empty list, with some exceptions.
20933 attribute_reference ::=
20934 attribute_prefix ' *<simple_attribute>_*simple_name [ (string_literal) ]
20935 attribute_prefix ::= *project*
20936 | *<project_>*simple_name
20937 | package_identifier
20938 | *<project_>*simple_name . package_identifier
20944 <project>'Object_Dir
20945 Naming'Dot_Replacement
20946 Imported_Project'Source_Dirs
20947 Imported_Project.Naming'Casing
20948 Builder'Default_Switches ("Ada")
20951 The exceptions to the empty defaults are:
20957 Object_Dir: default is "."
20960 Exec_Dir: default is 'Object_Dir, that is the value of attribute
20961 Object_Dir in the same project, declared or defaulted.
20964 Source_Dirs: default is (".")
20967 The prefix of an attribute may be:
20973 @cite{project} for an attribute of the current project
20976 The name of an existing package of the current project
20979 The name of an imported project
20982 The name of a parent project that is extended by the current project
20985 An expanded name whose prefix is imported/parent project name,
20986 and whose selector is a package name
20989 In the following sections, all predefined attributes are succinctly described,
20990 first the project level attributes, that is those attributes that are not in a
20991 package, then the attributes in the different packages.
20993 It is possible for different tools to dynamically create new packages with
20994 attributes, or new attributes in predefined packages. These attributes are
20995 not documented here.
20997 The attributes under Configuration headings are usually found only in
20998 configuration project files.
21000 The characteristics of each attribute are indicated as follows:
21006 @strong{Type of value}
21008 The value of an attribute may be a single string, indicated by the word
21009 "single", or a string list, indicated by the word "list".
21014 When the attribute is read-only, that is when it is not allowed to declare
21015 the attribute, this is indicated by the words "read-only".
21018 @strong{Optional index}
21020 If it is allowed in the value of the attribute (both single and list) to have
21021 an optional index, this is indicated by the words "optional index".
21024 @strong{Indexed attribute}
21026 When it is an indexed attribute, this is indicated by the word "indexed".
21029 @strong{Case-sensitivity of the index}
21031 For an indexed attribute, if the index is case-insensitive, this is indicated
21032 by the words "case-insensitive index".
21035 @strong{File name index}
21037 For an indexed attribute, when the index is a file name, this is indicated by
21038 the words "file name index". The index may or may not be case-sensitive,
21039 depending on the platform.
21042 @strong{others allowed in index}
21044 For an indexed attribute, if it is allowed to use @strong{others} as the index,
21045 this is indicated by the words "others allowed".
21047 When @strong{others} is used as the index of an indexed attribute, the value of
21048 the attribute indexed by @strong{others} is used when no other index would apply.
21052 * Project Level Attributes::
21053 * Package Binder Attributes::
21054 * Package Builder Attributes::
21055 * Package Clean Attributes::
21056 * Package Compiler Attributes::
21057 * Package Cross_Reference Attributes::
21058 * Package Finder Attributes::
21059 * Package gnatls Attributes::
21060 * Package IDE Attributes::
21061 * Package Install Attributes::
21062 * Package Linker Attributes::
21063 * Package Naming Attributes::
21064 * Package Remote Attributes::
21065 * Package Stack Attributes::
21066 * Package Synchronize Attributes::
21070 @node Project Level Attributes,Package Binder Attributes,,Attributes
21071 @anchor{gnat_ugn/gnat_project_manager project-level-attributes}@anchor{1a7}@anchor{gnat_ugn/gnat_project_manager id48}@anchor{1a8}
21072 @subsubsection Project Level Attributes
21085 @strong{Name}: single, read-only
21087 The name of the project.
21090 @strong{Project_Dir}: single, read-only
21092 The path name of the project directory.
21095 @strong{Main}: list, optional index
21097 The list of main sources for the executables.
21100 @strong{Languages}: list
21102 The list of languages of the sources of the project.
21105 @strong{Roots}: list, indexed, file name index
21107 The index is the file name of an executable source. Indicates the list of units
21108 from the main project that need to be bound and linked with their closures
21109 with the executable. The index is either a file name, a language name or "*".
21110 The roots for an executable source are those in @strong{Roots} with an index that
21111 is the executable source file name, if declared. Otherwise, they are those in
21112 @strong{Roots} with an index that is the language name of the executable source,
21113 if present. Otherwise, they are those in @strong{Roots ("*")}, if declared. If none
21114 of these three possibilities are declared, then there are no roots for the
21118 @strong{Externally_Built}: single
21120 Indicates if the project is externally built.
21121 Only case-insensitive values allowed are "true" and "false", the default.
21125 @strong{Directories}
21131 @strong{Object_Dir}: single
21133 Indicates the object directory for the project.
21136 @strong{Exec_Dir}: single
21138 Indicates the exec directory for the project, that is the directory where the
21142 @strong{Source_Dirs}: list
21144 The list of source directories of the project.
21147 @strong{Inherit_Source_Path}: list, indexed, case-insensitive index
21149 Index is a language name. Value is a list of language names. Indicates that
21150 in the source search path of the index language the source directories of
21151 the languages in the list should be included.
21156 for Inherit_Source_Path ("C++") use ("C");
21160 @strong{Exclude_Source_Dirs}: list
21162 The list of directories that are included in Source_Dirs but are not source
21163 directories of the project.
21166 @strong{Ignore_Source_Sub_Dirs}: list
21168 Value is a list of simple names for subdirectories that are removed from the
21169 list of source directories, including theur subdirectories.
21173 @strong{Source Files}
21179 @strong{Source_Files}: list
21181 Value is a list of source file simple names.
21184 @strong{Locally_Removed_Files}: list
21186 Obsolescent. Equivalent to Excluded_Source_Files.
21189 @strong{Excluded_Source_Files}: list
21191 Value is a list of simple file names that are not sources of the project.
21192 Allows to remove sources that are inherited or found in the source directories
21193 and that match the naming scheme.
21196 @strong{Source_List_File}: single
21198 Value is a text file name that contains a list of source file simple names,
21202 @strong{Excluded_Source_List_File}: single
21204 Value is a text file name that contains a list of file simple names that
21205 are not sources of the project.
21208 @strong{Interfaces}: list
21210 Value is a list of file names that constitutes the interfaces of the project.
21214 @strong{Aggregate Projects}
21220 @strong{Project_Files}: list
21222 Value is the list of aggregated projects.
21225 @strong{Project_Path}: list
21227 Value is a list of directories that are added to the project search path when
21228 looking for the aggregated projects.
21231 @strong{External}: single, indexed
21233 Index is the name of an external reference. Value is the value of the
21234 external reference to be used when parsing the aggregated projects.
21244 @strong{Library_Dir}: single
21246 Value is the name of the library directory. This attribute needs to be
21247 declared for each library project.
21250 @strong{Library_Name}: single
21252 Value is the name of the library. This attribute needs to be declared or
21253 inherited for each library project.
21256 @strong{Library_Kind}: single
21258 Specifies the kind of library: static library (archive) or shared library.
21259 Case-insensitive values must be one of "static" for archives (the default) or
21260 "dynamic" or "relocatable" for shared libraries.
21263 @strong{Library_Version}: single
21265 Value is the name of the library file.
21268 @strong{Library_Interface}: list
21270 Value is the list of unit names that constitutes the interfaces
21271 of a Stand-Alone Library project.
21274 @strong{Library_Standalone}: single
21276 Specifies if a Stand-Alone Library (SAL) is encapsulated or not.
21277 Only authorized case-insensitive values are "standard" for non encapsulated
21278 SALs, "encapsulated" for encapsulated SALs or "no" for non SAL library project.
21281 @strong{Library_Encapsulated_Options}: list
21283 Value is a list of options that need to be used when linking an encapsulated
21284 Stand-Alone Library.
21287 @strong{Library_Encapsulated_Supported}: single
21289 Indicates if encapsulated Stand-Alone Libraries are supported. Only
21290 authorized case-insensitive values are "true" and "false" (the default).
21293 @strong{Library_Auto_Init}: single
21295 Indicates if a Stand-Alone Library is auto-initialized. Only authorized
21296 case-insentive values are "true" and "false".
21299 @strong{Leading_Library_Options}: list
21301 Value is a list of options that are to be used at the beginning of
21302 the command line when linking a shared library.
21305 @strong{Library_Options}: list
21307 Value is a list of options that are to be used when linking a shared library.
21310 @strong{Library_Rpath_Options}: list, indexed, case-insensitive index
21312 Index is a language name. Value is a list of options for an invocation of the
21313 compiler of the language. This invocation is done for a shared library project
21314 with sources of the language. The output of the invocation is the path name
21315 of a shared library file. The directory name is to be put in the run path
21316 option switch when linking the shared library for the project.
21319 @strong{Library_Src_Dir}: single
21321 Value is the name of the directory where copies of the sources of the
21322 interfaces of a Stand-Alone Library are to be copied.
21325 @strong{Library_ALI_Dir}: single
21327 Value is the name of the directory where the ALI files of the interfaces
21328 of a Stand-Alone Library are to be copied. When this attribute is not declared,
21329 the directory is the library directory.
21332 @strong{Library_gcc}: single
21334 Obsolescent attribute. Specify the linker driver used to link a shared library.
21335 Use instead attribute Linker'Driver.
21338 @strong{Library_Symbol_File}: single
21340 Value is the name of the library symbol file.
21343 @strong{Library_Symbol_Policy}: single
21345 Indicates the symbol policy kind. Only authorized case-insensitive values are
21346 "autonomous", "default", "compliant", "controlled" or "direct".
21349 @strong{Library_Reference_Symbol_File}: single
21351 Value is the name of the reference symbol file.
21355 @strong{Configuration - General}
21361 @strong{Default_Language}: single
21363 Value is the case-insensitive name of the language of a project when attribute
21364 Languages is not specified.
21367 @strong{Run_Path_Option}: list
21369 Value is the list of switches to be used when specifying the run path option
21373 @strong{Run_Path_Origin}: single
21375 Value is the the string that may replace the path name of the executable
21376 directory in the run path options.
21379 @strong{Separate_Run_Path_Options}: single
21381 Indicates if there may be several run path options specified when linking an
21382 executable. Only authorized case-insensitive values are "true" or "false" (the
21386 @strong{Toolchain_Version}: single, indexed, case-insensitive index
21388 Index is a language name. Specify the version of a toolchain for a language.
21391 @strong{Toolchain_Description}: single, indexed, case-insensitive index
21393 Obsolescent. No longer used.
21396 @strong{Object_Generated}: single, indexed, case-insensitive index
21398 Index is a language name. Indicates if invoking the compiler for a language
21399 produces an object file. Only authorized case-insensitive values are "false"
21400 and "true" (the default).
21403 @strong{Objects_Linked}: single, indexed, case-insensitive index
21405 Index is a language name. Indicates if the object files created by the compiler
21406 for a language need to be linked in the executable. Only authorized
21407 case-insensitive values are "false" and "true" (the default).
21410 @strong{Target}: single
21412 Value is the name of the target platform. Taken into account only in the main
21415 Note that when the target is specified on the command line (usually with
21416 a switch --target=), the value of attribute reference 'Target is the one
21417 specified on the command line.
21420 @strong{Runtime}: single, indexed, case-insensitive index
21422 Index is a language name. Indicates the runtime directory that is to be used
21423 when using the compiler of the language. Taken into account only in the main
21426 Note that when the runtime is specified for a language on the command line
21427 (usually with a switch --RTS), the value of attribute reference 'Runtime
21428 for this language is the one specified on the command line.
21432 @strong{Configuration - Libraries}
21438 @strong{Library_Builder}: single
21440 Value is the path name of the application that is to be used to build
21441 libraries. Usually the path name of "gprlib".
21444 @strong{Library_Support}: single
21446 Indicates the level of support of libraries. Only authorized case-insensitive
21447 values are "static_only", "full" or "none" (the default).
21451 @strong{Configuration - Archives}
21457 @strong{Archive_Builder}: list
21459 Value is the name of the application to be used to create a static library
21460 (archive), followed by the options to be used.
21463 @strong{Archive_Builder_Append_Option}: list
21465 Value is the list of options to be used when invoking the archive builder
21466 to add project files into an archive.
21469 @strong{Archive_Indexer}: list
21471 Value is the name of the archive indexer, followed by the required options.
21474 @strong{Archive_Suffix}: single
21476 Value is the extension of archives. When not declared, the extension is ".a".
21479 @strong{Library_Partial_Linker}: list
21481 Value is the name of the partial linker executable, followed by the required
21486 @strong{Configuration - Shared Libraries}
21492 @strong{Shared_Library_Prefix}: single
21494 Value is the prefix in the name of shared library files. When not declared,
21495 the prefix is "lib".
21498 @strong{Shared_Library_Suffix}: single
21500 Value is the the extension of the name of shared library files. When not
21501 declared, the extension is ".so".
21504 @strong{Symbolic_Link_Supported}: single
21506 Indicates if symbolic links are supported on the platform. Only authorized
21507 case-insensitive values are "true" and "false" (the default).
21510 @strong{Library_Major_Minor_Id_Supported}: single
21512 Indicates if major and minor ids for shared library names are supported on
21513 the platform. Only authorized case-insensitive values are "true" and "false"
21517 @strong{Library_Auto_Init_Supported}: single
21519 Indicates if auto-initialization of Stand-Alone Libraries is supported. Only
21520 authorized case-insensitive values are "true" and "false" (the default).
21523 @strong{Shared_Library_Minimum_Switches}: list
21525 Value is the list of required switches when linking a shared library.
21528 @strong{Library_Version_Switches}: list
21530 Value is the list of switches to specify a internal name for a shared library.
21533 @strong{Library_Install_Name_Option}: single
21535 Value is the name of the option that needs to be used, concatenated with the
21536 path name of the library file, when linking a shared library.
21539 @strong{Runtime_Library_Dir}: single, indexed, case-insensitive index
21541 Index is a language name. Value is the path name of the directory where the
21542 runtime libraries are located.
21545 @strong{Runtime_Source_Dir}: single, indexed, case-insensitive index
21547 Index is a language name. Value is the path name of the directory where the
21548 sources of runtime libraries are located.
21552 @node Package Binder Attributes,Package Builder Attributes,Project Level Attributes,Attributes
21553 @anchor{gnat_ugn/gnat_project_manager package-binder-attributes}@anchor{1a9}@anchor{gnat_ugn/gnat_project_manager id49}@anchor{1aa}
21554 @subsubsection Package Binder Attributes
21567 @strong{Default_Switches}: list, indexed, case-insensitive index
21569 Index is a language name. Value is the list of switches to be used when binding
21570 code of the language, if there is no applicable attribute Switches.
21573 @strong{Switches}: list, optional index, indexed,
21574 case-insensitive index, others allowed
21576 Index is either a language name or a source file name. Value is the list of
21577 switches to be used when binding code. Index is either the source file name
21578 of the executable to be bound or the language name of the code to be bound.
21582 @strong{Configuration - Binding}
21588 @strong{Driver}: single, indexed, case-insensitive index
21590 Index is a language name. Value is the name of the application to be used when
21591 binding code of the language.
21594 @strong{Required_Switches}: list, indexed, case-insensitive index
21596 Index is a language name. Value is the list of the required switches to be
21597 used when binding code of the language.
21600 @strong{Prefix}: single, indexed, case-insensitive index
21602 Index is a language name. Value is a prefix to be used for the binder exchange
21603 file name for the language. Used to have different binder exchange file names
21604 when binding different languages.
21607 @strong{Objects_Path}: single,indexed, case-insensitive index
21609 Index is a language name. Value is the name of the environment variable that
21610 contains the path for the object directories.
21613 @strong{Object_Path_File}: single,indexed, case-insensitive index
21615 Index is a language name. Value is the name of the environment variable. The
21616 value of the environment variable is the path name of a text file that
21617 contains the list of object directories.
21621 @node Package Builder Attributes,Package Clean Attributes,Package Binder Attributes,Attributes
21622 @anchor{gnat_ugn/gnat_project_manager package-builder-attributes}@anchor{1ab}@anchor{gnat_ugn/gnat_project_manager id50}@anchor{1ac}
21623 @subsubsection Package Builder Attributes
21630 @strong{Default_Switches}: list, indexed, case-insensitive index
21632 Index is a language name. Value is the list of builder switches to be used when
21633 building an executable of the language, if there is no applicable attribute
21637 @strong{Switches}: list, optional index, indexed, case-insensitive index,
21640 Index is either a language name or a source file name. Value is the list of
21641 builder switches to be used when building an executable. Index is either the
21642 source file name of the executable to be built or its language name.
21645 @strong{Global_Compilation_Switches}: list, optional index, indexed,
21646 case-insensitive index
21648 Index is either a language name or a source file name. Value is the list of
21649 compilation switches to be used when building an executable. Index is either
21650 the source file name of the executable to be built or its language name.
21653 @strong{Executable}: single, indexed, case-insensitive index
21655 Index is an executable source file name. Value is the simple file name of the
21656 executable to be built.
21659 @strong{Executable_Suffix}: single
21661 Value is the extension of the file names of executable. When not specified,
21662 the extension is the default extension of executables on the platform.
21665 @strong{Global_Configuration_Pragmas}: single
21667 Value is the file name of a configuration pragmas file that is specified to
21668 the Ada compiler when compiling any Ada source in the project tree.
21671 @strong{Global_Config_File}: single, indexed, case-insensitive index
21673 Index is a language name. Value is the file name of a configuration file that
21674 is specified to the compiler when compiling any source of the language in the
21679 @node Package Clean Attributes,Package Compiler Attributes,Package Builder Attributes,Attributes
21680 @anchor{gnat_ugn/gnat_project_manager package-clean-attributes}@anchor{1ad}@anchor{gnat_ugn/gnat_project_manager id52}@anchor{1ae}
21681 @subsubsection Package Clean Attributes
21688 @strong{Switches}: list
21690 Value is a list of switches to be used by the cleaning application.
21693 @strong{Source_Artifact_Extensions}: list, indexed, case-insensitive index
21695 Index is a language names. Value is the list of extensions for file names
21696 derived from object file names that need to be cleaned in the object
21697 directory of the project.
21700 @strong{Object_Artifact_Extensions}: list, indexed, case-insensitive index
21702 Index is a language names. Value is the list of extensions for file names
21703 derived from source file names that need to be cleaned in the object
21704 directory of the project.
21707 @strong{Artifacts_In_Object_Dir}: single
21709 Value is a list of file names expressed as regular expressions that are to be
21710 deleted by gprclean in the object directory of the project.
21713 @strong{Artifacts_In_Exec_Dir}: single
21715 Value is list of file names expressed as regular expressions that are to be
21716 deleted by gprclean in the exec directory of the main project.
21719 @node Package Compiler Attributes,Package Cross_Reference Attributes,Package Clean Attributes,Attributes
21720 @anchor{gnat_ugn/gnat_project_manager id53}@anchor{1af}@anchor{gnat_ugn/gnat_project_manager package-compiler-attributes}@anchor{1b0}
21721 @subsubsection Package Compiler Attributes
21734 @strong{Default_Switches}: list, indexed, case-insensitive index
21736 Index is a language name. Value is a list of switches to be used when invoking
21737 the compiler for the language for a source of the project, if there is no
21738 applicable attribute Switches.
21741 @strong{Switches}: list, optional index, indexed, case-insensitive index,
21744 Index is a source file name or a language name. Value is the list of switches
21745 to be used when invoking the compiler for the source or for its language.
21748 @strong{Local_Configuration_Pragmas}: single
21750 Value is the file name of a configuration pragmas file that is specified to
21751 the Ada compiler when compiling any Ada source in the project.
21754 @strong{Local_Config_File}: single, indexed, case-insensitive index
21756 Index is a language name. Value is the file name of a configuration file that
21757 is specified to the compiler when compiling any source of the language in the
21762 @strong{Configuration - Compiling}
21768 @strong{Driver}: single, indexed, case-insensitive index
21770 Index is a language name. Value is the name of the executable for the compiler
21774 @strong{Language_Kind}: single, indexed, case-insensitive index
21776 Index is a language name. Indicates the kind of the language, either file based
21777 or unit based. Only authorized case-insensitive values are "unit_based" and
21778 "file_based" (the default).
21781 @strong{Dependency_Kind}: single, indexed, case-insensitive index
21783 Index is a language name. Indicates how the dependencies are handled for the
21784 language. Only authorized case-insensitive values are "makefile", "ali_file",
21785 "ali_closure" or "none" (the default).
21788 @strong{Required_Switches}: list, indexed, case-insensitive index
21790 Equivalent to attribute Leading_Required_Switches.
21793 @strong{Leading_Required_Switches}: list, indexed, case-insensitive index
21795 Index is a language name. Value is the list of the minimum switches to be used
21796 at the beginning of the command line when invoking the compiler for the
21800 @strong{Trailing_Required_Switches}: list, indexed, case-insensitive index
21802 Index is a language name. Value is the list of the minimum switches to be used
21803 at the end of the command line when invoking the compiler for the language.
21806 @strong{PIC_Option}: list, indexed, case-insensitive index
21808 Index is a language name. Value is the list of switches to be used when
21809 compiling a source of the language when the project is a shared library
21813 @strong{Path_Syntax}: single, indexed, case-insensitive index
21815 Index is a language name. Value is the kind of path syntax to be used when
21816 invoking the compiler for the language. Only authorized case-insensitive
21817 values are "canonical" and "host" (the default).
21820 @strong{Source_File_Switches}: single, indexed, case-insensitive index
21822 Index is a language name. Value is a list of switches to be used just before
21823 the path name of the source to compile when invoking the compiler for a source
21827 @strong{Object_File_Suffix}: single, indexed, case-insensitive index
21829 Index is a language name. Value is the extension of the object files created
21830 by the compiler of the language. When not specified, the extension is the
21831 default one for the platform.
21834 @strong{Object_File_Switches}: list, indexed, case-insensitive index
21836 Index is a language name. Value is the list of switches to be used by the
21837 compiler of the language to specify the path name of the object file. When not
21838 specified, the switch used is "-o".
21841 @strong{Multi_Unit_Switches}: list, indexed, case-insensitive index
21843 Index is a language name. Value is the list of switches to be used to compile
21844 a unit in a multi unit source of the language. The index of the unit in the
21845 source is concatenated with the last switches in the list.
21848 @strong{Multi_Unit_Object_Separator}: single, indexed, case-insensitive index
21850 Index is a language name. Value is the string to be used in the object file
21851 name before the index of the unit, when compiling a unit in a multi unit source
21856 @strong{Configuration - Mapping Files}
21862 @strong{Mapping_File_Switches}: list, indexed, case-insensitive index
21864 Index is a language name. Value is the list of switches to be used to specify
21865 a mapping file when invoking the compiler for a source of the language.
21868 @strong{Mapping_Spec_Suffix}: single, indexed, case-insensitive index
21870 Index is a language name. Value is the suffix to be used in a mapping file
21871 to indicate that the source is a spec.
21874 @strong{Mapping_Body_Suffix}: single, indexed, case-insensitive index
21876 Index is a language name. Value is the suffix to be used in a mapping file
21877 to indicate that the source is a body.
21881 @strong{Configuration - Config Files}
21887 @strong{Config_File_Switches}: list: single, indexed, case-insensitive index
21889 Index is a language name. Value is the list of switches to specify to the
21890 compiler of the language a configuration file.
21893 @strong{Config_Body_File_Name}: single, indexed, case-insensitive index
21895 Index is a language name. Value is the template to be used to indicate a
21896 configuration specific to a body of the language in a configuration
21900 @strong{Config_Body_File_Name_Index}: single, indexed, case-insensitive index
21902 Index is a language name. Value is the template to be used to indicate a
21903 configuration specific to the body a unit in a multi unit source of the
21904 language in a configuration file.
21907 @strong{Config_Body_File_Name_Pattern}: single, indexed,
21908 case-insensitive index
21910 Index is a language name. Value is the template to be used to indicate a
21911 configuration for all bodies of the languages in a configuration file.
21914 @strong{Config_Spec_File_Name}: single, indexed, case-insensitive index
21916 Index is a language name. Value is the template to be used to indicate a
21917 configuration specific to a spec of the language in a configuration
21921 @strong{Config_Spec_File_Name_Index}: single, indexed, case-insensitive index
21923 Index is a language name. Value is the template to be used to indicate a
21924 configuration specific to the spec a unit in a multi unit source of the
21925 language in a configuration file.
21928 @strong{Config_Spec_File_Name_Pattern}: single, indexed,
21929 case-insensitive index
21931 Index is a language name. Value is the template to be used to indicate a
21932 configuration for all specs of the languages in a configuration file.
21935 @strong{Config_File_Unique}: single, indexed, case-insensitive index
21937 Index is a language name. Indicates if there should be only one configuration
21938 file specified to the compiler of the language. Only authorized
21939 case-insensitive values are "true" and "false" (the default).
21943 @strong{Configuration - Dependencies}
21949 @strong{Dependency_Switches}: list, indexed, case-insensitive index
21951 Index is a language name. Value is the list of switches to be used to specify
21952 to the compiler the dependency file when the dependency kind of the language is
21953 file based, and when Dependency_Driver is not specified for the language.
21956 @strong{Dependency_Driver}: list, indexed, case-insensitive index
21958 Index is a language name. Value is the name of the executable to be used to
21959 create the dependency file for a source of the language, followed by the
21964 @strong{Configuration - Search Paths}
21970 @strong{Include_Switches}: list, indexed, case-insensitive index
21972 Index is a language name. Value is the list of switches to specify to the
21973 compiler of the language to indicate a directory to look for sources.
21976 @strong{Include_Path}: single, indexed, case-insensitive index
21978 Index is a language name. Value is the name of an environment variable that
21979 contains the path of all the directories that the compiler of the language
21980 may search for sources.
21983 @strong{Include_Path_File}: single, indexed, case-insensitive index
21985 Index is a language name. Value is the name of an environment variable the
21986 value of which is the path name of a text file that contains the directories
21987 that the compiler of the language may search for sources.
21990 @strong{Object_Path_Switches}: list, indexed, case-insensitive index
21992 Index is a language name. Value is the list of switches to specify to the
21993 compiler of the language the name of a text file that contains the list of
21994 object directories. When this attribute is not declared, the text file is
21999 @node Package Cross_Reference Attributes,Package Finder Attributes,Package Compiler Attributes,Attributes
22000 @anchor{gnat_ugn/gnat_project_manager id54}@anchor{1b1}@anchor{gnat_ugn/gnat_project_manager package-cross-reference-attributes}@anchor{1b2}
22001 @subsubsection Package Cross_Reference Attributes
22008 @strong{Default_Switches}: list, indexed, case-insensitive index
22010 Index is a language name. Value is a list of switches to be used when invoking
22011 @cite{gnatxref} for a source of the language, if there is no applicable
22012 attribute Switches.
22015 @strong{Switches}: list, optional index, indexed, case-insensitive index,
22018 Index is a source file name. Value is the list of switches to be used when
22019 invoking @cite{gnatxref} for the source.
22023 @node Package Finder Attributes,Package gnatls Attributes,Package Cross_Reference Attributes,Attributes
22024 @anchor{gnat_ugn/gnat_project_manager id56}@anchor{1b3}@anchor{gnat_ugn/gnat_project_manager package-finder-attributes}@anchor{1b4}
22025 @subsubsection Package Finder Attributes
22032 @strong{Default_Switches}: list, indexed, case-insensitive index
22034 Index is a language name. Value is a list of switches to be used when invoking
22035 @cite{gnatfind} for a source of the language, if there is no applicable
22036 attribute Switches.
22039 @strong{Switches}: list, optional index, indexed, case-insensitive index,
22042 Index is a source file name. Value is the list of switches to be used when
22043 invoking @cite{gnatfind} for the source.
22046 @node Package gnatls Attributes,Package IDE Attributes,Package Finder Attributes,Attributes
22047 @anchor{gnat_ugn/gnat_project_manager package-gnatls-attributes}@anchor{1b5}@anchor{gnat_ugn/gnat_project_manager id57}@anchor{1b6}
22048 @subsubsection Package gnatls Attributes
22055 @strong{Switches}: list
22057 Value is a list of switches to be used when invoking @cite{gnatls}.
22061 @node Package IDE Attributes,Package Install Attributes,Package gnatls Attributes,Attributes
22062 @anchor{gnat_ugn/gnat_project_manager id58}@anchor{1b7}@anchor{gnat_ugn/gnat_project_manager package-ide-attributes}@anchor{1b8}
22063 @subsubsection Package IDE Attributes
22070 @strong{Default_Switches}: list, indexed
22072 Index is the name of an external tool that the GNAT Programming System (GPS)
22073 is supporting. Value is a list of switches to use when invoking that tool.
22076 @strong{Remote_Host}: single
22078 Value is a string that designates the remote host in a cross-compilation
22079 environment, to be used for remote compilation and debugging. This attribute
22080 should not be specified when running on the local machine.
22083 @strong{Program_Host}: single
22085 Value is a string that specifies the name of IP address of the embedded target
22086 in a cross-compilation environment, on which the program should execute.
22089 @strong{Communication_Protocol}: single
22091 Value is the name of the protocol to use to communicate with the target
22092 in a cross-compilation environment, for example @cite{"wtx"} or
22096 @strong{Compiler_Command}: single, indexed, case-insensitive index
22098 Index is a language Name. Value is a string that denotes the command to be
22099 used to invoke the compiler. For historical reasons, the value of
22100 @cite{Compiler_Command ("Ada")} is expected to be a reference to @emph{gnatmake} or
22101 @emph{cross-gnatmake}.
22104 @strong{Debugger_Command}: single
22106 Value is a string that specifies the name of the debugger to be used, such as
22107 gdb, powerpc-wrs-vxworks-gdb or gdb-4.
22110 @strong{gnatlist}: single
22112 Value is a string that specifies the name of the @emph{gnatls} utility
22113 to be used to retrieve information about the predefined path; for example,
22114 @cite{"gnatls"}, @cite{"powerpc-wrs-vxworks-gnatls"}.
22117 @strong{VCS_Kind}: single
22119 Value is a string used to specify the Version Control System (VCS) to be used
22120 for this project, for example "Subversion", "ClearCase". If the
22121 value is set to "Auto", the IDE will try to detect the actual VCS used
22122 on the list of supported ones.
22125 @strong{VCS_File_Check}: single
22127 Value is a string that specifies the command used by the VCS to check
22128 the validity of a file, either when the user explicitly asks for a check,
22129 or as a sanity check before doing the check-in.
22132 @strong{VCS_Log_Check}: single
22134 Value is a string that specifies the command used by the VCS to check
22135 the validity of a log file.
22138 @strong{Documentation_Dir}: single
22140 Value is the directory used to generate the documentation of source code.
22143 @node Package Install Attributes,Package Linker Attributes,Package IDE Attributes,Attributes
22144 @anchor{gnat_ugn/gnat_project_manager package-install-attributes}@anchor{1b9}@anchor{gnat_ugn/gnat_project_manager id59}@anchor{1ba}
22145 @subsubsection Package Install Attributes
22152 @strong{Artifacts}: list, indexed
22154 An array attribute to declare a set of files not part of the sources
22155 to be installed. The array discriminant is the directory where the
22156 file is to be installed. If a relative directory then Prefix (see
22157 below) is prepended. Note also that if the same file name occurs
22158 multiple time in the attribute list, the last one will be the one
22162 @strong{Prefix}: single
22164 Value is the install destination directory.
22167 @strong{Sources_Subdir}: single
22169 Value is the sources directory or subdirectory of Prefix.
22172 @strong{Exec_Subdir}: single
22174 Value is the executables directory or subdirectory of Prefix.
22177 @strong{Lib_Subdir}: single
22179 Value is library directory or subdirectory of Prefix.
22182 @strong{Project_Subdir}: single
22184 Value is the project directory or subdirectory of Prefix.
22187 @strong{Active}: single
22189 Indicates that the project is to be installed or not. Case-insensitive value
22190 "false" means that the project is not to be installed, all other values mean
22191 that the project is to be installed.
22194 @strong{Mode}: single
22196 Value is the installation mode, it is either @strong{dev} (default) or @strong{usage}.
22199 @strong{Install_Name}: single
22201 Specify the name to use for recording the installation. The default is
22202 the project name without the extension.
22205 @node Package Linker Attributes,Package Naming Attributes,Package Install Attributes,Attributes
22206 @anchor{gnat_ugn/gnat_project_manager id60}@anchor{1bb}@anchor{gnat_ugn/gnat_project_manager package-linker-attributes}@anchor{1bc}
22207 @subsubsection Package Linker Attributes
22220 @strong{Required_Switches}: list
22222 Value is a list of switches that are required when invoking the linker to link
22226 @strong{Default_Switches}: list, indexed, case-insensitive index
22228 Index is a language name. Value is a list of switches for the linker when
22229 linking an executable for a main source of the language, when there is no
22230 applicable Switches.
22233 @strong{Leading_Switches}: list, optional index, indexed,
22234 case-insensitive index, others allowed
22236 Index is a source file name or a language name. Value is the list of switches
22237 to be used at the beginning of the command line when invoking the linker to
22238 build an executable for the source or for its language.
22241 @strong{Switches}: list, optional index, indexed, case-insensitive index,
22244 Index is a source file name or a language name. Value is the list of switches
22245 to be used when invoking the linker to build an executable for the source or
22249 @strong{Trailing_Switches}: list, optional index, indexed,
22250 case-insensitive index, others allowed
22252 Index is a source file name or a language name. Value is the list of switches
22253 to be used at the end of the command line when invoking the linker to
22254 build an executable for the source or for its language. These switches may
22255 override the Required_Switches.
22258 @strong{Linker_Options}: list
22260 Value is a list of switches/options that are to be added when linking an
22261 executable from a project importing the current project directly or indirectly.
22262 Linker_Options are not used when linking an executable from the current
22266 @strong{Map_File_Option}: single
22268 Value is the switch to specify the map file name that the linker needs to
22273 @strong{Configuration - Linking}
22279 @strong{Driver}: single
22281 Value is the name of the linker executable.
22285 @strong{Configuration - Response Files}
22291 @strong{Max_Command_Line_Length}: single
22293 Value is the maximum number of character in the command line when invoking
22294 the linker to link an executable.
22297 @strong{Response_File_Format}: single
22299 Indicates the kind of response file to create when the length of the linking
22300 command line is too large. Only authorized case-insensitive values are "none",
22301 "gnu", "object_list", "gcc_gnu", "gcc_option_list" and "gcc_object_list".
22304 @strong{Response_File_Switches}: list
22306 Value is the list of switches to specify a response file to the linker.
22312 @c .. _Package_Metrics_Attribute:
22314 @c Package Metrics Attribute
22315 @c ^^^^^^^^^^^^^^^^^^^^^^^^^
22317 @c * **Default_Switches**: list, indexed, case-insensitive index
22319 @c Index is a language name. Value is a list of switches to be used when invoking
22320 @c `gnatmetric` for a source of the language, if there is no applicable
22321 @c attribute Switches.
22323 @c * **Switches**: list, optional index, indexed, case-insensitive index,
22326 @c Index is a source file name. Value is the list of switches to be used when
22327 @c invoking `gnatmetric` for the source.
22329 @node Package Naming Attributes,Package Remote Attributes,Package Linker Attributes,Attributes
22330 @anchor{gnat_ugn/gnat_project_manager package-naming-attributes}@anchor{1bd}@anchor{gnat_ugn/gnat_project_manager id61}@anchor{1be}
22331 @subsubsection Package Naming Attributes
22338 @strong{Specification_Suffix}: single, indexed, case-insensitive index
22340 Equivalent to attribute Spec_Suffix.
22343 @strong{Spec_Suffix}: single, indexed, case-insensitive index
22345 Index is a language name. Value is the extension of file names for specs of
22349 @strong{Implementation_Suffix}: single, indexed, case-insensitive index
22351 Equivalent to attribute Body_Suffix.
22354 @strong{Body_Suffix}: single, indexed, case-insensitive index
22356 Index is a language name. Value is the extension of file names for bodies of
22360 @strong{Separate_Suffix}: single
22362 Value is the extension of file names for subunits of Ada.
22365 @strong{Casing}: single
22367 Indicates the casing of sources of the Ada language. Only authorized
22368 case-insensitive values are "lowercase", "uppercase" and "mixedcase".
22371 @strong{Dot_Replacement}: single
22373 Value is the string that replace the dot of unit names in the source file names
22374 of the Ada language.
22377 @strong{Specification}: single, optional index, indexed,
22378 case-insensitive index
22380 Equivalent to attribute Spec.
22383 @strong{Spec}: single, optional index, indexed, case-insensitive index
22385 Index is a unit name. Value is the file name of the spec of the unit.
22388 @strong{Implementation}: single, optional index, indexed,
22389 case-insensitive index
22391 Equivalent to attribute Body.
22394 @strong{Body}: single, optional index, indexed, case-insensitive index
22396 Index is a unit name. Value is the file name of the body of the unit.
22399 @strong{Specification_Exceptions}: list, indexed, case-insensitive index
22401 Index is a language name. Value is a list of specs for the language that do not
22402 necessarily follow the naming scheme for the language and that may or may not
22403 be found in the source directories of the project.
22406 @strong{Implementation_Exceptions}: list, indexed, case-insensitive index
22408 Index is a language name. Value is a list of bodies for the language that do not
22409 necessarily follow the naming scheme for the language and that may or may not
22410 be found in the source directories of the project.
22414 @node Package Remote Attributes,Package Stack Attributes,Package Naming Attributes,Attributes
22415 @anchor{gnat_ugn/gnat_project_manager package-remote-attributes}@anchor{1bf}@anchor{gnat_ugn/gnat_project_manager id63}@anchor{1c0}
22416 @subsubsection Package Remote Attributes
22423 @strong{Included_Patterns}: list
22425 If this attribute is defined it sets the patterns to
22426 synchronized from the master to the slaves. It is exclusive
22427 with Excluded_Patterns, that is it is an error to define
22431 @strong{Included_Artifact_Patterns}: list
22433 If this attribute is defined it sets the patterns of compilation
22434 artifacts to synchronized from the slaves to the build master.
22435 This attribute replace the default hard-coded patterns.
22438 @strong{Excluded_Patterns}: list
22440 Set of patterns to ignore when synchronizing sources from the build
22441 master to the slaves. A set of predefined patterns are supported
22442 (e.g. *.o, *.ali, *.exe, etc.), this attributes make it possible to
22443 add some more patterns.
22446 @strong{Root_Dir}: single
22448 Value is the root directory used by the slave machines.
22451 @node Package Stack Attributes,Package Synchronize Attributes,Package Remote Attributes,Attributes
22452 @anchor{gnat_ugn/gnat_project_manager id64}@anchor{1c1}@anchor{gnat_ugn/gnat_project_manager package-stack-attributes}@anchor{1c2}
22453 @subsubsection Package Stack Attributes
22460 @strong{Switches}: list
22462 Value is the list of switches to be used when invoking @cite{gnatstack}.
22465 @node Package Synchronize Attributes,,Package Stack Attributes,Attributes
22466 @anchor{gnat_ugn/gnat_project_manager package-synchronize-attributes}@anchor{1c3}
22467 @subsubsection Package Synchronize Attributes
22474 @strong{Default_Switches}: list, indexed, case-insensitive index
22476 Index is a language name. Value is a list of switches to be used when invoking
22477 @cite{gnatsync} for a source of the language, if there is no applicable
22478 attribute Switches.
22481 @strong{Switches}: list, optional index, indexed, case-insensitive index,
22484 Index is a source file name. Value is the list of switches to be used when
22485 invoking @cite{gnatsync} for the source.
22488 @node Tools Supporting Project Files,GNAT Utility Programs,GNAT Project Manager,Top
22489 @anchor{gnat_ugn/tools_supporting_project_files doc}@anchor{1c4}@anchor{gnat_ugn/tools_supporting_project_files tools-supporting-project-files}@anchor{c}@anchor{gnat_ugn/tools_supporting_project_files id1}@anchor{1c5}
22490 @chapter Tools Supporting Project Files
22493 This section describes how project files can be used in conjunction with a number of
22497 * gnatmake and Project Files::
22498 * The GNAT Driver and Project Files::
22502 @node gnatmake and Project Files,The GNAT Driver and Project Files,,Tools Supporting Project Files
22503 @anchor{gnat_ugn/tools_supporting_project_files id2}@anchor{1c6}@anchor{gnat_ugn/tools_supporting_project_files gnatmake-and-project-files}@anchor{e4}
22504 @section gnatmake and Project Files
22507 This section covers several topics related to @emph{gnatmake} and
22508 project files: defining switches for @emph{gnatmake}
22509 and for the tools that it invokes; specifying configuration pragmas;
22510 the use of the @cite{Main} attribute; building and rebuilding library project
22514 * Switches Related to Project Files::
22515 * Switches and Project Files::
22516 * Specifying Configuration Pragmas::
22517 * Project Files and Main Subprograms::
22518 * Library Project Files::
22522 @node Switches Related to Project Files,Switches and Project Files,,gnatmake and Project Files
22523 @anchor{gnat_ugn/tools_supporting_project_files switches-related-to-project-files}@anchor{e6}@anchor{gnat_ugn/tools_supporting_project_files id3}@anchor{1c7}
22524 @subsection Switches Related to Project Files
22527 The following switches are used by GNAT tools that support project files:
22531 @geindex -P (any project-aware tool)
22537 @item @code{-P@emph{project}}
22539 Indicates the name of a project file. This project file will be parsed with
22540 the verbosity indicated by @emph{-vP*x*},
22541 if any, and using the external references indicated
22542 by @emph{-X} switches, if any.
22543 There may zero, one or more spaces between @emph{-P} and @cite{project}.
22545 There must be only one @emph{-P} switch on the command line.
22547 Since the Project Manager parses the project file only after all the switches
22548 on the command line are checked, the order of the switches
22551 or @emph{-X} is not significant.
22553 @geindex -X (any project-aware tool)
22555 @item @code{-X@emph{name}=@emph{value}}
22557 Indicates that external variable @cite{name} has the value @cite{value}.
22558 The Project Manager will use this value for occurrences of
22559 @cite{external(name)} when parsing the project file.
22561 If @cite{name} or @cite{value} includes a space, then @cite{name=value} should be
22562 put between quotes.
22569 Several @emph{-X} switches can be used simultaneously.
22570 If several @emph{-X} switches specify the same
22571 @cite{name}, only the last one is used.
22573 An external variable specified with a @emph{-X} switch
22574 takes precedence over the value of the same name in the environment.
22576 @geindex -vP (any project-aware tool)
22578 @item @code{-vP@emph{x}}
22580 Indicates the verbosity of the parsing of GNAT project files.
22582 @emph{-vP0} means Default;
22583 @emph{-vP1} means Medium;
22584 @emph{-vP2} means High.
22586 The default is Default: no output for syntactically correct
22588 If several @emph{-vP*x*} switches are present,
22589 only the last one is used.
22591 @geindex -aP (any project-aware tool)
22593 @item @code{-aP@emph{dir}}
22595 Add directory @cite{dir} at the beginning of the project search path, in order,
22596 after the current working directory.
22598 @geindex -eL (any project-aware tool)
22602 Follow all symbolic links when processing project files.
22604 @geindex --subdirs= (gnatmake and gnatclean)
22606 @item @code{--subdirs=@emph{subdir}}
22608 This switch is recognized by @emph{gnatmake} and @emph{gnatclean}. It
22609 indicate that the real directories (except the source directories) are the
22610 subdirectories @cite{subdir} of the directories specified in the project files.
22611 This applies in particular to object directories, library directories and
22612 exec directories. If the subdirectories do not exist, they are created
22616 @node Switches and Project Files,Specifying Configuration Pragmas,Switches Related to Project Files,gnatmake and Project Files
22617 @anchor{gnat_ugn/tools_supporting_project_files id4}@anchor{1c8}@anchor{gnat_ugn/tools_supporting_project_files switches-and-project-files}@anchor{1c9}
22618 @subsection Switches and Project Files
22621 For each of the packages @cite{Builder}, @cite{Compiler}, @cite{Binder}, and
22622 @cite{Linker}, you can specify a @cite{Default_Switches}
22623 attribute, a @cite{Switches} attribute, or both;
22624 as their names imply, these switch-related
22625 attributes affect the switches that are used for each of these GNAT
22627 @emph{gnatmake} is invoked. As will be explained below, these
22628 component-specific switches precede
22629 the switches provided on the @emph{gnatmake} command line.
22631 The @cite{Default_Switches} attribute is an attribute
22632 indexed by language name (case insensitive) whose value is a string list.
22638 package Compiler is
22639 for Default_Switches ("Ada")
22646 The @cite{Switches} attribute is indexed on a file name (which may or may
22647 not be case sensitive, depending
22648 on the operating system) whose value is a string list. For example:
22654 for Switches ("main1.adb")
22656 for Switches ("main2.adb")
22662 For the @cite{Builder} package, the file names must designate source files
22663 for main subprograms. For the @cite{Binder} and @cite{Linker} packages, the
22664 file names must designate @code{ALI} or source files for main subprograms.
22665 In each case just the file name without an explicit extension is acceptable.
22667 For each tool used in a program build (@emph{gnatmake}, the compiler, the
22668 binder, and the linker), the corresponding package @@dfn@{contributes@} a set of
22669 switches for each file on which the tool is invoked, based on the
22670 switch-related attributes defined in the package.
22671 In particular, the switches
22672 that each of these packages contributes for a given file @cite{f} comprise:
22678 the value of attribute @cite{Switches (`f})`,
22679 if it is specified in the package for the given file,
22682 otherwise, the value of @cite{Default_Switches ("Ada")},
22683 if it is specified in the package.
22686 If neither of these attributes is defined in the package, then the package does
22687 not contribute any switches for the given file.
22689 When @emph{gnatmake} is invoked on a file, the switches comprise
22690 two sets, in the following order: those contributed for the file
22691 by the @cite{Builder} package;
22692 and the switches passed on the command line.
22694 When @emph{gnatmake} invokes a tool (compiler, binder, linker) on a file,
22695 the switches passed to the tool comprise three sets,
22696 in the following order:
22702 the applicable switches contributed for the file
22703 by the @cite{Builder} package in the project file supplied on the command line;
22706 those contributed for the file by the package (in the relevant project file --
22707 see below) corresponding to the tool; and
22710 the applicable switches passed on the command line.
22713 The term @emph{applicable switches} reflects the fact that
22714 @emph{gnatmake} switches may or may not be passed to individual
22715 tools, depending on the individual switch.
22717 @emph{gnatmake} may invoke the compiler on source files from different
22718 projects. The Project Manager will use the appropriate project file to
22719 determine the @cite{Compiler} package for each source file being compiled.
22720 Likewise for the @cite{Binder} and @cite{Linker} packages.
22722 As an example, consider the following package in a project file:
22728 package Compiler is
22729 for Default_Switches ("Ada")
22731 for Switches ("a.adb")
22733 for Switches ("b.adb")
22741 If @emph{gnatmake} is invoked with this project file, and it needs to
22742 compile, say, the files @code{a.adb}, @code{b.adb}, and @code{c.adb}, then
22743 @code{a.adb} will be compiled with the switch @emph{-O1},
22744 @code{b.adb} with switches @emph{-O2} and @emph{-gnaty},
22745 and @code{c.adb} with @emph{-g}.
22747 The following example illustrates the ordering of the switches
22748 contributed by different packages:
22755 for Switches ("main.adb")
22761 package Compiler is
22762 for Switches ("main.adb")
22769 If you issue the command:
22774 $ gnatmake -Pproj2 -O0 main
22778 then the compiler will be invoked on @code{main.adb} with the following
22779 sequence of switches
22788 with the last @emph{-O}
22789 switch having precedence over the earlier ones;
22790 several other switches
22791 (such as @emph{-c}) are added implicitly.
22793 The switches @emph{-g}
22794 and @emph{-O1} are contributed by package
22795 @cite{Builder}, @emph{-O2} is contributed
22796 by the package @cite{Compiler}
22797 and @emph{-O0} comes from the command line.
22799 The @emph{-g} switch will also be passed in the invocation of
22802 A final example illustrates switch contributions from packages in different
22809 for Source_Files use ("pack.ads", "pack.adb");
22810 package Compiler is
22811 for Default_Switches ("Ada")
22818 for Source_Files use ("foo_main.adb", "bar_main.adb");
22820 for Switches ("foo_main.adb")
22828 -- Ada source file:
22830 procedure Foo_Main is
22841 $ gnatmake -PProj4 foo_main.adb -cargs -gnato
22845 then the switches passed to the compiler for @code{foo_main.adb} are
22846 @emph{-g} (contributed by the package @cite{Proj4.Builder}) and
22847 @emph{-gnato} (passed on the command line).
22848 When the imported package @cite{Pack} is compiled, the switches used
22849 are @emph{-g} from @cite{Proj4.Builder},
22850 @emph{-gnata} (contributed from package @cite{Proj3.Compiler},
22851 and @emph{-gnato} from the command line.
22853 When using @emph{gnatmake} with project files, some switches or
22854 arguments may be expressed as relative paths. As the working directory where
22855 compilation occurs may change, these relative paths are converted to absolute
22856 paths. For the switches found in a project file, the relative paths
22857 are relative to the project file directory, for the switches on the command
22858 line, they are relative to the directory where @emph{gnatmake} is invoked.
22859 The switches for which this occurs are:
22865 -aI, as well as all arguments that are not switches (arguments to
22867 -o, object files specified in package @cite{Linker} or after
22868 -largs on the command line). The exception to this rule is the switch
22869 --RTS= for which a relative path argument is never converted.
22871 @node Specifying Configuration Pragmas,Project Files and Main Subprograms,Switches and Project Files,gnatmake and Project Files
22872 @anchor{gnat_ugn/tools_supporting_project_files id5}@anchor{1ca}@anchor{gnat_ugn/tools_supporting_project_files specifying-configuration-pragmas}@anchor{7d}
22873 @subsection Specifying Configuration Pragmas
22876 When using @emph{gnatmake} with project files, if there exists a file
22877 @code{gnat.adc} that contains configuration pragmas, this file will be
22880 Configuration pragmas can be defined by means of the following attributes in
22881 project files: @cite{Global_Configuration_Pragmas} in package @cite{Builder}
22882 and @cite{Local_Configuration_Pragmas} in package @cite{Compiler}.
22884 Both these attributes are single string attributes. Their values is the path
22885 name of a file containing configuration pragmas. If a path name is relative,
22886 then it is relative to the project directory of the project file where the
22887 attribute is defined.
22889 When compiling a source, the configuration pragmas used are, in order,
22890 those listed in the file designated by attribute
22891 @cite{Global_Configuration_Pragmas} in package @cite{Builder} of the main
22892 project file, if it is specified, and those listed in the file designated by
22893 attribute @cite{Local_Configuration_Pragmas} in package @cite{Compiler} of
22894 the project file of the source, if it exists.
22896 @node Project Files and Main Subprograms,Library Project Files,Specifying Configuration Pragmas,gnatmake and Project Files
22897 @anchor{gnat_ugn/tools_supporting_project_files id6}@anchor{1cb}@anchor{gnat_ugn/tools_supporting_project_files project-files-and-main-subprograms}@anchor{e5}
22898 @subsection Project Files and Main Subprograms
22901 When using a project file, you can invoke @emph{gnatmake}
22902 with one or several main subprograms, by specifying their source files on the
22908 $ gnatmake -Pprj main1.adb main2.adb main3.adb
22912 Each of these needs to be a source file of the same project, except
22913 when the switch @cite{-u} is used.
22915 When @cite{-u} is not used, all the mains need to be sources of the
22916 same project, one of the project in the tree rooted at the project specified
22917 on the command line. The package @cite{Builder} of this common project, the
22918 "main project" is the one that is considered by @emph{gnatmake}.
22920 When @cite{-u} is used, the specified source files may be in projects
22921 imported directly or indirectly by the project specified on the command line.
22922 Note that if such a source file is not part of the project specified on the
22923 command line, the switches found in package @cite{Builder} of the
22924 project specified on the command line, if any, that are transmitted
22925 to the compiler will still be used, not those found in the project file of
22928 When using a project file, you can also invoke @emph{gnatmake} without
22929 explicitly specifying any main, and the effect depends on whether you have
22930 defined the @cite{Main} attribute. This attribute has a string list value,
22931 where each element in the list is the name of a source file (the file
22932 extension is optional) that contains a unit that can be a main subprogram.
22934 If the @cite{Main} attribute is defined in a project file as a non-empty
22935 string list and the switch @emph{-u} is not used on the command
22936 line, then invoking @emph{gnatmake} with this project file but without any
22937 main on the command line is equivalent to invoking @emph{gnatmake} with all
22938 the file names in the @cite{Main} attribute on the command line.
22946 for Main use ("main1.adb", "main2.adb", "main3.adb");
22951 With this project file, @cite{"gnatmake -Pprj"}
22953 @cite{"gnatmake -Pprj main1.adb main2.adb main3.adb"}.
22955 When the project attribute @cite{Main} is not specified, or is specified
22956 as an empty string list, or when the switch @emph{-u} is used on the command
22957 line, then invoking @emph{gnatmake} with no main on the command line will
22958 result in all immediate sources of the project file being checked, and
22959 potentially recompiled. Depending on the presence of the switch @emph{-u},
22960 sources from other project files on which the immediate sources of the main
22961 project file depend are also checked and potentially recompiled. In other
22962 words, the @emph{-u} switch is applied to all of the immediate sources of the
22965 When no main is specified on the command line and attribute @cite{Main} exists
22966 and includes several mains, or when several mains are specified on the
22967 command line, the default switches in package @cite{Builder} will
22968 be used for all mains, even if there are specific switches
22969 specified for one or several mains.
22971 But the switches from package @cite{Binder} or @cite{Linker} will be
22972 the specific switches for each main, if they are specified.
22974 @node Library Project Files,,Project Files and Main Subprograms,gnatmake and Project Files
22975 @anchor{gnat_ugn/tools_supporting_project_files id7}@anchor{1cc}@anchor{gnat_ugn/tools_supporting_project_files library-project-files}@anchor{1cd}
22976 @subsection Library Project Files
22979 When @emph{gnatmake} is invoked with a main project file that is a library
22980 project file, it is not allowed to specify one or more mains on the command
22983 When a library project file is specified, switches @cite{-b} and
22984 @cite{-l} have special meanings.
22990 @cite{-b} is only allowed for stand-alone libraries. It indicates
22991 to @emph{gnatmake} that @emph{gnatbind} should be invoked for the
22995 @cite{-l} may be used for all library projects. It indicates
22996 to @emph{gnatmake} that the binder generated file should be compiled
22997 (in the case of a stand-alone library) and that the library should be built.
23000 @node The GNAT Driver and Project Files,,gnatmake and Project Files,Tools Supporting Project Files
23001 @anchor{gnat_ugn/tools_supporting_project_files id8}@anchor{1ce}@anchor{gnat_ugn/tools_supporting_project_files the-gnat-driver-and-project-files}@anchor{122}
23002 @section The GNAT Driver and Project Files
23005 A number of GNAT tools beyond @emph{gnatmake}
23006 can benefit from project files:
23031 However, none of these tools can be invoked
23032 directly with a project file switch (@emph{-P}).
23033 They must be invoked through the @emph{gnat} driver.
23035 The @emph{gnat} driver is a wrapper that accepts a number of commands and
23036 calls the corresponding tool. It was designed initially for VMS platforms (to
23037 convert VMS qualifiers to Unix-style switches), but it is now available on all
23040 On non-VMS platforms, the @emph{gnat} driver accepts the following commands
23041 (case insensitive):
23048 BIND to invoke @emph{gnatbind}
23051 CHOP to invoke @emph{gnatchop}
23054 CLEAN to invoke @emph{gnatclean}
23057 COMP or COMPILE to invoke the compiler
23060 FIND to invoke @emph{gnatfind}
23063 KR or KRUNCH to invoke @emph{gnatkr}
23066 LINK to invoke @emph{gnatlink}
23069 LS or LIST to invoke @emph{gnatls}
23072 MAKE to invoke @emph{gnatmake}
23075 NAME to invoke @emph{gnatname}
23078 PREP or PREPROCESS to invoke @emph{gnatprep}
23081 XREF to invoke @emph{gnatxref}
23084 Note that the command
23085 @emph{gnatmake -c -f -u} is used to invoke the compiler.
23087 On non-VMS platforms, between @emph{gnat} and the command, two
23088 special switches may be used:
23094 @emph{-v} to display the invocation of the tool.
23097 @emph{-dn} to prevent the @emph{gnat} driver from removing
23098 the temporary files it has created. These temporary files are
23099 configuration files and temporary file list files.
23102 The command may be followed by switches and arguments for the invoked
23108 $ gnat bind -C main.ali
23110 $ gnat chop foo.txt
23114 Switches may also be put in text files, one switch per line, and the text
23115 files may be specified with their path name preceded by '@@'.
23120 $ gnat bind @@args.txt main.ali
23124 In addition, for the following commands the project file related switches
23125 (@emph{-P}, @emph{-X} and @emph{-vPx}) may be used in addition to
23126 the switches of the invoking tool:
23152 For each of the following commands, there is optionally a corresponding
23153 package in the main project.
23160 package @cite{Binder} for command BIND (invoking @cite{gnatbind})
23163 package @cite{Compiler} for command COMP or COMPILE (invoking the compiler)
23166 package @cite{Cross_Reference} for command XREF (invoking @cite{gnatxref})
23169 package @cite{Finder} for command FIND (invoking @cite{gnatfind})
23172 package @cite{Gnatls} for command LS or LIST (invoking @cite{gnatls})
23175 package @cite{Linker} for command LINK (invoking @cite{gnatlink})
23178 Package @cite{Gnatls} has a unique attribute @cite{Switches},
23179 a simple variable with a string list value. It contains switches
23180 for the invocation of @cite{gnatls}.
23195 All other packages have two attribute @cite{Switches} and
23196 @cite{Default_Switches}.
23198 @cite{Switches} is an indexed attribute, indexed by the
23199 source file name, that has a string list value: the switches to be
23200 used when the tool corresponding to the package is invoked for the specific
23203 @cite{Default_Switches} is an attribute,
23204 indexed by the programming language that has a string list value.
23205 @cite{Default_Switches ("Ada")} contains the
23206 switches for the invocation of the tool corresponding
23207 to the package, except if a specific @cite{Switches} attribute
23208 is specified for the source file.
23215 for Source_Dirs use ("");
23223 package Compiler is
23224 for Default_Switches ("Ada")
23230 for Default_Switches ("Ada")
23236 for Default_Switches ("Ada")
23238 for Switches ("main.adb")
23245 for Default_Switches ("Ada")
23250 package Cross_Reference is
23251 for Default_Switches ("Ada")
23256 end Cross_Reference;
23261 With the above project file, commands such as
23266 $ gnat comp -Pproj main
23267 $ gnat ls -Pproj main
23268 $ gnat xref -Pproj main
23269 $ gnat bind -Pproj main.ali
23270 $ gnat link -Pproj main.ali
23274 will set up the environment properly and invoke the tool with the switches
23275 found in the package corresponding to the tool:
23276 @cite{Default_Switches ("Ada")} for all tools,
23277 except @cite{Switches ("main.adb")}
23278 for @cite{gnatlink}.
23281 @node GNAT Utility Programs,GNAT and Program Execution,Tools Supporting Project Files,Top
23282 @anchor{gnat_ugn/gnat_utility_programs doc}@anchor{1cf}@anchor{gnat_ugn/gnat_utility_programs gnat-utility-programs}@anchor{d}@anchor{gnat_ugn/gnat_utility_programs id1}@anchor{1d0}
23283 @chapter GNAT Utility Programs
23286 This chapter describes a number of utility programs:
23293 @ref{22,,The File Cleanup Utility gnatclean}
23296 @ref{23,,The GNAT Library Browser gnatls}
23299 @ref{24,,The Cross-Referencing Tools gnatxref and gnatfind}
23302 @ref{25,,The Ada to HTML Converter gnathtml}
23305 Other GNAT utilities are described elsewhere in this manual:
23311 @ref{5b,,Handling Arbitrary File Naming Conventions with gnatname}
23314 @ref{65,,File Name Krunching with gnatkr}
23317 @ref{38,,Renaming Files with gnatchop}
23320 @ref{19,,Preprocessing with gnatprep}
23324 * The File Cleanup Utility gnatclean::
23325 * The GNAT Library Browser gnatls::
23326 * The Cross-Referencing Tools gnatxref and gnatfind::
23327 * The Ada to HTML Converter gnathtml::
23331 @node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
23332 @anchor{gnat_ugn/gnat_utility_programs id2}@anchor{1d1}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{22}
23333 @section The File Cleanup Utility @emph{gnatclean}
23336 @geindex File cleanup tool
23340 @cite{gnatclean} is a tool that allows the deletion of files produced by the
23341 compiler, binder and linker, including ALI files, object files, tree files,
23342 expanded source files, library files, interface copy source files, binder
23343 generated files and executable files.
23346 * Running gnatclean::
23347 * Switches for gnatclean::
23351 @node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
23352 @anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{1d2}@anchor{gnat_ugn/gnat_utility_programs id3}@anchor{1d3}
23353 @subsection Running @cite{gnatclean}
23356 The @cite{gnatclean} command has the form:
23361 $ gnatclean switches `names`
23365 where @cite{names} is a list of source file names. Suffixes @code{.ads} and
23366 @code{adb} may be omitted. If a project file is specified using switch
23367 @code{-P}, then @cite{names} may be completely omitted.
23369 In normal mode, @cite{gnatclean} delete the files produced by the compiler and,
23370 if switch @cite{-c} is not specified, by the binder and
23371 the linker. In informative-only mode, specified by switch
23372 @cite{-n}, the list of files that would have been deleted in
23373 normal mode is listed, but no file is actually deleted.
23375 @node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
23376 @anchor{gnat_ugn/gnat_utility_programs id4}@anchor{1d4}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{1d5}
23377 @subsection Switches for @cite{gnatclean}
23380 @cite{gnatclean} recognizes the following switches:
23382 @geindex --version (gnatclean)
23387 @item @code{--version}
23389 Display Copyright and version, then exit disregarding all other options.
23392 @geindex --help (gnatclean)
23397 @item @code{--help}
23399 If @emph{--version} was not used, display usage, then exit disregarding
23402 @item @code{--subdirs=@emph{subdir}}
23404 Actual object directory of each project file is the subdirectory subdir of the
23405 object directory specified or defaulted in the project file.
23407 @item @code{--unchecked-shared-lib-imports}
23409 By default, shared library projects are not allowed to import static library
23410 projects. When this switch is used on the command line, this restriction is
23414 @geindex -c (gnatclean)
23421 Only attempt to delete the files produced by the compiler, not those produced
23422 by the binder or the linker. The files that are not to be deleted are library
23423 files, interface copy files, binder generated files and executable files.
23426 @geindex -D (gnatclean)
23431 @item @code{-D @emph{dir}}
23433 Indicate that ALI and object files should normally be found in directory @cite{dir}.
23436 @geindex -F (gnatclean)
23443 When using project files, if some errors or warnings are detected during
23444 parsing and verbose mode is not in effect (no use of switch
23445 -v), then error lines start with the full path name of the project
23446 file, rather than its simple file name.
23449 @geindex -h (gnatclean)
23456 Output a message explaining the usage of @cite{gnatclean}.
23459 @geindex -n (gnatclean)
23466 Informative-only mode. Do not delete any files. Output the list of the files
23467 that would have been deleted if this switch was not specified.
23470 @geindex -P (gnatclean)
23475 @item @code{-P@emph{project}}
23477 Use project file @cite{project}. Only one such switch can be used.
23478 When cleaning a project file, the files produced by the compilation of the
23479 immediate sources or inherited sources of the project files are to be
23480 deleted. This is not depending on the presence or not of executable names
23481 on the command line.
23484 @geindex -q (gnatclean)
23491 Quiet output. If there are no errors, do not output anything, except in
23492 verbose mode (switch -v) or in informative-only mode
23496 @geindex -r (gnatclean)
23503 When a project file is specified (using switch -P),
23504 clean all imported and extended project files, recursively. If this switch
23505 is not specified, only the files related to the main project file are to be
23506 deleted. This switch has no effect if no project file is specified.
23509 @geindex -v (gnatclean)
23519 @geindex -vP (gnatclean)
23524 @item @code{-vP@emph{x}}
23526 Indicates the verbosity of the parsing of GNAT project files.
23527 @ref{e6,,Switches Related to Project Files}.
23530 @geindex -X (gnatclean)
23535 @item @code{-X@emph{name}=@emph{value}}
23537 Indicates that external variable @cite{name} has the value @cite{value}.
23538 The Project Manager will use this value for occurrences of
23539 @cite{external(name)} when parsing the project file.
23540 @ref{e6,,Switches Related to Project Files}.
23543 @geindex -aO (gnatclean)
23548 @item @code{-aO@emph{dir}}
23550 When searching for ALI and object files, look in directory @cite{dir}.
23553 @geindex -I (gnatclean)
23558 @item @code{-I@emph{dir}}
23560 Equivalent to @code{-aO@emph{dir}}.
23563 @geindex -I- (gnatclean)
23565 @geindex Source files
23566 @geindex suppressing search
23573 Do not look for ALI or object files in the directory
23574 where @cite{gnatclean} was invoked.
23577 @node The GNAT Library Browser gnatls,The Cross-Referencing Tools gnatxref and gnatfind,The File Cleanup Utility gnatclean,GNAT Utility Programs
23578 @anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{23}@anchor{gnat_ugn/gnat_utility_programs id5}@anchor{1d6}
23579 @section The GNAT Library Browser @cite{gnatls}
23582 @geindex Library browser
23586 @cite{gnatls} is a tool that outputs information about compiled
23587 units. It gives the relationship between objects, unit names and source
23588 files. It can also be used to check the source dependencies of a unit
23589 as well as various characteristics.
23591 Note: to invoke @cite{gnatls} with a project file, use the @cite{gnat}
23592 driver (see @ref{122,,The GNAT Driver and Project Files}).
23596 * Switches for gnatls::
23597 * Example of gnatls Usage::
23601 @node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
23602 @anchor{gnat_ugn/gnat_utility_programs id6}@anchor{1d7}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{1d8}
23603 @subsection Running @cite{gnatls}
23606 The @cite{gnatls} command has the form
23611 $ gnatls switches `object_or_ali_file`
23615 The main argument is the list of object or @code{ali} files
23616 (see @ref{44,,The Ada Library Information Files})
23617 for which information is requested.
23619 In normal mode, without additional option, @cite{gnatls} produces a
23620 four-column listing. Each line represents information for a specific
23621 object. The first column gives the full path of the object, the second
23622 column gives the name of the principal unit in this object, the third
23623 column gives the status of the source and the fourth column gives the
23624 full path of the source representing this unit.
23625 Here is a simple example of use:
23631 ./demo1.o demo1 DIF demo1.adb
23632 ./demo2.o demo2 OK demo2.adb
23633 ./hello.o h1 OK hello.adb
23634 ./instr-child.o instr.child MOK instr-child.adb
23635 ./instr.o instr OK instr.adb
23636 ./tef.o tef DIF tef.adb
23637 ./text_io_example.o text_io_example OK text_io_example.adb
23638 ./tgef.o tgef DIF tgef.adb
23642 The first line can be interpreted as follows: the main unit which is
23644 object file @code{demo1.o} is demo1, whose main source is in
23645 @code{demo1.adb}. Furthermore, the version of the source used for the
23646 compilation of demo1 has been modified (DIF). Each source file has a status
23647 qualifier which can be:
23652 @item @emph{OK (unchanged)}
23654 The version of the source file used for the compilation of the
23655 specified unit corresponds exactly to the actual source file.
23657 @item @emph{MOK (slightly modified)}
23659 The version of the source file used for the compilation of the
23660 specified unit differs from the actual source file but not enough to
23661 require recompilation. If you use gnatmake with the qualifier
23662 @emph{-m (minimal recompilation)}, a file marked
23663 MOK will not be recompiled.
23665 @item @emph{DIF (modified)}
23667 No version of the source found on the path corresponds to the source
23668 used to build this object.
23670 @item @emph{??? (file not found)}
23672 No source file was found for this unit.
23674 @item @emph{HID (hidden, unchanged version not first on PATH)}
23676 The version of the source that corresponds exactly to the source used
23677 for compilation has been found on the path but it is hidden by another
23678 version of the same source that has been modified.
23681 @node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
23682 @anchor{gnat_ugn/gnat_utility_programs id7}@anchor{1d9}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{1da}
23683 @subsection Switches for @cite{gnatls}
23686 @cite{gnatls} recognizes the following switches:
23688 @geindex --version (gnatls)
23693 @item @code{--version}
23695 Display Copyright and version, then exit disregarding all other options.
23698 @geindex --help (gnatls)
23703 @item @code{*--help}
23705 If @emph{--version} was not used, display usage, then exit disregarding
23709 @geindex -a (gnatls)
23716 Consider all units, including those of the predefined Ada library.
23717 Especially useful with @emph{-d}.
23720 @geindex -d (gnatls)
23727 List sources from which specified units depend on.
23730 @geindex -h (gnatls)
23737 Output the list of options.
23740 @geindex -o (gnatls)
23747 Only output information about object files.
23750 @geindex -s (gnatls)
23757 Only output information about source files.
23760 @geindex -u (gnatls)
23767 Only output information about compilation units.
23770 @geindex -files (gnatls)
23775 @item @code{-files=@emph{file}}
23777 Take as arguments the files listed in text file @cite{file}.
23778 Text file @cite{file} may contain empty lines that are ignored.
23779 Each nonempty line should contain the name of an existing file.
23780 Several such switches may be specified simultaneously.
23783 @geindex -aO (gnatls)
23785 @geindex -aI (gnatls)
23787 @geindex -I (gnatls)
23789 @geindex -I- (gnatls)
23794 @item @code{-aO@emph{dir}}, @code{-aI@emph{dir}}, @code{-I@emph{dir}}, @code{-I-}, @code{-nostdinc}
23796 Source path manipulation. Same meaning as the equivalent @emph{gnatmake}
23797 flags (@ref{e2,,Switches for gnatmake}).
23800 @geindex -aP (gnatls)
23805 @item @code{-aP@emph{dir}}
23807 Add @cite{dir} at the beginning of the project search dir.
23810 @geindex --RTS (gnatls)
23815 @item @code{--RTS=@emph{rts-path}`}
23817 Specifies the default location of the runtime library. Same meaning as the
23818 equivalent @emph{gnatmake} flag (@ref{e2,,Switches for gnatmake}).
23821 @geindex -v (gnatls)
23828 Verbose mode. Output the complete source, object and project paths. Do not use
23829 the default column layout but instead use long format giving as much as
23830 information possible on each requested units, including special
23831 characteristics such as:
23837 @emph{Preelaborable}: The unit is preelaborable in the Ada sense.
23840 @emph{No_Elab_Code}: No elaboration code has been produced by the compiler for this unit.
23843 @emph{Pure}: The unit is pure in the Ada sense.
23846 @emph{Elaborate_Body}: The unit contains a pragma Elaborate_Body.
23849 @emph{Remote_Types}: The unit contains a pragma Remote_Types.
23852 @emph{Shared_Passive}: The unit contains a pragma Shared_Passive.
23855 @emph{Predefined}: This unit is part of the predefined environment and cannot be modified
23859 @emph{Remote_Call_Interface}: The unit contains a pragma Remote_Call_Interface.
23863 @node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
23864 @anchor{gnat_ugn/gnat_utility_programs id8}@anchor{1db}@anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{1dc}
23865 @subsection Example of @cite{gnatls} Usage
23868 Example of using the verbose switch. Note how the source and
23869 object paths are affected by the -I switch.
23874 $ gnatls -v -I.. demo1.o
23876 GNATLS 5.03w (20041123-34)
23877 Copyright 1997-2004 Free Software Foundation, Inc.
23879 Source Search Path:
23880 <Current_Directory>
23882 /home/comar/local/adainclude/
23884 Object Search Path:
23885 <Current_Directory>
23887 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
23889 Project Search Path:
23890 <Current_Directory>
23891 /home/comar/local/lib/gnat/
23896 Kind => subprogram body
23897 Flags => No_Elab_Code
23898 Source => demo1.adb modified
23902 The following is an example of use of the dependency list.
23903 Note the use of the -s switch
23904 which gives a straight list of source files. This can be useful for
23905 building specialized scripts.
23910 $ gnatls -d demo2.o
23911 ./demo2.o demo2 OK demo2.adb
23917 $ gnatls -d -s -a demo1.o
23919 /home/comar/local/adainclude/ada.ads
23920 /home/comar/local/adainclude/a-finali.ads
23921 /home/comar/local/adainclude/a-filico.ads
23922 /home/comar/local/adainclude/a-stream.ads
23923 /home/comar/local/adainclude/a-tags.ads
23926 /home/comar/local/adainclude/gnat.ads
23927 /home/comar/local/adainclude/g-io.ads
23929 /home/comar/local/adainclude/system.ads
23930 /home/comar/local/adainclude/s-exctab.ads
23931 /home/comar/local/adainclude/s-finimp.ads
23932 /home/comar/local/adainclude/s-finroo.ads
23933 /home/comar/local/adainclude/s-secsta.ads
23934 /home/comar/local/adainclude/s-stalib.ads
23935 /home/comar/local/adainclude/s-stoele.ads
23936 /home/comar/local/adainclude/s-stratt.ads
23937 /home/comar/local/adainclude/s-tasoli.ads
23938 /home/comar/local/adainclude/s-unstyp.ads
23939 /home/comar/local/adainclude/unchconv.ads
23943 @node The Cross-Referencing Tools gnatxref and gnatfind,The Ada to HTML Converter gnathtml,The GNAT Library Browser gnatls,GNAT Utility Programs
23944 @anchor{gnat_ugn/gnat_utility_programs the-cross-referencing-tools-gnatxref-and-gnatfind}@anchor{24}@anchor{gnat_ugn/gnat_utility_programs id9}@anchor{1dd}
23945 @section The Cross-Referencing Tools @cite{gnatxref} and @cite{gnatfind}
23952 The compiler generates cross-referencing information (unless
23953 you set the @code{-gnatx} switch), which are saved in the @code{.ali} files.
23954 This information indicates where in the source each entity is declared and
23955 referenced. Note that entities in package Standard are not included, but
23956 entities in all other predefined units are included in the output.
23958 Before using any of these two tools, you need to compile successfully your
23959 application, so that GNAT gets a chance to generate the cross-referencing
23962 The two tools @cite{gnatxref} and @cite{gnatfind} take advantage of this
23963 information to provide the user with the capability to easily locate the
23964 declaration and references to an entity. These tools are quite similar,
23965 the difference being that @cite{gnatfind} is intended for locating
23966 definitions and/or references to a specified entity or entities, whereas
23967 @cite{gnatxref} is oriented to generating a full report of all
23970 To use these tools, you must not compile your application using the
23971 @emph{-gnatx} switch on the @emph{gnatmake} command line
23972 (see @ref{1d,,Building with gnatmake}). Otherwise, cross-referencing
23973 information will not be generated.
23975 Note: to invoke @cite{gnatxref} or @cite{gnatfind} with a project file,
23976 use the @cite{gnat} driver (see @ref{122,,The GNAT Driver and Project Files}).
23979 * gnatxref Switches::
23980 * gnatfind Switches::
23981 * Project Files for gnatxref and gnatfind::
23982 * Regular Expressions in gnatfind and gnatxref::
23983 * Examples of gnatxref Usage::
23984 * Examples of gnatfind Usage::
23988 @node gnatxref Switches,gnatfind Switches,,The Cross-Referencing Tools gnatxref and gnatfind
23989 @anchor{gnat_ugn/gnat_utility_programs id10}@anchor{1de}@anchor{gnat_ugn/gnat_utility_programs gnatxref-switches}@anchor{1df}
23990 @subsection @cite{gnatxref} Switches
23993 The command invocation for @cite{gnatxref} is:
23998 $ gnatxref [`switches`] `sourcefile1` [`sourcefile2` ...]
24007 @item @emph{sourcefile1} [, @emph{sourcefile2} ...]
24009 identify the source files for which a report is to be generated. The
24010 'with'ed units will be processed too. You must provide at least one file.
24012 These file names are considered to be regular expressions, so for instance
24013 specifying @code{source*.adb} is the same as giving every file in the current
24014 directory whose name starts with @code{source} and whose extension is
24017 You shouldn't specify any directory name, just base names. @emph{gnatxref}
24018 and @emph{gnatfind} will be able to locate these files by themselves using
24019 the source path. If you specify directories, no result is produced.
24022 The following switches are available for @emph{gnatxref}:
24024 @geindex --version (gnatxref)
24029 @item @code{-version}
24031 Display Copyright and version, then exit disregarding all other options.
24034 @geindex --help (gnatxref)
24041 If @emph{--version} was not used, display usage, then exit disregarding
24045 @geindex -a (gnatxref)
24052 If this switch is present, @cite{gnatfind} and @cite{gnatxref} will parse
24053 the read-only files found in the library search path. Otherwise, these files
24054 will be ignored. This option can be used to protect Gnat sources or your own
24055 libraries from being parsed, thus making @cite{gnatfind} and @cite{gnatxref}
24056 much faster, and their output much smaller. Read-only here refers to access
24057 or permissions status in the file system for the current user.
24060 @geindex -aIDIR (gnatxref)
24065 @item @code{aI@emph{DIR}}
24067 When looking for source files also look in directory DIR. The order in which
24068 source file search is undertaken is the same as for @emph{gnatmake}.
24071 @geindex -aODIR (gnatxref)
24076 @item @code{aO@emph{DIR}}
24078 When searching for library and object files, look in directory
24079 DIR. The order in which library files are searched is the same as for
24083 @geindex -nostdinc (gnatxref)
24088 @item @code{nostdinc}
24090 Do not look for sources in the system default directory.
24093 @geindex -nostdlib (gnatxref)
24098 @item @code{nostdlib}
24100 Do not look for library files in the system default directory.
24103 @geindex --ext (gnatxref)
24108 @item @code{-ext=@emph{extension}}
24110 Specify an alternate ali file extension. The default is @cite{ali} and other
24111 extensions (e.g. @cite{gli} for C/C++ sources when using @emph{-fdump-xref})
24112 may be specified via this switch. Note that if this switch overrides the
24113 default, which means that only the new extension will be considered.
24116 @geindex --RTS (gnatxref)
24121 @item @code{-RTS=@emph{rts-path}}
24123 Specifies the default location of the runtime library. Same meaning as the
24124 equivalent @emph{gnatmake} flag (@ref{e2,,Switches for gnatmake}).
24127 @geindex -d (gnatxref)
24134 If this switch is set @cite{gnatxref} will output the parent type
24135 reference for each matching derived types.
24138 @geindex -f (gnatxref)
24145 If this switch is set, the output file names will be preceded by their
24146 directory (if the file was found in the search path). If this switch is
24147 not set, the directory will not be printed.
24150 @geindex -g (gnatxref)
24157 If this switch is set, information is output only for library-level
24158 entities, ignoring local entities. The use of this switch may accelerate
24159 @cite{gnatfind} and @cite{gnatxref}.
24162 @geindex -IDIR (gnatxref)
24167 @item @code{I@emph{DIR}}
24169 Equivalent to @code{-aODIR -aIDIR}.
24172 @geindex -pFILE (gnatxref)
24177 @item @code{p@emph{FILE}}
24179 Specify a project file to use @ref{b,,GNAT Project Manager}.
24180 If you need to use the @code{.gpr}
24181 project files, you should use gnatxref through the GNAT driver
24182 (@emph{gnat xref -Pproject}).
24184 By default, @cite{gnatxref} and @cite{gnatfind} will try to locate a
24185 project file in the current directory.
24187 If a project file is either specified or found by the tools, then the content
24188 of the source directory and object directory lines are added as if they
24189 had been specified respectively by @code{-aI}
24194 Output only unused symbols. This may be really useful if you give your
24195 main compilation unit on the command line, as @cite{gnatxref} will then
24196 display every unused entity and 'with'ed package.
24200 Instead of producing the default output, @cite{gnatxref} will generate a
24201 @code{tags} file that can be used by vi. For examples how to use this
24202 feature, see @ref{1e0,,Examples of gnatxref Usage}. The tags file is output
24203 to the standard output, thus you will have to redirect it to a file.
24206 All these switches may be in any order on the command line, and may even
24207 appear after the file names. They need not be separated by spaces, thus
24208 you can say @code{gnatxref -ag} instead of @code{gnatxref -a -g}.
24210 @node gnatfind Switches,Project Files for gnatxref and gnatfind,gnatxref Switches,The Cross-Referencing Tools gnatxref and gnatfind
24211 @anchor{gnat_ugn/gnat_utility_programs id11}@anchor{1e1}@anchor{gnat_ugn/gnat_utility_programs gnatfind-switches}@anchor{1e2}
24212 @subsection @cite{gnatfind} Switches
24215 The command invocation for @cite{gnatfind} is:
24220 $ gnatfind [`switches`] `pattern`[:`sourcefile`[:`line`[:`column`]]]
24221 [`file1` `file2` ...]
24225 with the following iterpretation of the command arguments:
24230 @item @emph{pattern}
24232 An entity will be output only if it matches the regular expression found
24233 in @cite{pattern}, see @ref{1e3,,Regular Expressions in gnatfind and gnatxref}.
24235 Omitting the pattern is equivalent to specifying @code{*}, which
24236 will match any entity. Note that if you do not provide a pattern, you
24237 have to provide both a sourcefile and a line.
24239 Entity names are given in Latin-1, with uppercase/lowercase equivalence
24240 for matching purposes. At the current time there is no support for
24241 8-bit codes other than Latin-1, or for wide characters in identifiers.
24243 @item @emph{sourcefile}
24245 @cite{gnatfind} will look for references, bodies or declarations
24246 of symbols referenced in @code{sourcefile}, at line @cite{line}
24247 and column @cite{column}. See @ref{1e4,,Examples of gnatfind Usage}
24248 for syntax examples.
24252 A decimal integer identifying the line number containing
24253 the reference to the entity (or entities) to be located.
24255 @item @emph{column}
24257 A decimal integer identifying the exact location on the
24258 line of the first character of the identifier for the
24259 entity reference. Columns are numbered from 1.
24261 @item @emph{file1 file2 ...}
24263 The search will be restricted to these source files. If none are given, then
24264 the search will be conducted for every library file in the search path.
24265 These files must appear only after the pattern or sourcefile.
24267 These file names are considered to be regular expressions, so for instance
24268 specifying @code{source*.adb} is the same as giving every file in the current
24269 directory whose name starts with @code{source} and whose extension is
24272 The location of the spec of the entity will always be displayed, even if it
24273 isn't in one of @code{file1}, @code{file2}, ... The
24274 occurrences of the entity in the separate units of the ones given on the
24275 command line will also be displayed.
24277 Note that if you specify at least one file in this part, @cite{gnatfind} may
24278 sometimes not be able to find the body of the subprograms.
24281 At least one of 'sourcefile' or 'pattern' has to be present on
24284 The following switches are available:
24286 @geindex --version (gnatfind)
24291 @item @code{--version}
24293 Display Copyright and version, then exit disregarding all other options.
24296 @geindex --help (gnatfind)
24303 If @emph{--version} was not used, display usage, then exit disregarding
24307 @geindex -a (gnatfind)
24314 If this switch is present, @cite{gnatfind} and @cite{gnatxref} will parse
24315 the read-only files found in the library search path. Otherwise, these files
24316 will be ignored. This option can be used to protect Gnat sources or your own
24317 libraries from being parsed, thus making @cite{gnatfind} and @cite{gnatxref}
24318 much faster, and their output much smaller. Read-only here refers to access
24319 or permission status in the file system for the current user.
24322 @geindex -aIDIR (gnatfind)
24327 @item @code{aI@emph{DIR}}
24329 When looking for source files also look in directory DIR. The order in which
24330 source file search is undertaken is the same as for @emph{gnatmake}.
24333 @geindex -aODIR (gnatfind)
24338 @item @code{aO@emph{DIR}}
24340 When searching for library and object files, look in directory
24341 DIR. The order in which library files are searched is the same as for
24345 @geindex -nostdinc (gnatfind)
24350 @item @code{nostdinc}
24352 Do not look for sources in the system default directory.
24355 @geindex -nostdlib (gnatfind)
24360 @item @code{nostdlib}
24362 Do not look for library files in the system default directory.
24365 @geindex --ext (gnatfind)
24370 @item @code{-ext=@emph{extension}}
24372 Specify an alternate ali file extension. The default is @cite{ali} and other
24373 extensions (e.g. @cite{gli} for C/C++ sources when using @emph{-fdump-xref})
24374 may be specified via this switch. Note that if this switch overrides the
24375 default, which means that only the new extension will be considered.
24378 @geindex --RTS (gnatfind)
24383 @item @code{-RTS=@emph{rts-path}}
24385 Specifies the default location of the runtime library. Same meaning as the
24386 equivalent @emph{gnatmake} flag (@ref{e2,,Switches for gnatmake}).
24389 @geindex -d (gnatfind)
24396 If this switch is set, then @cite{gnatfind} will output the parent type
24397 reference for each matching derived types.
24400 @geindex -e (gnatfind)
24407 By default, @cite{gnatfind} accept the simple regular expression set for
24408 @cite{pattern}. If this switch is set, then the pattern will be
24409 considered as full Unix-style regular expression.
24412 @geindex -f (gnatfind)
24419 If this switch is set, the output file names will be preceded by their
24420 directory (if the file was found in the search path). If this switch is
24421 not set, the directory will not be printed.
24424 @geindex -g (gnatfind)
24431 If this switch is set, information is output only for library-level
24432 entities, ignoring local entities. The use of this switch may accelerate
24433 @cite{gnatfind} and @cite{gnatxref}.
24436 @geindex -IDIR (gnatfind)
24441 @item @code{I@emph{DIR}}
24443 Equivalent to @code{-aODIR -aIDIR}.
24446 @geindex -pFILE (gnatfind)
24451 @item @code{p@emph{FILE}}
24453 Specify a project file (@ref{b,,GNAT Project Manager}) to use.
24454 By default, @cite{gnatxref} and @cite{gnatfind} will try to locate a
24455 project file in the current directory.
24457 If a project file is either specified or found by the tools, then the content
24458 of the source directory and object directory lines are added as if they
24459 had been specified respectively by @code{-aI} and
24463 @geindex -r (gnatfind)
24470 By default, @cite{gnatfind} will output only the information about the
24471 declaration, body or type completion of the entities. If this switch is
24472 set, the @cite{gnatfind} will locate every reference to the entities in
24473 the files specified on the command line (or in every file in the search
24474 path if no file is given on the command line).
24477 @geindex -s (gnatfind)
24484 If this switch is set, then @cite{gnatfind} will output the content
24485 of the Ada source file lines were the entity was found.
24488 @geindex -t (gnatfind)
24495 If this switch is set, then @cite{gnatfind} will output the type hierarchy for
24496 the specified type. It act like -d option but recursively from parent
24497 type to parent type. When this switch is set it is not possible to
24498 specify more than one file.
24501 All these switches may be in any order on the command line, and may even
24502 appear after the file names. They need not be separated by spaces, thus
24503 you can say @code{gnatxref -ag} instead of
24504 @code{gnatxref -a -g}.
24506 As stated previously, gnatfind will search in every directory in the
24507 search path. You can force it to look only in the current directory if
24508 you specify @cite{*} at the end of the command line.
24510 @node Project Files for gnatxref and gnatfind,Regular Expressions in gnatfind and gnatxref,gnatfind Switches,The Cross-Referencing Tools gnatxref and gnatfind
24511 @anchor{gnat_ugn/gnat_utility_programs project-files-for-gnatxref-and-gnatfind}@anchor{1e5}@anchor{gnat_ugn/gnat_utility_programs id12}@anchor{1e6}
24512 @subsection Project Files for @emph{gnatxref} and @emph{gnatfind}
24515 Project files allow a programmer to specify how to compile its
24516 application, where to find sources, etc. These files are used
24517 primarily by GPS, but they can also be used
24518 by the two tools @cite{gnatxref} and @cite{gnatfind}.
24520 A project file name must end with @code{.gpr}. If a single one is
24521 present in the current directory, then @cite{gnatxref} and @cite{gnatfind} will
24522 extract the information from it. If multiple project files are found, none of
24523 them is read, and you have to use the @code{-p} switch to specify the one
24526 The following lines can be included, even though most of them have default
24527 values which can be used in most cases.
24528 The lines can be entered in any order in the file.
24529 Except for @code{src_dir} and @code{obj_dir}, you can only have one instance of
24530 each line. If you have multiple instances, only the last one is taken into
24540 @item @emph{src_dir=DIR}
24542 [default: @cite{"./"}].
24543 Specifies a directory where to look for source files. Multiple @cite{src_dir}
24544 lines can be specified and they will be searched in the order they
24552 @item @emph{obj_dir=DIR}
24554 [default: @cite{"./"}].
24555 Specifies a directory where to look for object and library files. Multiple
24556 @cite{obj_dir} lines can be specified, and they will be searched in the order
24564 @item @emph{comp_opt=SWITCHES}
24566 [default: @cite{""}].
24567 Creates a variable which can be referred to subsequently by using
24568 the @cite{$@{comp_opt@}} notation. This is intended to store the default
24569 switches given to @emph{gnatmake} and @emph{gcc}.
24576 @item @emph{bind_opt=SWITCHES}
24578 [default: @cite{""}].
24579 Creates a variable which can be referred to subsequently by using
24580 the @code{$@emph{bind_opt}} notation. This is intended to store the default
24581 switches given to @emph{gnatbind}.
24588 @item @emph{link_opt=SWITCHES}
24590 [default: @cite{""}].
24591 Creates a variable which can be referred to subsequently by using
24592 the @code{$@emph{link_opt}} notation. This is intended to store the default
24593 switches given to @emph{gnatlink}.
24600 @item @emph{main=EXECUTABLE}
24602 [default: @cite{""}].
24603 Specifies the name of the executable for the application. This variable can
24604 be referred to in the following lines by using the @code{@emph{$@{main}} notation.
24611 @item @emph{comp_cmd=COMMAND}
24613 [default: @cite{"gcc -c -I$@{src_dir@} -g -gnatq"}].
24614 Specifies the command used to compile a single file in the application.
24621 @item @emph{make_cmd=COMMAND}
24623 [default: @cite{"gnatmake $@{main@} -aI$@{src_dir@} -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@} -bargs $@{bind_opt@} -largs $@{link_opt@}"}].
24624 Specifies the command used to recompile the whole application.
24631 @item @emph{run_cmd=COMMAND}
24633 [default: @cite{"$@{main@}"}].
24634 Specifies the command used to run the application.
24641 @item @emph{debug_cmd=COMMAND}
24643 [default: @cite{"gdb $@{main@}"}].
24644 Specifies the command used to debug the application
24648 @emph{gnatxref} and @emph{gnatfind} only take into account the
24649 @cite{src_dir} and @cite{obj_dir} lines, and ignore the others.
24651 @node Regular Expressions in gnatfind and gnatxref,Examples of gnatxref Usage,Project Files for gnatxref and gnatfind,The Cross-Referencing Tools gnatxref and gnatfind
24652 @anchor{gnat_ugn/gnat_utility_programs id13}@anchor{1e7}@anchor{gnat_ugn/gnat_utility_programs regular-expressions-in-gnatfind-and-gnatxref}@anchor{1e3}
24653 @subsection Regular Expressions in @cite{gnatfind} and @cite{gnatxref}
24656 As specified in the section about @emph{gnatfind}, the pattern can be a
24657 regular expression. Two kinds of regular expressions
24667 @item @emph{Globbing pattern}
24669 These are the most common regular expression. They are the same as are
24670 generally used in a Unix shell command line, or in a DOS session.
24672 Here is a more formal grammar:
24676 term ::= elmt -- matches elmt
24677 term ::= elmt elmt -- concatenation (elmt then elmt)
24678 term ::= * -- any string of 0 or more characters
24679 term ::= ? -- matches any character
24680 term ::= [char @{char@}] -- matches any character listed
24681 term ::= [char - char] -- matches any character in range
24689 @item @emph{Full regular expression}
24691 The second set of regular expressions is much more powerful. This is the
24692 type of regular expressions recognized by utilities such as @code{grep}.
24694 The following is the form of a regular expression, expressed in same BNF
24695 style as is found in the Ada Reference Manual:
24698 regexp ::= term @{| term@} -- alternation (term or term ...)
24700 term ::= item @{item@} -- concatenation (item then item)
24702 item ::= elmt -- match elmt
24703 item ::= elmt * -- zero or more elmt's
24704 item ::= elmt + -- one or more elmt's
24705 item ::= elmt ? -- matches elmt or nothing
24707 elmt ::= nschar -- matches given character
24708 elmt ::= [nschar @{nschar@}] -- matches any character listed
24709 elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
24710 elmt ::= [char - char] -- matches chars in given range
24711 elmt ::= \\ char -- matches given character
24712 elmt ::= . -- matches any single character
24713 elmt ::= ( regexp ) -- parens used for grouping
24715 char ::= any character, including special characters
24716 nschar ::= any character except ()[].*+?^
24719 Here are a few examples:
24726 @item @code{abcde|fghi}
24728 will match any of the two strings @code{abcde} and @code{fghi},
24732 will match any string like @code{abd}, @code{abcd}, @code{abccd},
24733 @code{abcccd}, and so on,
24735 @item @code{[a-z]+}
24737 will match any string which has only lowercase characters in it (and at
24738 least one character.
24744 @node Examples of gnatxref Usage,Examples of gnatfind Usage,Regular Expressions in gnatfind and gnatxref,The Cross-Referencing Tools gnatxref and gnatfind
24745 @anchor{gnat_ugn/gnat_utility_programs examples-of-gnatxref-usage}@anchor{1e0}@anchor{gnat_ugn/gnat_utility_programs id14}@anchor{1e8}
24746 @subsection Examples of @cite{gnatxref} Usage
24751 * Using gnatxref with vi::
24755 @node General Usage,Using gnatxref with vi,,Examples of gnatxref Usage
24756 @anchor{gnat_ugn/gnat_utility_programs general-usage}@anchor{1e9}
24757 @subsubsection General Usage
24760 For the following examples, we will consider the following units:
24768 3: procedure Foo (B : in Integer);
24775 1: package body Main is
24776 2: procedure Foo (B : in Integer) is
24787 2: procedure Print (B : Integer);
24792 The first thing to do is to recompile your application (for instance, in
24793 that case just by doing a @code{gnatmake main}, so that GNAT generates
24794 the cross-referencing information.
24795 You can then issue any of the following commands:
24803 @code{gnatxref main.adb}
24804 @cite{gnatxref} generates cross-reference information for main.adb
24805 and every unit 'with'ed by main.adb.
24807 The output would be:
24815 Decl: main.ads 3:20
24816 Body: main.adb 2:20
24817 Ref: main.adb 4:13 5:13 6:19
24820 Ref: main.adb 6:8 7:8
24830 Decl: main.ads 3:15
24831 Body: main.adb 2:15
24834 Body: main.adb 1:14
24837 Ref: main.adb 6:12 7:12
24841 This shows that the entity @cite{Main} is declared in main.ads, line 2, column 9,
24842 its body is in main.adb, line 1, column 14 and is not referenced any where.
24844 The entity @cite{Print} is declared in bar.ads, line 2, column 15 and it
24845 is referenced in main.adb, line 6 column 12 and line 7 column 12.
24848 @code{gnatxref package1.adb package2.ads}
24849 @cite{gnatxref} will generates cross-reference information for
24850 package1.adb, package2.ads and any other package 'with'ed by any
24855 @node Using gnatxref with vi,,General Usage,Examples of gnatxref Usage
24856 @anchor{gnat_ugn/gnat_utility_programs using-gnatxref-with-vi}@anchor{1ea}
24857 @subsubsection Using gnatxref with vi
24860 @cite{gnatxref} can generate a tags file output, which can be used
24861 directly from @emph{vi}. Note that the standard version of @emph{vi}
24862 will not work properly with overloaded symbols. Consider using another
24863 free implementation of @emph{vi}, such as @emph{vim}.
24868 $ gnatxref -v gnatfind.adb > tags
24872 The following command will generate the tags file for @cite{gnatfind} itself
24873 (if the sources are in the search path!):
24878 $ gnatxref -v gnatfind.adb > tags
24882 From @emph{vi}, you can then use the command @code{:tag @emph{entity}}
24883 (replacing @cite{entity} by whatever you are looking for), and vi will
24884 display a new file with the corresponding declaration of entity.
24886 @node Examples of gnatfind Usage,,Examples of gnatxref Usage,The Cross-Referencing Tools gnatxref and gnatfind
24887 @anchor{gnat_ugn/gnat_utility_programs id15}@anchor{1eb}@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatfind-usage}@anchor{1e4}
24888 @subsection Examples of @cite{gnatfind} Usage
24895 @code{gnatfind -f xyz:main.adb}
24896 Find declarations for all entities xyz referenced at least once in
24897 main.adb. The references are search in every library file in the search
24900 The directories will be printed as well (as the @code{-f}
24903 The output will look like:
24908 directory/main.ads:106:14: xyz <= declaration
24909 directory/main.adb:24:10: xyz <= body
24910 directory/foo.ads:45:23: xyz <= declaration
24914 I.e., one of the entities xyz found in main.adb is declared at
24915 line 12 of main.ads (and its body is in main.adb), and another one is
24916 declared at line 45 of foo.ads
24919 @code{gnatfind -fs xyz:main.adb}
24920 This is the same command as the previous one, but @cite{gnatfind} will
24921 display the content of the Ada source file lines.
24923 The output will look like:
24926 directory/main.ads:106:14: xyz <= declaration
24928 directory/main.adb:24:10: xyz <= body
24930 directory/foo.ads:45:23: xyz <= declaration
24934 This can make it easier to find exactly the location your are looking
24938 @code{gnatfind -r "*x*":main.ads:123 foo.adb}
24939 Find references to all entities containing an x that are
24940 referenced on line 123 of main.ads.
24941 The references will be searched only in main.ads and foo.adb.
24944 @code{gnatfind main.ads:123}
24945 Find declarations and bodies for all entities that are referenced on
24946 line 123 of main.ads.
24948 This is the same as @code{gnatfind "*":main.adb:123`}
24951 @code{gnatfind mydir/main.adb:123:45}
24952 Find the declaration for the entity referenced at column 45 in
24953 line 123 of file main.adb in directory mydir. Note that it
24954 is usual to omit the identifier name when the column is given,
24955 since the column position identifies a unique reference.
24957 The column has to be the beginning of the identifier, and should not
24958 point to any character in the middle of the identifier.
24961 @node The Ada to HTML Converter gnathtml,,The Cross-Referencing Tools gnatxref and gnatfind,GNAT Utility Programs
24962 @anchor{gnat_ugn/gnat_utility_programs the-ada-to-html-converter-gnathtml}@anchor{25}@anchor{gnat_ugn/gnat_utility_programs id16}@anchor{1ec}
24963 @section The Ada to HTML Converter @cite{gnathtml}
24968 @emph{gnathtml} is a Perl script that allows Ada source files to be browsed using
24969 standard Web browsers. For installation information, see @ref{1ed,,Installing gnathtml}.
24971 Ada reserved keywords are highlighted in a bold font and Ada comments in
24972 a blue font. Unless your program was compiled with the gcc @emph{-gnatx}
24973 switch to suppress the generation of cross-referencing information, user
24974 defined variables and types will appear in a different color; you will
24975 be able to click on any identifier and go to its declaration.
24978 * Invoking gnathtml::
24979 * Installing gnathtml::
24983 @node Invoking gnathtml,Installing gnathtml,,The Ada to HTML Converter gnathtml
24984 @anchor{gnat_ugn/gnat_utility_programs invoking-gnathtml}@anchor{1ee}@anchor{gnat_ugn/gnat_utility_programs id17}@anchor{1ef}
24985 @subsection Invoking @emph{gnathtml}
24988 The command line is as follows:
24993 $ perl gnathtml.pl [`switches`] `ada-files`
24997 You can specify as many Ada files as you want. @cite{gnathtml} will generate
24998 an html file for every ada file, and a global file called @code{index.htm}.
24999 This file is an index of every identifier defined in the files.
25001 The following switches are available:
25003 @geindex -83 (gnathtml)
25010 Only the Ada 83 subset of keywords will be highlighted.
25013 @geindex -cc (gnathtml)
25018 @item @code{cc @emph{color}}
25020 This option allows you to change the color used for comments. The default
25021 value is green. The color argument can be any name accepted by html.
25024 @geindex -d (gnathtml)
25031 If the Ada files depend on some other files (for instance through
25032 @cite{with} clauses, the latter files will also be converted to html.
25033 Only the files in the user project will be converted to html, not the files
25034 in the run-time library itself.
25037 @geindex -D (gnathtml)
25044 This command is the same as @emph{-d} above, but @emph{gnathtml} will
25045 also look for files in the run-time library, and generate html files for them.
25048 @geindex -ext (gnathtml)
25053 @item @code{ext @emph{extension}}
25055 This option allows you to change the extension of the generated HTML files.
25056 If you do not specify an extension, it will default to @code{htm}.
25059 @geindex -f (gnathtml)
25066 By default, gnathtml will generate html links only for global entities
25067 ('with'ed units, global variables and types,...). If you specify
25068 @emph{-f} on the command line, then links will be generated for local
25072 @geindex -l (gnathtml)
25077 @item @code{l @emph{number}}
25079 If this switch is provided and @cite{number} is not 0, then
25080 @cite{gnathtml} will number the html files every @cite{number} line.
25083 @geindex -I (gnathtml)
25088 @item @code{I @emph{dir}}
25090 Specify a directory to search for library files (@code{.ALI} files) and
25091 source files. You can provide several -I switches on the command line,
25092 and the directories will be parsed in the order of the command line.
25095 @geindex -o (gnathtml)
25100 @item @code{o @emph{dir}}
25102 Specify the output directory for html files. By default, gnathtml will
25103 saved the generated html files in a subdirectory named @code{html/}.
25106 @geindex -p (gnathtml)
25111 @item @code{p @emph{file}}
25113 If you are using Emacs and the most recent Emacs Ada mode, which provides
25114 a full Integrated Development Environment for compiling, checking,
25115 running and debugging applications, you may use @code{.gpr} files
25116 to give the directories where Emacs can find sources and object files.
25118 Using this switch, you can tell gnathtml to use these files.
25119 This allows you to get an html version of your application, even if it
25120 is spread over multiple directories.
25123 @geindex -sc (gnathtml)
25128 @item @code{sc @emph{color}}
25130 This switch allows you to change the color used for symbol
25132 The default value is red. The color argument can be any name accepted by html.
25135 @geindex -t (gnathtml)
25140 @item @code{t @emph{file}}
25142 This switch provides the name of a file. This file contains a list of
25143 file names to be converted, and the effect is exactly as though they had
25144 appeared explicitly on the command line. This
25145 is the recommended way to work around the command line length limit on some
25149 @node Installing gnathtml,,Invoking gnathtml,The Ada to HTML Converter gnathtml
25150 @anchor{gnat_ugn/gnat_utility_programs installing-gnathtml}@anchor{1ed}@anchor{gnat_ugn/gnat_utility_programs id18}@anchor{1f0}
25151 @subsection Installing @cite{gnathtml}
25154 @cite{Perl} needs to be installed on your machine to run this script.
25155 @cite{Perl} is freely available for almost every architecture and
25156 operating system via the Internet.
25158 On Unix systems, you may want to modify the first line of the script
25159 @cite{gnathtml}, to explicitly specify where Perl
25160 is located. The syntax of this line is:
25165 #!full_path_name_to_perl
25169 Alternatively, you may run the script using the following command line:
25174 $ perl gnathtml.pl [`switches`] `files`
25178 @c -- +---------------------------------------------------------------------+
25180 @c -- | The following sections are present only in the PRO and GPL editions |
25182 @c -- +---------------------------------------------------------------------+
25190 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
25192 @node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
25193 @anchor{gnat_ugn/gnat_and_program_execution gnat-and-program-execution}@anchor{e}@anchor{gnat_ugn/gnat_and_program_execution doc}@anchor{1f1}@anchor{gnat_ugn/gnat_and_program_execution id1}@anchor{1f2}
25194 @chapter GNAT and Program Execution
25197 This chapter covers several topics:
25203 @ref{1f3,,Running and Debugging Ada Programs}
25206 @ref{1f4,,Code Coverage and Profiling}
25209 @ref{1f5,,Improving Performance}
25212 @ref{1f6,,Overflow Check Handling in GNAT}
25215 @ref{1f7,,Performing Dimensionality Analysis in GNAT}
25218 @ref{1f8,,Stack Related Facilities}
25221 @ref{1f9,,Memory Management Issues}
25225 * Running and Debugging Ada Programs::
25226 * Code Coverage and Profiling::
25227 * Improving Performance::
25228 * Overflow Check Handling in GNAT::
25229 * Performing Dimensionality Analysis in GNAT::
25230 * Stack Related Facilities::
25231 * Memory Management Issues::
25235 @node Running and Debugging Ada Programs,Code Coverage and Profiling,,GNAT and Program Execution
25236 @anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{1f3}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{26}
25237 @section Running and Debugging Ada Programs
25242 This section discusses how to debug Ada programs.
25244 An incorrect Ada program may be handled in three ways by the GNAT compiler:
25250 The illegality may be a violation of the static semantics of Ada. In
25251 that case GNAT diagnoses the constructs in the program that are illegal.
25252 It is then a straightforward matter for the user to modify those parts of
25256 The illegality may be a violation of the dynamic semantics of Ada. In
25257 that case the program compiles and executes, but may generate incorrect
25258 results, or may terminate abnormally with some exception.
25261 When presented with a program that contains convoluted errors, GNAT
25262 itself may terminate abnormally without providing full diagnostics on
25263 the incorrect user program.
25271 * The GNAT Debugger GDB::
25273 * Introduction to GDB Commands::
25274 * Using Ada Expressions::
25275 * Calling User-Defined Subprograms::
25276 * Using the next Command in a Function::
25277 * Stopping When Ada Exceptions Are Raised::
25279 * Debugging Generic Units::
25280 * Remote Debugging with gdbserver::
25281 * GNAT Abnormal Termination or Failure to Terminate::
25282 * Naming Conventions for GNAT Source Files::
25283 * Getting Internal Debugging Information::
25284 * Stack Traceback::
25288 @node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
25289 @anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{1fa}@anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{1fb}
25290 @subsection The GNAT Debugger GDB
25293 @cite{GDB} is a general purpose, platform-independent debugger that
25294 can be used to debug mixed-language programs compiled with @emph{gcc},
25295 and in particular is capable of debugging Ada programs compiled with
25296 GNAT. The latest versions of @cite{GDB} are Ada-aware and can handle
25297 complex Ada data structures.
25299 See @cite{Debugging with GDB},
25300 for full details on the usage of @cite{GDB}, including a section on
25301 its usage on programs. This manual should be consulted for full
25302 details. The section that follows is a brief introduction to the
25303 philosophy and use of @cite{GDB}.
25305 When GNAT programs are compiled, the compiler optionally writes debugging
25306 information into the generated object file, including information on
25307 line numbers, and on declared types and variables. This information is
25308 separate from the generated code. It makes the object files considerably
25309 larger, but it does not add to the size of the actual executable that
25310 will be loaded into memory, and has no impact on run-time performance. The
25311 generation of debug information is triggered by the use of the
25312 -g switch in the @emph{gcc} or @emph{gnatmake} command
25313 used to carry out the compilations. It is important to emphasize that
25314 the use of these options does not change the generated code.
25316 The debugging information is written in standard system formats that
25317 are used by many tools, including debuggers and profilers. The format
25318 of the information is typically designed to describe C types and
25319 semantics, but GNAT implements a translation scheme which allows full
25320 details about Ada types and variables to be encoded into these
25321 standard C formats. Details of this encoding scheme may be found in
25322 the file exp_dbug.ads in the GNAT source distribution. However, the
25323 details of this encoding are, in general, of no interest to a user,
25324 since @cite{GDB} automatically performs the necessary decoding.
25326 When a program is bound and linked, the debugging information is
25327 collected from the object files, and stored in the executable image of
25328 the program. Again, this process significantly increases the size of
25329 the generated executable file, but it does not increase the size of
25330 the executable program itself. Furthermore, if this program is run in
25331 the normal manner, it runs exactly as if the debug information were
25332 not present, and takes no more actual memory.
25334 However, if the program is run under control of @cite{GDB}, the
25335 debugger is activated. The image of the program is loaded, at which
25336 point it is ready to run. If a run command is given, then the program
25337 will run exactly as it would have if @cite{GDB} were not present. This
25338 is a crucial part of the @cite{GDB} design philosophy. @cite{GDB} is
25339 entirely non-intrusive until a breakpoint is encountered. If no
25340 breakpoint is ever hit, the program will run exactly as it would if no
25341 debugger were present. When a breakpoint is hit, @cite{GDB} accesses
25342 the debugging information and can respond to user commands to inspect
25343 variables, and more generally to report on the state of execution.
25345 @node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
25346 @anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{1fc}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{1fd}
25347 @subsection Running GDB
25350 This section describes how to initiate the debugger.
25352 The debugger can be launched from a @cite{GPS} menu or
25353 directly from the command line. The description below covers the latter use.
25354 All the commands shown can be used in the @cite{GPS} debug console window,
25355 but there are usually more GUI-based ways to achieve the same effect.
25357 The command to run @cite{GDB} is
25366 where @cite{program} is the name of the executable file. This
25367 activates the debugger and results in a prompt for debugger commands.
25368 The simplest command is simply @cite{run}, which causes the program to run
25369 exactly as if the debugger were not present. The following section
25370 describes some of the additional commands that can be given to @cite{GDB}.
25372 @node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
25373 @anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{1fe}@anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{1ff}
25374 @subsection Introduction to GDB Commands
25377 @cite{GDB} contains a large repertoire of commands.
25378 See @cite{Debugging with GDB} for extensive documentation on the use
25379 of these commands, together with examples of their use. Furthermore,
25380 the command @emph{help} invoked from within GDB activates a simple help
25381 facility which summarizes the available commands and their options.
25382 In this section we summarize a few of the most commonly
25383 used commands to give an idea of what @cite{GDB} is about. You should create
25384 a simple program with debugging information and experiment with the use of
25385 these @cite{GDB} commands on the program as you read through the
25395 @item @emph{set args `arguments`}
25397 The @cite{arguments} list above is a list of arguments to be passed to
25398 the program on a subsequent run command, just as though the arguments
25399 had been entered on a normal invocation of the program. The @cite{set args}
25400 command is not needed if the program does not require arguments.
25409 The @cite{run} command causes execution of the program to start from
25410 the beginning. If the program is already running, that is to say if
25411 you are currently positioned at a breakpoint, then a prompt will ask
25412 for confirmation that you want to abandon the current execution and
25420 @item @emph{breakpoint `location`}
25422 The breakpoint command sets a breakpoint, that is to say a point at which
25423 execution will halt and @cite{GDB} will await further
25424 commands. @cite{location} is
25425 either a line number within a file, given in the format @cite{file:linenumber},
25426 or it is the name of a subprogram. If you request that a breakpoint be set on
25427 a subprogram that is overloaded, a prompt will ask you to specify on which of
25428 those subprograms you want to breakpoint. You can also
25429 specify that all of them should be breakpointed. If the program is run
25430 and execution encounters the breakpoint, then the program
25431 stops and @cite{GDB} signals that the breakpoint was encountered by
25432 printing the line of code before which the program is halted.
25439 @item @emph{catch exception `name`}
25441 This command causes the program execution to stop whenever exception
25442 @cite{name} is raised. If @cite{name} is omitted, then the execution is
25443 suspended when any exception is raised.
25450 @item @emph{print `expression`}
25452 This will print the value of the given expression. Most simple
25453 Ada expression formats are properly handled by @cite{GDB}, so the expression
25454 can contain function calls, variables, operators, and attribute references.
25461 @item @emph{continue}
25463 Continues execution following a breakpoint, until the next breakpoint or the
25464 termination of the program.
25473 Executes a single line after a breakpoint. If the next statement
25474 is a subprogram call, execution continues into (the first statement of)
25475 the called subprogram.
25484 Executes a single line. If this line is a subprogram call, executes and
25485 returns from the call.
25494 Lists a few lines around the current source location. In practice, it
25495 is usually more convenient to have a separate edit window open with the
25496 relevant source file displayed. Successive applications of this command
25497 print subsequent lines. The command can be given an argument which is a
25498 line number, in which case it displays a few lines around the specified one.
25505 @item @emph{backtrace}
25507 Displays a backtrace of the call chain. This command is typically
25508 used after a breakpoint has occurred, to examine the sequence of calls that
25509 leads to the current breakpoint. The display includes one line for each
25510 activation record (frame) corresponding to an active subprogram.
25519 At a breakpoint, @cite{GDB} can display the values of variables local
25520 to the current frame. The command @cite{up} can be used to
25521 examine the contents of other active frames, by moving the focus up
25522 the stack, that is to say from callee to caller, one frame at a time.
25531 Moves the focus of @cite{GDB} down from the frame currently being
25532 examined to the frame of its callee (the reverse of the previous command),
25539 @item @emph{frame `n`}
25541 Inspect the frame with the given number. The value 0 denotes the frame
25542 of the current breakpoint, that is to say the top of the call stack.
25551 Kills the child process in which the program is running under GDB.
25552 This may be useful for several purposes:
25558 It allows you to recompile and relink your program, since on many systems
25559 you cannot regenerate an executable file while it is running in a process.
25562 You can run your program outside the debugger, on systems that do not
25563 permit executing a program outside GDB while breakpoints are set
25567 It allows you to debug a core dump rather than a running process.
25572 The above list is a very short introduction to the commands that
25573 @cite{GDB} provides. Important additional capabilities, including conditional
25574 breakpoints, the ability to execute command sequences on a breakpoint,
25575 the ability to debug at the machine instruction level and many other
25576 features are described in detail in @cite{Debugging with GDB}.
25577 Note that most commands can be abbreviated
25578 (for example, c for continue, bt for backtrace).
25580 @node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
25581 @anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{200}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{201}
25582 @subsection Using Ada Expressions
25585 @geindex Ada expressions (in gdb)
25587 @cite{GDB} supports a fairly large subset of Ada expression syntax, with some
25588 extensions. The philosophy behind the design of this subset is
25596 That @cite{GDB} should provide basic literals and access to operations for
25597 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
25598 leaving more sophisticated computations to subprograms written into the
25599 program (which therefore may be called from @cite{GDB}).
25602 That type safety and strict adherence to Ada language restrictions
25603 are not particularly relevant in a debugging context.
25606 That brevity is important to the @cite{GDB} user.
25610 Thus, for brevity, the debugger acts as if there were
25611 implicit @cite{with} and @cite{use} clauses in effect for all user-written
25612 packages, thus making it unnecessary to fully qualify most names with
25613 their packages, regardless of context. Where this causes ambiguity,
25614 @cite{GDB} asks the user's intent.
25616 For details on the supported Ada syntax, see @cite{Debugging with GDB}.
25618 @node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
25619 @anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{202}@anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{203}
25620 @subsection Calling User-Defined Subprograms
25623 An important capability of @cite{GDB} is the ability to call user-defined
25624 subprograms while debugging. This is achieved simply by entering
25625 a subprogram call statement in the form:
25630 call subprogram-name (parameters)
25634 The keyword @cite{call} can be omitted in the normal case where the
25635 @cite{subprogram-name} does not coincide with any of the predefined
25636 @cite{GDB} commands.
25638 The effect is to invoke the given subprogram, passing it the
25639 list of parameters that is supplied. The parameters can be expressions and
25640 can include variables from the program being debugged. The
25641 subprogram must be defined
25642 at the library level within your program, and @cite{GDB} will call the
25643 subprogram within the environment of your program execution (which
25644 means that the subprogram is free to access or even modify variables
25645 within your program).
25647 The most important use of this facility is in allowing the inclusion of
25648 debugging routines that are tailored to particular data structures
25649 in your program. Such debugging routines can be written to provide a suitably
25650 high-level description of an abstract type, rather than a low-level dump
25651 of its physical layout. After all, the standard
25652 @cite{GDB print} command only knows the physical layout of your
25653 types, not their abstract meaning. Debugging routines can provide information
25654 at the desired semantic level and are thus enormously useful.
25656 For example, when debugging GNAT itself, it is crucial to have access to
25657 the contents of the tree nodes used to represent the program internally.
25658 But tree nodes are represented simply by an integer value (which in turn
25659 is an index into a table of nodes).
25660 Using the @cite{print} command on a tree node would simply print this integer
25661 value, which is not very useful. But the PN routine (defined in file
25662 treepr.adb in the GNAT sources) takes a tree node as input, and displays
25663 a useful high level representation of the tree node, which includes the
25664 syntactic category of the node, its position in the source, the integers
25665 that denote descendant nodes and parent node, as well as varied
25666 semantic information. To study this example in more detail, you might want to
25667 look at the body of the PN procedure in the stated file.
25669 Another useful application of this capability is to deal with situations of
25670 complex data which are not handled suitably by GDB. For example, if you specify
25671 Convention Fortran for a multi-dimensional array, GDB does not know that
25672 the ordering of array elements has been switched and will not properly
25673 address the array elements. In such a case, instead of trying to print the
25674 elements directly from GDB, you can write a callable procedure that prints
25675 the elements in the desired format.
25677 @node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
25678 @anchor{gnat_ugn/gnat_and_program_execution using-the-next-command-in-a-function}@anchor{204}@anchor{gnat_ugn/gnat_and_program_execution id8}@anchor{205}
25679 @subsection Using the @emph{next} Command in a Function
25682 When you use the @cite{next} command in a function, the current source
25683 location will advance to the next statement as usual. A special case
25684 arises in the case of a @cite{return} statement.
25686 Part of the code for a return statement is the 'epilogue' of the function.
25687 This is the code that returns to the caller. There is only one copy of
25688 this epilogue code, and it is typically associated with the last return
25689 statement in the function if there is more than one return. In some
25690 implementations, this epilogue is associated with the first statement
25693 The result is that if you use the @cite{next} command from a return
25694 statement that is not the last return statement of the function you
25695 may see a strange apparent jump to the last return statement or to
25696 the start of the function. You should simply ignore this odd jump.
25697 The value returned is always that from the first return statement
25698 that was stepped through.
25700 @node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
25701 @anchor{gnat_ugn/gnat_and_program_execution stopping-when-ada-exceptions-are-raised}@anchor{206}@anchor{gnat_ugn/gnat_and_program_execution id9}@anchor{207}
25702 @subsection Stopping When Ada Exceptions Are Raised
25705 @geindex Exceptions (in gdb)
25707 You can set catchpoints that stop the program execution when your program
25708 raises selected exceptions.
25717 @item @emph{catch exception}
25719 Set a catchpoint that stops execution whenever (any task in the) program
25720 raises any exception.
25727 @item @emph{catch exception `name`}
25729 Set a catchpoint that stops execution whenever (any task in the) program
25730 raises the exception @cite{name}.
25737 @item @emph{catch exception unhandled}
25739 Set a catchpoint that stops executing whenever (any task in the) program
25740 raises an exception for which there is no handler.
25747 @item @emph{info exceptions}, @emph{info exceptions `regexp`}
25749 The @cite{info exceptions} command permits the user to examine all defined
25750 exceptions within Ada programs. With a regular expression, @cite{regexp}, as
25751 argument, prints out only those exceptions whose name matches @cite{regexp}.
25755 @geindex Tasks (in gdb)
25757 @node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
25758 @anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{208}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{209}
25759 @subsection Ada Tasks
25762 @cite{GDB} allows the following task-related commands:
25771 @item @emph{info tasks}
25773 This command shows a list of current Ada tasks, as in the following example:
25777 ID TID P-ID Thread Pri State Name
25778 1 8088000 0 807e000 15 Child Activation Wait main_task
25779 2 80a4000 1 80ae000 15 Accept/Select Wait b
25780 3 809a800 1 80a4800 15 Child Activation Wait a
25781 * 4 80ae800 3 80b8000 15 Running c
25784 In this listing, the asterisk before the first task indicates it to be the
25785 currently running task. The first column lists the task ID that is used
25786 to refer to tasks in the following commands.
25790 @geindex Breakpoints and tasks
25796 @emph{break `linespec` task `taskid`}, @emph{break `linespec` task `taskid` if ...}
25800 These commands are like the @cite{break ... thread ...}.
25801 @cite{linespec} specifies source lines.
25803 Use the qualifier @code{task @emph{taskid}} with a breakpoint command
25804 to specify that you only want @cite{GDB} to stop the program when a
25805 particular Ada task reaches this breakpoint. @cite{taskid} is one of the
25806 numeric task identifiers assigned by @cite{GDB}, shown in the first
25807 column of the @code{info tasks} display.
25809 If you do not specify @code{task @emph{taskid}} when you set a
25810 breakpoint, the breakpoint applies to @emph{all} tasks of your
25813 You can use the @cite{task} qualifier on conditional breakpoints as
25814 well; in this case, place @code{task @emph{taskid}} before the
25815 breakpoint condition (before the @cite{if}).
25819 @geindex Task switching (in gdb)
25825 @emph{task `taskno`}
25829 This command allows switching to the task referred by @cite{taskno}. In
25830 particular, this allows browsing of the backtrace of the specified
25831 task. It is advisable to switch back to the original task before
25832 continuing execution otherwise the scheduling of the program may be
25837 For more detailed information on the tasking support,
25838 see @cite{Debugging with GDB}.
25840 @geindex Debugging Generic Units
25844 @node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
25845 @anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{20a}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{20b}
25846 @subsection Debugging Generic Units
25849 GNAT always uses code expansion for generic instantiation. This means that
25850 each time an instantiation occurs, a complete copy of the original code is
25851 made, with appropriate substitutions of formals by actuals.
25853 It is not possible to refer to the original generic entities in
25854 @cite{GDB}, but it is always possible to debug a particular instance of
25855 a generic, by using the appropriate expanded names. For example, if we have
25862 generic package k is
25863 procedure kp (v1 : in out integer);
25867 procedure kp (v1 : in out integer) is
25873 package k1 is new k;
25874 package k2 is new k;
25876 var : integer := 1;
25887 Then to break on a call to procedure kp in the k2 instance, simply
25893 (gdb) break g.k2.kp
25897 When the breakpoint occurs, you can step through the code of the
25898 instance in the normal manner and examine the values of local variables, as for
25901 @geindex Remote Debugging with gdbserver
25903 @node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
25904 @anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{20c}@anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{20d}
25905 @subsection Remote Debugging with gdbserver
25908 On platforms where gdbserver is supported, it is possible to use this tool
25909 to debug your application remotely. This can be useful in situations
25910 where the program needs to be run on a target host that is different
25911 from the host used for development, particularly when the target has
25912 a limited amount of resources (either CPU and/or memory).
25914 To do so, start your program using gdbserver on the target machine.
25915 gdbserver then automatically suspends the execution of your program
25916 at its entry point, waiting for a debugger to connect to it. The
25917 following commands starts an application and tells gdbserver to
25918 wait for a connection with the debugger on localhost port 4444.
25923 $ gdbserver localhost:4444 program
25924 Process program created; pid = 5685
25925 Listening on port 4444
25929 Once gdbserver has started listening, we can tell the debugger to establish
25930 a connection with this gdbserver, and then start the same debugging session
25931 as if the program was being debugged on the same host, directly under
25932 the control of GDB.
25938 (gdb) target remote targethost:4444
25939 Remote debugging using targethost:4444
25940 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
25942 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
25946 Breakpoint 1, foo () at foo.adb:4
25951 It is also possible to use gdbserver to attach to an already running
25952 program, in which case the execution of that program is simply suspended
25953 until the connection between the debugger and gdbserver is established.
25955 For more information on how to use gdbserver, see the @emph{Using the gdbserver Program}
25956 section in @cite{Debugging with GDB}.
25957 GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
25959 @geindex Abnormal Termination or Failure to Terminate
25961 @node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
25962 @anchor{gnat_ugn/gnat_and_program_execution gnat-abnormal-termination-or-failure-to-terminate}@anchor{20e}@anchor{gnat_ugn/gnat_and_program_execution id13}@anchor{20f}
25963 @subsection GNAT Abnormal Termination or Failure to Terminate
25966 When presented with programs that contain serious errors in syntax
25968 GNAT may on rare occasions experience problems in operation, such
25970 segmentation fault or illegal memory access, raising an internal
25971 exception, terminating abnormally, or failing to terminate at all.
25972 In such cases, you can activate
25973 various features of GNAT that can help you pinpoint the construct in your
25974 program that is the likely source of the problem.
25976 The following strategies are presented in increasing order of
25977 difficulty, corresponding to your experience in using GNAT and your
25978 familiarity with compiler internals.
25984 Run @emph{gcc} with the @emph{-gnatf}. This first
25985 switch causes all errors on a given line to be reported. In its absence,
25986 only the first error on a line is displayed.
25988 The @emph{-gnatdO} switch causes errors to be displayed as soon as they
25989 are encountered, rather than after compilation is terminated. If GNAT
25990 terminates prematurely or goes into an infinite loop, the last error
25991 message displayed may help to pinpoint the culprit.
25994 Run @emph{gcc} with the @emph{-v (verbose)} switch. In this
25995 mode, @emph{gcc} produces ongoing information about the progress of the
25996 compilation and provides the name of each procedure as code is
25997 generated. This switch allows you to find which Ada procedure was being
25998 compiled when it encountered a code generation problem.
26001 @geindex -gnatdc switch
26007 Run @emph{gcc} with the @emph{-gnatdc} switch. This is a GNAT specific
26008 switch that does for the front-end what @emph{-v} does
26009 for the back end. The system prints the name of each unit,
26010 either a compilation unit or nested unit, as it is being analyzed.
26013 Finally, you can start
26014 @cite{gdb} directly on the @cite{gnat1} executable. @cite{gnat1} is the
26015 front-end of GNAT, and can be run independently (normally it is just
26016 called from @emph{gcc}). You can use @cite{gdb} on @cite{gnat1} as you
26017 would on a C program (but @ref{1fa,,The GNAT Debugger GDB} for caveats). The
26018 @cite{where} command is the first line of attack; the variable
26019 @cite{lineno} (seen by @cite{print lineno}), used by the second phase of
26020 @cite{gnat1} and by the @emph{gcc} backend, indicates the source line at
26021 which the execution stopped, and @cite{input_file name} indicates the name of
26025 @node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
26026 @anchor{gnat_ugn/gnat_and_program_execution naming-conventions-for-gnat-source-files}@anchor{210}@anchor{gnat_ugn/gnat_and_program_execution id14}@anchor{211}
26027 @subsection Naming Conventions for GNAT Source Files
26030 In order to examine the workings of the GNAT system, the following
26031 brief description of its organization may be helpful:
26037 Files with prefix @code{sc} contain the lexical scanner.
26040 All files prefixed with @code{par} are components of the parser. The
26041 numbers correspond to chapters of the Ada Reference Manual. For example,
26042 parsing of select statements can be found in @code{par-ch9.adb}.
26045 All files prefixed with @code{sem} perform semantic analysis. The
26046 numbers correspond to chapters of the Ada standard. For example, all
26047 issues involving context clauses can be found in @code{sem_ch10.adb}. In
26048 addition, some features of the language require sufficient special processing
26049 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
26050 dynamic dispatching, etc.
26053 All files prefixed with @code{exp} perform normalization and
26054 expansion of the intermediate representation (abstract syntax tree, or AST).
26055 these files use the same numbering scheme as the parser and semantics files.
26056 For example, the construction of record initialization procedures is done in
26057 @code{exp_ch3.adb}.
26060 The files prefixed with @code{bind} implement the binder, which
26061 verifies the consistency of the compilation, determines an order of
26062 elaboration, and generates the bind file.
26065 The files @code{atree.ads} and @code{atree.adb} detail the low-level
26066 data structures used by the front-end.
26069 The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
26070 the abstract syntax tree as produced by the parser.
26073 The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
26074 all entities, computed during semantic analysis.
26077 Library management issues are dealt with in files with prefix
26080 @geindex Annex A (in Ada Reference Manual)
26083 Ada files with the prefix @code{a-} are children of @cite{Ada}, as
26084 defined in Annex A.
26086 @geindex Annex B (in Ada reference Manual)
26089 Files with prefix @code{i-} are children of @cite{Interfaces}, as
26090 defined in Annex B.
26092 @geindex System (package in Ada Reference Manual)
26095 Files with prefix @code{s-} are children of @cite{System}. This includes
26096 both language-defined children and GNAT run-time routines.
26098 @geindex GNAT (package)
26101 Files with prefix @code{g-} are children of @cite{GNAT}. These are useful
26102 general-purpose packages, fully documented in their specs. All
26103 the other @code{.c} files are modifications of common @emph{gcc} files.
26106 @node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
26107 @anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{212}@anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{213}
26108 @subsection Getting Internal Debugging Information
26111 Most compilers have internal debugging switches and modes. GNAT
26112 does also, except GNAT internal debugging switches and modes are not
26113 secret. A summary and full description of all the compiler and binder
26114 debug flags are in the file @code{debug.adb}. You must obtain the
26115 sources of the compiler to see the full detailed effects of these flags.
26117 The switches that print the source of the program (reconstructed from
26118 the internal tree) are of general interest for user programs, as are the
26120 the full internal tree, and the entity table (the symbol table
26121 information). The reconstructed source provides a readable version of the
26122 program after the front-end has completed analysis and expansion,
26123 and is useful when studying the performance of specific constructs.
26124 For example, constraint checks are indicated, complex aggregates
26125 are replaced with loops and assignments, and tasking primitives
26126 are replaced with run-time calls.
26130 @geindex stack traceback
26132 @geindex stack unwinding
26134 @node Stack Traceback,,Getting Internal Debugging Information,Running and Debugging Ada Programs
26135 @anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{214}@anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{215}
26136 @subsection Stack Traceback
26139 Traceback is a mechanism to display the sequence of subprogram calls that
26140 leads to a specified execution point in a program. Often (but not always)
26141 the execution point is an instruction at which an exception has been raised.
26142 This mechanism is also known as @emph{stack unwinding} because it obtains
26143 its information by scanning the run-time stack and recovering the activation
26144 records of all active subprograms. Stack unwinding is one of the most
26145 important tools for program debugging.
26147 The first entry stored in traceback corresponds to the deepest calling level,
26148 that is to say the subprogram currently executing the instruction
26149 from which we want to obtain the traceback.
26151 Note that there is no runtime performance penalty when stack traceback
26152 is enabled, and no exception is raised during program execution.
26155 @geindex non-symbolic
26158 * Non-Symbolic Traceback::
26159 * Symbolic Traceback::
26163 @node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
26164 @anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{216}@anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{217}
26165 @subsubsection Non-Symbolic Traceback
26168 Note: this feature is not supported on all platforms. See
26169 @code{GNAT.Traceback} spec in @code{g-traceb.ads}
26170 for a complete list of supported platforms.
26172 @subsubheading Tracebacks From an Unhandled Exception
26175 A runtime non-symbolic traceback is a list of addresses of call instructions.
26176 To enable this feature you must use the @emph{-E}
26177 @cite{gnatbind}'s option. With this option a stack traceback is stored as part
26178 of exception information. You can retrieve this information using the
26179 @cite{addr2line} tool.
26181 Here is a simple example:
26190 raise Constraint_Error;
26204 $ gnatmake stb -bargs -E
26207 Execution terminated by unhandled exception
26208 Exception name: CONSTRAINT_ERROR
26210 Call stack traceback locations:
26211 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
26215 As we see the traceback lists a sequence of addresses for the unhandled
26216 exception @cite{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
26217 guess that this exception come from procedure P1. To translate these
26218 addresses into the source lines where the calls appear, the
26219 @cite{addr2line} tool, described below, is invaluable. The use of this tool
26220 requires the program to be compiled with debug information.
26225 $ gnatmake -g stb -bargs -E
26228 Execution terminated by unhandled exception
26229 Exception name: CONSTRAINT_ERROR
26231 Call stack traceback locations:
26232 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
26234 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
26235 0x4011f1 0x77e892a4
26237 00401373 at d:/stb/stb.adb:5
26238 0040138B at d:/stb/stb.adb:10
26239 0040139C at d:/stb/stb.adb:14
26240 00401335 at d:/stb/b~stb.adb:104
26241 004011C4 at /build/.../crt1.c:200
26242 004011F1 at /build/.../crt1.c:222
26243 77E892A4 in ?? at ??:0
26247 The @cite{addr2line} tool has several other useful options:
26252 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
26259 to get the function name corresponding to any location
26263 @code{--demangle=gnat}
26267 to use the gnat decoding mode for the function names.
26268 Note that for binutils version 2.9.x the option is
26269 simply @code{--demangle}.
26275 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
26276 0x40139c 0x401335 0x4011c4 0x4011f1
26278 00401373 in stb.p1 at d:/stb/stb.adb:5
26279 0040138B in stb.p2 at d:/stb/stb.adb:10
26280 0040139C in stb at d:/stb/stb.adb:14
26281 00401335 in main at d:/stb/b~stb.adb:104
26282 004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
26283 004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
26287 From this traceback we can see that the exception was raised in
26288 @code{stb.adb} at line 5, which was reached from a procedure call in
26289 @code{stb.adb} at line 10, and so on. The @code{b~std.adb} is the binder file,
26290 which contains the call to the main program.
26291 @ref{123,,Running gnatbind}. The remaining entries are assorted runtime routines,
26292 and the output will vary from platform to platform.
26294 It is also possible to use @cite{GDB} with these traceback addresses to debug
26295 the program. For example, we can break at a given code location, as reported
26296 in the stack traceback:
26305 Furthermore, this feature is not implemented inside Windows DLL. Only
26306 the non-symbolic traceback is reported in this case.
26311 (gdb) break *0x401373
26312 Breakpoint 1 at 0x401373: file stb.adb, line 5.
26316 It is important to note that the stack traceback addresses
26317 do not change when debug information is included. This is particularly useful
26318 because it makes it possible to release software without debug information (to
26319 minimize object size), get a field report that includes a stack traceback
26320 whenever an internal bug occurs, and then be able to retrieve the sequence
26321 of calls with the same program compiled with debug information.
26323 @subsubheading Tracebacks From Exception Occurrences
26326 Non-symbolic tracebacks are obtained by using the @emph{-E} binder argument.
26327 The stack traceback is attached to the exception information string, and can
26328 be retrieved in an exception handler within the Ada program, by means of the
26329 Ada facilities defined in @cite{Ada.Exceptions}. Here is a simple example:
26335 with Ada.Exceptions;
26340 use Ada.Exceptions;
26348 Text_IO.Put_Line (Exception_Information (E));
26362 This program will output:
26369 Exception name: CONSTRAINT_ERROR
26370 Message: stb.adb:12
26371 Call stack traceback locations:
26372 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
26376 @subsubheading Tracebacks From Anywhere in a Program
26379 It is also possible to retrieve a stack traceback from anywhere in a
26380 program. For this you need to
26381 use the @cite{GNAT.Traceback} API. This package includes a procedure called
26382 @cite{Call_Chain} that computes a complete stack traceback, as well as useful
26383 display procedures described below. It is not necessary to use the
26384 @emph{-E gnatbind} option in this case, because the stack traceback mechanism
26385 is invoked explicitly.
26387 In the following example we compute a traceback at a specific location in
26388 the program, and we display it using @cite{GNAT.Debug_Utilities.Image} to
26389 convert addresses to strings:
26395 with GNAT.Traceback;
26396 with GNAT.Debug_Utilities;
26402 use GNAT.Traceback;
26405 TB : Tracebacks_Array (1 .. 10);
26406 -- We are asking for a maximum of 10 stack frames.
26408 -- Len will receive the actual number of stack frames returned.
26410 Call_Chain (TB, Len);
26412 Text_IO.Put ("In STB.P1 : ");
26414 for K in 1 .. Len loop
26415 Text_IO.Put (Debug_Utilities.Image (TB (K)));
26436 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
26437 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
26441 You can then get further information by invoking the @cite{addr2line}
26442 tool as described earlier (note that the hexadecimal addresses
26443 need to be specified in C format, with a leading '0x').
26448 @node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
26449 @anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{218}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{219}
26450 @subsubsection Symbolic Traceback
26453 A symbolic traceback is a stack traceback in which procedure names are
26454 associated with each code location.
26456 Note that this feature is not supported on all platforms. See
26457 @code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
26458 list of currently supported platforms.
26460 Note that the symbolic traceback requires that the program be compiled
26461 with debug information. If it is not compiled with debug information
26462 only the non-symbolic information will be valid.
26464 @subsubheading Tracebacks From Exception Occurrences
26467 Here is an example:
26473 with GNAT.Traceback.Symbolic;
26479 raise Constraint_Error;
26496 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
26501 $ gnatmake -g .\stb -bargs -E
26504 0040149F in stb.p1 at stb.adb:8
26505 004014B7 in stb.p2 at stb.adb:13
26506 004014CF in stb.p3 at stb.adb:18
26507 004015DD in ada.stb at stb.adb:22
26508 00401461 in main at b~stb.adb:168
26509 004011C4 in __mingw_CRTStartup at crt1.c:200
26510 004011F1 in mainCRTStartup at crt1.c:222
26511 77E892A4 in ?? at ??:0
26515 In the above example the @code{.\} syntax in the @emph{gnatmake} command
26516 is currently required by @emph{addr2line} for files that are in
26517 the current working directory.
26518 Moreover, the exact sequence of linker options may vary from platform
26520 The above @emph{-largs} section is for Windows platforms. By contrast,
26521 under Unix there is no need for the @emph{-largs} section.
26522 Differences across platforms are due to details of linker implementation.
26524 @subsubheading Tracebacks From Anywhere in a Program
26527 It is possible to get a symbolic stack traceback
26528 from anywhere in a program, just as for non-symbolic tracebacks.
26529 The first step is to obtain a non-symbolic
26530 traceback, and then call @cite{Symbolic_Traceback} to compute the symbolic
26531 information. Here is an example:
26537 with GNAT.Traceback;
26538 with GNAT.Traceback.Symbolic;
26543 use GNAT.Traceback;
26544 use GNAT.Traceback.Symbolic;
26547 TB : Tracebacks_Array (1 .. 10);
26548 -- We are asking for a maximum of 10 stack frames.
26550 -- Len will receive the actual number of stack frames returned.
26552 Call_Chain (TB, Len);
26553 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
26567 @subsubheading Automatic Symbolic Tracebacks
26570 Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
26571 in @cite{gprbuild -g ... -bargs -Es}).
26572 This will cause the Exception_Information to contain a symbolic traceback,
26573 which will also be printed if an unhandled exception terminates the
26576 @geindex Code Coverage
26580 @node Code Coverage and Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
26581 @anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{1f4}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-and-profiling}@anchor{27}
26582 @section Code Coverage and Profiling
26585 This section describes how to use the @cite{gcov} coverage testing tool and
26586 the @cite{gprof} profiler tool on Ada programs.
26591 * Code Coverage of Ada Programs with gcov::
26592 * Profiling an Ada Program with gprof::
26596 @node Code Coverage of Ada Programs with gcov,Profiling an Ada Program with gprof,,Code Coverage and Profiling
26597 @anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{21a}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-of-ada-programs-with-gcov}@anchor{21b}
26598 @subsection Code Coverage of Ada Programs with gcov
26601 @cite{gcov} is a test coverage program: it analyzes the execution of a given
26602 program on selected tests, to help you determine the portions of the program
26603 that are still untested.
26605 @cite{gcov} is part of the GCC suite, and is described in detail in the GCC
26606 User's Guide. You can refer to this documentation for a more complete
26609 This chapter provides a quick startup guide, and
26610 details some GNAT-specific features.
26613 * Quick startup guide::
26618 @node Quick startup guide,GNAT specifics,,Code Coverage of Ada Programs with gcov
26619 @anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{21c}@anchor{gnat_ugn/gnat_and_program_execution quick-startup-guide}@anchor{21d}
26620 @subsubsection Quick startup guide
26623 In order to perform coverage analysis of a program using @cite{gcov}, several
26630 Instrument the code during the compilation process,
26633 Execute the instrumented program, and
26636 Invoke the @cite{gcov} tool to generate the coverage results.
26639 @geindex -fprofile-arcs (gcc)
26641 @geindex -ftest-coverage (gcc
26643 @geindex -fprofile-arcs (gnatbind)
26645 The code instrumentation needed by gcov is created at the object level.
26646 The source code is not modified in any way, because the instrumentation code is
26647 inserted by gcc during the compilation process. To compile your code with code
26648 coverage activated, you need to recompile your whole project using the
26650 @cite{-fprofile-arcs} and @cite{-ftest-coverage}, and link it using
26651 @cite{-fprofile-arcs}.
26656 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \\
26657 -largs -fprofile-arcs
26661 This compilation process will create @code{.gcno} files together with
26662 the usual object files.
26664 Once the program is compiled with coverage instrumentation, you can
26665 run it as many times as needed -- on portions of a test suite for
26666 example. The first execution will produce @code{.gcda} files at the
26667 same location as the @code{.gcno} files. Subsequent executions
26668 will update those files, so that a cumulative result of the covered
26669 portions of the program is generated.
26671 Finally, you need to call the @cite{gcov} tool. The different options of
26672 @cite{gcov} are described in the GCC User's Guide, section 'Invoking gcov'.
26674 This will create annotated source files with a @code{.gcov} extension:
26675 @code{my_main.adb} file will be analyzed in @code{my_main.adb.gcov}.
26677 @node GNAT specifics,,Quick startup guide,Code Coverage of Ada Programs with gcov
26678 @anchor{gnat_ugn/gnat_and_program_execution gnat-specifics}@anchor{21e}@anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{21f}
26679 @subsubsection GNAT specifics
26682 Because of Ada semantics, portions of the source code may be shared among
26683 several object files. This is the case for example when generics are
26684 involved, when inlining is active or when declarations generate initialisation
26685 calls. In order to take
26686 into account this shared code, you need to call @cite{gcov} on all
26687 source files of the tested program at once.
26689 The list of source files might exceed the system's maximum command line
26690 length. In order to bypass this limitation, a new mechanism has been
26691 implemented in @cite{gcov}: you can now list all your project's files into a
26692 text file, and provide this file to gcov as a parameter, preceded by a @code{@@}
26693 (e.g. @code{gcov @@mysrclist.txt}).
26695 Note that on AIX compiling a static library with @cite{-fprofile-arcs} is
26696 not supported as there can be unresolved symbols during the final link.
26702 @node Profiling an Ada Program with gprof,,Code Coverage of Ada Programs with gcov,Code Coverage and Profiling
26703 @anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{220}@anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{221}
26704 @subsection Profiling an Ada Program with gprof
26707 This section is not meant to be an exhaustive documentation of @cite{gprof}.
26708 Full documentation for it can be found in the @cite{GNU Profiler User's Guide}
26709 documentation that is part of this GNAT distribution.
26711 Profiling a program helps determine the parts of a program that are executed
26712 most often, and are therefore the most time-consuming.
26714 @cite{gprof} is the standard GNU profiling tool; it has been enhanced to
26715 better handle Ada programs and multitasking.
26716 It is currently supported on the following platforms
26725 solaris sparc/sparc64/x86
26731 In order to profile a program using @cite{gprof}, several steps are needed:
26737 Instrument the code, which requires a full recompilation of the project with the
26741 Execute the program under the analysis conditions, i.e. with the desired
26745 Analyze the results using the @cite{gprof} tool.
26748 The following sections detail the different steps, and indicate how
26749 to interpret the results.
26752 * Compilation for profiling::
26753 * Program execution::
26755 * Interpretation of profiling results::
26759 @node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
26760 @anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{222}@anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{223}
26761 @subsubsection Compilation for profiling
26765 @geindex for profiling
26767 @geindex -pg (gnatlink)
26768 @geindex for profiling
26770 In order to profile a program the first step is to tell the compiler
26771 to generate the necessary profiling information. The compiler switch to be used
26772 is @code{-pg}, which must be added to other compilation switches. This
26773 switch needs to be specified both during compilation and link stages, and can
26774 be specified once when using gnatmake:
26779 $ gnatmake -f -pg -P my_project
26783 Note that only the objects that were compiled with the @code{-pg} switch will
26784 be profiled; if you need to profile your whole project, use the @code{-f}
26785 gnatmake switch to force full recompilation.
26787 @node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
26788 @anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{224}@anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{225}
26789 @subsubsection Program execution
26792 Once the program has been compiled for profiling, you can run it as usual.
26794 The only constraint imposed by profiling is that the program must terminate
26795 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
26798 Once the program completes execution, a data file called @code{gmon.out} is
26799 generated in the directory where the program was launched from. If this file
26800 already exists, it will be overwritten.
26802 @node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
26803 @anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{226}@anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{227}
26804 @subsubsection Running gprof
26807 The @cite{gprof} tool is called as follow:
26812 $ gprof my_prog gmon.out
26825 The complete form of the gprof command line is the following:
26830 $ gprof [switches] [executable [data-file]]
26834 @cite{gprof} supports numerous switches. The order of these
26835 switch does not matter. The full list of options can be found in
26836 the GNU Profiler User's Guide documentation that comes with this documentation.
26838 The following is the subset of those switches that is most relevant:
26840 @geindex --demangle (gprof)
26845 @item @code{--demangle[=@emph{style}]}, @code{--no-demangle}
26847 These options control whether symbol names should be demangled when
26848 printing output. The default is to demangle C++ symbols. The
26849 @code{--no-demangle} option may be used to turn off demangling. Different
26850 compilers have different mangling styles. The optional demangling style
26851 argument can be used to choose an appropriate demangling style for your
26852 compiler, in particular Ada symbols generated by GNAT can be demangled using
26853 @code{--demangle=gnat}.
26856 @geindex -e (gprof)
26861 @item @code{-e @emph{function_name}}
26863 The @code{-e @emph{function}} option tells @cite{gprof} not to print
26864 information about the function @cite{function_name} (and its
26865 children...) in the call graph. The function will still be listed
26866 as a child of any functions that call it, but its index number will be
26867 shown as @code{[not printed]}. More than one @code{-e} option may be
26868 given; only one @cite{function_name} may be indicated with each @code{-e}
26872 @geindex -E (gprof)
26877 @item @code{-E @emph{function_name}}
26879 The @code{-E @emph{function}} option works like the @code{-e} option, but
26880 execution time spent in the function (and children who were not called from
26881 anywhere else), will not be used to compute the percentages-of-time for
26882 the call graph. More than one @code{-E} option may be given; only one
26883 @cite{function_name} may be indicated with each @code{-E} option.
26886 @geindex -f (gprof)
26891 @item @code{-f @emph{function_name}}
26893 The @code{-f @emph{function}} option causes @cite{gprof} to limit the
26894 call graph to the function @cite{function_name} and its children (and
26895 their children...). More than one @code{-f} option may be given;
26896 only one @cite{function_name} may be indicated with each @code{-f}
26900 @geindex -F (gprof)
26905 @item @code{-F @emph{function_name}}
26907 The @code{-F @emph{function}} option works like the @code{-f} option, but
26908 only time spent in the function and its children (and their
26909 children...) will be used to determine total-time and
26910 percentages-of-time for the call graph. More than one @code{-F} option
26911 may be given; only one @cite{function_name} may be indicated with each
26912 @code{-F} option. The @code{-F} option overrides the @code{-E} option.
26915 @node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
26916 @anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{228}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{229}
26917 @subsubsection Interpretation of profiling results
26920 The results of the profiling analysis are represented by two arrays: the
26921 'flat profile' and the 'call graph'. Full documentation of those outputs
26922 can be found in the GNU Profiler User's Guide.
26924 The flat profile shows the time spent in each function of the program, and how
26925 many time it has been called. This allows you to locate easily the most
26926 time-consuming functions.
26928 The call graph shows, for each subprogram, the subprograms that call it,
26929 and the subprograms that it calls. It also provides an estimate of the time
26930 spent in each of those callers/called subprograms.
26932 @node Improving Performance,Overflow Check Handling in GNAT,Code Coverage and Profiling,GNAT and Program Execution
26933 @anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{28}@anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{1f5}
26934 @section Improving Performance
26937 @geindex Improving performance
26939 This section presents several topics related to program performance.
26940 It first describes some of the tradeoffs that need to be considered
26941 and some of the techniques for making your program run faster.
26944 It then documents the unused subprogram/data elimination feature,
26945 which can reduce the size of program executables.
26948 * Performance Considerations::
26949 * Text_IO Suggestions::
26950 * Reducing Size of Executables with Unused Subprogram/Data Elimination::
26954 @node Performance Considerations,Text_IO Suggestions,,Improving Performance
26955 @anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{22a}@anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{22b}
26956 @subsection Performance Considerations
26959 The GNAT system provides a number of options that allow a trade-off
26966 performance of the generated code
26969 speed of compilation
26972 minimization of dependences and recompilation
26975 the degree of run-time checking.
26978 The defaults (if no options are selected) aim at improving the speed
26979 of compilation and minimizing dependences, at the expense of performance
26980 of the generated code:
26989 no inlining of subprogram calls
26992 all run-time checks enabled except overflow and elaboration checks
26995 These options are suitable for most program development purposes. This
26996 section describes how you can modify these choices, and also provides
26997 some guidelines on debugging optimized code.
27000 * Controlling Run-Time Checks::
27001 * Use of Restrictions::
27002 * Optimization Levels::
27003 * Debugging Optimized Code::
27004 * Inlining of Subprograms::
27005 * Floating_Point_Operations::
27006 * Vectorization of loops::
27007 * Other Optimization Switches::
27008 * Optimization and Strict Aliasing::
27009 * Aliased Variables and Optimization::
27010 * Atomic Variables and Optimization::
27011 * Passive Task Optimization::
27015 @node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
27016 @anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{22c}@anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{22d}
27017 @subsubsection Controlling Run-Time Checks
27020 By default, GNAT generates all run-time checks, except stack overflow
27021 checks, and checks for access before elaboration on subprogram
27022 calls. The latter are not required in default mode, because all
27023 necessary checking is done at compile time.
27025 @geindex -gnatp (gcc)
27027 @geindex -gnato (gcc)
27029 The gnat switch, @emph{-gnatp} allows this default to be modified. See
27030 @ref{101,,Run-Time Checks}.
27032 Our experience is that the default is suitable for most development
27035 Elaboration checks are off by default, and also not needed by default, since
27036 GNAT uses a static elaboration analysis approach that avoids the need for
27037 run-time checking. This manual contains a full chapter discussing the issue
27038 of elaboration checks, and if the default is not satisfactory for your use,
27039 you should read this chapter.
27041 For validity checks, the minimal checks required by the Ada Reference
27042 Manual (for case statements and assignments to array elements) are on
27043 by default. These can be suppressed by use of the @emph{-gnatVn} switch.
27044 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
27045 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
27046 it may be reasonable to routinely use @emph{-gnatVn}. Validity checks
27047 are also suppressed entirely if @emph{-gnatp} is used.
27049 @geindex Overflow checks
27056 @geindex Unsuppress
27058 @geindex pragma Suppress
27060 @geindex pragma Unsuppress
27062 Note that the setting of the switches controls the default setting of
27063 the checks. They may be modified using either @cite{pragma Suppress} (to
27064 remove checks) or @cite{pragma Unsuppress} (to add back suppressed
27065 checks) in the program source.
27067 @node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
27068 @anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{22e}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{22f}
27069 @subsubsection Use of Restrictions
27072 The use of pragma Restrictions allows you to control which features are
27073 permitted in your program. Apart from the obvious point that if you avoid
27074 relatively expensive features like finalization (enforceable by the use
27075 of pragma Restrictions (No_Finalization), the use of this pragma does not
27076 affect the generated code in most cases.
27078 One notable exception to this rule is that the possibility of task abort
27079 results in some distributed overhead, particularly if finalization or
27080 exception handlers are used. The reason is that certain sections of code
27081 have to be marked as non-abortable.
27083 If you use neither the @cite{abort} statement, nor asynchronous transfer
27084 of control (@cite{select ... then abort}), then this distributed overhead
27085 is removed, which may have a general positive effect in improving
27086 overall performance. Especially code involving frequent use of tasking
27087 constructs and controlled types will show much improved performance.
27088 The relevant restrictions pragmas are
27093 pragma Restrictions (No_Abort_Statements);
27094 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
27098 It is recommended that these restriction pragmas be used if possible. Note
27099 that this also means that you can write code without worrying about the
27100 possibility of an immediate abort at any point.
27102 @node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
27103 @anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{230}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{104}
27104 @subsubsection Optimization Levels
27109 Without any optimization option,
27110 the compiler's goal is to reduce the cost of
27111 compilation and to make debugging produce the expected results.
27112 Statements are independent: if you stop the program with a breakpoint between
27113 statements, you can then assign a new value to any variable or change
27114 the program counter to any other statement in the subprogram and get exactly
27115 the results you would expect from the source code.
27117 Turning on optimization makes the compiler attempt to improve the
27118 performance and/or code size at the expense of compilation time and
27119 possibly the ability to debug the program.
27121 If you use multiple
27122 -O options, with or without level numbers,
27123 the last such option is the one that is effective.
27125 The default is optimization off. This results in the fastest compile
27126 times, but GNAT makes absolutely no attempt to optimize, and the
27127 generated programs are considerably larger and slower than when
27128 optimization is enabled. You can use the
27129 @emph{-O} switch (the permitted forms are @emph{-O0}, @emph{-O1}
27130 @emph{-O2}, @emph{-O3}, and @emph{-Os})
27131 to @emph{gcc} to control the optimization level:
27142 No optimization (the default);
27143 generates unoptimized code but has
27144 the fastest compilation time.
27146 Note that many other compilers do fairly extensive optimization
27147 even if 'no optimization' is specified. With gcc, it is
27148 very unusual to use -O0 for production if
27149 execution time is of any concern, since -O0
27150 really does mean no optimization at all. This difference between
27151 gcc and other compilers should be kept in mind when doing
27152 performance comparisons.
27161 Moderate optimization;
27162 optimizes reasonably well but does not
27163 degrade compilation time significantly.
27173 generates highly optimized code and has
27174 the slowest compilation time.
27183 Full optimization as in @emph{-O2};
27184 also uses more aggressive automatic inlining of subprograms within a unit
27185 (@ref{117,,Inlining of Subprograms}) and attempts to vectorize loops.
27194 Optimize space usage (code and data) of resulting program.
27198 Higher optimization levels perform more global transformations on the
27199 program and apply more expensive analysis algorithms in order to generate
27200 faster and more compact code. The price in compilation time, and the
27201 resulting improvement in execution time,
27202 both depend on the particular application and the hardware environment.
27203 You should experiment to find the best level for your application.
27205 Since the precise set of optimizations done at each level will vary from
27206 release to release (and sometime from target to target), it is best to think
27207 of the optimization settings in general terms.
27208 See the @emph{Options That Control Optimization} section in
27209 @cite{Using the GNU Compiler Collection (GCC)}
27211 the @emph{-O} settings and a number of @emph{-f} options that
27212 individually enable or disable specific optimizations.
27214 Unlike some other compilation systems, @emph{gcc} has
27215 been tested extensively at all optimization levels. There are some bugs
27216 which appear only with optimization turned on, but there have also been
27217 bugs which show up only in @emph{unoptimized} code. Selecting a lower
27218 level of optimization does not improve the reliability of the code
27219 generator, which in practice is highly reliable at all optimization
27222 Note regarding the use of @emph{-O3}: The use of this optimization level
27223 is generally discouraged with GNAT, since it often results in larger
27224 executables which may run more slowly. See further discussion of this point
27225 in @ref{117,,Inlining of Subprograms}.
27227 @node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
27228 @anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{231}@anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{232}
27229 @subsubsection Debugging Optimized Code
27232 @geindex Debugging optimized code
27234 @geindex Optimization and debugging
27236 Although it is possible to do a reasonable amount of debugging at
27237 nonzero optimization levels,
27238 the higher the level the more likely that
27239 source-level constructs will have been eliminated by optimization.
27240 For example, if a loop is strength-reduced, the loop
27241 control variable may be completely eliminated and thus cannot be
27242 displayed in the debugger.
27243 This can only happen at @emph{-O2} or @emph{-O3}.
27244 Explicit temporary variables that you code might be eliminated at
27245 level @emph{-O1} or higher.
27249 The use of the @emph{-g} switch,
27250 which is needed for source-level debugging,
27251 affects the size of the program executable on disk,
27252 and indeed the debugging information can be quite large.
27253 However, it has no effect on the generated code (and thus does not
27254 degrade performance)
27256 Since the compiler generates debugging tables for a compilation unit before
27257 it performs optimizations, the optimizing transformations may invalidate some
27258 of the debugging data. You therefore need to anticipate certain
27259 anomalous situations that may arise while debugging optimized code.
27260 These are the most common cases:
27266 @emph{The 'hopping Program Counter':} Repeated @cite{step} or @cite{next}
27268 the PC bouncing back and forth in the code. This may result from any of
27269 the following optimizations:
27275 @emph{Common subexpression elimination:} using a single instance of code for a
27276 quantity that the source computes several times. As a result you
27277 may not be able to stop on what looks like a statement.
27280 @emph{Invariant code motion:} moving an expression that does not change within a
27281 loop, to the beginning of the loop.
27284 @emph{Instruction scheduling:} moving instructions so as to
27285 overlap loads and stores (typically) with other code, or in
27286 general to move computations of values closer to their uses. Often
27287 this causes you to pass an assignment statement without the assignment
27288 happening and then later bounce back to the statement when the
27289 value is actually needed. Placing a breakpoint on a line of code
27290 and then stepping over it may, therefore, not always cause all the
27291 expected side-effects.
27295 @emph{The 'big leap':} More commonly known as @emph{cross-jumping}, in which
27296 two identical pieces of code are merged and the program counter suddenly
27297 jumps to a statement that is not supposed to be executed, simply because
27298 it (and the code following) translates to the same thing as the code
27299 that @emph{was} supposed to be executed. This effect is typically seen in
27300 sequences that end in a jump, such as a @cite{goto}, a @cite{return}, or
27301 a @cite{break} in a C @cite{switch} statement.
27304 @emph{The 'roving variable':} The symptom is an unexpected value in a variable.
27305 There are various reasons for this effect:
27311 In a subprogram prologue, a parameter may not yet have been moved to its
27315 A variable may be dead, and its register re-used. This is
27316 probably the most common cause.
27319 As mentioned above, the assignment of a value to a variable may
27323 A variable may be eliminated entirely by value propagation or
27324 other means. In this case, GCC may incorrectly generate debugging
27325 information for the variable
27328 In general, when an unexpected value appears for a local variable or parameter
27329 you should first ascertain if that value was actually computed by
27330 your program, as opposed to being incorrectly reported by the debugger.
27332 array elements in an object designated by an access value
27333 are generally less of a problem, once you have ascertained that the access
27335 Typically, this means checking variables in the preceding code and in the
27336 calling subprogram to verify that the value observed is explainable from other
27337 values (one must apply the procedure recursively to those
27338 other values); or re-running the code and stopping a little earlier
27339 (perhaps before the call) and stepping to better see how the variable obtained
27340 the value in question; or continuing to step @emph{from} the point of the
27341 strange value to see if code motion had simply moved the variable's
27345 In light of such anomalies, a recommended technique is to use @emph{-O0}
27346 early in the software development cycle, when extensive debugging capabilities
27347 are most needed, and then move to @emph{-O1} and later @emph{-O2} as
27348 the debugger becomes less critical.
27349 Whether to use the @emph{-g} switch in the release version is
27350 a release management issue.
27351 Note that if you use @emph{-g} you can then use the @emph{strip} program
27352 on the resulting executable,
27353 which removes both debugging information and global symbols.
27355 @node Inlining of Subprograms,Floating_Point_Operations,Debugging Optimized Code,Performance Considerations
27356 @anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{233}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{117}
27357 @subsubsection Inlining of Subprograms
27360 A call to a subprogram in the current unit is inlined if all the
27361 following conditions are met:
27367 The optimization level is at least @emph{-O1}.
27370 The called subprogram is suitable for inlining: It must be small enough
27371 and not contain something that @emph{gcc} cannot support in inlined
27374 @geindex pragma Inline
27379 Any one of the following applies: @cite{pragma Inline} is applied to the
27380 subprogram and the @emph{-gnatn} switch is specified; the
27381 subprogram is local to the unit and called once from within it; the
27382 subprogram is small and optimization level @emph{-O2} is specified;
27383 optimization level @emph{-O3} is specified.
27386 Calls to subprograms in @emph{with}ed units are normally not inlined.
27387 To achieve actual inlining (that is, replacement of the call by the code
27388 in the body of the subprogram), the following conditions must all be true:
27394 The optimization level is at least @emph{-O1}.
27397 The called subprogram is suitable for inlining: It must be small enough
27398 and not contain something that @emph{gcc} cannot support in inlined
27402 The call appears in a body (not in a package spec).
27405 There is a @cite{pragma Inline} for the subprogram.
27408 The @emph{-gnatn} switch is used on the command line.
27411 Even if all these conditions are met, it may not be possible for
27412 the compiler to inline the call, due to the length of the body,
27413 or features in the body that make it impossible for the compiler
27414 to do the inlining.
27416 Note that specifying the @emph{-gnatn} switch causes additional
27417 compilation dependencies. Consider the following:
27439 With the default behavior (no @emph{-gnatn} switch specified), the
27440 compilation of the @cite{Main} procedure depends only on its own source,
27441 @code{main.adb}, and the spec of the package in file @code{r.ads}. This
27442 means that editing the body of @cite{R} does not require recompiling
27445 On the other hand, the call @cite{R.Q} is not inlined under these
27446 circumstances. If the @emph{-gnatn} switch is present when @cite{Main}
27447 is compiled, the call will be inlined if the body of @cite{Q} is small
27448 enough, but now @cite{Main} depends on the body of @cite{R} in
27449 @code{r.adb} as well as on the spec. This means that if this body is edited,
27450 the main program must be recompiled. Note that this extra dependency
27451 occurs whether or not the call is in fact inlined by @emph{gcc}.
27453 The use of front end inlining with @emph{-gnatN} generates similar
27454 additional dependencies.
27456 @geindex -fno-inline (gcc)
27458 Note: The @emph{-fno-inline} switch overrides all other conditions and ensures that
27459 no inlining occurs, unless requested with pragma Inline_Always for gcc
27460 back-ends. The extra dependences resulting from @emph{-gnatn} will still be active,
27461 even if this switch is used to suppress the resulting inlining actions.
27463 @geindex -fno-inline-functions (gcc)
27465 Note: The @emph{-fno-inline-functions} switch can be used to prevent
27466 automatic inlining of subprograms if @emph{-O3} is used.
27468 @geindex -fno-inline-small-functions (gcc)
27470 Note: The @emph{-fno-inline-small-functions} switch can be used to prevent
27471 automatic inlining of small subprograms if @emph{-O2} is used.
27473 @geindex -fno-inline-functions-called-once (gcc)
27475 Note: The @emph{-fno-inline-functions-called-once} switch
27476 can be used to prevent inlining of subprograms local to the unit
27477 and called once from within it if @emph{-O1} is used.
27479 Note regarding the use of @emph{-O3}: @emph{-gnatn} is made up of two
27480 sub-switches @emph{-gnatn1} and @emph{-gnatn2} that can be directly
27481 specified in lieu of it, @emph{-gnatn} being translated into one of them
27482 based on the optimization level. With @emph{-O2} or below, @emph{-gnatn}
27483 is equivalent to @emph{-gnatn1} which activates pragma @cite{Inline} with
27484 moderate inlining across modules. With @emph{-O3}, @emph{-gnatn} is
27485 equivalent to @emph{-gnatn2} which activates pragma @cite{Inline} with
27486 full inlining across modules. If you have used pragma @cite{Inline} in
27487 appropriate cases, then it is usually much better to use @emph{-O2}
27488 and @emph{-gnatn} and avoid the use of @emph{-O3} which has the additional
27489 effect of inlining subprograms you did not think should be inlined. We have
27490 found that the use of @emph{-O3} may slow down the compilation and increase
27491 the code size by performing excessive inlining, leading to increased
27492 instruction cache pressure from the increased code size and thus minor
27493 performance improvements. So the bottom line here is that you should not
27494 automatically assume that @emph{-O3} is better than @emph{-O2}, and
27495 indeed you should use @emph{-O3} only if tests show that it actually
27496 improves performance for your program.
27498 @node Floating_Point_Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
27499 @anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{234}@anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{235}
27500 @subsubsection Floating_Point_Operations
27503 @geindex Floating-Point Operations
27505 On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
27506 64-bit standard IEEE floating-point representations, and operations will
27507 use standard IEEE arithmetic as provided by the processor. On most, but
27508 not all, architectures, the attribute Machine_Overflows is False for these
27509 types, meaning that the semantics of overflow is implementation-defined.
27510 In the case of GNAT, these semantics correspond to the normal IEEE
27511 treatment of infinities and NaN (not a number) values. For example,
27512 1.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
27513 avoiding explicit overflow checks, the performance is greatly improved
27514 on many targets. However, if required, floating-point overflow can be
27515 enabled by the use of the pragma Check_Float_Overflow.
27517 Another consideration that applies specifically to x86 32-bit
27518 architectures is which form of floating-point arithmetic is used.
27519 By default the operations use the old style x86 floating-point,
27520 which implements an 80-bit extended precision form (on these
27521 architectures the type Long_Long_Float corresponds to that form).
27522 In addition, generation of efficient code in this mode means that
27523 the extended precision form will be used for intermediate results.
27524 This may be helpful in improving the final precision of a complex
27525 expression. However it means that the results obtained on the x86
27526 will be different from those on other architectures, and for some
27527 algorithms, the extra intermediate precision can be detrimental.
27529 In addition to this old-style floating-point, all modern x86 chips
27530 implement an alternative floating-point operation model referred
27531 to as SSE2. In this model there is no extended form, and furthermore
27532 execution performance is significantly enhanced. To force GNAT to use
27533 this more modern form, use both of the switches:
27537 -msse2 -mfpmath=sse
27540 A unit compiled with these switches will automatically use the more
27541 efficient SSE2 instruction set for Float and Long_Float operations.
27542 Note that the ABI has the same form for both floating-point models,
27543 so it is permissible to mix units compiled with and without these
27546 @node Vectorization of loops,Other Optimization Switches,Floating_Point_Operations,Performance Considerations
27547 @anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{236}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{237}
27548 @subsubsection Vectorization of loops
27551 @geindex Optimization Switches
27553 You can take advantage of the auto-vectorizer present in the @emph{gcc}
27554 back end to vectorize loops with GNAT. The corresponding command line switch
27555 is @emph{-ftree-vectorize} but, as it is enabled by default at @emph{-O3}
27556 and other aggressive optimizations helpful for vectorization also are enabled
27557 by default at this level, using @emph{-O3} directly is recommended.
27559 You also need to make sure that the target architecture features a supported
27560 SIMD instruction set. For example, for the x86 architecture, you should at
27561 least specify @emph{-msse2} to get significant vectorization (but you don't
27562 need to specify it for x86-64 as it is part of the base 64-bit architecture).
27563 Similarly, for the PowerPC architecture, you should specify @emph{-maltivec}.
27565 The preferred loop form for vectorization is the @cite{for} iteration scheme.
27566 Loops with a @cite{while} iteration scheme can also be vectorized if they are
27567 very simple, but the vectorizer will quickly give up otherwise. With either
27568 iteration scheme, the flow of control must be straight, in particular no
27569 @cite{exit} statement may appear in the loop body. The loop may however
27570 contain a single nested loop, if it can be vectorized when considered alone:
27575 A : array (1..4, 1..4) of Long_Float;
27576 S : array (1..4) of Long_Float;
27580 for I in A'Range(1) loop
27581 for J in A'Range(2) loop
27582 S (I) := S (I) + A (I, J);
27589 The vectorizable operations depend on the targeted SIMD instruction set, but
27590 the adding and some of the multiplying operators are generally supported, as
27591 well as the logical operators for modular types. Note that compiling
27592 with @emph{-gnatp} might well reveal cases where some checks do thwart
27595 Type conversions may also prevent vectorization if they involve semantics that
27596 are not directly supported by the code generator or the SIMD instruction set.
27597 A typical example is direct conversion from floating-point to integer types.
27598 The solution in this case is to use the following idiom:
27603 Integer (S'Truncation (F))
27607 if @cite{S} is the subtype of floating-point object @cite{F}.
27609 In most cases, the vectorizable loops are loops that iterate over arrays.
27610 All kinds of array types are supported, i.e. constrained array types with
27616 type Array_Type is array (1 .. 4) of Long_Float;
27620 constrained array types with dynamic bounds:
27625 type Array_Type is array (1 .. Q.N) of Long_Float;
27627 type Array_Type is array (Q.K .. 4) of Long_Float;
27629 type Array_Type is array (Q.K .. Q.N) of Long_Float;
27633 or unconstrained array types:
27638 type Array_Type is array (Positive range <>) of Long_Float;
27642 The quality of the generated code decreases when the dynamic aspect of the
27643 array type increases, the worst code being generated for unconstrained array
27644 types. This is so because, the less information the compiler has about the
27645 bounds of the array, the more fallback code it needs to generate in order to
27646 fix things up at run time.
27648 It is possible to specify that a given loop should be subject to vectorization
27649 preferably to other optimizations by means of pragma @cite{Loop_Optimize}:
27654 pragma Loop_Optimize (Vector);
27658 placed immediately within the loop will convey the appropriate hint to the
27659 compiler for this loop.
27661 It is also possible to help the compiler generate better vectorized code
27662 for a given loop by asserting that there are no loop-carried dependencies
27663 in the loop. Consider for example the procedure:
27668 type Arr is array (1 .. 4) of Long_Float;
27670 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
27672 for I in Arr'Range loop
27673 R(I) := X(I) + Y(I);
27679 By default, the compiler cannot unconditionally vectorize the loop because
27680 assigning to a component of the array designated by R in one iteration could
27681 change the value read from the components of the array designated by X or Y
27682 in a later iteration. As a result, the compiler will generate two versions
27683 of the loop in the object code, one vectorized and the other not vectorized,
27684 as well as a test to select the appropriate version at run time. This can
27685 be overcome by another hint:
27690 pragma Loop_Optimize (Ivdep);
27694 placed immediately within the loop will tell the compiler that it can safely
27695 omit the non-vectorized version of the loop as well as the run-time test.
27697 @node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
27698 @anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{238}@anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{239}
27699 @subsubsection Other Optimization Switches
27702 @geindex Optimization Switches
27704 Since @cite{GNAT} uses the @emph{gcc} back end, all the specialized
27705 @emph{gcc} optimization switches are potentially usable. These switches
27706 have not been extensively tested with GNAT but can generally be expected
27707 to work. Examples of switches in this category are @emph{-funroll-loops}
27708 and the various target-specific @emph{-m} options (in particular, it has
27709 been observed that @emph{-march=xxx} can significantly improve performance
27710 on appropriate machines). For full details of these switches, see
27711 the @cite{Submodel Options} section in the @cite{Hardware Models and Configurations}
27712 chapter of @cite{Using the GNU Compiler Collection (GCC)}.
27714 @node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
27715 @anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{fb}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{23a}
27716 @subsubsection Optimization and Strict Aliasing
27721 @geindex Strict Aliasing
27723 @geindex No_Strict_Aliasing
27725 The strong typing capabilities of Ada allow an optimizer to generate
27726 efficient code in situations where other languages would be forced to
27727 make worst case assumptions preventing such optimizations. Consider
27728 the following example:
27734 type Int1 is new Integer;
27735 type Int2 is new Integer;
27736 type Int1A is access Int1;
27737 type Int2A is access Int2;
27744 for J in Data'Range loop
27745 if Data (J) = Int1V.all then
27746 Int2V.all := Int2V.all + 1;
27754 In this example, since the variable @cite{Int1V} can only access objects
27755 of type @cite{Int1}, and @cite{Int2V} can only access objects of type
27756 @cite{Int2}, there is no possibility that the assignment to
27757 @cite{Int2V.all} affects the value of @cite{Int1V.all}. This means that
27758 the compiler optimizer can "know" that the value @cite{Int1V.all} is constant
27759 for all iterations of the loop and avoid the extra memory reference
27760 required to dereference it each time through the loop.
27762 This kind of optimization, called strict aliasing analysis, is
27763 triggered by specifying an optimization level of @emph{-O2} or
27764 higher or @emph{-Os} and allows @cite{GNAT} to generate more efficient code
27765 when access values are involved.
27767 However, although this optimization is always correct in terms of
27768 the formal semantics of the Ada Reference Manual, difficulties can
27769 arise if features like @cite{Unchecked_Conversion} are used to break
27770 the typing system. Consider the following complete program example:
27776 type int1 is new integer;
27777 type int2 is new integer;
27778 type a1 is access int1;
27779 type a2 is access int2;
27784 function to_a2 (Input : a1) return a2;
27787 with Unchecked_Conversion;
27789 function to_a2 (Input : a1) return a2 is
27791 new Unchecked_Conversion (a1, a2);
27793 return to_a2u (Input);
27799 with Text_IO; use Text_IO;
27801 v1 : a1 := new int1;
27802 v2 : a2 := to_a2 (v1);
27806 put_line (int1'image (v1.all));
27811 This program prints out 0 in @emph{-O0} or @emph{-O1}
27812 mode, but it prints out 1 in @emph{-O2} mode. That's
27813 because in strict aliasing mode, the compiler can and
27814 does assume that the assignment to @cite{v2.all} could not
27815 affect the value of @cite{v1.all}, since different types
27818 This behavior is not a case of non-conformance with the standard, since
27819 the Ada RM specifies that an unchecked conversion where the resulting
27820 bit pattern is not a correct value of the target type can result in an
27821 abnormal value and attempting to reference an abnormal value makes the
27822 execution of a program erroneous. That's the case here since the result
27823 does not point to an object of type @cite{int2}. This means that the
27824 effect is entirely unpredictable.
27826 However, although that explanation may satisfy a language
27827 lawyer, in practice an applications programmer expects an
27828 unchecked conversion involving pointers to create true
27829 aliases and the behavior of printing 1 seems plain wrong.
27830 In this case, the strict aliasing optimization is unwelcome.
27832 Indeed the compiler recognizes this possibility, and the
27833 unchecked conversion generates a warning:
27838 p2.adb:5:07: warning: possible aliasing problem with type "a2"
27839 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
27840 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
27844 Unfortunately the problem is recognized when compiling the body of
27845 package @cite{p2}, but the actual "bad" code is generated while
27846 compiling the body of @cite{m} and this latter compilation does not see
27847 the suspicious @cite{Unchecked_Conversion}.
27849 As implied by the warning message, there are approaches you can use to
27850 avoid the unwanted strict aliasing optimization in a case like this.
27852 One possibility is to simply avoid the use of @emph{-O2}, but
27853 that is a bit drastic, since it throws away a number of useful
27854 optimizations that do not involve strict aliasing assumptions.
27856 A less drastic approach is to compile the program using the
27857 option @emph{-fno-strict-aliasing}. Actually it is only the
27858 unit containing the dereferencing of the suspicious pointer
27859 that needs to be compiled. So in this case, if we compile
27860 unit @cite{m} with this switch, then we get the expected
27861 value of zero printed. Analyzing which units might need
27862 the switch can be painful, so a more reasonable approach
27863 is to compile the entire program with options @emph{-O2}
27864 and @emph{-fno-strict-aliasing}. If the performance is
27865 satisfactory with this combination of options, then the
27866 advantage is that the entire issue of possible "wrong"
27867 optimization due to strict aliasing is avoided.
27869 To avoid the use of compiler switches, the configuration
27870 pragma @cite{No_Strict_Aliasing} with no parameters may be
27871 used to specify that for all access types, the strict
27872 aliasing optimization should be suppressed.
27874 However, these approaches are still overkill, in that they causes
27875 all manipulations of all access values to be deoptimized. A more
27876 refined approach is to concentrate attention on the specific
27877 access type identified as problematic.
27879 First, if a careful analysis of uses of the pointer shows
27880 that there are no possible problematic references, then
27881 the warning can be suppressed by bracketing the
27882 instantiation of @cite{Unchecked_Conversion} to turn
27888 pragma Warnings (Off);
27890 new Unchecked_Conversion (a1, a2);
27891 pragma Warnings (On);
27895 Of course that approach is not appropriate for this particular
27896 example, since indeed there is a problematic reference. In this
27897 case we can take one of two other approaches.
27899 The first possibility is to move the instantiation of unchecked
27900 conversion to the unit in which the type is declared. In
27901 this example, we would move the instantiation of
27902 @cite{Unchecked_Conversion} from the body of package
27903 @cite{p2} to the spec of package @cite{p1}. Now the
27904 warning disappears. That's because any use of the
27905 access type knows there is a suspicious unchecked
27906 conversion, and the strict aliasing optimization
27907 is automatically suppressed for the type.
27909 If it is not practical to move the unchecked conversion to the same unit
27910 in which the destination access type is declared (perhaps because the
27911 source type is not visible in that unit), you may use pragma
27912 @cite{No_Strict_Aliasing} for the type. This pragma must occur in the
27913 same declarative sequence as the declaration of the access type:
27918 type a2 is access int2;
27919 pragma No_Strict_Aliasing (a2);
27923 Here again, the compiler now knows that the strict aliasing optimization
27924 should be suppressed for any reference to type @cite{a2} and the
27925 expected behavior is obtained.
27927 Finally, note that although the compiler can generate warnings for
27928 simple cases of unchecked conversions, there are tricker and more
27929 indirect ways of creating type incorrect aliases which the compiler
27930 cannot detect. Examples are the use of address overlays and unchecked
27931 conversions involving composite types containing access types as
27932 components. In such cases, no warnings are generated, but there can
27933 still be aliasing problems. One safe coding practice is to forbid the
27934 use of address clauses for type overlaying, and to allow unchecked
27935 conversion only for primitive types. This is not really a significant
27936 restriction since any possible desired effect can be achieved by
27937 unchecked conversion of access values.
27939 The aliasing analysis done in strict aliasing mode can certainly
27940 have significant benefits. We have seen cases of large scale
27941 application code where the time is increased by up to 5% by turning
27942 this optimization off. If you have code that includes significant
27943 usage of unchecked conversion, you might want to just stick with
27944 @emph{-O1} and avoid the entire issue. If you get adequate
27945 performance at this level of optimization level, that's probably
27946 the safest approach. If tests show that you really need higher
27947 levels of optimization, then you can experiment with @emph{-O2}
27948 and @emph{-O2 -fno-strict-aliasing} to see how much effect this
27949 has on size and speed of the code. If you really need to use
27950 @emph{-O2} with strict aliasing in effect, then you should
27951 review any uses of unchecked conversion of access types,
27952 particularly if you are getting the warnings described above.
27954 @node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
27955 @anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{23b}@anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{23c}
27956 @subsubsection Aliased Variables and Optimization
27961 There are scenarios in which programs may
27962 use low level techniques to modify variables
27963 that otherwise might be considered to be unassigned. For example,
27964 a variable can be passed to a procedure by reference, which takes
27965 the address of the parameter and uses the address to modify the
27966 variable's value, even though it is passed as an IN parameter.
27967 Consider the following example:
27973 Max_Length : constant Natural := 16;
27974 type Char_Ptr is access all Character;
27976 procedure Get_String(Buffer: Char_Ptr; Size : Integer);
27977 pragma Import (C, Get_String, "get_string");
27979 Name : aliased String (1 .. Max_Length) := (others => ' ');
27982 function Addr (S : String) return Char_Ptr is
27983 function To_Char_Ptr is
27984 new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
27986 return To_Char_Ptr (S (S'First)'Address);
27990 Temp := Addr (Name);
27991 Get_String (Temp, Max_Length);
27996 where Get_String is a C function that uses the address in Temp to
27997 modify the variable @cite{Name}. This code is dubious, and arguably
27998 erroneous, and the compiler would be entitled to assume that
27999 @cite{Name} is never modified, and generate code accordingly.
28001 However, in practice, this would cause some existing code that
28002 seems to work with no optimization to start failing at high
28003 levels of optimzization.
28005 What the compiler does for such cases is to assume that marking
28006 a variable as aliased indicates that some "funny business" may
28007 be going on. The optimizer recognizes the aliased keyword and
28008 inhibits optimizations that assume the value cannot be assigned.
28009 This means that the above example will in fact "work" reliably,
28010 that is, it will produce the expected results.
28012 @node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
28013 @anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{23d}@anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{23e}
28014 @subsubsection Atomic Variables and Optimization
28019 There are two considerations with regard to performance when
28020 atomic variables are used.
28022 First, the RM only guarantees that access to atomic variables
28023 be atomic, it has nothing to say about how this is achieved,
28024 though there is a strong implication that this should not be
28025 achieved by explicit locking code. Indeed GNAT will never
28026 generate any locking code for atomic variable access (it will
28027 simply reject any attempt to make a variable or type atomic
28028 if the atomic access cannot be achieved without such locking code).
28030 That being said, it is important to understand that you cannot
28031 assume that the entire variable will always be accessed. Consider
28038 A,B,C,D : Character;
28041 for R'Alignment use 4;
28044 pragma Atomic (RV);
28051 You cannot assume that the reference to @cite{RV.B}
28052 will read the entire 32-bit
28053 variable with a single load instruction. It is perfectly legitimate if
28054 the hardware allows it to do a byte read of just the B field. This read
28055 is still atomic, which is all the RM requires. GNAT can and does take
28056 advantage of this, depending on the architecture and optimization level.
28057 Any assumption to the contrary is non-portable and risky. Even if you
28058 examine the assembly language and see a full 32-bit load, this might
28059 change in a future version of the compiler.
28061 If your application requires that all accesses to @cite{RV} in this
28062 example be full 32-bit loads, you need to make a copy for the access
28069 RV_Copy : constant R := RV;
28076 Now the reference to RV must read the whole variable.
28077 Actually one can imagine some compiler which figures
28078 out that the whole copy is not required (because only
28079 the B field is actually accessed), but GNAT
28080 certainly won't do that, and we don't know of any
28081 compiler that would not handle this right, and the
28082 above code will in practice work portably across
28083 all architectures (that permit the Atomic declaration).
28085 The second issue with atomic variables has to do with
28086 the possible requirement of generating synchronization
28087 code. For more details on this, consult the sections on
28088 the pragmas Enable/Disable_Atomic_Synchronization in the
28089 GNAT Reference Manual. If performance is critical, and
28090 such synchronization code is not required, it may be
28091 useful to disable it.
28093 @node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
28094 @anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{23f}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{240}
28095 @subsubsection Passive Task Optimization
28098 @geindex Passive Task
28100 A passive task is one which is sufficiently simple that
28101 in theory a compiler could recognize it an implement it
28102 efficiently without creating a new thread. The original design
28103 of Ada 83 had in mind this kind of passive task optimization, but
28104 only a few Ada 83 compilers attempted it. The problem was that
28105 it was difficult to determine the exact conditions under which
28106 the optimization was possible. The result is a very fragile
28107 optimization where a very minor change in the program can
28108 suddenly silently make a task non-optimizable.
28110 With the revisiting of this issue in Ada 95, there was general
28111 agreement that this approach was fundamentally flawed, and the
28112 notion of protected types was introduced. When using protected
28113 types, the restrictions are well defined, and you KNOW that the
28114 operations will be optimized, and furthermore this optimized
28115 performance is fully portable.
28117 Although it would theoretically be possible for GNAT to attempt to
28118 do this optimization, but it really doesn't make sense in the
28119 context of Ada 95, and none of the Ada 95 compilers implement
28120 this optimization as far as we know. In particular GNAT never
28121 attempts to perform this optimization.
28123 In any new Ada 95 code that is written, you should always
28124 use protected types in place of tasks that might be able to
28125 be optimized in this manner.
28126 Of course this does not help if you have legacy Ada 83 code
28127 that depends on this optimization, but it is unusual to encounter
28128 a case where the performance gains from this optimization
28131 Your program should work correctly without this optimization. If
28132 you have performance problems, then the most practical
28133 approach is to figure out exactly where these performance problems
28134 arise, and update those particular tasks to be protected types. Note
28135 that typically clients of the tasks who call entries, will not have
28136 to be modified, only the task definition itself.
28138 @node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
28139 @anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{241}@anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{242}
28140 @subsection @cite{Text_IO} Suggestions
28143 @geindex Text_IO and performance
28145 The @cite{Ada.Text_IO} package has fairly high overheads due in part to
28146 the requirement of maintaining page and line counts. If performance
28147 is critical, a recommendation is to use @cite{Stream_IO} instead of
28148 @cite{Text_IO} for volume output, since this package has less overhead.
28150 If @cite{Text_IO} must be used, note that by default output to the standard
28151 output and standard error files is unbuffered (this provides better
28152 behavior when output statements are used for debugging, or if the
28153 progress of a program is observed by tracking the output, e.g. by
28154 using the Unix @emph{tail -f} command to watch redirected output.
28156 If you are generating large volumes of output with @cite{Text_IO} and
28157 performance is an important factor, use a designated file instead
28158 of the standard output file, or change the standard output file to
28159 be buffered using @cite{Interfaces.C_Streams.setvbuf}.
28161 @node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
28162 @anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{243}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{244}
28163 @subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
28166 @geindex Uunused subprogram/data elimination
28168 This section describes how you can eliminate unused subprograms and data from
28169 your executable just by setting options at compilation time.
28172 * About unused subprogram/data elimination::
28173 * Compilation options::
28174 * Example of unused subprogram/data elimination::
28178 @node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
28179 @anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{245}@anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{246}
28180 @subsubsection About unused subprogram/data elimination
28183 By default, an executable contains all code and data of its composing objects
28184 (directly linked or coming from statically linked libraries), even data or code
28185 never used by this executable.
28187 This feature will allow you to eliminate such unused code from your
28188 executable, making it smaller (in disk and in memory).
28190 This functionality is available on all Linux platforms except for the IA-64
28191 architecture and on all cross platforms using the ELF binary file format.
28192 In both cases GNU binutils version 2.16 or later are required to enable it.
28194 @node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
28195 @anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{247}@anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{248}
28196 @subsubsection Compilation options
28199 The operation of eliminating the unused code and data from the final executable
28200 is directly performed by the linker.
28202 @geindex -ffunction-sections (gcc)
28204 @geindex -fdata-sections (gcc)
28206 In order to do this, it has to work with objects compiled with the
28208 @emph{-ffunction-sections} @emph{-fdata-sections}.
28210 These options are usable with C and Ada files.
28211 They will place respectively each
28212 function or data in a separate section in the resulting object file.
28214 Once the objects and static libraries are created with these options, the
28215 linker can perform the dead code elimination. You can do this by setting
28216 the @emph{-Wl,--gc-sections} option to gcc command or in the
28217 @emph{-largs} section of @emph{gnatmake}. This will perform a
28218 garbage collection of code and data never referenced.
28220 If the linker performs a partial link (@emph{-r} linker option), then you
28221 will need to provide the entry point using the @emph{-e} / @emph{--entry}
28224 Note that objects compiled without the @emph{-ffunction-sections} and
28225 @emph{-fdata-sections} options can still be linked with the executable.
28226 However, no dead code elimination will be performed on those objects (they will
28229 The GNAT static library is now compiled with -ffunction-sections and
28230 -fdata-sections on some platforms. This allows you to eliminate the unused code
28231 and data of the GNAT library from your executable.
28233 @node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
28234 @anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{249}@anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{24a}
28235 @subsubsection Example of unused subprogram/data elimination
28238 Here is a simple example:
28251 Used_Data : Integer;
28252 Unused_Data : Integer;
28254 procedure Used (Data : Integer);
28255 procedure Unused (Data : Integer);
28258 package body Aux is
28259 procedure Used (Data : Integer) is
28264 procedure Unused (Data : Integer) is
28266 Unused_Data := Data;
28272 @cite{Unused} and @cite{Unused_Data} are never referenced in this code
28273 excerpt, and hence they may be safely removed from the final executable.
28280 $ nm test | grep used
28281 020015f0 T aux__unused
28282 02005d88 B aux__unused_data
28283 020015cc T aux__used
28284 02005d84 B aux__used_data
28286 $ gnatmake test -cargs -fdata-sections -ffunction-sections \\
28287 -largs -Wl,--gc-sections
28289 $ nm test | grep used
28290 02005350 T aux__used
28291 0201ffe0 B aux__used_data
28295 It can be observed that the procedure @cite{Unused} and the object
28296 @cite{Unused_Data} are removed by the linker when using the
28297 appropriate options.
28299 @geindex Overflow checks
28301 @geindex Checks (overflow)
28304 @node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
28305 @anchor{gnat_ugn/gnat_and_program_execution id54}@anchor{1f6}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{29}
28306 @section Overflow Check Handling in GNAT
28309 This section explains how to control the handling of overflow checks.
28313 * Management of Overflows in GNAT::
28314 * Specifying the Desired Mode::
28315 * Default Settings::
28316 * Implementation Notes::
28320 @node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
28321 @anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{24b}@anchor{gnat_ugn/gnat_and_program_execution background}@anchor{24c}
28322 @subsection Background
28325 Overflow checks are checks that the compiler may make to ensure
28326 that intermediate results are not out of range. For example:
28337 If @cite{A} has the value @cite{Integer'Last}, then the addition may cause
28338 overflow since the result is out of range of the type @cite{Integer}.
28339 In this case @cite{Constraint_Error} will be raised if checks are
28342 A trickier situation arises in examples like the following:
28353 where @cite{A} is @cite{Integer'Last} and @cite{C} is @cite{-1}.
28354 Now the final result of the expression on the right hand side is
28355 @cite{Integer'Last} which is in range, but the question arises whether the
28356 intermediate addition of @cite{(A + 1)} raises an overflow error.
28358 The (perhaps surprising) answer is that the Ada language
28359 definition does not answer this question. Instead it leaves
28360 it up to the implementation to do one of two things if overflow
28361 checks are enabled.
28367 raise an exception (@cite{Constraint_Error}), or
28370 yield the correct mathematical result which is then used in
28371 subsequent operations.
28374 If the compiler chooses the first approach, then the assignment of this
28375 example will indeed raise @cite{Constraint_Error} if overflow checking is
28376 enabled, or result in erroneous execution if overflow checks are suppressed.
28378 But if the compiler
28379 chooses the second approach, then it can perform both additions yielding
28380 the correct mathematical result, which is in range, so no exception
28381 will be raised, and the right result is obtained, regardless of whether
28382 overflow checks are suppressed.
28384 Note that in the first example an
28385 exception will be raised in either case, since if the compiler
28386 gives the correct mathematical result for the addition, it will
28387 be out of range of the target type of the assignment, and thus
28388 fails the range check.
28390 This lack of specified behavior in the handling of overflow for
28391 intermediate results is a source of non-portability, and can thus
28392 be problematic when programs are ported. Most typically this arises
28393 in a situation where the original compiler did not raise an exception,
28394 and then the application is moved to a compiler where the check is
28395 performed on the intermediate result and an unexpected exception is
28398 Furthermore, when using Ada 2012's preconditions and other
28399 assertion forms, another issue arises. Consider:
28404 procedure P (A, B : Integer) with
28405 Pre => A + B <= Integer'Last;
28409 One often wants to regard arithmetic in a context like this from
28410 a mathematical point of view. So for example, if the two actual parameters
28411 for a call to @cite{P} are both @cite{Integer'Last}, then
28412 the precondition should be regarded as False. If we are executing
28413 in a mode with run-time checks enabled for preconditions, then we would
28414 like this precondition to fail, rather than raising an exception
28415 because of the intermediate overflow.
28417 However, the language definition leaves the specification of
28418 whether the above condition fails (raising @cite{Assert_Error}) or
28419 causes an intermediate overflow (raising @cite{Constraint_Error})
28420 up to the implementation.
28422 The situation is worse in a case such as the following:
28427 procedure Q (A, B, C : Integer) with
28428 Pre => A + B + C <= Integer'Last;
28437 Q (A => Integer'Last, B => 1, C => -1);
28441 From a mathematical point of view the precondition
28442 is True, but at run time we may (but are not guaranteed to) get an
28443 exception raised because of the intermediate overflow (and we really
28444 would prefer this precondition to be considered True at run time).
28446 @node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
28447 @anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{24d}@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{24e}
28448 @subsection Management of Overflows in GNAT
28451 To deal with the portability issue, and with the problem of
28452 mathematical versus run-time interpretation of the expressions in
28453 assertions, GNAT provides comprehensive control over the handling
28454 of intermediate overflow. GNAT can operate in three modes, and
28455 furthemore, permits separate selection of operating modes for
28456 the expressions within assertions (here the term 'assertions'
28457 is used in the technical sense, which includes preconditions and so forth)
28458 and for expressions appearing outside assertions.
28460 The three modes are:
28466 @emph{Use base type for intermediate operations} (@cite{STRICT})
28468 In this mode, all intermediate results for predefined arithmetic
28469 operators are computed using the base type, and the result must
28470 be in range of the base type. If this is not the
28471 case then either an exception is raised (if overflow checks are
28472 enabled) or the execution is erroneous (if overflow checks are suppressed).
28473 This is the normal default mode.
28476 @emph{Most intermediate overflows avoided} (@cite{MINIMIZED})
28478 In this mode, the compiler attempts to avoid intermediate overflows by
28479 using a larger integer type, typically @cite{Long_Long_Integer},
28480 as the type in which arithmetic is
28481 performed for predefined arithmetic operators. This may be slightly more
28483 run time (compared to suppressing intermediate overflow checks), though
28484 the cost is negligible on modern 64-bit machines. For the examples given
28485 earlier, no intermediate overflows would have resulted in exceptions,
28486 since the intermediate results are all in the range of
28487 @cite{Long_Long_Integer} (typically 64-bits on nearly all implementations
28488 of GNAT). In addition, if checks are enabled, this reduces the number of
28489 checks that must be made, so this choice may actually result in an
28490 improvement in space and time behavior.
28492 However, there are cases where @cite{Long_Long_Integer} is not large
28493 enough, consider the following example:
28498 procedure R (A, B, C, D : Integer) with
28499 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
28503 where @cite{A} = @cite{B} = @cite{C} = @cite{D} = @cite{Integer'Last}.
28504 Now the intermediate results are
28505 out of the range of @cite{Long_Long_Integer} even though the final result
28506 is in range and the precondition is True (from a mathematical point
28507 of view). In such a case, operating in this mode, an overflow occurs
28508 for the intermediate computation (which is why this mode
28509 says @emph{most} intermediate overflows are avoided). In this case,
28510 an exception is raised if overflow checks are enabled, and the
28511 execution is erroneous if overflow checks are suppressed.
28514 @emph{All intermediate overflows avoided} (@cite{ELIMINATED})
28516 In this mode, the compiler avoids all intermediate overflows
28517 by using arbitrary precision arithmetic as required. In this
28518 mode, the above example with @cite{A**2 * B**2} would
28519 not cause intermediate overflow, because the intermediate result
28520 would be evaluated using sufficient precision, and the result
28521 of evaluating the precondition would be True.
28523 This mode has the advantage of avoiding any intermediate
28524 overflows, but at the expense of significant run-time overhead,
28525 including the use of a library (included automatically in this
28526 mode) for multiple-precision arithmetic.
28528 This mode provides cleaner semantics for assertions, since now
28529 the run-time behavior emulates true arithmetic behavior for the
28530 predefined arithmetic operators, meaning that there is never a
28531 conflict between the mathematical view of the assertion, and its
28534 Note that in this mode, the behavior is unaffected by whether or
28535 not overflow checks are suppressed, since overflow does not occur.
28536 It is possible for gigantic intermediate expressions to raise
28537 @cite{Storage_Error} as a result of attempting to compute the
28538 results of such expressions (e.g. @cite{Integer'Last ** Integer'Last})
28539 but overflow is impossible.
28542 Note that these modes apply only to the evaluation of predefined
28543 arithmetic, membership, and comparison operators for signed integer
28546 For fixed-point arithmetic, checks can be suppressed. But if checks
28548 then fixed-point values are always checked for overflow against the
28549 base type for intermediate expressions (that is such checks always
28550 operate in the equivalent of @cite{STRICT} mode).
28552 For floating-point, on nearly all architectures, @cite{Machine_Overflows}
28553 is False, and IEEE infinities are generated, so overflow exceptions
28554 are never raised. If you want to avoid infinities, and check that
28555 final results of expressions are in range, then you can declare a
28556 constrained floating-point type, and range checks will be carried
28557 out in the normal manner (with infinite values always failing all
28560 @node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
28561 @anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{100}@anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{24f}
28562 @subsection Specifying the Desired Mode
28565 @geindex pragma Overflow_Mode
28567 The desired mode of for handling intermediate overflow can be specified using
28568 either the @cite{Overflow_Mode} pragma or an equivalent compiler switch.
28569 The pragma has the form
28574 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
28578 where @cite{MODE} is one of
28584 @cite{STRICT}: intermediate overflows checked (using base type)
28587 @cite{MINIMIZED}: minimize intermediate overflows
28590 @cite{ELIMINATED}: eliminate intermediate overflows
28593 The case is ignored, so @cite{MINIMIZED}, @cite{Minimized} and
28594 @cite{minimized} all have the same effect.
28596 If only the @cite{General} parameter is present, then the given @cite{MODE}
28598 to expressions both within and outside assertions. If both arguments
28599 are present, then @cite{General} applies to expressions outside assertions,
28600 and @cite{Assertions} applies to expressions within assertions. For example:
28605 pragma Overflow_Mode
28606 (General => Minimized, Assertions => Eliminated);
28610 specifies that general expressions outside assertions be evaluated
28611 in 'minimize intermediate overflows' mode, and expressions within
28612 assertions be evaluated in 'eliminate intermediate overflows' mode.
28613 This is often a reasonable choice, avoiding excessive overhead
28614 outside assertions, but assuring a high degree of portability
28615 when importing code from another compiler, while incurring
28616 the extra overhead for assertion expressions to ensure that
28617 the behavior at run time matches the expected mathematical
28620 The @cite{Overflow_Mode} pragma has the same scoping and placement
28621 rules as pragma @cite{Suppress}, so it can occur either as a
28622 configuration pragma, specifying a default for the whole
28623 program, or in a declarative scope, where it applies to the
28624 remaining declarations and statements in that scope.
28626 Note that pragma @cite{Overflow_Mode} does not affect whether
28627 overflow checks are enabled or suppressed. It only controls the
28628 method used to compute intermediate values. To control whether
28629 overflow checking is enabled or suppressed, use pragma @cite{Suppress}
28630 or @cite{Unsuppress} in the usual manner
28632 @geindex -gnato? (gcc)
28634 @geindex -gnato?? (gcc)
28636 Additionally, a compiler switch @emph{-gnato?} or @emph{-gnato??}
28637 can be used to control the checking mode default (which can be subsequently
28638 overridden using pragmas).
28640 Here @code{?} is one of the digits @code{1} through @code{3}:
28645 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
28652 use base type for intermediate operations (@cite{STRICT})
28660 minimize intermediate overflows (@cite{MINIMIZED})
28668 eliminate intermediate overflows (@cite{ELIMINATED})
28674 As with the pragma, if only one digit appears then it applies to all
28675 cases; if two digits are given, then the first applies outside
28676 assertions, and the second within assertions. Thus the equivalent
28677 of the example pragma above would be
28680 If no digits follow the @emph{-gnato}, then it is equivalent to
28682 causing all intermediate operations to be computed using the base
28683 type (@cite{STRICT} mode).
28685 @node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
28686 @anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{250}@anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{251}
28687 @subsection Default Settings
28690 The default mode for overflow checks is
28699 which causes all computations both inside and outside assertions to use
28702 This retains compatibility with previous versions of
28703 GNAT which suppressed overflow checks by default and always
28704 used the base type for computation of intermediate results.
28706 @c Sphinx allows no emphasis within :index: role. As a workaround we
28707 @c point the index to "switch" and use emphasis for "-gnato".
28710 @geindex -gnato (gcc)
28711 switch @emph{-gnato} (with no digits following)
28721 which causes overflow checking of all intermediate overflows
28722 both inside and outside assertions against the base type.
28724 The pragma @cite{Suppress (Overflow_Check)} disables overflow
28725 checking, but it has no effect on the method used for computing
28726 intermediate results.
28728 The pragma @cite{Unsuppress (Overflow_Check)} enables overflow
28729 checking, but it has no effect on the method used for computing
28730 intermediate results.
28732 @node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
28733 @anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{252}@anchor{gnat_ugn/gnat_and_program_execution id59}@anchor{253}
28734 @subsection Implementation Notes
28737 In practice on typical 64-bit machines, the @cite{MINIMIZED} mode is
28738 reasonably efficient, and can be generally used. It also helps
28739 to ensure compatibility with code imported from some other
28742 Setting all intermediate overflows checking (@cite{CHECKED} mode)
28743 makes sense if you want to
28744 make sure that your code is compatible with any other possible
28745 Ada implementation. This may be useful in ensuring portability
28746 for code that is to be exported to some other compiler than GNAT.
28748 The Ada standard allows the reassociation of expressions at
28749 the same precedence level if no parentheses are present. For
28750 example, @cite{A+B+C} parses as though it were @cite{(A+B)+C}, but
28751 the compiler can reintepret this as @cite{A+(B+C)}, possibly
28752 introducing or eliminating an overflow exception. The GNAT
28753 compiler never takes advantage of this freedom, and the
28754 expression @cite{A+B+C} will be evaluated as @cite{(A+B)+C}.
28755 If you need the other order, you can write the parentheses
28756 explicitly @cite{A+(B+C)} and GNAT will respect this order.
28758 The use of @cite{ELIMINATED} mode will cause the compiler to
28759 automatically include an appropriate arbitrary precision
28760 integer arithmetic package. The compiler will make calls
28761 to this package, though only in cases where it cannot be
28762 sure that @cite{Long_Long_Integer} is sufficient to guard against
28763 intermediate overflows. This package does not use dynamic
28764 alllocation, but it does use the secondary stack, so an
28765 appropriate secondary stack package must be present (this
28766 is always true for standard full Ada, but may require
28767 specific steps for restricted run times such as ZFP).
28769 Although @cite{ELIMINATED} mode causes expressions to use arbitrary
28770 precision arithmetic, avoiding overflow, the final result
28771 must be in an appropriate range. This is true even if the
28772 final result is of type @cite{[Long_[Long_]]Integer'Base}, which
28773 still has the same bounds as its associated constrained
28776 Currently, the @cite{ELIMINATED} mode is only available on target
28777 platforms for which @cite{Long_Long_Integer} is 64-bits (nearly all GNAT
28780 @node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
28781 @anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{2a}@anchor{gnat_ugn/gnat_and_program_execution id60}@anchor{1f7}
28782 @section Performing Dimensionality Analysis in GNAT
28785 @geindex Dimensionality analysis
28787 The GNAT compiler supports dimensionality checking. The user can
28788 specify physical units for objects, and the compiler will verify that uses
28789 of these objects are compatible with their dimensions, in a fashion that is
28790 familiar to engineering practice. The dimensions of algebraic expressions
28791 (including powers with static exponents) are computed from their constituents.
28793 @geindex Dimension_System aspect
28795 @geindex Dimension aspect
28797 This feature depends on Ada 2012 aspect specifications, and is available from
28798 version 7.0.1 of GNAT onwards.
28799 The GNAT-specific aspect @cite{Dimension_System}
28800 allows you to define a system of units; the aspect @cite{Dimension}
28801 then allows the user to declare dimensioned quantities within a given system.
28802 (These aspects are described in the @emph{Implementation Defined Aspects}
28803 chapter of the @emph{GNAT Reference Manual}).
28805 The major advantage of this model is that it does not require the declaration of
28806 multiple operators for all possible combinations of types: it is only necessary
28807 to use the proper subtypes in object declarations.
28809 @geindex System.Dim.Mks package (GNAT library)
28811 @geindex MKS_Type type
28813 The simplest way to impose dimensionality checking on a computation is to make
28814 use of the package @cite{System.Dim.Mks},
28815 which is part of the GNAT library. This
28816 package defines a floating-point type @cite{MKS_Type},
28817 for which a sequence of
28818 dimension names are specified, together with their conventional abbreviations.
28819 The following should be read together with the full specification of the
28820 package, in file @code{s-dimmks.ads}.
28824 @geindex s-dimmks.ads file
28827 type Mks_Type is new Long_Long_Float
28829 Dimension_System => (
28830 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'),
28831 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'),
28832 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'),
28833 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'),
28834 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"),
28835 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'),
28836 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J'));
28840 The package then defines a series of subtypes that correspond to these
28841 conventional units. For example:
28846 subtype Length is Mks_Type
28848 Dimension => (Symbol => 'm', Meter => 1, others => 0);
28852 and similarly for @cite{Mass}, @cite{Time}, @cite{Electric_Current},
28853 @cite{Thermodynamic_Temperature}, @cite{Amount_Of_Substance}, and
28854 @cite{Luminous_Intensity} (the standard set of units of the SI system).
28856 The package also defines conventional names for values of each unit, for
28861 @c code-block":: ada
28863 @c m : constant Length := 1.0;
28864 @c kg : constant Mass := 1.0;
28865 @c s : constant Time := 1.0;
28866 @c A : constant Electric_Current := 1.0;
28869 as well as useful multiples of these units:
28874 cm : constant Length := 1.0E-02;
28875 g : constant Mass := 1.0E-03;
28876 min : constant Time := 60.0;
28877 day : constant Time := 60.0 * 24.0 * min;
28882 Using this package, you can then define a derived unit by
28883 providing the aspect that
28884 specifies its dimensions within the MKS system, as well as the string to
28885 be used for output of a value of that unit:
28890 subtype Acceleration is Mks_Type
28891 with Dimension => ("m/sec^2",
28898 Here is a complete example of use:
28903 with System.Dim.MKS; use System.Dim.Mks;
28904 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
28905 with Text_IO; use Text_IO;
28906 procedure Free_Fall is
28907 subtype Acceleration is Mks_Type
28908 with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
28909 G : constant acceleration := 9.81 * m / (s ** 2);
28910 T : Time := 10.0*s;
28914 Put ("Gravitational constant: ");
28915 Put (G, Aft => 2, Exp => 0); Put_Line ("");
28916 Distance := 0.5 * G * T ** 2;
28917 Put ("distance travelled in 10 seconds of free fall ");
28918 Put (Distance, Aft => 2, Exp => 0);
28924 Execution of this program yields:
28929 Gravitational constant: 9.81 m/sec^2
28930 distance travelled in 10 seconds of free fall 490.50 m
28934 However, incorrect assignments such as:
28940 Distance := 5.0 * kg:
28944 are rejected with the following diagnoses:
28950 >>> dimensions mismatch in assignment
28951 >>> left-hand side has dimension [L]
28952 >>> right-hand side is dimensionless
28954 Distance := 5.0 * kg:
28955 >>> dimensions mismatch in assignment
28956 >>> left-hand side has dimension [L]
28957 >>> right-hand side has dimension [M]
28961 The dimensions of an expression are properly displayed, even if there is
28962 no explicit subtype for it. If we add to the program:
28967 Put ("Final velocity: ");
28968 Put (G * T, Aft =>2, Exp =>0);
28973 then the output includes:
28978 Final velocity: 98.10 m.s**(-1)
28982 @node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
28983 @anchor{gnat_ugn/gnat_and_program_execution id61}@anchor{1f8}@anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{2b}
28984 @section Stack Related Facilities
28987 This section describes some useful tools associated with stack
28988 checking and analysis. In
28989 particular, it deals with dynamic and static stack usage measurements.
28992 * Stack Overflow Checking::
28993 * Static Stack Usage Analysis::
28994 * Dynamic Stack Usage Analysis::
28998 @node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
28999 @anchor{gnat_ugn/gnat_and_program_execution id62}@anchor{254}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{fc}
29000 @subsection Stack Overflow Checking
29003 @geindex Stack Overflow Checking
29005 @geindex -fstack-check (gcc)
29007 For most operating systems, @emph{gcc} does not perform stack overflow
29008 checking by default. This means that if the main environment task or
29009 some other task exceeds the available stack space, then unpredictable
29010 behavior will occur. Most native systems offer some level of protection by
29011 adding a guard page at the end of each task stack. This mechanism is usually
29012 not enough for dealing properly with stack overflow situations because
29013 a large local variable could "jump" above the guard page.
29014 Furthermore, when the
29015 guard page is hit, there may not be any space left on the stack for executing
29016 the exception propagation code. Enabling stack checking avoids
29019 To activate stack checking, compile all units with the gcc option
29020 @cite{-fstack-check}. For example:
29025 $ gcc -c -fstack-check package1.adb
29029 Units compiled with this option will generate extra instructions to check
29030 that any use of the stack (for procedure calls or for declaring local
29031 variables in declare blocks) does not exceed the available stack space.
29032 If the space is exceeded, then a @cite{Storage_Error} exception is raised.
29034 For declared tasks, the stack size is controlled by the size
29035 given in an applicable @cite{Storage_Size} pragma or by the value specified
29036 at bind time with @code{-d} (@ref{126,,Switches for gnatbind}) or is set to
29037 the default size as defined in the GNAT runtime otherwise.
29039 @geindex GNAT_STACK_LIMIT
29041 For the environment task, the stack size depends on
29042 system defaults and is unknown to the compiler. Stack checking
29043 may still work correctly if a fixed
29044 size stack is allocated, but this cannot be guaranteed.
29045 To ensure that a clean exception is signalled for stack
29046 overflow, set the environment variable
29047 @geindex GNAT_STACK_LIMIT
29048 @geindex environment variable; GNAT_STACK_LIMIT
29049 @code{GNAT_STACK_LIMIT} to indicate the maximum
29050 stack area that can be used, as in:
29055 $ SET GNAT_STACK_LIMIT 1600
29059 The limit is given in kilobytes, so the above declaration would
29060 set the stack limit of the environment task to 1.6 megabytes.
29061 Note that the only purpose of this usage is to limit the amount
29062 of stack used by the environment task. If it is necessary to
29063 increase the amount of stack for the environment task, then this
29064 is an operating systems issue, and must be addressed with the
29065 appropriate operating systems commands.
29067 @node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
29068 @anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{fd}@anchor{gnat_ugn/gnat_and_program_execution id63}@anchor{255}
29069 @subsection Static Stack Usage Analysis
29072 @geindex Static Stack Usage Analysis
29074 @geindex -fstack-usage
29076 A unit compiled with @code{-fstack-usage} will generate an extra file
29078 the maximum amount of stack used, on a per-function basis.
29079 The file has the same
29080 basename as the target object file with a @code{.su} extension.
29081 Each line of this file is made up of three fields:
29087 The name of the function.
29093 One or more qualifiers: @cite{static}, @cite{dynamic}, @cite{bounded}.
29096 The second field corresponds to the size of the known part of the function
29099 The qualifier @cite{static} means that the function frame size
29101 It usually means that all local variables have a static size.
29102 In this case, the second field is a reliable measure of the function stack
29105 The qualifier @cite{dynamic} means that the function frame size is not static.
29106 It happens mainly when some local variables have a dynamic size. When this
29107 qualifier appears alone, the second field is not a reliable measure
29108 of the function stack analysis. When it is qualified with @cite{bounded}, it
29109 means that the second field is a reliable maximum of the function stack
29112 A unit compiled with @code{-Wstack-usage} will issue a warning for each
29113 subprogram whose stack usage might be larger than the specified amount of
29114 bytes. The wording is in keeping with the qualifier documented above.
29116 @node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
29117 @anchor{gnat_ugn/gnat_and_program_execution id64}@anchor{256}@anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{128}
29118 @subsection Dynamic Stack Usage Analysis
29121 It is possible to measure the maximum amount of stack used by a task, by
29122 adding a switch to @emph{gnatbind}, as:
29127 $ gnatbind -u0 file
29131 With this option, at each task termination, its stack usage is output on
29133 It is not always convenient to output the stack usage when the program
29134 is still running. Hence, it is possible to delay this output until program
29135 termination. for a given number of tasks specified as the argument of the
29136 @code{-u} option. For instance:
29141 $ gnatbind -u100 file
29145 will buffer the stack usage information of the first 100 tasks to terminate and
29146 output this info at program termination. Results are displayed in four
29152 Index | Task Name | Stack Size | Stack Usage
29162 @emph{Index} is a number associated with each task.
29165 @emph{Task Name} is the name of the task analyzed.
29168 @emph{Stack Size} is the maximum size for the stack.
29171 @emph{Stack Usage} is the measure done by the stack analyzer.
29172 In order to prevent overflow, the stack
29173 is not entirely analyzed, and it's not possible to know exactly how
29174 much has actually been used.
29177 The environment task stack, e.g., the stack that contains the main unit, is
29178 only processed when the environment variable GNAT_STACK_LIMIT is set.
29180 The package @cite{GNAT.Task_Stack_Usage} provides facilities to get
29181 stack usage reports at run-time. See its body for the details.
29183 @node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
29184 @anchor{gnat_ugn/gnat_and_program_execution id65}@anchor{1f9}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{2c}
29185 @section Memory Management Issues
29188 This section describes some useful memory pools provided in the GNAT library
29189 and in particular the GNAT Debug Pool facility, which can be used to detect
29190 incorrect uses of access values (including 'dangling references').
29194 * Some Useful Memory Pools::
29195 * The GNAT Debug Pool Facility::
29199 @node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
29200 @anchor{gnat_ugn/gnat_and_program_execution id66}@anchor{257}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{258}
29201 @subsection Some Useful Memory Pools
29204 @geindex Memory Pool
29209 The @cite{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
29210 storage pool. Allocations use the standard system call @cite{malloc} while
29211 deallocations use the standard system call @cite{free}. No reclamation is
29212 performed when the pool goes out of scope. For performance reasons, the
29213 standard default Ada allocators/deallocators do not use any explicit storage
29214 pools but if they did, they could use this storage pool without any change in
29215 behavior. That is why this storage pool is used when the user
29216 manages to make the default implicit allocator explicit as in this example:
29221 type T1 is access Something;
29222 -- no Storage pool is defined for T2
29224 type T2 is access Something_Else;
29225 for T2'Storage_Pool use T1'Storage_Pool;
29226 -- the above is equivalent to
29227 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
29231 The @cite{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
29232 pool. The allocation strategy is similar to @cite{Pool_Local}'s
29233 except that the all
29234 storage allocated with this pool is reclaimed when the pool object goes out of
29235 scope. This pool provides a explicit mechanism similar to the implicit one
29236 provided by several Ada 83 compilers for allocations performed through a local
29237 access type and whose purpose was to reclaim memory when exiting the
29238 scope of a given local access. As an example, the following program does not
29239 leak memory even though it does not perform explicit deallocation:
29244 with System.Pool_Local;
29245 procedure Pooloc1 is
29246 procedure Internal is
29247 type A is access Integer;
29248 X : System.Pool_Local.Unbounded_Reclaim_Pool;
29249 for A'Storage_Pool use X;
29252 for I in 1 .. 50 loop
29257 for I in 1 .. 100 loop
29264 The @cite{System.Pool_Size} package implements the Stack_Bounded_Pool used when
29265 @cite{Storage_Size} is specified for an access type.
29266 The whole storage for the pool is
29267 allocated at once, usually on the stack at the point where the access type is
29268 elaborated. It is automatically reclaimed when exiting the scope where the
29269 access type is defined. This package is not intended to be used directly by the
29270 user and it is implicitly used for each such declaration:
29275 type T1 is access Something;
29276 for T1'Storage_Size use 10_000;
29280 @node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
29281 @anchor{gnat_ugn/gnat_and_program_execution id67}@anchor{259}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{25a}
29282 @subsection The GNAT Debug Pool Facility
29285 @geindex Debug Pool
29289 @geindex memory corruption
29291 The use of unchecked deallocation and unchecked conversion can easily
29292 lead to incorrect memory references. The problems generated by such
29293 references are usually difficult to tackle because the symptoms can be
29294 very remote from the origin of the problem. In such cases, it is
29295 very helpful to detect the problem as early as possible. This is the
29296 purpose of the Storage Pool provided by @cite{GNAT.Debug_Pools}.
29298 In order to use the GNAT specific debugging pool, the user must
29299 associate a debug pool object with each of the access types that may be
29300 related to suspected memory problems. See Ada Reference Manual 13.11.
29305 type Ptr is access Some_Type;
29306 Pool : GNAT.Debug_Pools.Debug_Pool;
29307 for Ptr'Storage_Pool use Pool;
29311 @cite{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
29312 pool: the @cite{Checked_Pool}. Such pools, like standard Ada storage pools,
29313 allow the user to redefine allocation and deallocation strategies. They
29314 also provide a checkpoint for each dereference, through the use of
29315 the primitive operation @cite{Dereference} which is implicitly called at
29316 each dereference of an access value.
29318 Once an access type has been associated with a debug pool, operations on
29319 values of the type may raise four distinct exceptions,
29320 which correspond to four potential kinds of memory corruption:
29326 @cite{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
29329 @cite{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
29332 @cite{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
29335 @cite{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
29338 For types associated with a Debug_Pool, dynamic allocation is performed using
29339 the standard GNAT allocation routine. References to all allocated chunks of
29340 memory are kept in an internal dictionary. Several deallocation strategies are
29341 provided, whereupon the user can choose to release the memory to the system,
29342 keep it allocated for further invalid access checks, or fill it with an easily
29343 recognizable pattern for debug sessions. The memory pattern is the old IBM
29344 hexadecimal convention: @cite{16#DEADBEEF#}.
29346 See the documentation in the file g-debpoo.ads for more information on the
29347 various strategies.
29349 Upon each dereference, a check is made that the access value denotes a
29350 properly allocated memory location. Here is a complete example of use of
29351 @cite{Debug_Pools}, that includes typical instances of memory corruption:
29356 with Gnat.Io; use Gnat.Io;
29357 with Unchecked_Deallocation;
29358 with Unchecked_Conversion;
29359 with GNAT.Debug_Pools;
29360 with System.Storage_Elements;
29361 with Ada.Exceptions; use Ada.Exceptions;
29362 procedure Debug_Pool_Test is
29364 type T is access Integer;
29365 type U is access all T;
29367 P : GNAT.Debug_Pools.Debug_Pool;
29368 for T'Storage_Pool use P;
29370 procedure Free is new Unchecked_Deallocation (Integer, T);
29371 function UC is new Unchecked_Conversion (U, T);
29374 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
29384 Put_Line (Integer'Image(B.all));
29386 when E : others => Put_Line ("raised: " & Exception_Name (E));
29391 when E : others => Put_Line ("raised: " & Exception_Name (E));
29395 Put_Line (Integer'Image(B.all));
29397 when E : others => Put_Line ("raised: " & Exception_Name (E));
29402 when E : others => Put_Line ("raised: " & Exception_Name (E));
29405 end Debug_Pool_Test;
29409 The debug pool mechanism provides the following precise diagnostics on the
29410 execution of this erroneous program:
29416 Total allocated bytes : 0
29417 Total deallocated bytes : 0
29418 Current Water Mark: 0
29422 Total allocated bytes : 8
29423 Total deallocated bytes : 0
29424 Current Water Mark: 8
29427 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
29428 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
29429 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
29430 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
29432 Total allocated bytes : 8
29433 Total deallocated bytes : 4
29434 Current Water Mark: 4
29440 @c -- Non-breaking space in running text
29441 @c -- E.g. Ada |nbsp| 95
29443 @node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
29444 @anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{f}@anchor{gnat_ugn/platform_specific_information doc}@anchor{25b}@anchor{gnat_ugn/platform_specific_information id1}@anchor{25c}
29445 @chapter Platform-Specific Information
29448 This appendix contains information relating to the implementation
29449 of run-time libraries on various platforms and also covers
29450 topics related to the GNAT implementation on Windows and Mac OS.
29453 * Run-Time Libraries::
29454 * Specifying a Run-Time Library::
29455 * Microsoft Windows Topics::
29460 @node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
29461 @anchor{gnat_ugn/platform_specific_information id2}@anchor{25d}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{2d}
29462 @section Run-Time Libraries
29465 @geindex Tasking and threads libraries
29467 @geindex Threads libraries and tasking
29469 @geindex Run-time libraries (platform-specific information)
29471 The GNAT run-time implementation may vary with respect to both the
29472 underlying threads library and the exception handling scheme.
29473 For threads support, one or more of the following are supplied:
29479 @strong{native threads library}, a binding to the thread package from
29480 the underlying operating system
29483 @strong{pthreads library} (Sparc Solaris only), a binding to the Solaris
29484 POSIX thread package
29487 For exception handling, either or both of two models are supplied:
29491 @geindex Zero-Cost Exceptions
29493 @geindex ZCX (Zero-Cost Exceptions)
29500 @strong{Zero-Cost Exceptions} ("ZCX"),
29501 which uses binder-generated tables that
29502 are interrogated at run time to locate a handler.
29504 @geindex setjmp/longjmp Exception Model
29506 @geindex SJLJ (setjmp/longjmp Exception Model)
29509 @strong{setjmp / longjmp} ('SJLJ'),
29510 which uses dynamically-set data to establish
29511 the set of handlers
29514 Most programs should experience a substantial speed improvement by
29515 being compiled with a ZCX run-time.
29516 This is especially true for
29517 tasking applications or applications with many exception handlers.@}
29519 This section summarizes which combinations of threads and exception support
29520 are supplied on various GNAT platforms.
29521 It then shows how to select a particular library either
29522 permanently or temporarily,
29523 explains the properties of (and tradeoffs among) the various threads
29524 libraries, and provides some additional
29525 information about several specific platforms.
29528 * Summary of Run-Time Configurations::
29532 @node Summary of Run-Time Configurations,,,Run-Time Libraries
29533 @anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{25e}@anchor{gnat_ugn/platform_specific_information id3}@anchor{25f}
29534 @subsection Summary of Run-Time Configurations
29538 @multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx}
29685 native LynxOS threads
29733 native Win32 threads
29745 native Win32 threads
29783 @node Specifying a Run-Time Library,Microsoft Windows Topics,Run-Time Libraries,Platform-Specific Information
29784 @anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{260}@anchor{gnat_ugn/platform_specific_information id4}@anchor{261}
29785 @section Specifying a Run-Time Library
29788 The @code{adainclude} subdirectory containing the sources of the GNAT
29789 run-time library, and the @code{adalib} subdirectory containing the
29790 @code{ALI} files and the static and/or shared GNAT library, are located
29791 in the gcc target-dependent area:
29796 target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
29800 As indicated above, on some platforms several run-time libraries are supplied.
29801 These libraries are installed in the target dependent area and
29802 contain a complete source and binary subdirectory. The detailed description
29803 below explains the differences between the different libraries in terms of
29804 their thread support.
29806 The default run-time library (when GNAT is installed) is @emph{rts-native}.
29807 This default run time is selected by the means of soft links.
29808 For example on x86-linux:
29814 -- +--- adainclude----------+
29816 -- +--- adalib-----------+ |
29818 -- +--- rts-native | |
29820 -- | +--- adainclude <---+
29822 -- | +--- adalib <----+
29831 If the @emph{rts-sjlj} library is to be selected on a permanent basis,
29832 these soft links can be modified with the following commands:
29838 $ rm -f adainclude adalib
29839 $ ln -s rts-sjlj/adainclude adainclude
29840 $ ln -s rts-sjlj/adalib adalib
29844 Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
29845 @code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
29846 @code{$target/ada_object_path}.
29848 @geindex --RTS option
29850 Selecting another run-time library temporarily can be
29851 achieved by using the @emph{--RTS} switch, e.g., @emph{--RTS=sjlj}
29852 @anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{262}
29853 @geindex SCHED_FIFO scheduling policy
29855 @geindex SCHED_RR scheduling policy
29857 @geindex SCHED_OTHER scheduling policy
29860 * Choosing the Scheduling Policy::
29861 * Solaris-Specific Considerations::
29862 * Solaris Threads Issues::
29863 * AIX-Specific Considerations::
29867 @node Choosing the Scheduling Policy,Solaris-Specific Considerations,,Specifying a Run-Time Library
29868 @anchor{gnat_ugn/platform_specific_information id5}@anchor{263}
29869 @subsection Choosing the Scheduling Policy
29872 When using a POSIX threads implementation, you have a choice of several
29873 scheduling policies: @cite{SCHED_FIFO}, @cite{SCHED_RR} and @cite{SCHED_OTHER}.
29875 Typically, the default is @cite{SCHED_OTHER}, while using @cite{SCHED_FIFO}
29876 or @cite{SCHED_RR} requires special (e.g., root) privileges.
29878 @geindex pragma Time_Slice
29880 @geindex -T0 option
29882 @geindex pragma Task_Dispatching_Policy
29884 By default, GNAT uses the @cite{SCHED_OTHER} policy. To specify
29886 you can use one of the following:
29892 @cite{pragma Time_Slice (0.0)}
29895 the corresponding binder option @emph{-T0}
29898 @cite{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
29901 To specify @cite{SCHED_RR},
29902 you should use @cite{pragma Time_Slice} with a
29903 value greater than 0.0, or else use the corresponding @emph{-T}
29906 @geindex Solaris Sparc threads libraries
29908 @node Solaris-Specific Considerations,Solaris Threads Issues,Choosing the Scheduling Policy,Specifying a Run-Time Library
29909 @anchor{gnat_ugn/platform_specific_information id6}@anchor{264}@anchor{gnat_ugn/platform_specific_information solaris-specific-considerations}@anchor{265}
29910 @subsection Solaris-Specific Considerations
29913 This section addresses some topics related to the various threads libraries
29916 @geindex rts-pthread threads library
29918 @node Solaris Threads Issues,AIX-Specific Considerations,Solaris-Specific Considerations,Specifying a Run-Time Library
29919 @anchor{gnat_ugn/platform_specific_information id7}@anchor{266}@anchor{gnat_ugn/platform_specific_information solaris-threads-issues}@anchor{267}
29920 @subsection Solaris Threads Issues
29923 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
29924 library based on POSIX threads --- @emph{rts-pthread}.
29926 @geindex PTHREAD_PRIO_INHERIT policy (under rts-pthread)
29928 @geindex PTHREAD_PRIO_PROTECT policy (under rts-pthread)
29930 @geindex pragma Locking_Policy (under rts-pthread)
29932 @geindex Inheritance_Locking (under rts-pthread)
29934 @geindex Ceiling_Locking (under rts-pthread)
29936 This run-time library has the advantage of being mostly shared across all
29937 POSIX-compliant thread implementations, and it also provides under
29938 Solaris 8 the @cite{PTHREAD_PRIO_INHERIT}
29939 and @cite{PTHREAD_PRIO_PROTECT}
29940 semantics that can be selected using the predefined pragma
29941 @cite{Locking_Policy}
29943 @cite{Inheritance_Locking} and @cite{Ceiling_Locking} as the policy.
29945 As explained above, the native run-time library is based on the Solaris thread
29946 library (@cite{libthread}) and is the default library.
29948 @geindex GNAT_PROCESSOR environment variable (on Sparc Solaris)
29950 When the Solaris threads library is used (this is the default), programs
29951 compiled with GNAT can automatically take advantage of
29952 and can thus execute on multiple processors.
29953 The user can alternatively specify a processor on which the program should run
29954 to emulate a single-processor system. The multiprocessor / uniprocessor choice
29956 setting the environment variable
29957 @geindex GNAT_PROCESSOR
29958 @geindex environment variable; GNAT_PROCESSOR
29959 @code{GNAT_PROCESSOR}
29960 to one of the following:
29965 @multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
29968 @code{GNAT_PROCESSOR} Value
29980 Use the default configuration (run the program on all
29981 available processors) - this is the same as having @cite{GNAT_PROCESSOR}
29990 Let the run-time implementation choose one processor and run the
29991 program on that processor
29995 @emph{0 .. Last_Proc}
29999 Run the program on the specified processor.
30000 @cite{Last_Proc} is equal to @cite{_SC_NPROCESSORS_CONF - 1}
30001 (where @cite{_SC_NPROCESSORS_CONF} is a system variable).
30007 @node AIX-Specific Considerations,,Solaris Threads Issues,Specifying a Run-Time Library
30008 @anchor{gnat_ugn/platform_specific_information aix-specific-considerations}@anchor{268}@anchor{gnat_ugn/platform_specific_information id8}@anchor{269}
30009 @subsection AIX-Specific Considerations
30012 @geindex AIX resolver library
30014 On AIX, the resolver library initializes some internal structure on
30015 the first call to @cite{get*by*} functions, which are used to implement
30016 @cite{GNAT.Sockets.Get_Host_By_Name} and
30017 @cite{GNAT.Sockets.Get_Host_By_Address}.
30018 If such initialization occurs within an Ada task, and the stack size for
30019 the task is the default size, a stack overflow may occur.
30021 To avoid this overflow, the user should either ensure that the first call
30022 to @cite{GNAT.Sockets.Get_Host_By_Name} or
30023 @cite{GNAT.Sockets.Get_Host_By_Addrss}
30024 occurs in the environment task, or use @cite{pragma Storage_Size} to
30025 specify a sufficiently large size for the stack of the task that contains
30028 @geindex Windows NT
30030 @geindex Windows 95
30032 @geindex Windows 98
30034 @node Microsoft Windows Topics,Mac OS Topics,Specifying a Run-Time Library,Platform-Specific Information
30035 @anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{2e}@anchor{gnat_ugn/platform_specific_information id9}@anchor{26a}
30036 @section Microsoft Windows Topics
30039 This section describes topics that are specific to the Microsoft Windows
30047 * Using GNAT on Windows::
30048 * Using a network installation of GNAT::
30049 * CONSOLE and WINDOWS subsystems::
30050 * Temporary Files::
30051 * Mixed-Language Programming on Windows::
30052 * Windows Specific Add-Ons::
30056 @node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
30057 @anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{26b}@anchor{gnat_ugn/platform_specific_information id10}@anchor{26c}
30058 @subsection Using GNAT on Windows
30061 One of the strengths of the GNAT technology is that its tool set
30062 (@emph{gcc}, @emph{gnatbind}, @emph{gnatlink}, @emph{gnatmake}, the
30063 @cite{gdb} debugger, etc.) is used in the same way regardless of the
30066 On Windows this tool set is complemented by a number of Microsoft-specific
30067 tools that have been provided to facilitate interoperability with Windows
30068 when this is required. With these tools:
30074 You can build applications using the @cite{CONSOLE} or @cite{WINDOWS}
30078 You can use any Dynamically Linked Library (DLL) in your Ada code (both
30079 relocatable and non-relocatable DLLs are supported).
30082 You can build Ada DLLs for use in other applications. These applications
30083 can be written in a language other than Ada (e.g., C, C++, etc). Again both
30084 relocatable and non-relocatable Ada DLLs are supported.
30087 You can include Windows resources in your Ada application.
30090 You can use or create COM/DCOM objects.
30093 Immediately below are listed all known general GNAT-for-Windows restrictions.
30094 Other restrictions about specific features like Windows Resources and DLLs
30095 are listed in separate sections below.
30101 It is not possible to use @cite{GetLastError} and @cite{SetLastError}
30102 when tasking, protected records, or exceptions are used. In these
30103 cases, in order to implement Ada semantics, the GNAT run-time system
30104 calls certain Win32 routines that set the last error variable to 0 upon
30105 success. It should be possible to use @cite{GetLastError} and
30106 @cite{SetLastError} when tasking, protected record, and exception
30107 features are not used, but it is not guaranteed to work.
30110 It is not possible to link against Microsoft C++ libraries except for
30111 import libraries. Interfacing must be done by the mean of DLLs.
30114 It is possible to link against Microsoft C libraries. Yet the preferred
30115 solution is to use C/C++ compiler that comes with GNAT, since it
30116 doesn't require having two different development environments and makes the
30117 inter-language debugging experience smoother.
30120 When the compilation environment is located on FAT32 drives, users may
30121 experience recompilations of the source files that have not changed if
30122 Daylight Saving Time (DST) state has changed since the last time files
30123 were compiled. NTFS drives do not have this problem.
30126 No components of the GNAT toolset use any entries in the Windows
30127 registry. The only entries that can be created are file associations and
30128 PATH settings, provided the user has chosen to create them at installation
30129 time, as well as some minimal book-keeping information needed to correctly
30130 uninstall or integrate different GNAT products.
30133 @node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
30134 @anchor{gnat_ugn/platform_specific_information id11}@anchor{26d}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{26e}
30135 @subsection Using a network installation of GNAT
30138 Make sure the system on which GNAT is installed is accessible from the
30139 current machine, i.e., the install location is shared over the network.
30140 Shared resources are accessed on Windows by means of UNC paths, which
30141 have the format @cite{\\server\sharename\path}
30143 In order to use such a network installation, simply add the UNC path of the
30144 @code{bin} directory of your GNAT installation in front of your PATH. For
30145 example, if GNAT is installed in @code{\GNAT} directory of a share location
30146 called @code{c-drive} on a machine @code{LOKI}, the following command will
30152 $ path \\loki\c-drive\gnat\bin;%path%`
30156 Be aware that every compilation using the network installation results in the
30157 transfer of large amounts of data across the network and will likely cause
30158 serious performance penalty.
30160 @node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
30161 @anchor{gnat_ugn/platform_specific_information id12}@anchor{26f}@anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{270}
30162 @subsection CONSOLE and WINDOWS subsystems
30165 @geindex CONSOLE Subsystem
30167 @geindex WINDOWS Subsystem
30171 There are two main subsystems under Windows. The @cite{CONSOLE} subsystem
30172 (which is the default subsystem) will always create a console when
30173 launching the application. This is not something desirable when the
30174 application has a Windows GUI. To get rid of this console the
30175 application must be using the @cite{WINDOWS} subsystem. To do so
30176 the @emph{-mwindows} linker option must be specified.
30181 $ gnatmake winprog -largs -mwindows
30185 @node Temporary Files,Mixed-Language Programming on Windows,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
30186 @anchor{gnat_ugn/platform_specific_information id13}@anchor{271}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{272}
30187 @subsection Temporary Files
30190 @geindex Temporary files
30192 It is possible to control where temporary files gets created by setting
30195 @geindex environment variable; TMP
30196 @code{TMP} environment variable. The file will be created:
30202 Under the directory pointed to by the
30204 @geindex environment variable; TMP
30205 @code{TMP} environment variable if
30206 this directory exists.
30209 Under @code{c:\temp}, if the
30211 @geindex environment variable; TMP
30212 @code{TMP} environment variable is not
30213 set (or not pointing to a directory) and if this directory exists.
30216 Under the current working directory otherwise.
30219 This allows you to determine exactly where the temporary
30220 file will be created. This is particularly useful in networked
30221 environments where you may not have write access to some
30224 @node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Temporary Files,Microsoft Windows Topics
30225 @anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{273}@anchor{gnat_ugn/platform_specific_information id14}@anchor{274}
30226 @subsection Mixed-Language Programming on Windows
30229 Developing pure Ada applications on Windows is no different than on
30230 other GNAT-supported platforms. However, when developing or porting an
30231 application that contains a mix of Ada and C/C++, the choice of your
30232 Windows C/C++ development environment conditions your overall
30233 interoperability strategy.
30235 If you use @emph{gcc} or Microsoft C to compile the non-Ada part of
30236 your application, there are no Windows-specific restrictions that
30237 affect the overall interoperability with your Ada code. If you do want
30238 to use the Microsoft tools for your C++ code, you have two choices:
30244 Encapsulate your C++ code in a DLL to be linked with your Ada
30245 application. In this case, use the Microsoft or whatever environment to
30246 build the DLL and use GNAT to build your executable
30247 (@ref{275,,Using DLLs with GNAT}).
30250 Or you can encapsulate your Ada code in a DLL to be linked with the
30251 other part of your application. In this case, use GNAT to build the DLL
30252 (@ref{276,,Building DLLs with GNAT Project files}) and use the Microsoft
30253 or whatever environment to build your executable.
30256 In addition to the description about C main in
30257 @ref{46,,Mixed Language Programming} section, if the C main uses a
30258 stand-alone library it is required on x86-windows to
30259 setup the SEH context. For this the C main must looks like this:
30265 extern void adainit (void);
30266 extern void adafinal (void);
30267 extern void __gnat_initialize(void*);
30268 extern void call_to_ada (void);
30270 int main (int argc, char *argv[])
30274 /* Initialize the SEH context */
30275 __gnat_initialize (&SEH);
30279 /* Then call Ada services in the stand-alone library */
30288 Note that this is not needed on x86_64-windows where the Windows
30289 native SEH support is used.
30292 * Windows Calling Conventions::
30293 * Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs.
30294 * Using DLLs with GNAT::
30295 * Building DLLs with GNAT Project files::
30296 * Building DLLs with GNAT::
30297 * Building DLLs with gnatdll::
30298 * Ada DLLs and Finalization::
30299 * Creating a Spec for Ada DLLs::
30300 * GNAT and Windows Resources::
30301 * Using GNAT DLLs from Microsoft Visual Studio Applications::
30302 * Debugging a DLL::
30303 * Setting Stack Size from gnatlink::
30304 * Setting Heap Size from gnatlink::
30308 @node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
30309 @anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{277}@anchor{gnat_ugn/platform_specific_information id15}@anchor{278}
30310 @subsubsection Windows Calling Conventions
30317 This section pertain only to Win32. On Win64 there is a single native
30318 calling convention. All convention specifiers are ignored on this
30321 When a subprogram @cite{F} (caller) calls a subprogram @cite{G}
30322 (callee), there are several ways to push @cite{G}'s parameters on the
30323 stack and there are several possible scenarios to clean up the stack
30324 upon @cite{G}'s return. A calling convention is an agreed upon software
30325 protocol whereby the responsibilities between the caller (@cite{F}) and
30326 the callee (@cite{G}) are clearly defined. Several calling conventions
30327 are available for Windows:
30333 @cite{C} (Microsoft defined)
30336 @cite{Stdcall} (Microsoft defined)
30339 @cite{Win32} (GNAT specific)
30342 @cite{DLL} (GNAT specific)
30346 * C Calling Convention::
30347 * Stdcall Calling Convention::
30348 * Win32 Calling Convention::
30349 * DLL Calling Convention::
30353 @node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
30354 @anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{279}@anchor{gnat_ugn/platform_specific_information id16}@anchor{27a}
30355 @subsubsection @cite{C} Calling Convention
30358 This is the default calling convention used when interfacing to C/C++
30359 routines compiled with either @emph{gcc} or Microsoft Visual C++.
30361 In the @cite{C} calling convention subprogram parameters are pushed on the
30362 stack by the caller from right to left. The caller itself is in charge of
30363 cleaning up the stack after the call. In addition, the name of a routine
30364 with @cite{C} calling convention is mangled by adding a leading underscore.
30366 The name to use on the Ada side when importing (or exporting) a routine
30367 with @cite{C} calling convention is the name of the routine. For
30368 instance the C function:
30373 int get_val (long);
30377 should be imported from Ada as follows:
30382 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30383 pragma Import (C, Get_Val, External_Name => "get_val");
30387 Note that in this particular case the @cite{External_Name} parameter could
30388 have been omitted since, when missing, this parameter is taken to be the
30389 name of the Ada entity in lower case. When the @cite{Link_Name} parameter
30390 is missing, as in the above example, this parameter is set to be the
30391 @cite{External_Name} with a leading underscore.
30393 When importing a variable defined in C, you should always use the @cite{C}
30394 calling convention unless the object containing the variable is part of a
30395 DLL (in which case you should use the @cite{Stdcall} calling
30396 convention, @ref{27b,,Stdcall Calling Convention}).
30398 @node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
30399 @anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{27b}@anchor{gnat_ugn/platform_specific_information id17}@anchor{27c}
30400 @subsubsection @cite{Stdcall} Calling Convention
30403 This convention, which was the calling convention used for Pascal
30404 programs, is used by Microsoft for all the routines in the Win32 API for
30405 efficiency reasons. It must be used to import any routine for which this
30406 convention was specified.
30408 In the @cite{Stdcall} calling convention subprogram parameters are pushed
30409 on the stack by the caller from right to left. The callee (and not the
30410 caller) is in charge of cleaning the stack on routine exit. In addition,
30411 the name of a routine with @cite{Stdcall} calling convention is mangled by
30412 adding a leading underscore (as for the @cite{C} calling convention) and a
30413 trailing @code{@@@emph{nn}}, where @cite{nn} is the overall size (in
30414 bytes) of the parameters passed to the routine.
30416 The name to use on the Ada side when importing a C routine with a
30417 @cite{Stdcall} calling convention is the name of the C routine. The leading
30418 underscore and trailing @code{@@@emph{nn}} are added automatically by
30419 the compiler. For instance the Win32 function:
30424 APIENTRY int get_val (long);
30428 should be imported from Ada as follows:
30433 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30434 pragma Import (Stdcall, Get_Val);
30435 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
30439 As for the @cite{C} calling convention, when the @cite{External_Name}
30440 parameter is missing, it is taken to be the name of the Ada entity in lower
30441 case. If instead of writing the above import pragma you write:
30446 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30447 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
30451 then the imported routine is @cite{_retrieve_val@@4}. However, if instead
30452 of specifying the @cite{External_Name} parameter you specify the
30453 @cite{Link_Name} as in the following example:
30458 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30459 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
30463 then the imported routine is @cite{retrieve_val}, that is, there is no
30464 decoration at all. No leading underscore and no Stdcall suffix
30465 @code{@@@emph{nn}}.
30467 This is especially important as in some special cases a DLL's entry
30468 point name lacks a trailing @code{@@@emph{nn}} while the exported
30469 name generated for a call has it.
30471 It is also possible to import variables defined in a DLL by using an
30472 import pragma for a variable. As an example, if a DLL contains a
30473 variable defined as:
30482 then, to access this variable from Ada you should write:
30487 My_Var : Interfaces.C.int;
30488 pragma Import (Stdcall, My_Var);
30492 Note that to ease building cross-platform bindings this convention
30493 will be handled as a @cite{C} calling convention on non-Windows platforms.
30495 @node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
30496 @anchor{gnat_ugn/platform_specific_information id18}@anchor{27d}@anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{27e}
30497 @subsubsection @cite{Win32} Calling Convention
30500 This convention, which is GNAT-specific is fully equivalent to the
30501 @cite{Stdcall} calling convention described above.
30503 @node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
30504 @anchor{gnat_ugn/platform_specific_information id19}@anchor{27f}@anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{280}
30505 @subsubsection @cite{DLL} Calling Convention
30508 This convention, which is GNAT-specific is fully equivalent to the
30509 @cite{Stdcall} calling convention described above.
30511 @node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
30512 @anchor{gnat_ugn/platform_specific_information id20}@anchor{281}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{282}
30513 @subsubsection Introduction to Dynamic Link Libraries (DLLs)
30518 A Dynamically Linked Library (DLL) is a library that can be shared by
30519 several applications running under Windows. A DLL can contain any number of
30520 routines and variables.
30522 One advantage of DLLs is that you can change and enhance them without
30523 forcing all the applications that depend on them to be relinked or
30524 recompiled. However, you should be aware than all calls to DLL routines are
30525 slower since, as you will understand below, such calls are indirect.
30527 To illustrate the remainder of this section, suppose that an application
30528 wants to use the services of a DLL @code{API.dll}. To use the services
30529 provided by @code{API.dll} you must statically link against the DLL or
30530 an import library which contains a jump table with an entry for each
30531 routine and variable exported by the DLL. In the Microsoft world this
30532 import library is called @code{API.lib}. When using GNAT this import
30533 library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
30534 @code{libAPI.a} or @code{libapi.a} (names are case insensitive).
30536 After you have linked your application with the DLL or the import library
30537 and you run your application, here is what happens:
30543 Your application is loaded into memory.
30546 The DLL @code{API.dll} is mapped into the address space of your
30547 application. This means that:
30553 The DLL will use the stack of the calling thread.
30556 The DLL will use the virtual address space of the calling process.
30559 The DLL will allocate memory from the virtual address space of the calling
30563 Handles (pointers) can be safely exchanged between routines in the DLL
30564 routines and routines in the application using the DLL.
30568 The entries in the jump table (from the import library @code{libAPI.dll.a}
30569 or @code{API.lib} or automatically created when linking against a DLL)
30570 which is part of your application are initialized with the addresses
30571 of the routines and variables in @code{API.dll}.
30574 If present in @code{API.dll}, routines @cite{DllMain} or
30575 @cite{DllMainCRTStartup} are invoked. These routines typically contain
30576 the initialization code needed for the well-being of the routines and
30577 variables exported by the DLL.
30580 There is an additional point which is worth mentioning. In the Windows
30581 world there are two kind of DLLs: relocatable and non-relocatable
30582 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
30583 in the target application address space. If the addresses of two
30584 non-relocatable DLLs overlap and these happen to be used by the same
30585 application, a conflict will occur and the application will run
30586 incorrectly. Hence, when possible, it is always preferable to use and
30587 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
30588 supported by GNAT. Note that the @emph{-s} linker option (see GNU Linker
30589 User's Guide) removes the debugging symbols from the DLL but the DLL can
30590 still be relocated.
30592 As a side note, an interesting difference between Microsoft DLLs and
30593 Unix shared libraries, is the fact that on most Unix systems all public
30594 routines are exported by default in a Unix shared library, while under
30595 Windows it is possible (but not required) to list exported routines in
30596 a definition file (see @ref{283,,The Definition File}).
30598 @node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
30599 @anchor{gnat_ugn/platform_specific_information id21}@anchor{284}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{275}
30600 @subsubsection Using DLLs with GNAT
30603 To use the services of a DLL, say @code{API.dll}, in your Ada application
30610 The Ada spec for the routines and/or variables you want to access in
30611 @code{API.dll}. If not available this Ada spec must be built from the C/C++
30612 header files provided with the DLL.
30615 The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
30616 mentioned an import library is a statically linked library containing the
30617 import table which will be filled at load time to point to the actual
30618 @code{API.dll} routines. Sometimes you don't have an import library for the
30619 DLL you want to use. The following sections will explain how to build
30620 one. Note that this is optional.
30623 The actual DLL, @code{API.dll}.
30626 Once you have all the above, to compile an Ada application that uses the
30627 services of @code{API.dll} and whose main subprogram is @cite{My_Ada_App},
30628 you simply issue the command
30633 $ gnatmake my_ada_app -largs -lAPI
30637 The argument @emph{-largs -lAPI} at the end of the @emph{gnatmake} command
30638 tells the GNAT linker to look for an import library. The linker will
30639 look for a library name in this specific order:
30645 @code{libAPI.dll.a}
30663 The first three are the GNU style import libraries. The third is the
30664 Microsoft style import libraries. The last two are the actual DLL names.
30666 Note that if the Ada package spec for @code{API.dll} contains the
30672 pragma Linker_Options ("-lAPI");
30676 you do not have to add @emph{-largs -lAPI} at the end of the
30677 @emph{gnatmake} command.
30679 If any one of the items above is missing you will have to create it
30680 yourself. The following sections explain how to do so using as an
30681 example a fictitious DLL called @code{API.dll}.
30684 * Creating an Ada Spec for the DLL Services::
30685 * Creating an Import Library::
30689 @node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
30690 @anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{285}@anchor{gnat_ugn/platform_specific_information id22}@anchor{286}
30691 @subsubsection Creating an Ada Spec for the DLL Services
30694 A DLL typically comes with a C/C++ header file which provides the
30695 definitions of the routines and variables exported by the DLL. The Ada
30696 equivalent of this header file is a package spec that contains definitions
30697 for the imported entities. If the DLL you intend to use does not come with
30698 an Ada spec you have to generate one such spec yourself. For example if
30699 the header file of @code{API.dll} is a file @code{api.h} containing the
30700 following two definitions:
30710 then the equivalent Ada spec could be:
30715 with Interfaces.C.Strings;
30720 function Get (Str : C.Strings.Chars_Ptr) return C.int;
30723 pragma Import (C, Get);
30724 pragma Import (DLL, Some_Var);
30729 @node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
30730 @anchor{gnat_ugn/platform_specific_information id23}@anchor{287}@anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{288}
30731 @subsubsection Creating an Import Library
30734 @geindex Import library
30736 If a Microsoft-style import library @code{API.lib} or a GNAT-style
30737 import library @code{libAPI.dll.a} or @code{libAPI.a} is available
30738 with @code{API.dll} you can skip this section. You can also skip this
30739 section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
30740 as in this case it is possible to link directly against the
30741 DLL. Otherwise read on.
30743 @geindex Definition file
30744 @anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{283}
30745 @subsubheading The Definition File
30748 As previously mentioned, and unlike Unix systems, the list of symbols
30749 that are exported from a DLL must be provided explicitly in Windows.
30750 The main goal of a definition file is precisely that: list the symbols
30751 exported by a DLL. A definition file (usually a file with a @cite{.def}
30752 suffix) has the following structure:
30758 [DESCRIPTION `string`]
30769 @item @emph{LIBRARY `name`}
30771 This section, which is optional, gives the name of the DLL.
30773 @item @emph{DESCRIPTION `string`}
30775 This section, which is optional, gives a description string that will be
30776 embedded in the import library.
30778 @item @emph{EXPORTS}
30780 This section gives the list of exported symbols (procedures, functions or
30781 variables). For instance in the case of @code{API.dll} the @cite{EXPORTS}
30782 section of @code{API.def} looks like:
30791 Note that you must specify the correct suffix (@code{@@@emph{nn}})
30792 (see @ref{277,,Windows Calling Conventions}) for a Stdcall
30793 calling convention function in the exported symbols list.
30795 There can actually be other sections in a definition file, but these
30796 sections are not relevant to the discussion at hand.
30797 @anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{289}
30798 @subsubheading Creating a Definition File Automatically
30801 You can automatically create the definition file @code{API.def}
30802 (see @ref{283,,The Definition File}) from a DLL.
30803 For that use the @cite{dlltool} program as follows:
30808 $ dlltool API.dll -z API.def --export-all-symbols
30811 Note that if some routines in the DLL have the @cite{Stdcall} convention
30812 (@ref{277,,Windows Calling Conventions}) with stripped @code{@@@emph{nn}}
30813 suffix then you'll have to edit @code{api.def} to add it, and specify
30814 @emph{-k} to @emph{gnatdll} when creating the import library.
30816 Here are some hints to find the right @code{@@@emph{nn}} suffix.
30822 If you have the Microsoft import library (.lib), it is possible to get
30823 the right symbols by using Microsoft @cite{dumpbin} tool (see the
30824 corresponding Microsoft documentation for further details).
30827 $ dumpbin /exports api.lib
30831 If you have a message about a missing symbol at link time the compiler
30832 tells you what symbol is expected. You just have to go back to the
30833 definition file and add the right suffix.
30836 @anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{28a}
30837 @subsubheading GNAT-Style Import Library
30840 To create a static import library from @code{API.dll} with the GNAT tools
30841 you should create the .def file, then use @cite{gnatdll} tool
30842 (see @ref{28b,,Using gnatdll}) as follows:
30847 $ gnatdll -e API.def -d API.dll
30850 @cite{gnatdll} takes as input a definition file @code{API.def} and the
30851 name of the DLL containing the services listed in the definition file
30852 @code{API.dll}. The name of the static import library generated is
30853 computed from the name of the definition file as follows: if the
30854 definition file name is @cite{xyz`}.def`, the import library name will
30855 be @cite{lib`@w{`}xyz`}.a`. Note that in the previous example option
30856 @emph{-e} could have been removed because the name of the definition
30857 file (before the '@cite{.def}' suffix) is the same as the name of the
30858 DLL (@ref{28b,,Using gnatdll} for more information about @cite{gnatdll}).
30860 @anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{28c}
30861 @subsubheading Microsoft-Style Import Library
30864 A Microsoft import library is needed only if you plan to make an
30865 Ada DLL available to applications developed with Microsoft
30866 tools (@ref{273,,Mixed-Language Programming on Windows}).
30868 To create a Microsoft-style import library for @code{API.dll} you
30869 should create the .def file, then build the actual import library using
30870 Microsoft's @cite{lib} utility:
30875 $ lib -machine:IX86 -def:API.def -out:API.lib
30878 If you use the above command the definition file @code{API.def} must
30879 contain a line giving the name of the DLL:
30885 See the Microsoft documentation for further details about the usage of
30889 @node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
30890 @anchor{gnat_ugn/platform_specific_information id24}@anchor{28d}@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{276}
30891 @subsubsection Building DLLs with GNAT Project files
30897 There is nothing specific to Windows in the build process.
30898 @ref{8a,,Library Projects}.
30900 Due to a system limitation, it is not possible under Windows to create threads
30901 when inside the @cite{DllMain} routine which is used for auto-initialization
30902 of shared libraries, so it is not possible to have library level tasks in SALs.
30904 @node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
30905 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{28e}@anchor{gnat_ugn/platform_specific_information id25}@anchor{28f}
30906 @subsubsection Building DLLs with GNAT
30912 This section explain how to build DLLs using the GNAT built-in DLL
30913 support. With the following procedure it is straight forward to build
30914 and use DLLs with GNAT.
30920 Building object files.
30921 The first step is to build all objects files that are to be included
30922 into the DLL. This is done by using the standard @emph{gnatmake} tool.
30926 To build the DLL you must use @emph{gcc}'s @emph{-shared} and
30927 @emph{-shared-libgcc} options. It is quite simple to use this method:
30930 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
30933 It is important to note that in this case all symbols found in the
30934 object files are automatically exported. It is possible to restrict
30935 the set of symbols to export by passing to @emph{gcc} a definition
30936 file (see @ref{283,,The Definition File}).
30940 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
30943 If you use a definition file you must export the elaboration procedures
30944 for every package that required one. Elaboration procedures are named
30945 using the package name followed by "_E".
30948 Preparing DLL to be used.
30949 For the DLL to be used by client programs the bodies must be hidden
30950 from it and the .ali set with read-only attribute. This is very important
30951 otherwise GNAT will recompile all packages and will not actually use
30952 the code in the DLL. For example:
30956 $ copy *.ads *.ali api.dll apilib
30957 $ attrib +R apilib\\*.ali
30961 At this point it is possible to use the DLL by directly linking
30962 against it. Note that you must use the GNAT shared runtime when using
30963 GNAT shared libraries. This is achieved by using @emph{-shared} binder's
30969 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30973 @node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
30974 @anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{290}@anchor{gnat_ugn/platform_specific_information id26}@anchor{291}
30975 @subsubsection Building DLLs with gnatdll
30981 Note that it is preferred to use GNAT Project files
30982 (@ref{276,,Building DLLs with GNAT Project files}) or the built-in GNAT
30983 DLL support (@ref{28e,,Building DLLs with GNAT}) or to build DLLs.
30985 This section explains how to build DLLs containing Ada code using
30986 @cite{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30987 remainder of this section.
30989 The steps required to build an Ada DLL that is to be used by Ada as well as
30990 non-Ada applications are as follows:
30996 You need to mark each Ada @emph{entity} exported by the DLL with a @cite{C} or
30997 @cite{Stdcall} calling convention to avoid any Ada name mangling for the
30998 entities exported by the DLL
30999 (see @ref{292,,Exporting Ada Entities}). You can
31000 skip this step if you plan to use the Ada DLL only from Ada applications.
31003 Your Ada code must export an initialization routine which calls the routine
31004 @cite{adainit} generated by @emph{gnatbind} to perform the elaboration of
31005 the Ada code in the DLL (@ref{293,,Ada DLLs and Elaboration}). The initialization
31006 routine exported by the Ada DLL must be invoked by the clients of the DLL
31007 to initialize the DLL.
31010 When useful, the DLL should also export a finalization routine which calls
31011 routine @cite{adafinal} generated by @emph{gnatbind} to perform the
31012 finalization of the Ada code in the DLL (@ref{294,,Ada DLLs and Finalization}).
31013 The finalization routine exported by the Ada DLL must be invoked by the
31014 clients of the DLL when the DLL services are no further needed.
31017 You must provide a spec for the services exported by the Ada DLL in each
31018 of the programming languages to which you plan to make the DLL available.
31021 You must provide a definition file listing the exported entities
31022 (@ref{283,,The Definition File}).
31025 Finally you must use @cite{gnatdll} to produce the DLL and the import
31026 library (@ref{28b,,Using gnatdll}).
31029 Note that a relocatable DLL stripped using the @cite{strip}
31030 binutils tool will not be relocatable anymore. To build a DLL without
31031 debug information pass @cite{-largs -s} to @cite{gnatdll}. This
31032 restriction does not apply to a DLL built using a Library Project.
31033 See @ref{8a,,Library Projects}.
31035 @c Limitations_When_Using_Ada_DLLs_from Ada:
31038 * Limitations When Using Ada DLLs from Ada::
31039 * Exporting Ada Entities::
31040 * Ada DLLs and Elaboration::
31044 @node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
31045 @anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{295}
31046 @subsubsection Limitations When Using Ada DLLs from Ada
31049 When using Ada DLLs from Ada applications there is a limitation users
31050 should be aware of. Because on Windows the GNAT run time is not in a DLL of
31051 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
31052 each Ada DLL includes the services of the GNAT run time that are necessary
31053 to the Ada code inside the DLL. As a result, when an Ada program uses an
31054 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
31055 one in the main program.
31057 It is therefore not possible to exchange GNAT run-time objects between the
31058 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
31059 handles (e.g., @cite{Text_IO.File_Type}), tasks types, protected objects
31062 It is completely safe to exchange plain elementary, array or record types,
31063 Windows object handles, etc.
31065 @node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
31066 @anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{292}@anchor{gnat_ugn/platform_specific_information id27}@anchor{296}
31067 @subsubsection Exporting Ada Entities
31070 @geindex Export table
31072 Building a DLL is a way to encapsulate a set of services usable from any
31073 application. As a result, the Ada entities exported by a DLL should be
31074 exported with the @cite{C} or @cite{Stdcall} calling conventions to avoid
31075 any Ada name mangling. As an example here is an Ada package
31076 @cite{API}, spec and body, exporting two procedures, a function, and a
31082 with Interfaces.C; use Interfaces;
31084 Count : C.int := 0;
31085 function Factorial (Val : C.int) return C.int;
31087 procedure Initialize_API;
31088 procedure Finalize_API;
31089 -- Initialization & Finalization routines. More in the next section.
31091 pragma Export (C, Initialize_API);
31092 pragma Export (C, Finalize_API);
31093 pragma Export (C, Count);
31094 pragma Export (C, Factorial);
31099 package body API is
31100 function Factorial (Val : C.int) return C.int is
31103 Count := Count + 1;
31104 for K in 1 .. Val loop
31110 procedure Initialize_API is
31112 pragma Import (C, Adainit);
31115 end Initialize_API;
31117 procedure Finalize_API is
31118 procedure Adafinal;
31119 pragma Import (C, Adafinal);
31127 If the Ada DLL you are building will only be used by Ada applications
31128 you do not have to export Ada entities with a @cite{C} or @cite{Stdcall}
31129 convention. As an example, the previous package could be written as
31136 Count : Integer := 0;
31137 function Factorial (Val : Integer) return Integer;
31139 procedure Initialize_API;
31140 procedure Finalize_API;
31141 -- Initialization and Finalization routines.
31146 package body API is
31147 function Factorial (Val : Integer) return Integer is
31148 Fact : Integer := 1;
31150 Count := Count + 1;
31151 for K in 1 .. Val loop
31158 -- The remainder of this package body is unchanged.
31163 Note that if you do not export the Ada entities with a @cite{C} or
31164 @cite{Stdcall} convention you will have to provide the mangled Ada names
31165 in the definition file of the Ada DLL
31166 (@ref{297,,Creating the Definition File}).
31168 @node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
31169 @anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{293}@anchor{gnat_ugn/platform_specific_information id28}@anchor{298}
31170 @subsubsection Ada DLLs and Elaboration
31173 @geindex DLLs and elaboration
31175 The DLL that you are building contains your Ada code as well as all the
31176 routines in the Ada library that are needed by it. The first thing a
31177 user of your DLL must do is elaborate the Ada code
31178 (@ref{11,,Elaboration Order Handling in GNAT}).
31180 To achieve this you must export an initialization routine
31181 (@cite{Initialize_API} in the previous example), which must be invoked
31182 before using any of the DLL services. This elaboration routine must call
31183 the Ada elaboration routine @cite{adainit} generated by the GNAT binder
31184 (@ref{ba,,Binding with Non-Ada Main Programs}). See the body of
31185 @cite{Initialize_Api} for an example. Note that the GNAT binder is
31186 automatically invoked during the DLL build process by the @cite{gnatdll}
31187 tool (@ref{28b,,Using gnatdll}).
31189 When a DLL is loaded, Windows systematically invokes a routine called
31190 @cite{DllMain}. It would therefore be possible to call @cite{adainit}
31191 directly from @cite{DllMain} without having to provide an explicit
31192 initialization routine. Unfortunately, it is not possible to call
31193 @cite{adainit} from the @cite{DllMain} if your program has library level
31194 tasks because access to the @cite{DllMain} entry point is serialized by
31195 the system (that is, only a single thread can execute 'through' it at a
31196 time), which means that the GNAT run time will deadlock waiting for the
31197 newly created task to complete its initialization.
31199 @node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
31200 @anchor{gnat_ugn/platform_specific_information id29}@anchor{299}@anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{294}
31201 @subsubsection Ada DLLs and Finalization
31204 @geindex DLLs and finalization
31206 When the services of an Ada DLL are no longer needed, the client code should
31207 invoke the DLL finalization routine, if available. The DLL finalization
31208 routine is in charge of releasing all resources acquired by the DLL. In the
31209 case of the Ada code contained in the DLL, this is achieved by calling
31210 routine @cite{adafinal} generated by the GNAT binder
31211 (@ref{ba,,Binding with Non-Ada Main Programs}).
31212 See the body of @cite{Finalize_Api} for an
31213 example. As already pointed out the GNAT binder is automatically invoked
31214 during the DLL build process by the @cite{gnatdll} tool
31215 (@ref{28b,,Using gnatdll}).
31217 @node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
31218 @anchor{gnat_ugn/platform_specific_information id30}@anchor{29a}@anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{29b}
31219 @subsubsection Creating a Spec for Ada DLLs
31222 To use the services exported by the Ada DLL from another programming
31223 language (e.g., C), you have to translate the specs of the exported Ada
31224 entities in that language. For instance in the case of @cite{API.dll},
31225 the corresponding C header file could look like:
31230 extern int *_imp__count;
31231 #define count (*_imp__count)
31232 int factorial (int);
31236 It is important to understand that when building an Ada DLL to be used by
31237 other Ada applications, you need two different specs for the packages
31238 contained in the DLL: one for building the DLL and the other for using
31239 the DLL. This is because the @cite{DLL} calling convention is needed to
31240 use a variable defined in a DLL, but when building the DLL, the variable
31241 must have either the @cite{Ada} or @cite{C} calling convention. As an
31242 example consider a DLL comprising the following package @cite{API}:
31248 Count : Integer := 0;
31250 -- Remainder of the package omitted.
31255 After producing a DLL containing package @cite{API}, the spec that
31256 must be used to import @cite{API.Count} from Ada code outside of the
31264 pragma Import (DLL, Count);
31270 * Creating the Definition File::
31275 @node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
31276 @anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{297}@anchor{gnat_ugn/platform_specific_information id31}@anchor{29c}
31277 @subsubsection Creating the Definition File
31280 The definition file is the last file needed to build the DLL. It lists
31281 the exported symbols. As an example, the definition file for a DLL
31282 containing only package @cite{API} (where all the entities are exported
31283 with a @cite{C} calling convention) is:
31296 If the @cite{C} calling convention is missing from package @cite{API},
31297 then the definition file contains the mangled Ada names of the above
31298 entities, which in this case are:
31307 api__initialize_api
31311 @node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
31312 @anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{28b}@anchor{gnat_ugn/platform_specific_information id32}@anchor{29d}
31313 @subsubsection Using @cite{gnatdll}
31318 @cite{gnatdll} is a tool to automate the DLL build process once all the Ada
31319 and non-Ada sources that make up your DLL have been compiled.
31320 @cite{gnatdll} is actually in charge of two distinct tasks: build the
31321 static import library for the DLL and the actual DLL. The form of the
31322 @cite{gnatdll} command is
31327 $ gnatdll [`switches`] `list-of-files` [-largs `opts`]
31331 where @cite{list-of-files} is a list of ALI and object files. The object
31332 file list must be the exact list of objects corresponding to the non-Ada
31333 sources whose services are to be included in the DLL. The ALI file list
31334 must be the exact list of ALI files for the corresponding Ada sources
31335 whose services are to be included in the DLL. If @cite{list-of-files} is
31336 missing, only the static import library is generated.
31338 You may specify any of the following switches to @cite{gnatdll}:
31342 @geindex -a (gnatdll)
31348 @item @code{-a[@emph{address}]}
31350 Build a non-relocatable DLL at @cite{address}. If @cite{address} is not
31351 specified the default address @cite{0x11000000} will be used. By default,
31352 when this switch is missing, @cite{gnatdll} builds relocatable DLL. We
31353 advise the reader to build relocatable DLL.
31355 @geindex -b (gnatdll)
31357 @item @code{-b @emph{address}}
31359 Set the relocatable DLL base address. By default the address is
31362 @geindex -bargs (gnatdll)
31364 @item @code{-bargs @emph{opts}}
31366 Binder options. Pass @cite{opts} to the binder.
31368 @geindex -d (gnatdll)
31370 @item @code{-d @emph{dllfile}}
31372 @cite{dllfile} is the name of the DLL. This switch must be present for
31373 @cite{gnatdll} to do anything. The name of the generated import library is
31374 obtained algorithmically from @cite{dllfile} as shown in the following
31375 example: if @cite{dllfile} is @cite{xyz.dll}, the import library name is
31376 @cite{libxyz.dll.a}. The name of the definition file to use (if not specified
31377 by option @emph{-e}) is obtained algorithmically from @cite{dllfile}
31378 as shown in the following example:
31379 if @cite{dllfile} is @cite{xyz.dll}, the definition
31380 file used is @cite{xyz.def}.
31382 @geindex -e (gnatdll)
31384 @item @code{-e @emph{deffile}}
31386 @cite{deffile} is the name of the definition file.
31388 @geindex -g (gnatdll)
31392 Generate debugging information. This information is stored in the object
31393 file and copied from there to the final DLL file by the linker,
31394 where it can be read by the debugger. You must use the
31395 @emph{-g} switch if you plan on using the debugger or the symbolic
31398 @geindex -h (gnatdll)
31402 Help mode. Displays @cite{gnatdll} switch usage information.
31404 @geindex -I (gnatdll)
31406 @item @code{-I@emph{dir}}
31408 Direct @cite{gnatdll} to search the @cite{dir} directory for source and
31409 object files needed to build the DLL.
31410 (@ref{8e,,Search Paths and the Run-Time Library (RTL)}).
31412 @geindex -k (gnatdll)
31416 Removes the @code{@@@emph{nn}} suffix from the import library's exported
31417 names, but keeps them for the link names. You must specify this
31418 option if you want to use a @cite{Stdcall} function in a DLL for which
31419 the @code{@@@emph{nn}} suffix has been removed. This is the case for most
31420 of the Windows NT DLL for example. This option has no effect when
31421 @emph{-n} option is specified.
31423 @geindex -l (gnatdll)
31425 @item @code{-l @emph{file}}
31427 The list of ALI and object files used to build the DLL are listed in
31428 @cite{file}, instead of being given in the command line. Each line in
31429 @cite{file} contains the name of an ALI or object file.
31431 @geindex -n (gnatdll)
31435 No Import. Do not create the import library.
31437 @geindex -q (gnatdll)
31441 Quiet mode. Do not display unnecessary messages.
31443 @geindex -v (gnatdll)
31447 Verbose mode. Display extra information.
31449 @geindex -largs (gnatdll)
31451 @item @code{-largs @emph{opts}}
31453 Linker options. Pass @cite{opts} to the linker.
31456 @subsubheading @cite{gnatdll} Example
31459 As an example the command to build a relocatable DLL from @code{api.adb}
31460 once @code{api.adb} has been compiled and @code{api.def} created is
31465 $ gnatdll -d api.dll api.ali
31469 The above command creates two files: @code{libapi.dll.a} (the import
31470 library) and @code{api.dll} (the actual DLL). If you want to create
31471 only the DLL, just type:
31476 $ gnatdll -d api.dll -n api.ali
31480 Alternatively if you want to create just the import library, type:
31485 $ gnatdll -d api.dll
31489 @subsubheading @cite{gnatdll} behind the Scenes
31492 This section details the steps involved in creating a DLL. @cite{gnatdll}
31493 does these steps for you. Unless you are interested in understanding what
31494 goes on behind the scenes, you should skip this section.
31496 We use the previous example of a DLL containing the Ada package @cite{API},
31497 to illustrate the steps necessary to build a DLL. The starting point is a
31498 set of objects that will make up the DLL and the corresponding ALI
31499 files. In the case of this example this means that @code{api.o} and
31500 @code{api.ali} are available. To build a relocatable DLL, @cite{gnatdll} does
31507 @cite{gnatdll} builds the base file (@code{api.base}). A base file gives
31508 the information necessary to generate relocation information for the
31513 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
31516 In addition to the base file, the @emph{gnatlink} command generates an
31517 output file @code{api.jnk} which can be discarded. The @emph{-mdll} switch
31518 asks @emph{gnatlink} to generate the routines @cite{DllMain} and
31519 @cite{DllMainCRTStartup} that are called by the Windows loader when the DLL
31520 is loaded into memory.
31523 @cite{gnatdll} uses @cite{dlltool} (see @ref{29e,,Using dlltool}) to build the
31524 export table (@code{api.exp}). The export table contains the relocation
31525 information in a form which can be used during the final link to ensure
31526 that the Windows loader is able to place the DLL anywhere in memory.
31529 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
31530 --output-exp api.exp
31534 @cite{gnatdll} builds the base file using the new export table. Note that
31535 @emph{gnatbind} must be called once again since the binder generated file
31536 has been deleted during the previous call to @emph{gnatlink}.
31540 $ gnatlink api -o api.jnk api.exp -mdll
31541 -Wl,--base-file,api.base
31545 @cite{gnatdll} builds the new export table using the new base file and
31546 generates the DLL import library @code{libAPI.dll.a}.
31549 $ dlltool --dllname api.dll --def api.def --base-file api.base \\
31550 --output-exp api.exp --output-lib libAPI.a
31554 Finally @cite{gnatdll} builds the relocatable DLL using the final export
31559 $ gnatlink api api.exp -o api.dll -mdll
31562 @anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{29e}
31563 @subsubheading Using @cite{dlltool}
31566 @cite{dlltool} is the low-level tool used by @cite{gnatdll} to build
31567 DLLs and static import libraries. This section summarizes the most
31568 common @cite{dlltool} switches. The form of the @cite{dlltool} command
31574 $ dlltool [`switches`]
31578 @cite{dlltool} switches include:
31580 @geindex --base-file (dlltool)
31585 @item @code{--base-file @emph{basefile}}
31587 Read the base file @cite{basefile} generated by the linker. This switch
31588 is used to create a relocatable DLL.
31591 @geindex --def (dlltool)
31596 @item @code{--def @emph{deffile}}
31598 Read the definition file.
31601 @geindex --dllname (dlltool)
31606 @item @code{--dllname @emph{name}}
31608 Gives the name of the DLL. This switch is used to embed the name of the
31609 DLL in the static import library generated by @cite{dlltool} with switch
31610 @emph{--output-lib}.
31613 @geindex -k (dlltool)
31620 Kill @code{@@@emph{nn}} from exported names
31621 (@ref{277,,Windows Calling Conventions}
31622 for a discussion about @cite{Stdcall}-style symbols.
31625 @geindex --help (dlltool)
31630 @item @code{--help}
31632 Prints the @cite{dlltool} switches with a concise description.
31635 @geindex --output-exp (dlltool)
31640 @item @code{--output-exp @emph{exportfile}}
31642 Generate an export file @cite{exportfile}. The export file contains the
31643 export table (list of symbols in the DLL) and is used to create the DLL.
31646 @geindex --output-lib (dlltool)
31651 @item @code{--output-lib @emph{libfile}}
31653 Generate a static import library @cite{libfile}.
31656 @geindex -v (dlltool)
31666 @geindex --as (dlltool)
31671 @item @code{--as @emph{assembler-name}}
31673 Use @cite{assembler-name} as the assembler. The default is @cite{as}.
31676 @node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
31677 @anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{29f}@anchor{gnat_ugn/platform_specific_information id33}@anchor{2a0}
31678 @subsubsection GNAT and Windows Resources
31684 Resources are an easy way to add Windows specific objects to your
31685 application. The objects that can be added as resources include:
31715 version information
31718 For example, a version information resource can be defined as follow and
31719 embedded into an executable or DLL:
31721 A version information resource can be used to embed information into an
31722 executable or a DLL. These information can be viewed using the file properties
31723 from the Windows Explorer. Here is an example of a version information
31730 FILEVERSION 1,0,0,0
31731 PRODUCTVERSION 1,0,0,0
31733 BLOCK "StringFileInfo"
31737 VALUE "CompanyName", "My Company Name"
31738 VALUE "FileDescription", "My application"
31739 VALUE "FileVersion", "1.0"
31740 VALUE "InternalName", "my_app"
31741 VALUE "LegalCopyright", "My Name"
31742 VALUE "OriginalFilename", "my_app.exe"
31743 VALUE "ProductName", "My App"
31744 VALUE "ProductVersion", "1.0"
31748 BLOCK "VarFileInfo"
31750 VALUE "Translation", 0x809, 1252
31756 The value @cite{0809} (langID) is for the U.K English language and
31757 @cite{04E4} (charsetID), which is equal to @cite{1252} decimal, for
31760 This section explains how to build, compile and use resources. Note that this
31761 section does not cover all resource objects, for a complete description see
31762 the corresponding Microsoft documentation.
31765 * Building Resources::
31766 * Compiling Resources::
31767 * Using Resources::
31771 @node Building Resources,Compiling Resources,,GNAT and Windows Resources
31772 @anchor{gnat_ugn/platform_specific_information building-resources}@anchor{2a1}@anchor{gnat_ugn/platform_specific_information id34}@anchor{2a2}
31773 @subsubsection Building Resources
31779 A resource file is an ASCII file. By convention resource files have an
31780 @code{.rc} extension.
31781 The easiest way to build a resource file is to use Microsoft tools
31782 such as @cite{imagedit.exe} to build bitmaps, icons and cursors and
31783 @cite{dlgedit.exe} to build dialogs.
31784 It is always possible to build an @code{.rc} file yourself by writing a
31787 It is not our objective to explain how to write a resource file. A
31788 complete description of the resource script language can be found in the
31789 Microsoft documentation.
31791 @node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
31792 @anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{2a3}@anchor{gnat_ugn/platform_specific_information id35}@anchor{2a4}
31793 @subsubsection Compiling Resources
31803 This section describes how to build a GNAT-compatible (COFF) object file
31804 containing the resources. This is done using the Resource Compiler
31805 @cite{windres} as follows:
31810 $ windres -i myres.rc -o myres.o
31814 By default @cite{windres} will run @emph{gcc} to preprocess the @code{.rc}
31815 file. You can specify an alternate preprocessor (usually named
31816 @code{cpp.exe}) using the @cite{windres} @emph{--preprocessor}
31817 parameter. A list of all possible options may be obtained by entering
31818 the command @cite{windres} @emph{--help}.
31820 It is also possible to use the Microsoft resource compiler @cite{rc.exe}
31821 to produce a @code{.res} file (binary resource file). See the
31822 corresponding Microsoft documentation for further details. In this case
31823 you need to use @cite{windres} to translate the @code{.res} file to a
31824 GNAT-compatible object file as follows:
31829 $ windres -i myres.res -o myres.o
31833 @node Using Resources,,Compiling Resources,GNAT and Windows Resources
31834 @anchor{gnat_ugn/platform_specific_information id36}@anchor{2a5}@anchor{gnat_ugn/platform_specific_information using-resources}@anchor{2a6}
31835 @subsubsection Using Resources
31841 To include the resource file in your program just add the
31842 GNAT-compatible object file for the resource(s) to the linker
31843 arguments. With @emph{gnatmake} this is done by using the @emph{-largs}
31849 $ gnatmake myprog -largs myres.o
31853 @node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
31854 @anchor{gnat_ugn/platform_specific_information using-gnat-dll-from-msvs}@anchor{2a7}@anchor{gnat_ugn/platform_specific_information using-gnat-dlls-from-microsoft-visual-studio-applications}@anchor{2a8}
31855 @subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
31858 @geindex Microsoft Visual Studio
31859 @geindex use with GNAT DLLs
31861 This section describes a common case of mixed GNAT/Microsoft Visual Studio
31862 application development, where the main program is developed using MSVS, and
31863 is linked with a DLL developed using GNAT. Such a mixed application should
31864 be developed following the general guidelines outlined above; below is the
31865 cookbook-style sequence of steps to follow:
31871 First develop and build the GNAT shared library using a library project
31872 (let's assume the project is @cite{mylib.gpr}, producing the library @cite{libmylib.dll}):
31878 $ gprbuild -p mylib.gpr
31886 Produce a .def file for the symbols you need to interface with, either by
31887 hand or automatically with possibly some manual adjustments
31888 (see @ref{289,,Creating Definition File Automatically}):
31894 $ dlltool libmylib.dll -z libmylib.def --export-all-symbols
31902 Make sure that MSVS command-line tools are accessible on the path.
31905 Create the Microsoft-style import library (see @ref{28c,,MSVS-Style Import Library}):
31911 $ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
31915 If you are using a 64-bit toolchain, the above becomes...
31920 $ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
31934 $ cl /O2 /MD main.c libmylib.lib
31942 Before running the executable, make sure you have set the PATH to the DLL,
31943 or copy the DLL into into the directory containing the .exe.
31946 @node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
31947 @anchor{gnat_ugn/platform_specific_information id37}@anchor{2a9}@anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{2aa}
31948 @subsubsection Debugging a DLL
31951 @geindex DLL debugging
31953 Debugging a DLL is similar to debugging a standard program. But
31954 we have to deal with two different executable parts: the DLL and the
31955 program that uses it. We have the following four possibilities:
31961 The program and the DLL are built with @cite{GCC/GNAT}.
31964 The program is built with foreign tools and the DLL is built with
31968 The program is built with @cite{GCC/GNAT} and the DLL is built with
31972 In this section we address only cases one and two above.
31973 There is no point in trying to debug
31974 a DLL with @cite{GNU/GDB}, if there is no GDB-compatible debugging
31975 information in it. To do so you must use a debugger compatible with the
31976 tools suite used to build the DLL.
31979 * Program and DLL Both Built with GCC/GNAT::
31980 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31984 @node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
31985 @anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{2ab}@anchor{gnat_ugn/platform_specific_information id38}@anchor{2ac}
31986 @subsubsection Program and DLL Both Built with GCC/GNAT
31989 This is the simplest case. Both the DLL and the program have @cite{GDB}
31990 compatible debugging information. It is then possible to break anywhere in
31991 the process. Let's suppose here that the main procedure is named
31992 @cite{ada_main} and that in the DLL there is an entry point named
31995 The DLL (@ref{282,,Introduction to Dynamic Link Libraries (DLLs)}) and
31996 program must have been built with the debugging information (see GNAT -g
31997 switch). Here are the step-by-step instructions for debugging it:
32003 Launch @cite{GDB} on the main program.
32010 Start the program and stop at the beginning of the main procedure
32016 This step is required to be able to set a breakpoint inside the DLL. As long
32017 as the program is not run, the DLL is not loaded. This has the
32018 consequence that the DLL debugging information is also not loaded, so it is not
32019 possible to set a breakpoint in the DLL.
32022 Set a breakpoint inside the DLL
32025 (gdb) break ada_dll
32030 At this stage a breakpoint is set inside the DLL. From there on
32031 you can use the standard approach to debug the whole program
32032 (@ref{26,,Running and Debugging Ada Programs}).
32034 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
32035 @anchor{gnat_ugn/platform_specific_information program-built-with-foreign-tools-and-dll-built-with-gcc-gnat}@anchor{2ad}@anchor{gnat_ugn/platform_specific_information id39}@anchor{2ae}
32036 @subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
32039 In this case things are slightly more complex because it is not possible to
32040 start the main program and then break at the beginning to load the DLL and the
32041 associated DLL debugging information. It is not possible to break at the
32042 beginning of the program because there is no @cite{GDB} debugging information,
32043 and therefore there is no direct way of getting initial control. This
32044 section addresses this issue by describing some methods that can be used
32045 to break somewhere in the DLL to debug it.
32047 First suppose that the main procedure is named @cite{main} (this is for
32048 example some C code built with Microsoft Visual C) and that there is a
32049 DLL named @cite{test.dll} containing an Ada entry point named
32052 The DLL (see @ref{282,,Introduction to Dynamic Link Libraries (DLLs)}) must have
32053 been built with debugging information (see GNAT @cite{-g} option).
32055 @subsubheading Debugging the DLL Directly
32062 Find out the executable starting address
32065 $ objdump --file-header main.exe
32068 The starting address is reported on the last line. For example:
32071 main.exe: file format pei-i386
32072 architecture: i386, flags 0x0000010a:
32073 EXEC_P, HAS_DEBUG, D_PAGED
32074 start address 0x00401010
32078 Launch the debugger on the executable.
32085 Set a breakpoint at the starting address, and launch the program.
32088 $ (gdb) break *0x00401010
32092 The program will stop at the given address.
32095 Set a breakpoint on a DLL subroutine.
32098 (gdb) break ada_dll.adb:45
32101 Or if you want to break using a symbol on the DLL, you need first to
32102 select the Ada language (language used by the DLL).
32105 (gdb) set language ada
32106 (gdb) break ada_dll
32110 Continue the program.
32116 This will run the program until it reaches the breakpoint that has been
32117 set. From that point you can use the standard way to debug a program
32118 as described in (@ref{26,,Running and Debugging Ada Programs}).
32121 It is also possible to debug the DLL by attaching to a running process.
32123 @subsubheading Attaching to a Running Process
32126 @geindex DLL debugging
32127 @geindex attach to process
32129 With @cite{GDB} it is always possible to debug a running process by
32130 attaching to it. It is possible to debug a DLL this way. The limitation
32131 of this approach is that the DLL must run long enough to perform the
32132 attach operation. It may be useful for instance to insert a time wasting
32133 loop in the code of the DLL to meet this criterion.
32139 Launch the main program @code{main.exe}.
32146 Use the Windows @emph{Task Manager} to find the process ID. Let's say
32147 that the process PID for @code{main.exe} is 208.
32157 Attach to the running process to be debugged.
32164 Load the process debugging information.
32167 (gdb) symbol-file main.exe
32171 Break somewhere in the DLL.
32174 (gdb) break ada_dll
32178 Continue process execution.
32185 This last step will resume the process execution, and stop at
32186 the breakpoint we have set. From there you can use the standard
32187 approach to debug a program as described in
32188 @ref{26,,Running and Debugging Ada Programs}.
32190 @node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
32191 @anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{13d}@anchor{gnat_ugn/platform_specific_information id40}@anchor{2af}
32192 @subsubsection Setting Stack Size from @emph{gnatlink}
32195 It is possible to specify the program stack size at link time. On modern
32196 versions of Windows, starting with XP, this is mostly useful to set the size of
32197 the main stack (environment task). The other task stacks are set with pragma
32198 Storage_Size or with the @emph{gnatbind -d} command.
32200 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
32201 reserve size of individual tasks, the link-time stack size applies to all
32202 tasks, and pragma Storage_Size has no effect.
32203 In particular, Stack Overflow checks are made against this
32204 link-time specified size.
32206 This setting can be done with @emph{gnatlink} using either of the following:
32212 @emph{-Xlinker} linker option
32215 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
32218 This sets the stack reserve size to 0x10000 bytes and the stack commit
32219 size to 0x1000 bytes.
32222 @emph{-Wl} linker option
32225 $ gnatlink hello -Wl,--stack=0x1000000
32228 This sets the stack reserve size to 0x1000000 bytes. Note that with
32229 @emph{-Wl} option it is not possible to set the stack commit size
32230 because the coma is a separator for this option.
32233 @node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
32234 @anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{13e}@anchor{gnat_ugn/platform_specific_information id41}@anchor{2b0}
32235 @subsubsection Setting Heap Size from @emph{gnatlink}
32238 Under Windows systems, it is possible to specify the program heap size from
32239 @emph{gnatlink} using either of the following:
32245 @emph{-Xlinker} linker option
32248 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
32251 This sets the heap reserve size to 0x10000 bytes and the heap commit
32252 size to 0x1000 bytes.
32255 @emph{-Wl} linker option
32258 $ gnatlink hello -Wl,--heap=0x1000000
32261 This sets the heap reserve size to 0x1000000 bytes. Note that with
32262 @emph{-Wl} option it is not possible to set the heap commit size
32263 because the coma is a separator for this option.
32266 @node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
32267 @anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{2b1}@anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{2b2}
32268 @subsection Windows Specific Add-Ons
32271 This section describes the Windows specific add-ons.
32279 @node Win32Ada,wPOSIX,,Windows Specific Add-Ons
32280 @anchor{gnat_ugn/platform_specific_information win32ada}@anchor{2b3}@anchor{gnat_ugn/platform_specific_information id42}@anchor{2b4}
32281 @subsubsection Win32Ada
32284 Win32Ada is a binding for the Microsoft Win32 API. This binding can be
32285 easily installed from the provided installer. To use the Win32Ada
32286 binding you need to use a project file, and adding a single with_clause
32287 will give you full access to the Win32Ada binding sources and ensure
32288 that the proper libraries are passed to the linker.
32295 for Sources use ...;
32300 To build the application you just need to call gprbuild for the
32301 application's project, here p.gpr:
32310 @node wPOSIX,,Win32Ada,Windows Specific Add-Ons
32311 @anchor{gnat_ugn/platform_specific_information id43}@anchor{2b5}@anchor{gnat_ugn/platform_specific_information wposix}@anchor{2b6}
32312 @subsubsection wPOSIX
32315 wPOSIX is a minimal POSIX binding whose goal is to help with building
32316 cross-platforms applications. This binding is not complete though, as
32317 the Win32 API does not provide the necessary support for all POSIX APIs.
32319 To use the wPOSIX binding you need to use a project file, and adding
32320 a single with_clause will give you full access to the wPOSIX binding
32321 sources and ensure that the proper libraries are passed to the linker.
32328 for Sources use ...;
32333 To build the application you just need to call gprbuild for the
32334 application's project, here p.gpr:
32343 @node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
32344 @anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{2f}@anchor{gnat_ugn/platform_specific_information id44}@anchor{2b7}
32345 @section Mac OS Topics
32350 This section describes topics that are specific to Apple's OS X
32354 * Codesigning the Debugger::
32358 @node Codesigning the Debugger,,,Mac OS Topics
32359 @anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{2b8}
32360 @subsection Codesigning the Debugger
32363 The Darwin Kernel requires the debugger to have special permissions
32364 before it is allowed to control other processes. These permissions
32365 are granted by codesigning the GDB executable. Without these
32366 permissions, the debugger will report error messages such as:
32369 Starting program: /x/y/foo
32370 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
32371 (please check gdb is codesigned - see taskgated(8))
32374 Codesigning requires a certificate. The following procedure explains
32381 Start the Keychain Access application (in
32382 /Applications/Utilities/Keychain Access.app)
32385 Select the Keychain Access -> Certificate Assistant ->
32386 Create a Certificate... menu
32395 Choose a name for the new certificate (this procedure will use
32396 "gdb-cert" as an example)
32399 Set "Identity Type" to "Self Signed Root"
32402 Set "Certificate Type" to "Code Signing"
32405 Activate the "Let me override defaults" option
32409 Click several times on "Continue" until the "Specify a Location
32410 For The Certificate" screen appears, then set "Keychain" to "System"
32413 Click on "Continue" until the certificate is created
32416 Finally, in the view, double-click on the new certificate,
32417 and set "When using this certificate" to "Always Trust"
32420 Exit the Keychain Access application and restart the computer
32421 (this is unfortunately required)
32424 Once a certificate has been created, the debugger can be codesigned
32425 as follow. In a Terminal, run the following command:
32430 $ codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb
32434 where "gdb-cert" should be replaced by the actual certificate
32435 name chosen above, and <gnat_install_prefix> should be replaced by
32436 the location where you installed GNAT. Also, be sure that users are
32437 in the Unix group @code{_developer}.
32439 @node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
32440 @anchor{gnat_ugn/example_of_binder_output example-of-binder-output-file}@anchor{10}@anchor{gnat_ugn/example_of_binder_output doc}@anchor{2b9}@anchor{gnat_ugn/example_of_binder_output id1}@anchor{2ba}
32441 @chapter Example of Binder Output File
32444 @geindex Binder output (example)
32446 This Appendix displays the source code for the output file
32447 generated by @emph{gnatbind} for a simple 'Hello World' program.
32448 Comments have been added for clarification purposes.
32451 -- The package is called Ada_Main unless this name is actually used
32452 -- as a unit name in the partition, in which case some other unique
32457 package ada_main is
32458 pragma Warnings (Off);
32460 -- The main program saves the parameters (argument count,
32461 -- argument values, environment pointer) in global variables
32462 -- for later access by other units including
32463 -- Ada.Command_Line.
32465 gnat_argc : Integer;
32466 gnat_argv : System.Address;
32467 gnat_envp : System.Address;
32469 -- The actual variables are stored in a library routine. This
32470 -- is useful for some shared library situations, where there
32471 -- are problems if variables are not in the library.
32473 pragma Import (C, gnat_argc);
32474 pragma Import (C, gnat_argv);
32475 pragma Import (C, gnat_envp);
32477 -- The exit status is similarly an external location
32479 gnat_exit_status : Integer;
32480 pragma Import (C, gnat_exit_status);
32482 GNAT_Version : constant String :=
32483 "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
32484 pragma Export (C, GNAT_Version, "__gnat_version");
32486 Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
32487 pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
32489 -- This is the generated adainit routine that performs
32490 -- initialization at the start of execution. In the case
32491 -- where Ada is the main program, this main program makes
32492 -- a call to adainit at program startup.
32495 pragma Export (C, adainit, "adainit");
32497 -- This is the generated adafinal routine that performs
32498 -- finalization at the end of execution. In the case where
32499 -- Ada is the main program, this main program makes a call
32500 -- to adafinal at program termination.
32502 procedure adafinal;
32503 pragma Export (C, adafinal, "adafinal");
32505 -- This routine is called at the start of execution. It is
32506 -- a dummy routine that is used by the debugger to breakpoint
32507 -- at the start of execution.
32509 -- This is the actual generated main program (it would be
32510 -- suppressed if the no main program switch were used). As
32511 -- required by standard system conventions, this program has
32512 -- the external name main.
32516 argv : System.Address;
32517 envp : System.Address)
32519 pragma Export (C, main, "main");
32521 -- The following set of constants give the version
32522 -- identification values for every unit in the bound
32523 -- partition. This identification is computed from all
32524 -- dependent semantic units, and corresponds to the
32525 -- string that would be returned by use of the
32526 -- Body_Version or Version attributes.
32528 -- The following Export pragmas export the version numbers
32529 -- with symbolic names ending in B (for body) or S
32530 -- (for spec) so that they can be located in a link. The
32531 -- information provided here is sufficient to track down
32532 -- the exact versions of units used in a given build.
32534 type Version_32 is mod 2 ** 32;
32535 u00001 : constant Version_32 := 16#8ad6e54a#;
32536 pragma Export (C, u00001, "helloB");
32537 u00002 : constant Version_32 := 16#fbff4c67#;
32538 pragma Export (C, u00002, "system__standard_libraryB");
32539 u00003 : constant Version_32 := 16#1ec6fd90#;
32540 pragma Export (C, u00003, "system__standard_libraryS");
32541 u00004 : constant Version_32 := 16#3ffc8e18#;
32542 pragma Export (C, u00004, "adaS");
32543 u00005 : constant Version_32 := 16#28f088c2#;
32544 pragma Export (C, u00005, "ada__text_ioB");
32545 u00006 : constant Version_32 := 16#f372c8ac#;
32546 pragma Export (C, u00006, "ada__text_ioS");
32547 u00007 : constant Version_32 := 16#2c143749#;
32548 pragma Export (C, u00007, "ada__exceptionsB");
32549 u00008 : constant Version_32 := 16#f4f0cce8#;
32550 pragma Export (C, u00008, "ada__exceptionsS");
32551 u00009 : constant Version_32 := 16#a46739c0#;
32552 pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
32553 u00010 : constant Version_32 := 16#3aac8c92#;
32554 pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
32555 u00011 : constant Version_32 := 16#1d274481#;
32556 pragma Export (C, u00011, "systemS");
32557 u00012 : constant Version_32 := 16#a207fefe#;
32558 pragma Export (C, u00012, "system__soft_linksB");
32559 u00013 : constant Version_32 := 16#467d9556#;
32560 pragma Export (C, u00013, "system__soft_linksS");
32561 u00014 : constant Version_32 := 16#b01dad17#;
32562 pragma Export (C, u00014, "system__parametersB");
32563 u00015 : constant Version_32 := 16#630d49fe#;
32564 pragma Export (C, u00015, "system__parametersS");
32565 u00016 : constant Version_32 := 16#b19b6653#;
32566 pragma Export (C, u00016, "system__secondary_stackB");
32567 u00017 : constant Version_32 := 16#b6468be8#;
32568 pragma Export (C, u00017, "system__secondary_stackS");
32569 u00018 : constant Version_32 := 16#39a03df9#;
32570 pragma Export (C, u00018, "system__storage_elementsB");
32571 u00019 : constant Version_32 := 16#30e40e85#;
32572 pragma Export (C, u00019, "system__storage_elementsS");
32573 u00020 : constant Version_32 := 16#41837d1e#;
32574 pragma Export (C, u00020, "system__stack_checkingB");
32575 u00021 : constant Version_32 := 16#93982f69#;
32576 pragma Export (C, u00021, "system__stack_checkingS");
32577 u00022 : constant Version_32 := 16#393398c1#;
32578 pragma Export (C, u00022, "system__exception_tableB");
32579 u00023 : constant Version_32 := 16#b33e2294#;
32580 pragma Export (C, u00023, "system__exception_tableS");
32581 u00024 : constant Version_32 := 16#ce4af020#;
32582 pragma Export (C, u00024, "system__exceptionsB");
32583 u00025 : constant Version_32 := 16#75442977#;
32584 pragma Export (C, u00025, "system__exceptionsS");
32585 u00026 : constant Version_32 := 16#37d758f1#;
32586 pragma Export (C, u00026, "system__exceptions__machineS");
32587 u00027 : constant Version_32 := 16#b895431d#;
32588 pragma Export (C, u00027, "system__exceptions_debugB");
32589 u00028 : constant Version_32 := 16#aec55d3f#;
32590 pragma Export (C, u00028, "system__exceptions_debugS");
32591 u00029 : constant Version_32 := 16#570325c8#;
32592 pragma Export (C, u00029, "system__img_intB");
32593 u00030 : constant Version_32 := 16#1ffca443#;
32594 pragma Export (C, u00030, "system__img_intS");
32595 u00031 : constant Version_32 := 16#b98c3e16#;
32596 pragma Export (C, u00031, "system__tracebackB");
32597 u00032 : constant Version_32 := 16#831a9d5a#;
32598 pragma Export (C, u00032, "system__tracebackS");
32599 u00033 : constant Version_32 := 16#9ed49525#;
32600 pragma Export (C, u00033, "system__traceback_entriesB");
32601 u00034 : constant Version_32 := 16#1d7cb2f1#;
32602 pragma Export (C, u00034, "system__traceback_entriesS");
32603 u00035 : constant Version_32 := 16#8c33a517#;
32604 pragma Export (C, u00035, "system__wch_conB");
32605 u00036 : constant Version_32 := 16#065a6653#;
32606 pragma Export (C, u00036, "system__wch_conS");
32607 u00037 : constant Version_32 := 16#9721e840#;
32608 pragma Export (C, u00037, "system__wch_stwB");
32609 u00038 : constant Version_32 := 16#2b4b4a52#;
32610 pragma Export (C, u00038, "system__wch_stwS");
32611 u00039 : constant Version_32 := 16#92b797cb#;
32612 pragma Export (C, u00039, "system__wch_cnvB");
32613 u00040 : constant Version_32 := 16#09eddca0#;
32614 pragma Export (C, u00040, "system__wch_cnvS");
32615 u00041 : constant Version_32 := 16#6033a23f#;
32616 pragma Export (C, u00041, "interfacesS");
32617 u00042 : constant Version_32 := 16#ece6fdb6#;
32618 pragma Export (C, u00042, "system__wch_jisB");
32619 u00043 : constant Version_32 := 16#899dc581#;
32620 pragma Export (C, u00043, "system__wch_jisS");
32621 u00044 : constant Version_32 := 16#10558b11#;
32622 pragma Export (C, u00044, "ada__streamsB");
32623 u00045 : constant Version_32 := 16#2e6701ab#;
32624 pragma Export (C, u00045, "ada__streamsS");
32625 u00046 : constant Version_32 := 16#db5c917c#;
32626 pragma Export (C, u00046, "ada__io_exceptionsS");
32627 u00047 : constant Version_32 := 16#12c8cd7d#;
32628 pragma Export (C, u00047, "ada__tagsB");
32629 u00048 : constant Version_32 := 16#ce72c228#;
32630 pragma Export (C, u00048, "ada__tagsS");
32631 u00049 : constant Version_32 := 16#c3335bfd#;
32632 pragma Export (C, u00049, "system__htableB");
32633 u00050 : constant Version_32 := 16#99e5f76b#;
32634 pragma Export (C, u00050, "system__htableS");
32635 u00051 : constant Version_32 := 16#089f5cd0#;
32636 pragma Export (C, u00051, "system__string_hashB");
32637 u00052 : constant Version_32 := 16#3bbb9c15#;
32638 pragma Export (C, u00052, "system__string_hashS");
32639 u00053 : constant Version_32 := 16#807fe041#;
32640 pragma Export (C, u00053, "system__unsigned_typesS");
32641 u00054 : constant Version_32 := 16#d27be59e#;
32642 pragma Export (C, u00054, "system__val_lluB");
32643 u00055 : constant Version_32 := 16#fa8db733#;
32644 pragma Export (C, u00055, "system__val_lluS");
32645 u00056 : constant Version_32 := 16#27b600b2#;
32646 pragma Export (C, u00056, "system__val_utilB");
32647 u00057 : constant Version_32 := 16#b187f27f#;
32648 pragma Export (C, u00057, "system__val_utilS");
32649 u00058 : constant Version_32 := 16#d1060688#;
32650 pragma Export (C, u00058, "system__case_utilB");
32651 u00059 : constant Version_32 := 16#392e2d56#;
32652 pragma Export (C, u00059, "system__case_utilS");
32653 u00060 : constant Version_32 := 16#84a27f0d#;
32654 pragma Export (C, u00060, "interfaces__c_streamsB");
32655 u00061 : constant Version_32 := 16#8bb5f2c0#;
32656 pragma Export (C, u00061, "interfaces__c_streamsS");
32657 u00062 : constant Version_32 := 16#6db6928f#;
32658 pragma Export (C, u00062, "system__crtlS");
32659 u00063 : constant Version_32 := 16#4e6a342b#;
32660 pragma Export (C, u00063, "system__file_ioB");
32661 u00064 : constant Version_32 := 16#ba56a5e4#;
32662 pragma Export (C, u00064, "system__file_ioS");
32663 u00065 : constant Version_32 := 16#b7ab275c#;
32664 pragma Export (C, u00065, "ada__finalizationB");
32665 u00066 : constant Version_32 := 16#19f764ca#;
32666 pragma Export (C, u00066, "ada__finalizationS");
32667 u00067 : constant Version_32 := 16#95817ed8#;
32668 pragma Export (C, u00067, "system__finalization_rootB");
32669 u00068 : constant Version_32 := 16#52d53711#;
32670 pragma Export (C, u00068, "system__finalization_rootS");
32671 u00069 : constant Version_32 := 16#769e25e6#;
32672 pragma Export (C, u00069, "interfaces__cB");
32673 u00070 : constant Version_32 := 16#4a38bedb#;
32674 pragma Export (C, u00070, "interfaces__cS");
32675 u00071 : constant Version_32 := 16#07e6ee66#;
32676 pragma Export (C, u00071, "system__os_libB");
32677 u00072 : constant Version_32 := 16#d7b69782#;
32678 pragma Export (C, u00072, "system__os_libS");
32679 u00073 : constant Version_32 := 16#1a817b8e#;
32680 pragma Export (C, u00073, "system__stringsB");
32681 u00074 : constant Version_32 := 16#639855e7#;
32682 pragma Export (C, u00074, "system__stringsS");
32683 u00075 : constant Version_32 := 16#e0b8de29#;
32684 pragma Export (C, u00075, "system__file_control_blockS");
32685 u00076 : constant Version_32 := 16#b5b2aca1#;
32686 pragma Export (C, u00076, "system__finalization_mastersB");
32687 u00077 : constant Version_32 := 16#69316dc1#;
32688 pragma Export (C, u00077, "system__finalization_mastersS");
32689 u00078 : constant Version_32 := 16#57a37a42#;
32690 pragma Export (C, u00078, "system__address_imageB");
32691 u00079 : constant Version_32 := 16#bccbd9bb#;
32692 pragma Export (C, u00079, "system__address_imageS");
32693 u00080 : constant Version_32 := 16#7268f812#;
32694 pragma Export (C, u00080, "system__img_boolB");
32695 u00081 : constant Version_32 := 16#e8fe356a#;
32696 pragma Export (C, u00081, "system__img_boolS");
32697 u00082 : constant Version_32 := 16#d7aac20c#;
32698 pragma Export (C, u00082, "system__ioB");
32699 u00083 : constant Version_32 := 16#8365b3ce#;
32700 pragma Export (C, u00083, "system__ioS");
32701 u00084 : constant Version_32 := 16#6d4d969a#;
32702 pragma Export (C, u00084, "system__storage_poolsB");
32703 u00085 : constant Version_32 := 16#e87cc305#;
32704 pragma Export (C, u00085, "system__storage_poolsS");
32705 u00086 : constant Version_32 := 16#e34550ca#;
32706 pragma Export (C, u00086, "system__pool_globalB");
32707 u00087 : constant Version_32 := 16#c88d2d16#;
32708 pragma Export (C, u00087, "system__pool_globalS");
32709 u00088 : constant Version_32 := 16#9d39c675#;
32710 pragma Export (C, u00088, "system__memoryB");
32711 u00089 : constant Version_32 := 16#445a22b5#;
32712 pragma Export (C, u00089, "system__memoryS");
32713 u00090 : constant Version_32 := 16#6a859064#;
32714 pragma Export (C, u00090, "system__storage_pools__subpoolsB");
32715 u00091 : constant Version_32 := 16#e3b008dc#;
32716 pragma Export (C, u00091, "system__storage_pools__subpoolsS");
32717 u00092 : constant Version_32 := 16#63f11652#;
32718 pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
32719 u00093 : constant Version_32 := 16#fe2f4b3a#;
32720 pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
32722 -- BEGIN ELABORATION ORDER
32726 -- system.case_util%s
32727 -- system.case_util%b
32729 -- system.img_bool%s
32730 -- system.img_bool%b
32731 -- system.img_int%s
32732 -- system.img_int%b
32735 -- system.parameters%s
32736 -- system.parameters%b
32738 -- interfaces.c_streams%s
32739 -- interfaces.c_streams%b
32740 -- system.standard_library%s
32741 -- system.exceptions_debug%s
32742 -- system.exceptions_debug%b
32743 -- system.storage_elements%s
32744 -- system.storage_elements%b
32745 -- system.stack_checking%s
32746 -- system.stack_checking%b
32747 -- system.string_hash%s
32748 -- system.string_hash%b
32750 -- system.strings%s
32751 -- system.strings%b
32753 -- system.traceback_entries%s
32754 -- system.traceback_entries%b
32755 -- ada.exceptions%s
32756 -- system.soft_links%s
32757 -- system.unsigned_types%s
32758 -- system.val_llu%s
32759 -- system.val_util%s
32760 -- system.val_util%b
32761 -- system.val_llu%b
32762 -- system.wch_con%s
32763 -- system.wch_con%b
32764 -- system.wch_cnv%s
32765 -- system.wch_jis%s
32766 -- system.wch_jis%b
32767 -- system.wch_cnv%b
32768 -- system.wch_stw%s
32769 -- system.wch_stw%b
32770 -- ada.exceptions.last_chance_handler%s
32771 -- ada.exceptions.last_chance_handler%b
32772 -- system.address_image%s
32773 -- system.exception_table%s
32774 -- system.exception_table%b
32775 -- ada.io_exceptions%s
32780 -- system.exceptions%s
32781 -- system.exceptions%b
32782 -- system.exceptions.machine%s
32783 -- system.finalization_root%s
32784 -- system.finalization_root%b
32785 -- ada.finalization%s
32786 -- ada.finalization%b
32787 -- system.storage_pools%s
32788 -- system.storage_pools%b
32789 -- system.finalization_masters%s
32790 -- system.storage_pools.subpools%s
32791 -- system.storage_pools.subpools.finalization%s
32792 -- system.storage_pools.subpools.finalization%b
32795 -- system.standard_library%b
32796 -- system.pool_global%s
32797 -- system.pool_global%b
32798 -- system.file_control_block%s
32799 -- system.file_io%s
32800 -- system.secondary_stack%s
32801 -- system.file_io%b
32802 -- system.storage_pools.subpools%b
32803 -- system.finalization_masters%b
32806 -- system.soft_links%b
32808 -- system.secondary_stack%b
32809 -- system.address_image%b
32810 -- system.traceback%s
32811 -- ada.exceptions%b
32812 -- system.traceback%b
32816 -- END ELABORATION ORDER
32823 -- The following source file name pragmas allow the generated file
32824 -- names to be unique for different main programs. They are needed
32825 -- since the package name will always be Ada_Main.
32827 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
32828 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
32830 pragma Suppress (Overflow_Check);
32831 with Ada.Exceptions;
32833 -- Generated package body for Ada_Main starts here
32835 package body ada_main is
32836 pragma Warnings (Off);
32838 -- These values are reference counter associated to units which have
32839 -- been elaborated. It is also used to avoid elaborating the
32840 -- same unit twice.
32842 E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
32843 E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
32844 E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
32845 E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
32846 E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
32847 E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
32848 E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
32849 E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
32850 E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
32851 E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
32852 E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
32853 E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
32854 E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
32855 E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
32856 E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
32857 E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
32858 E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
32859 E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
32861 Local_Priority_Specific_Dispatching : constant String := "";
32862 Local_Interrupt_States : constant String := "";
32864 Is_Elaborated : Boolean := False;
32866 procedure finalize_library is
32871 pragma Import (Ada, F1, "ada__text_io__finalize_spec");
32879 pragma Import (Ada, F2, "system__file_io__finalize_body");
32886 pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
32894 pragma Import (Ada, F4, "system__pool_global__finalize_spec");
32900 pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
32906 pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
32911 procedure Reraise_Library_Exception_If_Any;
32912 pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
32914 Reraise_Library_Exception_If_Any;
32916 end finalize_library;
32922 procedure adainit is
32924 Main_Priority : Integer;
32925 pragma Import (C, Main_Priority, "__gl_main_priority");
32926 Time_Slice_Value : Integer;
32927 pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
32928 WC_Encoding : Character;
32929 pragma Import (C, WC_Encoding, "__gl_wc_encoding");
32930 Locking_Policy : Character;
32931 pragma Import (C, Locking_Policy, "__gl_locking_policy");
32932 Queuing_Policy : Character;
32933 pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
32934 Task_Dispatching_Policy : Character;
32935 pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
32936 Priority_Specific_Dispatching : System.Address;
32937 pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
32938 Num_Specific_Dispatching : Integer;
32939 pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
32940 Main_CPU : Integer;
32941 pragma Import (C, Main_CPU, "__gl_main_cpu");
32942 Interrupt_States : System.Address;
32943 pragma Import (C, Interrupt_States, "__gl_interrupt_states");
32944 Num_Interrupt_States : Integer;
32945 pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
32946 Unreserve_All_Interrupts : Integer;
32947 pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
32948 Detect_Blocking : Integer;
32949 pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
32950 Default_Stack_Size : Integer;
32951 pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
32952 Leap_Seconds_Support : Integer;
32953 pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
32955 procedure Runtime_Initialize;
32956 pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
32958 Finalize_Library_Objects : No_Param_Proc;
32959 pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
32961 -- Start of processing for adainit
32965 -- Record various information for this partition. The values
32966 -- are derived by the binder from information stored in the ali
32967 -- files by the compiler.
32969 if Is_Elaborated then
32972 Is_Elaborated := True;
32973 Main_Priority := -1;
32974 Time_Slice_Value := -1;
32975 WC_Encoding := 'b';
32976 Locking_Policy := ' ';
32977 Queuing_Policy := ' ';
32978 Task_Dispatching_Policy := ' ';
32979 Priority_Specific_Dispatching :=
32980 Local_Priority_Specific_Dispatching'Address;
32981 Num_Specific_Dispatching := 0;
32983 Interrupt_States := Local_Interrupt_States'Address;
32984 Num_Interrupt_States := 0;
32985 Unreserve_All_Interrupts := 0;
32986 Detect_Blocking := 0;
32987 Default_Stack_Size := -1;
32988 Leap_Seconds_Support := 0;
32990 Runtime_Initialize;
32992 Finalize_Library_Objects := finalize_library'access;
32994 -- Now we have the elaboration calls for all units in the partition.
32995 -- The Elab_Spec and Elab_Body attributes generate references to the
32996 -- implicit elaboration procedures generated by the compiler for
32997 -- each unit that requires elaboration. Increment a counter of
32998 -- reference for each unit.
33000 System.Soft_Links'Elab_Spec;
33001 System.Exception_Table'Elab_Body;
33003 Ada.Io_Exceptions'Elab_Spec;
33005 Ada.Tags'Elab_Spec;
33006 Ada.Streams'Elab_Spec;
33008 Interfaces.C'Elab_Spec;
33009 System.Exceptions'Elab_Spec;
33011 System.Finalization_Root'Elab_Spec;
33013 Ada.Finalization'Elab_Spec;
33015 System.Storage_Pools'Elab_Spec;
33017 System.Finalization_Masters'Elab_Spec;
33018 System.Storage_Pools.Subpools'Elab_Spec;
33019 System.Pool_Global'Elab_Spec;
33021 System.File_Control_Block'Elab_Spec;
33023 System.File_Io'Elab_Body;
33026 System.Finalization_Masters'Elab_Body;
33029 Ada.Tags'Elab_Body;
33031 System.Soft_Links'Elab_Body;
33033 System.Os_Lib'Elab_Body;
33035 System.Secondary_Stack'Elab_Body;
33037 Ada.Text_Io'Elab_Spec;
33038 Ada.Text_Io'Elab_Body;
33046 procedure adafinal is
33047 procedure s_stalib_adafinal;
33048 pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
33050 procedure Runtime_Finalize;
33051 pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
33054 if not Is_Elaborated then
33057 Is_Elaborated := False;
33062 -- We get to the main program of the partition by using
33063 -- pragma Import because if we try to with the unit and
33064 -- call it Ada style, then not only do we waste time
33065 -- recompiling it, but also, we don't really know the right
33066 -- switches (e.g.@@: identifier character set) to be used
33069 procedure Ada_Main_Program;
33070 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
33076 -- main is actually a function, as in the ANSI C standard,
33077 -- defined to return the exit status. The three parameters
33078 -- are the argument count, argument values and environment
33083 argv : System.Address;
33084 envp : System.Address)
33087 -- The initialize routine performs low level system
33088 -- initialization using a standard library routine which
33089 -- sets up signal handling and performs any other
33090 -- required setup. The routine can be found in file
33093 procedure initialize;
33094 pragma Import (C, initialize, "__gnat_initialize");
33096 -- The finalize routine performs low level system
33097 -- finalization using a standard library routine. The
33098 -- routine is found in file a-final.c and in the standard
33099 -- distribution is a dummy routine that does nothing, so
33100 -- really this is a hook for special user finalization.
33102 procedure finalize;
33103 pragma Import (C, finalize, "__gnat_finalize");
33105 -- The following is to initialize the SEH exceptions
33107 SEH : aliased array (1 .. 2) of Integer;
33109 Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
33110 pragma Volatile (Ensure_Reference);
33112 -- Start of processing for main
33115 -- Save global variables
33121 -- Call low level system initialization
33123 Initialize (SEH'Address);
33125 -- Call our generated Ada initialization routine
33129 -- Now we call the main program of the partition
33133 -- Perform Ada finalization
33137 -- Perform low level system finalization
33141 -- Return the proper exit status
33142 return (gnat_exit_status);
33145 -- This section is entirely comments, so it has no effect on the
33146 -- compilation of the Ada_Main package. It provides the list of
33147 -- object files and linker options, as well as some standard
33148 -- libraries needed for the link. The gnatlink utility parses
33149 -- this b~hello.adb file to read these comment lines to generate
33150 -- the appropriate command line arguments for the call to the
33151 -- system linker. The BEGIN/END lines are used for sentinels for
33152 -- this parsing operation.
33154 -- The exact file names will of course depend on the environment,
33155 -- host/target and location of files on the host system.
33157 -- BEGIN Object file/option list
33160 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
33161 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
33162 -- END Object file/option list
33167 The Ada code in the above example is exactly what is generated by the
33168 binder. We have added comments to more clearly indicate the function
33169 of each part of the generated @cite{Ada_Main} package.
33171 The code is standard Ada in all respects, and can be processed by any
33172 tools that handle Ada. In particular, it is possible to use the debugger
33173 in Ada mode to debug the generated @cite{Ada_Main} package. For example,
33174 suppose that for reasons that you do not understand, your program is crashing
33175 during elaboration of the body of @cite{Ada.Text_IO}. To locate this bug,
33176 you can place a breakpoint on the call:
33181 Ada.Text_Io'Elab_Body;
33185 and trace the elaboration routine for this package to find out where
33186 the problem might be (more usually of course you would be debugging
33187 elaboration code in your own application).
33189 @c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
33191 @node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
33192 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order-handling-in-gnat}@anchor{11}@anchor{gnat_ugn/elaboration_order_handling_in_gnat doc}@anchor{2bb}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id1}@anchor{2bc}
33193 @chapter Elaboration Order Handling in GNAT
33196 @geindex Order of elaboration
33198 @geindex Elaboration control
33200 This appendix describes the handling of elaboration code in Ada and
33201 in GNAT, and discusses how the order of elaboration of program units can
33202 be controlled in GNAT, either automatically or with explicit programming
33206 * Elaboration Code::
33207 * Checking the Elaboration Order::
33208 * Controlling the Elaboration Order::
33209 * Controlling Elaboration in GNAT - Internal Calls::
33210 * Controlling Elaboration in GNAT - External Calls::
33211 * Default Behavior in GNAT - Ensuring Safety::
33212 * Treatment of Pragma Elaborate::
33213 * Elaboration Issues for Library Tasks::
33214 * Mixing Elaboration Models::
33215 * What to Do If the Default Elaboration Behavior Fails::
33216 * Elaboration for Indirect Calls::
33217 * Summary of Procedures for Elaboration Control::
33218 * Other Elaboration Order Considerations::
33219 * Determining the Chosen Elaboration Order::
33223 @node Elaboration Code,Checking the Elaboration Order,,Elaboration Order Handling in GNAT
33224 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{2bd}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{2be}
33225 @section Elaboration Code
33228 Ada provides rather general mechanisms for executing code at elaboration
33229 time, that is to say before the main program starts executing. Such code arises
33236 @emph{Initializers for variables}
33238 Variables declared at the library level, in package specs or bodies, can
33239 require initialization that is performed at elaboration time, as in:
33242 Sqrt_Half : Float := Sqrt (0.5);
33246 @emph{Package initialization code}
33248 Code in a @cite{BEGIN-END} section at the outer level of a package body is
33249 executed as part of the package body elaboration code.
33252 @emph{Library level task allocators}
33254 Tasks that are declared using task allocators at the library level
33255 start executing immediately and hence can execute at elaboration time.
33258 Subprogram calls are possible in any of these contexts, which means that
33259 any arbitrary part of the program may be executed as part of the elaboration
33260 code. It is even possible to write a program which does all its work at
33261 elaboration time, with a null main program, although stylistically this
33262 would usually be considered an inappropriate way to structure
33265 An important concern arises in the context of elaboration code:
33266 we have to be sure that it is executed in an appropriate order. What we
33267 have is a series of elaboration code sections, potentially one section
33268 for each unit in the program. It is important that these execute
33269 in the correct order. Correctness here means that, taking the above
33270 example of the declaration of @cite{Sqrt_Half},
33271 if some other piece of
33272 elaboration code references @cite{Sqrt_Half},
33273 then it must run after the
33274 section of elaboration code that contains the declaration of
33277 There would never be any order of elaboration problem if we made a rule
33278 that whenever you @emph{with} a unit, you must elaborate both the spec and body
33279 of that unit before elaborating the unit doing the @emph{with}ing:
33283 package Unit_2 is ...
33286 would require that both the body and spec of @cite{Unit_1} be elaborated
33287 before the spec of @cite{Unit_2}. However, a rule like that would be far too
33288 restrictive. In particular, it would make it impossible to have routines
33289 in separate packages that were mutually recursive.
33291 You might think that a clever enough compiler could look at the actual
33292 elaboration code and determine an appropriate correct order of elaboration,
33293 but in the general case, this is not possible. Consider the following
33296 In the body of @cite{Unit_1}, we have a procedure @cite{Func_1}
33298 the variable @cite{Sqrt_1}, which is declared in the elaboration code
33299 of the body of @cite{Unit_1}:
33302 Sqrt_1 : Float := Sqrt (0.1);
33305 The elaboration code of the body of @cite{Unit_1} also contains:
33308 if expression_1 = 1 then
33309 Q := Unit_2.Func_2;
33313 @cite{Unit_2} is exactly parallel,
33314 it has a procedure @cite{Func_2} that references
33315 the variable @cite{Sqrt_2}, which is declared in the elaboration code of
33316 the body @cite{Unit_2}:
33319 Sqrt_2 : Float := Sqrt (0.1);
33322 The elaboration code of the body of @cite{Unit_2} also contains:
33325 if expression_2 = 2 then
33326 Q := Unit_1.Func_1;
33330 Now the question is, which of the following orders of elaboration is
33349 If you carefully analyze the flow here, you will see that you cannot tell
33350 at compile time the answer to this question.
33351 If @cite{expression_1} is not equal to 1,
33352 and @cite{expression_2} is not equal to 2,
33353 then either order is acceptable, because neither of the function calls is
33354 executed. If both tests evaluate to true, then neither order is acceptable
33355 and in fact there is no correct order.
33357 If one of the two expressions is true, and the other is false, then one
33358 of the above orders is correct, and the other is incorrect. For example,
33359 if @cite{expression_1} /= 1 and @cite{expression_2} = 2,
33360 then the call to @cite{Func_1}
33361 will occur, but not the call to @cite{Func_2.}
33362 This means that it is essential
33363 to elaborate the body of @cite{Unit_1} before
33364 the body of @cite{Unit_2}, so the first
33365 order of elaboration is correct and the second is wrong.
33367 By making @cite{expression_1} and @cite{expression_2}
33368 depend on input data, or perhaps
33369 the time of day, we can make it impossible for the compiler or binder
33370 to figure out which of these expressions will be true, and hence it
33371 is impossible to guarantee a safe order of elaboration at run time.
33373 @node Checking the Elaboration Order,Controlling the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
33374 @anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{2bf}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{2c0}
33375 @section Checking the Elaboration Order
33378 In some languages that involve the same kind of elaboration problems,
33379 e.g., Java and C++, the programmer needs to take these
33380 ordering problems into account, and it is common to
33381 write a program in which an incorrect elaboration order gives
33382 surprising results, because it references variables before they
33384 Ada is designed to be a safe language, and a programmer-beware approach is
33385 clearly not sufficient. Consequently, the language provides three lines
33392 @emph{Standard rules}
33394 Some standard rules restrict the possible choice of elaboration
33395 order. In particular, if you @emph{with} a unit, then its spec is always
33396 elaborated before the unit doing the @emph{with}. Similarly, a parent
33397 spec is always elaborated before the child spec, and finally
33398 a spec is always elaborated before its corresponding body.
33401 @geindex Elaboration checks
33404 @geindex elaboration
33410 @emph{Dynamic elaboration checks}
33412 Dynamic checks are made at run time, so that if some entity is accessed
33413 before it is elaborated (typically by means of a subprogram call)
33414 then the exception (@cite{Program_Error}) is raised.
33417 @emph{Elaboration control}
33419 Facilities are provided for the programmer to specify the desired order
33423 Let's look at these facilities in more detail. First, the rules for
33424 dynamic checking. One possible rule would be simply to say that the
33425 exception is raised if you access a variable which has not yet been
33426 elaborated. The trouble with this approach is that it could require
33427 expensive checks on every variable reference. Instead Ada has two
33428 rules which are a little more restrictive, but easier to check, and
33435 @emph{Restrictions on calls}
33437 A subprogram can only be called at elaboration time if its body
33438 has been elaborated. The rules for elaboration given above guarantee
33439 that the spec of the subprogram has been elaborated before the
33440 call, but not the body. If this rule is violated, then the
33441 exception @cite{Program_Error} is raised.
33444 @emph{Restrictions on instantiations}
33446 A generic unit can only be instantiated if the body of the generic
33447 unit has been elaborated. Again, the rules for elaboration given above
33448 guarantee that the spec of the generic unit has been elaborated
33449 before the instantiation, but not the body. If this rule is
33450 violated, then the exception @cite{Program_Error} is raised.
33453 The idea is that if the body has been elaborated, then any variables
33454 it references must have been elaborated; by checking for the body being
33455 elaborated we guarantee that none of its references causes any
33456 trouble. As we noted above, this is a little too restrictive, because a
33457 subprogram that has no non-local references in its body may in fact be safe
33458 to call. However, it really would be unsafe to rely on this, because
33459 it would mean that the caller was aware of details of the implementation
33460 in the body. This goes against the basic tenets of Ada.
33462 A plausible implementation can be described as follows.
33463 A Boolean variable is associated with each subprogram
33464 and each generic unit. This variable is initialized to False, and is set to
33465 True at the point body is elaborated. Every call or instantiation checks the
33466 variable, and raises @cite{Program_Error} if the variable is False.
33468 Note that one might think that it would be good enough to have one Boolean
33469 variable for each package, but that would not deal with cases of trying
33470 to call a body in the same package as the call
33471 that has not been elaborated yet.
33472 Of course a compiler may be able to do enough analysis to optimize away
33473 some of the Boolean variables as unnecessary, and @cite{GNAT} indeed
33474 does such optimizations, but still the easiest conceptual model is to
33475 think of there being one variable per subprogram.
33477 @node Controlling the Elaboration Order,Controlling Elaboration in GNAT - Internal Calls,Checking the Elaboration Order,Elaboration Order Handling in GNAT
33478 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{2c1}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order}@anchor{2c2}
33479 @section Controlling the Elaboration Order
33482 In the previous section we discussed the rules in Ada which ensure
33483 that @cite{Program_Error} is raised if an incorrect elaboration order is
33484 chosen. This prevents erroneous executions, but we need mechanisms to
33485 specify a correct execution and avoid the exception altogether.
33486 To achieve this, Ada provides a number of features for controlling
33487 the order of elaboration. We discuss these features in this section.
33489 First, there are several ways of indicating to the compiler that a given
33490 unit has no elaboration problems:
33496 @emph{packages that do not require a body}
33498 A library package that does not require a body does not permit
33499 a body (this rule was introduced in Ada 95).
33500 Thus if we have a such a package, as in:
33503 package Definitions is
33505 type m is new integer;
33507 type a is array (1 .. 10) of m;
33508 type b is array (1 .. 20) of m;
33513 A package that @emph{with}s @cite{Definitions} may safely instantiate
33514 @cite{Definitions.Subp} because the compiler can determine that there
33515 definitely is no package body to worry about in this case
33518 @geindex pragma Pure
33526 This pragma places sufficient restrictions on a unit to guarantee that
33527 no call to any subprogram in the unit can result in an
33528 elaboration problem. This means that the compiler does not need
33529 to worry about the point of elaboration of such units, and in
33530 particular, does not need to check any calls to any subprograms
33534 @geindex pragma Preelaborate
33540 @emph{pragma Preelaborate}
33542 This pragma places slightly less stringent restrictions on a unit than
33544 but these restrictions are still sufficient to ensure that there
33545 are no elaboration problems with any calls to the unit.
33548 @geindex pragma Elaborate_Body
33554 @emph{pragma Elaborate_Body}
33556 This pragma requires that the body of a unit be elaborated immediately
33557 after its spec. Suppose a unit @cite{A} has such a pragma,
33558 and unit @cite{B} does
33559 a @emph{with} of unit @cite{A}. Recall that the standard rules require
33560 the spec of unit @cite{A}
33561 to be elaborated before the @emph{with}ing unit; given the pragma in
33562 @cite{A}, we also know that the body of @cite{A}
33563 will be elaborated before @cite{B}, so
33564 that calls to @cite{A} are safe and do not need a check.
33566 Note that, unlike pragma @cite{Pure} and pragma @cite{Preelaborate},
33567 the use of @cite{Elaborate_Body} does not guarantee that the program is
33568 free of elaboration problems, because it may not be possible
33569 to satisfy the requested elaboration order.
33570 Let's go back to the example with @cite{Unit_1} and @cite{Unit_2}.
33571 If a programmer marks @cite{Unit_1} as @cite{Elaborate_Body},
33572 and not @cite{Unit_2@comma{}} then the order of
33573 elaboration will be:
33582 Now that means that the call to @cite{Func_1} in @cite{Unit_2}
33583 need not be checked,
33584 it must be safe. But the call to @cite{Func_2} in
33585 @cite{Unit_1} may still fail if
33586 @cite{Expression_1} is equal to 1,
33587 and the programmer must still take
33588 responsibility for this not being the case.
33590 If all units carry a pragma @cite{Elaborate_Body}, then all problems are
33591 eliminated, except for calls entirely within a body, which are
33592 in any case fully under programmer control. However, using the pragma
33593 everywhere is not always possible.
33594 In particular, for our @cite{Unit_1}/@cite{Unit_2} example, if
33595 we marked both of them as having pragma @cite{Elaborate_Body}, then
33596 clearly there would be no possible elaboration order.
33599 The above pragmas allow a server to guarantee safe use by clients, and
33600 clearly this is the preferable approach. Consequently a good rule
33601 is to mark units as @cite{Pure} or @cite{Preelaborate} if possible,
33602 and if this is not possible,
33603 mark them as @cite{Elaborate_Body} if possible.
33604 As we have seen, there are situations where neither of these
33605 three pragmas can be used.
33606 So we also provide methods for clients to control the
33607 order of elaboration of the servers on which they depend:
33609 @geindex pragma Elaborate
33615 @emph{pragma Elaborate (unit)}
33617 This pragma is placed in the context clause, after a @emph{with} clause,
33618 and it requires that the body of the named unit be elaborated before
33619 the unit in which the pragma occurs. The idea is to use this pragma
33620 if the current unit calls at elaboration time, directly or indirectly,
33621 some subprogram in the named unit.
33624 @geindex pragma Elaborate_All
33630 @emph{pragma Elaborate_All (unit)}
33632 This is a stronger version of the Elaborate pragma. Consider the
33636 Unit A |withs| unit B and calls B.Func in elab code
33637 Unit B |withs| unit C, and B.Func calls C.Func
33640 Now if we put a pragma @cite{Elaborate (B)}
33641 in unit @cite{A}, this ensures that the
33642 body of @cite{B} is elaborated before the call, but not the
33643 body of @cite{C}, so
33644 the call to @cite{C.Func} could still cause @cite{Program_Error} to
33647 The effect of a pragma @cite{Elaborate_All} is stronger, it requires
33648 not only that the body of the named unit be elaborated before the
33649 unit doing the @emph{with}, but also the bodies of all units that the
33650 named unit uses, following @emph{with} links transitively. For example,
33651 if we put a pragma @cite{Elaborate_All (B)} in unit @cite{A},
33652 then it requires not only that the body of @cite{B} be elaborated before @cite{A},
33653 but also the body of @cite{C}, because @cite{B} @emph{with}s @cite{C}.
33656 We are now in a position to give a usage rule in Ada for avoiding
33657 elaboration problems, at least if dynamic dispatching and access to
33658 subprogram values are not used. We will handle these cases separately
33661 The rule is simple:
33663 @emph{If a unit has elaboration code that can directly or
33664 indirectly make a call to a subprogram in a |withed| unit, or instantiate
33665 a generic package in a |withed| unit,
33666 then if the |withed| unit does not have
33667 pragma `Pure` or `Preelaborate`, then the client should have
33668 a pragma `Elaborate_All`for the |withed| unit.*}
33670 By following this rule a client is
33671 assured that calls can be made without risk of an exception.
33673 For generic subprogram instantiations, the rule can be relaxed to
33674 require only a pragma @cite{Elaborate} since elaborating the body
33675 of a subprogram cannot cause any transitive elaboration (we are
33676 not calling the subprogram in this case, just elaborating its
33679 If this rule is not followed, then a program may be in one of four
33686 @emph{No order exists}
33688 No order of elaboration exists which follows the rules, taking into
33689 account any @cite{Elaborate}, @cite{Elaborate_All},
33690 or @cite{Elaborate_Body} pragmas. In
33691 this case, an Ada compiler must diagnose the situation at bind
33692 time, and refuse to build an executable program.
33695 @emph{One or more orders exist, all incorrect}
33697 One or more acceptable elaboration orders exist, and all of them
33698 generate an elaboration order problem. In this case, the binder
33699 can build an executable program, but @cite{Program_Error} will be raised
33700 when the program is run.
33703 @emph{Several orders exist, some right, some incorrect}
33705 One or more acceptable elaboration orders exists, and some of them
33706 work, and some do not. The programmer has not controlled
33707 the order of elaboration, so the binder may or may not pick one of
33708 the correct orders, and the program may or may not raise an
33709 exception when it is run. This is the worst case, because it means
33710 that the program may fail when moved to another compiler, or even
33711 another version of the same compiler.
33714 @emph{One or more orders exists, all correct}
33716 One ore more acceptable elaboration orders exist, and all of them
33717 work. In this case the program runs successfully. This state of
33718 affairs can be guaranteed by following the rule we gave above, but
33719 may be true even if the rule is not followed.
33722 Note that one additional advantage of following our rules on the use
33723 of @cite{Elaborate} and @cite{Elaborate_All}
33724 is that the program continues to stay in the ideal (all orders OK) state
33725 even if maintenance
33726 changes some bodies of some units. Conversely, if a program that does
33727 not follow this rule happens to be safe at some point, this state of affairs
33728 may deteriorate silently as a result of maintenance changes.
33730 You may have noticed that the above discussion did not mention
33731 the use of @cite{Elaborate_Body}. This was a deliberate omission. If you
33732 @emph{with} an @cite{Elaborate_Body} unit, it still may be the case that
33733 code in the body makes calls to some other unit, so it is still necessary
33734 to use @cite{Elaborate_All} on such units.
33736 @node Controlling Elaboration in GNAT - Internal Calls,Controlling Elaboration in GNAT - External Calls,Controlling the Elaboration Order,Elaboration Order Handling in GNAT
33737 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{2c3}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-internal-calls}@anchor{2c4}
33738 @section Controlling Elaboration in GNAT - Internal Calls
33741 In the case of internal calls, i.e., calls within a single package, the
33742 programmer has full control over the order of elaboration, and it is up
33743 to the programmer to elaborate declarations in an appropriate order. For
33747 function One return Float;
33751 function One return Float is
33757 will obviously raise @cite{Program_Error} at run time, because function
33758 One will be called before its body is elaborated. In this case GNAT will
33759 generate a warning that the call will raise @cite{Program_Error}:
33763 2. function One return Float;
33765 4. Q : Float := One;
33767 >>> warning: cannot call "One" before body is elaborated
33768 >>> warning: Program_Error will be raised at run time
33771 6. function One return Float is
33781 Note that in this particular case, it is likely that the call is safe, because
33782 the function @cite{One} does not access any global variables.
33783 Nevertheless in Ada, we do not want the validity of the check to depend on
33784 the contents of the body (think about the separate compilation case), so this
33785 is still wrong, as we discussed in the previous sections.
33787 The error is easily corrected by rearranging the declarations so that the
33788 body of @cite{One} appears before the declaration containing the call
33789 (note that in Ada 95 as well as later versions of the Ada standard,
33790 declarations can appear in any order, so there is no restriction that
33791 would prevent this reordering, and if we write:
33794 function One return Float;
33796 function One return Float is
33804 then all is well, no warning is generated, and no
33805 @cite{Program_Error} exception
33807 Things are more complicated when a chain of subprograms is executed:
33810 function A return Integer;
33811 function B return Integer;
33812 function C return Integer;
33814 function B return Integer is begin return A; end;
33815 function C return Integer is begin return B; end;
33819 function A return Integer is begin return 1; end;
33822 Now the call to @cite{C}
33823 at elaboration time in the declaration of @cite{X} is correct, because
33824 the body of @cite{C} is already elaborated,
33825 and the call to @cite{B} within the body of
33826 @cite{C} is correct, but the call
33827 to @cite{A} within the body of @cite{B} is incorrect, because the body
33828 of @cite{A} has not been elaborated, so @cite{Program_Error}
33829 will be raised on the call to @cite{A}.
33830 In this case GNAT will generate a
33831 warning that @cite{Program_Error} may be
33832 raised at the point of the call. Let's look at the warning:
33836 2. function A return Integer;
33837 3. function B return Integer;
33838 4. function C return Integer;
33840 6. function B return Integer is begin return A; end;
33842 >>> warning: call to "A" before body is elaborated may
33843 raise Program_Error
33844 >>> warning: "B" called at line 7
33845 >>> warning: "C" called at line 9
33847 7. function C return Integer is begin return B; end;
33849 9. X : Integer := C;
33851 11. function A return Integer is begin return 1; end;
33858 Note that the message here says 'may raise', instead of the direct case,
33859 where the message says 'will be raised'. That's because whether
33861 actually called depends in general on run-time flow of control.
33862 For example, if the body of @cite{B} said
33865 function B return Integer is
33867 if some-condition-depending-on-input-data then
33875 then we could not know until run time whether the incorrect call to A would
33876 actually occur, so @cite{Program_Error} might
33877 or might not be raised. It is possible for a compiler to
33878 do a better job of analyzing bodies, to
33879 determine whether or not @cite{Program_Error}
33880 might be raised, but it certainly
33881 couldn't do a perfect job (that would require solving the halting problem
33882 and is provably impossible), and because this is a warning anyway, it does
33883 not seem worth the effort to do the analysis. Cases in which it
33884 would be relevant are rare.
33886 In practice, warnings of either of the forms given
33887 above will usually correspond to
33888 real errors, and should be examined carefully and eliminated.
33889 In the rare case where a warning is bogus, it can be suppressed by any of
33890 the following methods:
33896 Compile with the @emph{-gnatws} switch set
33899 Suppress @cite{Elaboration_Check} for the called subprogram
33902 Use pragma @cite{Warnings_Off} to turn warnings off for the call
33905 For the internal elaboration check case,
33906 GNAT by default generates the
33907 necessary run-time checks to ensure
33908 that @cite{Program_Error} is raised if any
33909 call fails an elaboration check. Of course this can only happen if a
33910 warning has been issued as described above. The use of pragma
33911 @cite{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
33912 some of these checks, meaning that it may be possible (but is not
33913 guaranteed) for a program to be able to call a subprogram whose body
33914 is not yet elaborated, without raising a @cite{Program_Error} exception.
33916 @node Controlling Elaboration in GNAT - External Calls,Default Behavior in GNAT - Ensuring Safety,Controlling Elaboration in GNAT - Internal Calls,Elaboration Order Handling in GNAT
33917 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{2c5}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-elaboration-in-gnat-external-calls}@anchor{2c6}
33918 @section Controlling Elaboration in GNAT - External Calls
33921 The previous section discussed the case in which the execution of a
33922 particular thread of elaboration code occurred entirely within a
33923 single unit. This is the easy case to handle, because a programmer
33924 has direct and total control over the order of elaboration, and
33925 furthermore, checks need only be generated in cases which are rare
33926 and which the compiler can easily detect.
33927 The situation is more complex when separate compilation is taken into account.
33928 Consider the following:
33932 function Sqrt (Arg : Float) return Float;
33935 package body Math is
33936 function Sqrt (Arg : Float) return Float is
33944 X : Float := Math.Sqrt (0.5);
33954 where @cite{Main} is the main program. When this program is executed, the
33955 elaboration code must first be executed, and one of the jobs of the
33956 binder is to determine the order in which the units of a program are
33957 to be elaborated. In this case we have four units: the spec and body
33959 the spec of @cite{Stuff} and the body of @cite{Main}).
33960 In what order should the four separate sections of elaboration code
33963 There are some restrictions in the order of elaboration that the binder
33964 can choose. In particular, if unit U has a @emph{with}
33965 for a package @cite{X}, then you
33966 are assured that the spec of @cite{X}
33967 is elaborated before U , but you are
33968 not assured that the body of @cite{X}
33969 is elaborated before U.
33970 This means that in the above case, the binder is allowed to choose the
33980 but that's not good, because now the call to @cite{Math.Sqrt}
33981 that happens during
33982 the elaboration of the @cite{Stuff}
33983 spec happens before the body of @cite{Math.Sqrt} is
33984 elaborated, and hence causes @cite{Program_Error} exception to be raised.
33985 At first glance, one might say that the binder is misbehaving, because
33986 obviously you want to elaborate the body of something you @emph{with} first, but
33987 that is not a general rule that can be followed in all cases. Consider
33995 package body Y is ...
33998 package body X is ...
34001 This is a common arrangement, and, apart from the order of elaboration
34002 problems that might arise in connection with elaboration code, this works fine.
34003 A rule that says that you must first elaborate the body of anything you
34004 @emph{with} cannot work in this case:
34005 the body of @cite{X} @emph{with}s @cite{Y},
34006 which means you would have to
34007 elaborate the body of @cite{Y} first, but that @emph{with}s @cite{X},
34009 you have to elaborate the body of @cite{X} first, but ... and we have a
34010 loop that cannot be broken.
34012 It is true that the binder can in many cases guess an order of elaboration
34013 that is unlikely to cause a @cite{Program_Error}
34014 exception to be raised, and it tries to do so (in the
34015 above example of @cite{Math/Stuff/Spec}, the GNAT binder will
34017 elaborate the body of @cite{Math} right after its spec, so all will be well).
34019 However, a program that blindly relies on the binder to be helpful can
34020 get into trouble, as we discussed in the previous sections, so GNAT
34021 provides a number of facilities for assisting the programmer in
34022 developing programs that are robust with respect to elaboration order.
34024 @node Default Behavior in GNAT - Ensuring Safety,Treatment of Pragma Elaborate,Controlling Elaboration in GNAT - External Calls,Elaboration Order Handling in GNAT
34025 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{2c7}@anchor{gnat_ugn/elaboration_order_handling_in_gnat default-behavior-in-gnat-ensuring-safety}@anchor{2c8}
34026 @section Default Behavior in GNAT - Ensuring Safety
34029 The default behavior in GNAT ensures elaboration safety. In its
34030 default mode GNAT implements the
34031 rule we previously described as the right approach. Let's restate it:
34033 @emph{If a unit has elaboration code that can directly or indirectly make a
34034 call to a subprogram in a |withed| unit, or instantiate a generic
34035 package in a |withed| unit, then if the |withed| unit
34036 does not have pragma `Pure` or `Preelaborate`, then the client should have an
34037 `Elaborate_All` pragma for the |withed| unit.}
34039 @emph{In the case of instantiating a generic subprogram, it is always
34040 sufficient to have only an `Elaborate` pragma for the
34043 By following this rule a client is assured that calls and instantiations
34044 can be made without risk of an exception.
34046 In this mode GNAT traces all calls that are potentially made from
34047 elaboration code, and puts in any missing implicit @cite{Elaborate}
34048 and @cite{Elaborate_All} pragmas.
34049 The advantage of this approach is that no elaboration problems
34050 are possible if the binder can find an elaboration order that is
34051 consistent with these implicit @cite{Elaborate} and
34052 @cite{Elaborate_All} pragmas. The
34053 disadvantage of this approach is that no such order may exist.
34055 If the binder does not generate any diagnostics, then it means that it has
34056 found an elaboration order that is guaranteed to be safe. However, the binder
34057 may still be relying on implicitly generated @cite{Elaborate} and
34058 @cite{Elaborate_All} pragmas so portability to other compilers than GNAT is not
34061 If it is important to guarantee portability, then the compilations should
34062 use the @emph{-gnatel}
34063 (info messages for elaboration pragmas) switch. This will cause info messages
34064 to be generated indicating the missing @cite{Elaborate} and
34065 @cite{Elaborate_All} pragmas.
34066 Consider the following source program:
34071 m : integer := k.r;
34075 where it is clear that there
34076 should be a pragma @cite{Elaborate_All}
34077 for unit @cite{k}. An implicit pragma will be generated, and it is
34078 likely that the binder will be able to honor it. However, if you want
34079 to port this program to some other Ada compiler than GNAT.
34080 it is safer to include the pragma explicitly in the source. If this
34081 unit is compiled with the @emph{-gnatel}
34082 switch, then the compiler outputs an information message:
34087 3. m : integer := k.r;
34089 >>> info: call to "r" may raise Program_Error
34090 >>> info: missing pragma Elaborate_All for "k"
34095 and these messages can be used as a guide for supplying manually
34096 the missing pragmas. It is usually a bad idea to use this
34097 option during development. That's because it will tell you when
34098 you need to put in a pragma, but cannot tell you when it is time
34099 to take it out. So the use of pragma @cite{Elaborate_All} may lead to
34100 unnecessary dependencies and even false circularities.
34102 This default mode is more restrictive than the Ada Reference
34103 Manual, and it is possible to construct programs which will compile
34104 using the dynamic model described there, but will run into a
34105 circularity using the safer static model we have described.
34107 Of course any Ada compiler must be able to operate in a mode
34108 consistent with the requirements of the Ada Reference Manual,
34109 and in particular must have the capability of implementing the
34110 standard dynamic model of elaboration with run-time checks.
34112 In GNAT, this standard mode can be achieved either by the use of
34113 the @emph{-gnatE} switch on the compiler (@emph{gcc} or
34114 @emph{gnatmake}) command, or by the use of the configuration pragma:
34117 pragma Elaboration_Checks (DYNAMIC);
34120 Either approach will cause the unit affected to be compiled using the
34121 standard dynamic run-time elaboration checks described in the Ada
34122 Reference Manual. The static model is generally preferable, since it
34123 is clearly safer to rely on compile and link time checks rather than
34124 run-time checks. However, in the case of legacy code, it may be
34125 difficult to meet the requirements of the static model. This
34126 issue is further discussed in
34127 @ref{2c9,,What to Do If the Default Elaboration Behavior Fails}.
34129 Note that the static model provides a strict subset of the allowed
34130 behavior and programs of the Ada Reference Manual, so if you do
34131 adhere to the static model and no circularities exist,
34132 then you are assured that your program will
34133 work using the dynamic model, providing that you remove any
34134 pragma Elaborate statements from the source.
34136 @node Treatment of Pragma Elaborate,Elaboration Issues for Library Tasks,Default Behavior in GNAT - Ensuring Safety,Elaboration Order Handling in GNAT
34137 @anchor{gnat_ugn/elaboration_order_handling_in_gnat treatment-of-pragma-elaborate}@anchor{2ca}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{2cb}
34138 @section Treatment of Pragma Elaborate
34141 @geindex Pragma Elaborate
34143 The use of @cite{pragma Elaborate}
34144 should generally be avoided in Ada 95 and Ada 2005 programs,
34145 since there is no guarantee that transitive calls
34146 will be properly handled. Indeed at one point, this pragma was placed
34147 in Annex J (Obsolescent Features), on the grounds that it is never useful.
34149 Now that's a bit restrictive. In practice, the case in which
34150 @cite{pragma Elaborate} is useful is when the caller knows that there
34151 are no transitive calls, or that the called unit contains all necessary
34152 transitive @cite{pragma Elaborate} statements, and legacy code often
34153 contains such uses.
34155 Strictly speaking the static mode in GNAT should ignore such pragmas,
34156 since there is no assurance at compile time that the necessary safety
34157 conditions are met. In practice, this would cause GNAT to be incompatible
34158 with correctly written Ada 83 code that had all necessary
34159 @cite{pragma Elaborate} statements in place. Consequently, we made the
34160 decision that GNAT in its default mode will believe that if it encounters
34161 a @cite{pragma Elaborate} then the programmer knows what they are doing,
34162 and it will trust that no elaboration errors can occur.
34164 The result of this decision is two-fold. First to be safe using the
34165 static mode, you should remove all @cite{pragma Elaborate} statements.
34166 Second, when fixing circularities in existing code, you can selectively
34167 use @cite{pragma Elaborate} statements to convince the static mode of
34168 GNAT that it need not generate an implicit @cite{pragma Elaborate_All}
34171 When using the static mode with @emph{-gnatwl}, any use of
34172 @cite{pragma Elaborate} will generate a warning about possible
34175 @node Elaboration Issues for Library Tasks,Mixing Elaboration Models,Treatment of Pragma Elaborate,Elaboration Order Handling in GNAT
34176 @anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-issues-for-library-tasks}@anchor{2cc}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{2cd}
34177 @section Elaboration Issues for Library Tasks
34180 @geindex Library tasks
34181 @geindex elaboration issues
34183 @geindex Elaboration of library tasks
34185 In this section we examine special elaboration issues that arise for
34186 programs that declare library level tasks.
34188 Generally the model of execution of an Ada program is that all units are
34189 elaborated, and then execution of the program starts. However, the
34190 declaration of library tasks definitely does not fit this model. The
34191 reason for this is that library tasks start as soon as they are declared
34192 (more precisely, as soon as the statement part of the enclosing package
34193 body is reached), that is to say before elaboration
34194 of the program is complete. This means that if such a task calls a
34195 subprogram, or an entry in another task, the callee may or may not be
34196 elaborated yet, and in the standard
34197 Reference Manual model of dynamic elaboration checks, you can even
34198 get timing dependent Program_Error exceptions, since there can be
34199 a race between the elaboration code and the task code.
34201 The static model of elaboration in GNAT seeks to avoid all such
34202 dynamic behavior, by being conservative, and the conservative
34203 approach in this particular case is to assume that all the code
34204 in a task body is potentially executed at elaboration time if
34205 a task is declared at the library level.
34207 This can definitely result in unexpected circularities. Consider
34208 the following example
34216 type My_Int is new Integer;
34218 function Ident (M : My_Int) return My_Int;
34222 package body Decls is
34223 task body Lib_Task is
34229 function Ident (M : My_Int) return My_Int is
34237 procedure Put_Val (Arg : Decls.My_Int);
34241 package body Utils is
34242 procedure Put_Val (Arg : Decls.My_Int) is
34244 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
34251 Decls.Lib_Task.Start;
34255 If the above example is compiled in the default static elaboration
34256 mode, then a circularity occurs. The circularity comes from the call
34257 @cite{Utils.Put_Val} in the task body of @cite{Decls.Lib_Task}. Since
34258 this call occurs in elaboration code, we need an implicit pragma
34259 @cite{Elaborate_All} for @cite{Utils}. This means that not only must
34260 the spec and body of @cite{Utils} be elaborated before the body
34261 of @cite{Decls}, but also the spec and body of any unit that is
34262 @emph{with}ed by the body of @cite{Utils} must also be elaborated before
34263 the body of @cite{Decls}. This is the transitive implication of
34264 pragma @cite{Elaborate_All} and it makes sense, because in general
34265 the body of @cite{Put_Val} might have a call to something in a
34266 @emph{with}ed unit.
34268 In this case, the body of Utils (actually its spec) @emph{with}s
34269 @cite{Decls}. Unfortunately this means that the body of @cite{Decls}
34270 must be elaborated before itself, in case there is a call from the
34271 body of @cite{Utils}.
34273 Here is the exact chain of events we are worrying about:
34279 In the body of @cite{Decls} a call is made from within the body of a library
34280 task to a subprogram in the package @cite{Utils}. Since this call may
34281 occur at elaboration time (given that the task is activated at elaboration
34282 time), we have to assume the worst, i.e., that the
34283 call does happen at elaboration time.
34286 This means that the body and spec of @cite{Util} must be elaborated before
34287 the body of @cite{Decls} so that this call does not cause an access before
34291 Within the body of @cite{Util}, specifically within the body of
34292 @cite{Util.Put_Val} there may be calls to any unit @emph{with}ed
34296 One such @emph{with}ed package is package @cite{Decls}, so there
34297 might be a call to a subprogram in @cite{Decls} in @cite{Put_Val}.
34298 In fact there is such a call in this example, but we would have to
34299 assume that there was such a call even if it were not there, since
34300 we are not supposed to write the body of @cite{Decls} knowing what
34301 is in the body of @cite{Utils}; certainly in the case of the
34302 static elaboration model, the compiler does not know what is in
34303 other bodies and must assume the worst.
34306 This means that the spec and body of @cite{Decls} must also be
34307 elaborated before we elaborate the unit containing the call, but
34308 that unit is @cite{Decls}! This means that the body of @cite{Decls}
34309 must be elaborated before itself, and that's a circularity.
34312 Indeed, if you add an explicit pragma @cite{Elaborate_All} for @cite{Utils} in
34313 the body of @cite{Decls} you will get a true Ada Reference Manual
34314 circularity that makes the program illegal.
34316 In practice, we have found that problems with the static model of
34317 elaboration in existing code often arise from library tasks, so
34318 we must address this particular situation.
34320 Note that if we compile and run the program above, using the dynamic model of
34321 elaboration (that is to say use the @emph{-gnatE} switch),
34322 then it compiles, binds,
34323 links, and runs, printing the expected result of 2. Therefore in some sense
34324 the circularity here is only apparent, and we need to capture
34325 the properties of this program that distinguish it from other library-level
34326 tasks that have real elaboration problems.
34328 We have four possible answers to this question:
34334 Use the dynamic model of elaboration.
34336 If we use the @emph{-gnatE} switch, then as noted above, the program works.
34337 Why is this? If we examine the task body, it is apparent that the task cannot
34339 @cite{accept} statement until after elaboration has been completed, because
34340 the corresponding entry call comes from the main program, not earlier.
34341 This is why the dynamic model works here. But that's really giving
34342 up on a precise analysis, and we prefer to take this approach only if we cannot
34344 problem in any other manner. So let us examine two ways to reorganize
34345 the program to avoid the potential elaboration problem.
34348 Split library tasks into separate packages.
34350 Write separate packages, so that library tasks are isolated from
34351 other declarations as much as possible. Let us look at a variation on
34362 package body Decls1 is
34363 task body Lib_Task is
34371 type My_Int is new Integer;
34372 function Ident (M : My_Int) return My_Int;
34376 package body Decls2 is
34377 function Ident (M : My_Int) return My_Int is
34385 procedure Put_Val (Arg : Decls2.My_Int);
34389 package body Utils is
34390 procedure Put_Val (Arg : Decls2.My_Int) is
34392 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
34399 Decls1.Lib_Task.Start;
34403 All we have done is to split @cite{Decls} into two packages, one
34404 containing the library task, and one containing everything else. Now
34405 there is no cycle, and the program compiles, binds, links and executes
34406 using the default static model of elaboration.
34409 Declare separate task types.
34411 A significant part of the problem arises because of the use of the
34412 single task declaration form. This means that the elaboration of
34413 the task type, and the elaboration of the task itself (i.e., the
34414 creation of the task) happen at the same time. A good rule
34415 of style in Ada is to always create explicit task types. By
34416 following the additional step of placing task objects in separate
34417 packages from the task type declaration, many elaboration problems
34418 are avoided. Here is another modified example of the example program:
34422 task type Lib_Task_Type is
34426 type My_Int is new Integer;
34428 function Ident (M : My_Int) return My_Int;
34432 package body Decls is
34433 task body Lib_Task_Type is
34439 function Ident (M : My_Int) return My_Int is
34447 procedure Put_Val (Arg : Decls.My_Int);
34451 package body Utils is
34452 procedure Put_Val (Arg : Decls.My_Int) is
34454 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
34460 Lib_Task : Decls.Lib_Task_Type;
34466 Declst.Lib_Task.Start;
34470 What we have done here is to replace the @cite{task} declaration in
34471 package @cite{Decls} with a @cite{task type} declaration. Then we
34472 introduce a separate package @cite{Declst} to contain the actual
34473 task object. This separates the elaboration issues for
34474 the @cite{task type}
34475 declaration, which causes no trouble, from the elaboration issues
34476 of the task object, which is also unproblematic, since it is now independent
34477 of the elaboration of @cite{Utils}.
34478 This separation of concerns also corresponds to
34479 a generally sound engineering principle of separating declarations
34480 from instances. This version of the program also compiles, binds, links,
34481 and executes, generating the expected output.
34484 @geindex No_Entry_Calls_In_Elaboration_Code restriction
34490 Use No_Entry_Calls_In_Elaboration_Code restriction.
34492 The previous two approaches described how a program can be restructured
34493 to avoid the special problems caused by library task bodies. in practice,
34494 however, such restructuring may be difficult to apply to existing legacy code,
34495 so we must consider solutions that do not require massive rewriting.
34497 Let us consider more carefully why our original sample program works
34498 under the dynamic model of elaboration. The reason is that the code
34499 in the task body blocks immediately on the @cite{accept}
34500 statement. Now of course there is nothing to prohibit elaboration
34501 code from making entry calls (for example from another library level task),
34502 so we cannot tell in isolation that
34503 the task will not execute the accept statement during elaboration.
34505 However, in practice it is very unusual to see elaboration code
34506 make any entry calls, and the pattern of tasks starting
34507 at elaboration time and then immediately blocking on @cite{accept} or
34508 @cite{select} statements is very common. What this means is that
34509 the compiler is being too pessimistic when it analyzes the
34510 whole package body as though it might be executed at elaboration
34513 If we know that the elaboration code contains no entry calls, (a very safe
34514 assumption most of the time, that could almost be made the default
34515 behavior), then we can compile all units of the program under control
34516 of the following configuration pragma:
34519 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
34522 This pragma can be placed in the @code{gnat.adc} file in the usual
34523 manner. If we take our original unmodified program and compile it
34524 in the presence of a @code{gnat.adc} containing the above pragma,
34525 then once again, we can compile, bind, link, and execute, obtaining
34526 the expected result. In the presence of this pragma, the compiler does
34527 not trace calls in a task body, that appear after the first @cite{accept}
34528 or @cite{select} statement, and therefore does not report a potential
34529 circularity in the original program.
34531 The compiler will check to the extent it can that the above
34532 restriction is not violated, but it is not always possible to do a
34533 complete check at compile time, so it is important to use this
34534 pragma only if the stated restriction is in fact met, that is to say
34535 no task receives an entry call before elaboration of all units is completed.
34538 @node Mixing Elaboration Models,What to Do If the Default Elaboration Behavior Fails,Elaboration Issues for Library Tasks,Elaboration Order Handling in GNAT
34539 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{2ce}@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{2cf}
34540 @section Mixing Elaboration Models
34543 So far, we have assumed that the entire program is either compiled
34544 using the dynamic model or static model, ensuring consistency. It
34545 is possible to mix the two models, but rules have to be followed
34546 if this mixing is done to ensure that elaboration checks are not
34549 The basic rule is that
34550 @strong{a unit compiled with the static model cannot
34551 be |withed| by a unit compiled with the dynamic model}.
34552 The reason for this is that in the static model, a unit assumes that
34553 its clients guarantee to use (the equivalent of) pragma
34554 @cite{Elaborate_All} so that no elaboration checks are required
34555 in inner subprograms, and this assumption is violated if the
34556 client is compiled with dynamic checks.
34558 The precise rule is as follows. A unit that is compiled with dynamic
34559 checks can only @emph{with} a unit that meets at least one of the
34560 following criteria:
34566 The @emph{with}ed unit is itself compiled with dynamic elaboration
34567 checks (that is with the @emph{-gnatE} switch.
34570 The @emph{with}ed unit is an internal GNAT implementation unit from
34571 the System, Interfaces, Ada, or GNAT hierarchies.
34574 The @emph{with}ed unit has pragma Preelaborate or pragma Pure.
34577 The @emph{with}ing unit (that is the client) has an explicit pragma
34578 @cite{Elaborate_All} for the @emph{with}ed unit.
34581 If this rule is violated, that is if a unit with dynamic elaboration
34582 checks @emph{with}s a unit that does not meet one of the above four
34583 criteria, then the binder (@cite{gnatbind}) will issue a warning
34584 similar to that in the following example:
34587 warning: "x.ads" has dynamic elaboration checks and with's
34588 warning: "y.ads" which has static elaboration checks
34591 These warnings indicate that the rule has been violated, and that as a result
34592 elaboration checks may be missed in the resulting executable file.
34593 This warning may be suppressed using the @emph{-ws} binder switch
34594 in the usual manner.
34596 One useful application of this mixing rule is in the case of a subsystem
34597 which does not itself @emph{with} units from the remainder of the
34598 application. In this case, the entire subsystem can be compiled with
34599 dynamic checks to resolve a circularity in the subsystem, while
34600 allowing the main application that uses this subsystem to be compiled
34601 using the more reliable default static model.
34603 @node What to Do If the Default Elaboration Behavior Fails,Elaboration for Indirect Calls,Mixing Elaboration Models,Elaboration Order Handling in GNAT
34604 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{2d0}@anchor{gnat_ugn/elaboration_order_handling_in_gnat what-to-do-if-the-default-elaboration-behavior-fails}@anchor{2c9}
34605 @section What to Do If the Default Elaboration Behavior Fails
34608 If the binder cannot find an acceptable order, it outputs detailed
34609 diagnostics. For example:
34612 error: elaboration circularity detected
34613 info: "proc (body)" must be elaborated before "pack (body)"
34614 info: reason: Elaborate_All probably needed in unit "pack (body)"
34615 info: recompile "pack (body)" with -gnatel
34616 info: for full details
34617 info: "proc (body)"
34618 info: is needed by its spec:
34619 info: "proc (spec)"
34620 info: which is withed by:
34621 info: "pack (body)"
34622 info: "pack (body)" must be elaborated before "proc (body)"
34623 info: reason: pragma Elaborate in unit "proc (body)"
34626 In this case we have a cycle that the binder cannot break. On the one
34627 hand, there is an explicit pragma Elaborate in @cite{proc} for
34628 @cite{pack}. This means that the body of @cite{pack} must be elaborated
34629 before the body of @cite{proc}. On the other hand, there is elaboration
34630 code in @cite{pack} that calls a subprogram in @cite{proc}. This means
34631 that for maximum safety, there should really be a pragma
34632 Elaborate_All in @cite{pack} for @cite{proc} which would require that
34633 the body of @cite{proc} be elaborated before the body of
34634 @cite{pack}. Clearly both requirements cannot be satisfied.
34635 Faced with a circularity of this kind, you have three different options.
34641 @emph{Fix the program}
34643 The most desirable option from the point of view of long-term maintenance
34644 is to rearrange the program so that the elaboration problems are avoided.
34645 One useful technique is to place the elaboration code into separate
34646 child packages. Another is to move some of the initialization code to
34647 explicitly called subprograms, where the program controls the order
34648 of initialization explicitly. Although this is the most desirable option,
34649 it may be impractical and involve too much modification, especially in
34650 the case of complex legacy code.
34653 @emph{Perform dynamic checks}
34655 If the compilations are done using the @emph{-gnatE}
34656 (dynamic elaboration check) switch, then GNAT behaves in a quite different
34657 manner. Dynamic checks are generated for all calls that could possibly result
34658 in raising an exception. With this switch, the compiler does not generate
34659 implicit @cite{Elaborate} or @cite{Elaborate_All} pragmas. The behavior then is
34660 exactly as specified in the @cite{Ada Reference Manual}.
34661 The binder will generate
34662 an executable program that may or may not raise @cite{Program_Error}, and then
34663 it is the programmer's job to ensure that it does not raise an exception. Note
34664 that it is important to compile all units with the switch, it cannot be used
34668 @emph{Suppress checks}
34670 The drawback of dynamic checks is that they generate a
34671 significant overhead at run time, both in space and time. If you
34672 are absolutely sure that your program cannot raise any elaboration
34673 exceptions, and you still want to use the dynamic elaboration model,
34674 then you can use the configuration pragma
34675 @cite{Suppress (Elaboration_Check)} to suppress all such checks. For
34676 example this pragma could be placed in the @code{gnat.adc} file.
34679 @emph{Suppress checks selectively}
34681 When you know that certain calls or instantiations in elaboration code cannot
34682 possibly lead to an elaboration error, and the binder nevertheless complains
34683 about implicit @cite{Elaborate} and @cite{Elaborate_All} pragmas that lead to
34684 elaboration circularities, it is possible to remove those warnings locally and
34685 obtain a program that will bind. Clearly this can be unsafe, and it is the
34686 responsibility of the programmer to make sure that the resulting program has no
34687 elaboration anomalies. The pragma @cite{Suppress (Elaboration_Check)} can be
34688 used with different granularity to suppress warnings and break elaboration
34695 Place the pragma that names the called subprogram in the declarative part
34696 that contains the call.
34699 Place the pragma in the declarative part, without naming an entity. This
34700 disables warnings on all calls in the corresponding declarative region.
34703 Place the pragma in the package spec that declares the called subprogram,
34704 and name the subprogram. This disables warnings on all elaboration calls to
34708 Place the pragma in the package spec that declares the called subprogram,
34709 without naming any entity. This disables warnings on all elaboration calls to
34710 all subprograms declared in this spec.
34713 Use Pragma Elaborate.
34715 As previously described in section @ref{2ca,,Treatment of Pragma Elaborate},
34716 GNAT in static mode assumes that a @cite{pragma} Elaborate indicates correctly
34717 that no elaboration checks are required on calls to the designated unit.
34718 There may be cases in which the caller knows that no transitive calls
34719 can occur, so that a @cite{pragma Elaborate} will be sufficient in a
34720 case where @cite{pragma Elaborate_All} would cause a circularity.
34723 These five cases are listed in order of decreasing safety, and therefore
34724 require increasing programmer care in their application. Consider the
34729 function F1 return Integer;
34734 function F2 return Integer;
34735 function Pure (x : integer) return integer;
34736 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
34737 -- pragma Suppress (Elaboration_Check); -- (4)
34741 package body Pack1 is
34742 function F1 return Integer is
34746 Val : integer := Pack2.Pure (11); -- Elab. call (1)
34749 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
34750 -- pragma Suppress(Elaboration_Check); -- (2)
34752 X1 := Pack2.F2 + 1; -- Elab. call (2)
34757 package body Pack2 is
34758 function F2 return Integer is
34762 function Pure (x : integer) return integer is
34764 return x ** 3 - 3 * x;
34768 with Pack1, Ada.Text_IO;
34771 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
34775 In the absence of any pragmas, an attempt to bind this program produces
34776 the following diagnostics:
34779 error: elaboration circularity detected
34780 info: "pack1 (body)" must be elaborated before "pack1 (body)"
34781 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
34782 info: recompile "pack1 (body)" with -gnatel for full details
34783 info: "pack1 (body)"
34784 info: must be elaborated along with its spec:
34785 info: "pack1 (spec)"
34786 info: which is withed by:
34787 info: "pack2 (body)"
34788 info: which must be elaborated along with its spec:
34789 info: "pack2 (spec)"
34790 info: which is withed by:
34791 info: "pack1 (body)"
34794 The sources of the circularity are the two calls to @cite{Pack2.Pure} and
34795 @cite{Pack2.F2} in the body of @cite{Pack1}. We can see that the call to
34796 F2 is safe, even though F2 calls F1, because the call appears after the
34797 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
34798 remove the warning on the call. It is also possible to use pragma (2)
34799 because there are no other potentially unsafe calls in the block.
34801 The call to @cite{Pure} is safe because this function does not depend on the
34802 state of @cite{Pack2}. Therefore any call to this function is safe, and it
34803 is correct to place pragma (3) in the corresponding package spec.
34805 Finally, we could place pragma (4) in the spec of @cite{Pack2} to disable
34806 warnings on all calls to functions declared therein. Note that this is not
34807 necessarily safe, and requires more detailed examination of the subprogram
34808 bodies involved. In particular, a call to @cite{F2} requires that @cite{F1}
34809 be already elaborated.
34812 It is hard to generalize on which of these four approaches should be
34813 taken. Obviously if it is possible to fix the program so that the default
34814 treatment works, this is preferable, but this may not always be practical.
34815 It is certainly simple enough to use @emph{-gnatE}
34816 but the danger in this case is that, even if the GNAT binder
34817 finds a correct elaboration order, it may not always do so,
34818 and certainly a binder from another Ada compiler might not. A
34819 combination of testing and analysis (for which the
34820 information messages generated with the @emph{-gnatel}
34821 switch can be useful) must be used to ensure that the program is free
34822 of errors. One switch that is useful in this testing is the
34823 @emph{-p (pessimistic elaboration order)} switch for @cite{gnatbind}.
34824 Normally the binder tries to find an order that has the best chance
34825 of avoiding elaboration problems. However, if this switch is used, the binder
34826 plays a devil's advocate role, and tries to choose the order that
34827 has the best chance of failing. If your program works even with this
34828 switch, then it has a better chance of being error free, but this is still
34831 For an example of this approach in action, consider the C-tests (executable
34832 tests) from the ACATS suite. If these are compiled and run with the default
34833 treatment, then all but one of them succeed without generating any error
34834 diagnostics from the binder. However, there is one test that fails, and
34835 this is not surprising, because the whole point of this test is to ensure
34836 that the compiler can handle cases where it is impossible to determine
34837 a correct order statically, and it checks that an exception is indeed
34838 raised at run time.
34840 This one test must be compiled and run using the @emph{-gnatE}
34841 switch, and then it passes. Alternatively, the entire suite can
34842 be run using this switch. It is never wrong to run with the dynamic
34843 elaboration switch if your code is correct, and we assume that the
34844 C-tests are indeed correct (it is less efficient, but efficiency is
34845 not a factor in running the ACATS tests.)
34847 @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
34848 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{2d1}@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-for-indirect-calls}@anchor{2d2}
34849 @section Elaboration for Indirect Calls
34852 @geindex Dispatching calls
34854 @geindex Indirect calls
34856 In rare cases, the static elaboration model fails to prevent
34857 dispatching calls to not-yet-elaborated subprograms. In such cases, we
34858 fall back to run-time checks; premature calls to any primitive
34859 operation of a tagged type before the body of the operation has been
34860 elaborated will raise @cite{Program_Error}.
34862 Access-to-subprogram types, however, are handled conservatively, and
34863 do not require run-time checks. This was not true in earlier versions
34864 of the compiler; you can use the @emph{-gnatd.U} debug switch to
34865 revert to the old behavior if the new conservative behavior causes
34866 elaboration cycles. Here, 'conservative' means that if you do
34867 @cite{P'Access} during elaboration, the compiler will assume that you
34868 might call @cite{P} indirectly during elaboration, so it adds an
34869 implicit @cite{pragma Elaborate_All} on the library unit containing
34870 @cite{P}. The @emph{-gnatd.U} switch is safe if you know there are
34871 no such calls. If the program worked before, it will continue to work
34872 with @emph{-gnatd.U}. But beware that code modifications such as
34873 adding an indirect call can cause erroneous behavior in the presence
34874 of @emph{-gnatd.U}.
34876 @node Summary of Procedures for Elaboration Control,Other Elaboration Order Considerations,Elaboration for Indirect Calls,Elaboration Order Handling in GNAT
34877 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{2d3}@anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{2d4}
34878 @section Summary of Procedures for Elaboration Control
34881 @geindex Elaboration control
34883 First, compile your program with the default options, using none of
34884 the special elaboration control switches. If the binder successfully
34885 binds your program, then you can be confident that, apart from issues
34886 raised by the use of access-to-subprogram types and dynamic dispatching,
34887 the program is free of elaboration errors. If it is important that the
34888 program be portable to other compilers than GNAT, then use the
34890 switch to generate messages about missing @cite{Elaborate} or
34891 @cite{Elaborate_All} pragmas, and supply the missing pragmas.
34893 If the program fails to bind using the default static elaboration
34894 handling, then you can fix the program to eliminate the binder
34895 message, or recompile the entire program with the
34896 @emph{-gnatE} switch to generate dynamic elaboration checks,
34897 and, if you are sure there really are no elaboration problems,
34898 use a global pragma @cite{Suppress (Elaboration_Check)}.
34900 @node Other Elaboration Order Considerations,Determining the Chosen Elaboration Order,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
34901 @anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{2d5}@anchor{gnat_ugn/elaboration_order_handling_in_gnat other-elaboration-order-considerations}@anchor{2d6}
34902 @section Other Elaboration Order Considerations
34905 This section has been entirely concerned with the issue of finding a valid
34906 elaboration order, as defined by the Ada Reference Manual. In a case
34907 where several elaboration orders are valid, the task is to find one
34908 of the possible valid elaboration orders (and the static model in GNAT
34909 will ensure that this is achieved).
34911 The purpose of the elaboration rules in the Ada Reference Manual is to
34912 make sure that no entity is accessed before it has been elaborated. For
34913 a subprogram, this means that the spec and body must have been elaborated
34914 before the subprogram is called. For an object, this means that the object
34915 must have been elaborated before its value is read or written. A violation
34916 of either of these two requirements is an access before elaboration order,
34917 and this section has been all about avoiding such errors.
34919 In the case where more than one order of elaboration is possible, in the
34920 sense that access before elaboration errors are avoided, then any one of
34921 the orders is 'correct' in the sense that it meets the requirements of
34922 the Ada Reference Manual, and no such error occurs.
34924 However, it may be the case for a given program, that there are
34925 constraints on the order of elaboration that come not from consideration
34926 of avoiding elaboration errors, but rather from extra-lingual logic
34927 requirements. Consider this example:
34930 with Init_Constants;
34931 package Constants is
34936 package Init_Constants is
34937 procedure P; --* require a body*
34938 end Init_Constants;
34941 package body Init_Constants is
34942 procedure P is begin null; end;
34946 end Init_Constants;
34950 Z : Integer := Constants.X + Constants.Y;
34954 with Text_IO; use Text_IO;
34957 Put_Line (Calc.Z'Img);
34961 In this example, there is more than one valid order of elaboration. For
34962 example both the following are correct orders:
34965 Init_Constants spec
34968 Init_Constants body
34975 Init_Constants spec
34976 Init_Constants body
34982 There is no language rule to prefer one or the other, both are correct
34983 from an order of elaboration point of view. But the programmatic effects
34984 of the two orders are very different. In the first, the elaboration routine
34985 of @cite{Calc} initializes @cite{Z} to zero, and then the main program
34986 runs with this value of zero. But in the second order, the elaboration
34987 routine of @cite{Calc} runs after the body of Init_Constants has set
34988 @cite{X} and @cite{Y} and thus @cite{Z} is set to 7 before @cite{Main} runs.
34990 One could perhaps by applying pretty clever non-artificial intelligence
34991 to the situation guess that it is more likely that the second order of
34992 elaboration is the one desired, but there is no formal linguistic reason
34993 to prefer one over the other. In fact in this particular case, GNAT will
34994 prefer the second order, because of the rule that bodies are elaborated
34995 as soon as possible, but it's just luck that this is what was wanted
34996 (if indeed the second order was preferred).
34998 If the program cares about the order of elaboration routines in a case like
34999 this, it is important to specify the order required. In this particular
35000 case, that could have been achieved by adding to the spec of Calc:
35003 pragma Elaborate_All (Constants);
35006 which requires that the body (if any) and spec of @cite{Constants},
35007 as well as the body and spec of any unit @emph{with}ed by
35008 @cite{Constants} be elaborated before @cite{Calc} is elaborated.
35010 Clearly no automatic method can always guess which alternative you require,
35011 and if you are working with legacy code that had constraints of this kind
35012 which were not properly specified by adding @cite{Elaborate} or
35013 @cite{Elaborate_All} pragmas, then indeed it is possible that two different
35014 compilers can choose different orders.
35016 However, GNAT does attempt to diagnose the common situation where there
35017 are uninitialized variables in the visible part of a package spec, and the
35018 corresponding package body has an elaboration block that directly or
35019 indirectly initialized one or more of these variables. This is the situation
35020 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
35021 a warning that suggests this addition if it detects this situation.
35023 The @cite{gnatbind} @emph{-p} switch may be useful in smoking
35024 out problems. This switch causes bodies to be elaborated as late as possible
35025 instead of as early as possible. In the example above, it would have forced
35026 the choice of the first elaboration order. If you get different results
35027 when using this switch, and particularly if one set of results is right,
35028 and one is wrong as far as you are concerned, it shows that you have some
35029 missing @cite{Elaborate} pragmas. For the example above, we have the
35033 $ gnatmake -f -q main
35036 $ gnatmake -f -q main -bargs -p
35041 It is of course quite unlikely that both these results are correct, so
35042 it is up to you in a case like this to investigate the source of the
35043 difference, by looking at the two elaboration orders that are chosen,
35044 and figuring out which is correct, and then adding the necessary
35045 @cite{Elaborate} or @cite{Elaborate_All} pragmas to ensure the desired order.
35047 @node Determining the Chosen Elaboration Order,,Other Elaboration Order Considerations,Elaboration Order Handling in GNAT
35048 @anchor{gnat_ugn/elaboration_order_handling_in_gnat determining-the-chosen-elaboration-order}@anchor{2d7}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id15}@anchor{2d8}
35049 @section Determining the Chosen Elaboration Order
35052 To see the elaboration order that the binder chooses, you can look at
35053 the last part of the file:@cite{b~xxx.adb} binder output file. Here is an example:
35056 System.Soft_Links'Elab_Body;
35058 System.Secondary_Stack'Elab_Body;
35060 System.Exception_Table'Elab_Body;
35062 Ada.Io_Exceptions'Elab_Spec;
35064 Ada.Tags'Elab_Spec;
35065 Ada.Streams'Elab_Spec;
35067 Interfaces.C'Elab_Spec;
35069 System.Finalization_Root'Elab_Spec;
35071 System.Os_Lib'Elab_Body;
35073 System.Finalization_Implementation'Elab_Spec;
35074 System.Finalization_Implementation'Elab_Body;
35076 Ada.Finalization'Elab_Spec;
35078 Ada.Finalization.List_Controller'Elab_Spec;
35080 System.File_Control_Block'Elab_Spec;
35082 System.File_Io'Elab_Body;
35084 Ada.Tags'Elab_Body;
35086 Ada.Text_Io'Elab_Spec;
35087 Ada.Text_Io'Elab_Body;
35091 Here Elab_Spec elaborates the spec
35092 and Elab_Body elaborates the body. The assignments to the @code{E@emph{xx}} flags
35093 flag that the corresponding body is now elaborated.
35095 You can also ask the binder to generate a more
35096 readable list of the elaboration order using the
35097 @cite{-l} switch when invoking the binder. Here is
35098 an example of the output generated by this switch:
35104 system.case_util (spec)
35105 system.case_util (body)
35106 system.concat_2 (spec)
35107 system.concat_2 (body)
35108 system.concat_3 (spec)
35109 system.concat_3 (body)
35110 system.htable (spec)
35111 system.parameters (spec)
35112 system.parameters (body)
35114 interfaces.c_streams (spec)
35115 interfaces.c_streams (body)
35116 system.restrictions (spec)
35117 system.restrictions (body)
35118 system.standard_library (spec)
35119 system.exceptions (spec)
35120 system.exceptions (body)
35121 system.storage_elements (spec)
35122 system.storage_elements (body)
35123 system.secondary_stack (spec)
35124 system.stack_checking (spec)
35125 system.stack_checking (body)
35126 system.string_hash (spec)
35127 system.string_hash (body)
35128 system.htable (body)
35129 system.strings (spec)
35130 system.strings (body)
35131 system.traceback (spec)
35132 system.traceback (body)
35133 system.traceback_entries (spec)
35134 system.traceback_entries (body)
35135 ada.exceptions (spec)
35136 ada.exceptions.last_chance_handler (spec)
35137 system.soft_links (spec)
35138 system.soft_links (body)
35139 ada.exceptions.last_chance_handler (body)
35140 system.secondary_stack (body)
35141 system.exception_table (spec)
35142 system.exception_table (body)
35143 ada.io_exceptions (spec)
35146 interfaces.c (spec)
35147 interfaces.c (body)
35148 system.finalization_root (spec)
35149 system.finalization_root (body)
35150 system.memory (spec)
35151 system.memory (body)
35152 system.standard_library (body)
35153 system.os_lib (spec)
35154 system.os_lib (body)
35155 system.unsigned_types (spec)
35156 system.stream_attributes (spec)
35157 system.stream_attributes (body)
35158 system.finalization_implementation (spec)
35159 system.finalization_implementation (body)
35160 ada.finalization (spec)
35161 ada.finalization (body)
35162 ada.finalization.list_controller (spec)
35163 ada.finalization.list_controller (body)
35164 system.file_control_block (spec)
35165 system.file_io (spec)
35166 system.file_io (body)
35167 system.val_uns (spec)
35168 system.val_util (spec)
35169 system.val_util (body)
35170 system.val_uns (body)
35171 system.wch_con (spec)
35172 system.wch_con (body)
35173 system.wch_cnv (spec)
35174 system.wch_jis (spec)
35175 system.wch_jis (body)
35176 system.wch_cnv (body)
35177 system.wch_stw (spec)
35178 system.wch_stw (body)
35180 ada.exceptions (body)
35187 @node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
35188 @anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{12}@anchor{gnat_ugn/inline_assembler doc}@anchor{2d9}@anchor{gnat_ugn/inline_assembler id1}@anchor{2da}
35189 @chapter Inline Assembler
35192 @geindex Inline Assembler
35194 If you need to write low-level software that interacts directly
35195 with the hardware, Ada provides two ways to incorporate assembly
35196 language code into your program. First, you can import and invoke
35197 external routines written in assembly language, an Ada feature fully
35198 supported by GNAT. However, for small sections of code it may be simpler
35199 or more efficient to include assembly language statements directly
35200 in your Ada source program, using the facilities of the implementation-defined
35201 package @cite{System.Machine_Code}, which incorporates the gcc
35202 Inline Assembler. The Inline Assembler approach offers a number of advantages,
35203 including the following:
35209 No need to use non-Ada tools
35212 Consistent interface over different targets
35215 Automatic usage of the proper calling conventions
35218 Access to Ada constants and variables
35221 Definition of intrinsic routines
35224 Possibility of inlining a subprogram comprising assembler code
35227 Code optimizer can take Inline Assembler code into account
35230 This appendix presents a series of examples to show you how to use
35231 the Inline Assembler. Although it focuses on the Intel x86,
35232 the general approach applies also to other processors.
35233 It is assumed that you are familiar with Ada
35234 and with assembly language programming.
35237 * Basic Assembler Syntax::
35238 * A Simple Example of Inline Assembler::
35239 * Output Variables in Inline Assembler::
35240 * Input Variables in Inline Assembler::
35241 * Inlining Inline Assembler Code::
35242 * Other Asm Functionality::
35246 @node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
35247 @anchor{gnat_ugn/inline_assembler id2}@anchor{2db}@anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{2dc}
35248 @section Basic Assembler Syntax
35251 The assembler used by GNAT and gcc is based not on the Intel assembly
35252 language, but rather on a language that descends from the AT&T Unix
35253 assembler @emph{as} (and which is often referred to as 'AT&T syntax').
35254 The following table summarizes the main features of @emph{as} syntax
35255 and points out the differences from the Intel conventions.
35256 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
35257 pre-processor) documentation for further information.
35261 @emph{Register names}@w{ }
35263 gcc / @emph{as}: Prefix with '%'; for example @cite{%eax}@w{ }
35264 Intel: No extra punctuation; for example @cite{eax}@w{ }
35272 @emph{Immediate operand}@w{ }
35274 gcc / @emph{as}: Prefix with '$'; for example @cite{$4}@w{ }
35275 Intel: No extra punctuation; for example @cite{4}@w{ }
35283 @emph{Address}@w{ }
35285 gcc / @emph{as}: Prefix with '$'; for example @cite{$loc}@w{ }
35286 Intel: No extra punctuation; for example @cite{loc}@w{ }
35294 @emph{Memory contents}@w{ }
35296 gcc / @emph{as}: No extra punctuation; for example @cite{loc}@w{ }
35297 Intel: Square brackets; for example @cite{[loc]}@w{ }
35305 @emph{Register contents}@w{ }
35307 gcc / @emph{as}: Parentheses; for example @cite{(%eax)}@w{ }
35308 Intel: Square brackets; for example @cite{[eax]}@w{ }
35316 @emph{Hexadecimal numbers}@w{ }
35318 gcc / @emph{as}: Leading '0x' (C language syntax); for example @cite{0xA0}@w{ }
35319 Intel: Trailing 'h'; for example @cite{A0h}@w{ }
35327 @emph{Operand size}@w{ }
35329 gcc / @emph{as}: Explicit in op code; for example @cite{movw} to move a 16-bit word@w{ }
35330 Intel: Implicit, deduced by assembler; for example @cite{mov}@w{ }
35338 @emph{Instruction repetition}@w{ }
35340 gcc / @emph{as}: Split into two lines; for example@w{ }
35345 Intel: Keep on one line; for example @cite{rep stosl}@w{ }
35353 @emph{Order of operands}@w{ }
35355 gcc / @emph{as}: Source first; for example @cite{movw $4@comma{} %eax}@w{ }
35356 Intel: Destination first; for example @cite{mov eax@comma{} 4}@w{ }
35362 @node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
35363 @anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{2dd}@anchor{gnat_ugn/inline_assembler id3}@anchor{2de}
35364 @section A Simple Example of Inline Assembler
35367 The following example will generate a single assembly language statement,
35368 @cite{nop}, which does nothing. Despite its lack of run-time effect,
35369 the example will be useful in illustrating the basics of
35370 the Inline Assembler facility.
35375 with System.Machine_Code; use System.Machine_Code;
35376 procedure Nothing is
35383 @cite{Asm} is a procedure declared in package @cite{System.Machine_Code};
35384 here it takes one parameter, a @emph{template string} that must be a static
35385 expression and that will form the generated instruction.
35386 @cite{Asm} may be regarded as a compile-time procedure that parses
35387 the template string and additional parameters (none here),
35388 from which it generates a sequence of assembly language instructions.
35390 The examples in this chapter will illustrate several of the forms
35391 for invoking @cite{Asm}; a complete specification of the syntax
35392 is found in the @cite{Machine_Code_Insertions} section of the
35393 @cite{GNAT Reference Manual}.
35395 Under the standard GNAT conventions, the @cite{Nothing} procedure
35396 should be in a file named @code{nothing.adb}.
35397 You can build the executable in the usual way:
35406 However, the interesting aspect of this example is not its run-time behavior
35407 but rather the generated assembly code.
35408 To see this output, invoke the compiler as follows:
35413 $ gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
35417 where the options are:
35428 compile only (no bind or link)
35437 generate assembler listing
35444 @item @code{-fomit-frame-pointer}
35446 do not set up separate stack frames
35453 @item @code{-gnatp}
35455 do not add runtime checks
35459 This gives a human-readable assembler version of the code. The resulting
35460 file will have the same name as the Ada source file, but with a @cite{.s}
35461 extension. In our example, the file @code{nothing.s} has the following
35467 .file "nothing.adb"
35469 ___gnu_compiled_ada:
35472 .globl __ada_nothing
35484 The assembly code you included is clearly indicated by
35485 the compiler, between the @cite{#APP} and @cite{#NO_APP}
35486 delimiters. The character before the 'APP' and 'NOAPP'
35487 can differ on different targets. For example, GNU/Linux uses '#APP' while
35488 on NT you will see '/APP'.
35490 If you make a mistake in your assembler code (such as using the
35491 wrong size modifier, or using a wrong operand for the instruction) GNAT
35492 will report this error in a temporary file, which will be deleted when
35493 the compilation is finished. Generating an assembler file will help
35494 in such cases, since you can assemble this file separately using the
35495 @emph{as} assembler that comes with gcc.
35497 Assembling the file using the command
35506 will give you error messages whose lines correspond to the assembler
35507 input file, so you can easily find and correct any mistakes you made.
35508 If there are no errors, @emph{as} will generate an object file
35509 @code{nothing.out}.
35511 @node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
35512 @anchor{gnat_ugn/inline_assembler id4}@anchor{2df}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{2e0}
35513 @section Output Variables in Inline Assembler
35516 The examples in this section, showing how to access the processor flags,
35517 illustrate how to specify the destination operands for assembly language
35523 with Interfaces; use Interfaces;
35524 with Ada.Text_IO; use Ada.Text_IO;
35525 with System.Machine_Code; use System.Machine_Code;
35526 procedure Get_Flags is
35527 Flags : Unsigned_32;
35530 Asm ("pushfl" & LF & HT & -- push flags on stack
35531 "popl %%eax" & LF & HT & -- load eax with flags
35532 "movl %%eax, %0", -- store flags in variable
35533 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35534 Put_Line ("Flags register:" & Flags'Img);
35539 In order to have a nicely aligned assembly listing, we have separated
35540 multiple assembler statements in the Asm template string with linefeed
35541 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
35542 The resulting section of the assembly output file is:
35550 movl %eax, -40(%ebp)
35555 It would have been legal to write the Asm invocation as:
35560 Asm ("pushfl popl %%eax movl %%eax, %0")
35564 but in the generated assembler file, this would come out as:
35570 pushfl popl %eax movl %eax, -40(%ebp)
35575 which is not so convenient for the human reader.
35577 We use Ada comments
35578 at the end of each line to explain what the assembler instructions
35579 actually do. This is a useful convention.
35581 When writing Inline Assembler instructions, you need to precede each register
35582 and variable name with a percent sign. Since the assembler already requires
35583 a percent sign at the beginning of a register name, you need two consecutive
35584 percent signs for such names in the Asm template string, thus @cite{%%eax}.
35585 In the generated assembly code, one of the percent signs will be stripped off.
35587 Names such as @cite{%0}, @cite{%1}, @cite{%2}, etc., denote input or output
35588 variables: operands you later define using @cite{Input} or @cite{Output}
35589 parameters to @cite{Asm}.
35590 An output variable is illustrated in
35591 the third statement in the Asm template string:
35600 The intent is to store the contents of the eax register in a variable that can
35601 be accessed in Ada. Simply writing @cite{movl %%eax@comma{} Flags} would not
35602 necessarily work, since the compiler might optimize by using a register
35603 to hold Flags, and the expansion of the @cite{movl} instruction would not be
35604 aware of this optimization. The solution is not to store the result directly
35605 but rather to advise the compiler to choose the correct operand form;
35606 that is the purpose of the @cite{%0} output variable.
35608 Information about the output variable is supplied in the @cite{Outputs}
35609 parameter to @cite{Asm}:
35614 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35618 The output is defined by the @cite{Asm_Output} attribute of the target type;
35619 the general format is
35624 Type'Asm_Output (constraint_string, variable_name)
35628 The constraint string directs the compiler how
35629 to store/access the associated variable. In the example
35634 Unsigned_32'Asm_Output ("=m", Flags);
35638 the @cite{"m"} (memory) constraint tells the compiler that the variable
35639 @cite{Flags} should be stored in a memory variable, thus preventing
35640 the optimizer from keeping it in a register. In contrast,
35645 Unsigned_32'Asm_Output ("=r", Flags);
35649 uses the @cite{"r"} (register) constraint, telling the compiler to
35650 store the variable in a register.
35652 If the constraint is preceded by the equal character '=', it tells
35653 the compiler that the variable will be used to store data into it.
35655 In the @cite{Get_Flags} example, we used the @cite{"g"} (global) constraint,
35656 allowing the optimizer to choose whatever it deems best.
35658 There are a fairly large number of constraints, but the ones that are
35659 most useful (for the Intel x86 processor) are the following:
35664 @multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
35679 global (i.e., can be stored anywhere)
35751 use one of eax, ebx, ecx or edx
35759 use one of eax, ebx, ecx, edx, esi or edi
35765 The full set of constraints is described in the gcc and @emph{as}
35766 documentation; note that it is possible to combine certain constraints
35767 in one constraint string.
35769 You specify the association of an output variable with an assembler operand
35770 through the @code{%@emph{n}} notation, where @emph{n} is a non-negative
35776 Asm ("pushfl" & LF & HT & -- push flags on stack
35777 "popl %%eax" & LF & HT & -- load eax with flags
35778 "movl %%eax, %0", -- store flags in variable
35779 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35783 @cite{%0} will be replaced in the expanded code by the appropriate operand,
35785 the compiler decided for the @cite{Flags} variable.
35787 In general, you may have any number of output variables:
35793 Count the operands starting at 0; thus @cite{%0}, @cite{%1}, etc.
35796 Specify the @cite{Outputs} parameter as a parenthesized comma-separated list
35797 of @cite{Asm_Output} attributes
35805 Asm ("movl %%eax, %0" & LF & HT &
35806 "movl %%ebx, %1" & LF & HT &
35808 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
35809 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
35810 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
35814 where @cite{Var_A}, @cite{Var_B}, and @cite{Var_C} are variables
35815 in the Ada program.
35817 As a variation on the @cite{Get_Flags} example, we can use the constraints
35818 string to direct the compiler to store the eax register into the @cite{Flags}
35819 variable, instead of including the store instruction explicitly in the
35820 @cite{Asm} template string:
35825 with Interfaces; use Interfaces;
35826 with Ada.Text_IO; use Ada.Text_IO;
35827 with System.Machine_Code; use System.Machine_Code;
35828 procedure Get_Flags_2 is
35829 Flags : Unsigned_32;
35832 Asm ("pushfl" & LF & HT & -- push flags on stack
35833 "popl %%eax", -- save flags in eax
35834 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
35835 Put_Line ("Flags register:" & Flags'Img);
35840 The @cite{"a"} constraint tells the compiler that the @cite{Flags}
35841 variable will come from the eax register. Here is the resulting code:
35850 movl %eax,-40(%ebp)
35854 The compiler generated the store of eax into Flags after
35855 expanding the assembler code.
35857 Actually, there was no need to pop the flags into the eax register;
35858 more simply, we could just pop the flags directly into the program variable:
35863 with Interfaces; use Interfaces;
35864 with Ada.Text_IO; use Ada.Text_IO;
35865 with System.Machine_Code; use System.Machine_Code;
35866 procedure Get_Flags_3 is
35867 Flags : Unsigned_32;
35870 Asm ("pushfl" & LF & HT & -- push flags on stack
35871 "pop %0", -- save flags in Flags
35872 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
35873 Put_Line ("Flags register:" & Flags'Img);
35878 @node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
35879 @anchor{gnat_ugn/inline_assembler id5}@anchor{2e1}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{2e2}
35880 @section Input Variables in Inline Assembler
35883 The example in this section illustrates how to specify the source operands
35884 for assembly language statements.
35885 The program simply increments its input value by 1:
35890 with Interfaces; use Interfaces;
35891 with Ada.Text_IO; use Ada.Text_IO;
35892 with System.Machine_Code; use System.Machine_Code;
35893 procedure Increment is
35895 function Incr (Value : Unsigned_32) return Unsigned_32 is
35896 Result : Unsigned_32;
35899 Outputs => Unsigned_32'Asm_Output ("=a", Result),
35900 Inputs => Unsigned_32'Asm_Input ("a", Value));
35904 Value : Unsigned_32;
35908 Put_Line ("Value before is" & Value'Img);
35909 Value := Incr (Value);
35910 Put_Line ("Value after is" & Value'Img);
35915 The @cite{Outputs} parameter to @cite{Asm} specifies
35916 that the result will be in the eax register and that it is to be stored
35917 in the @cite{Result} variable.
35919 The @cite{Inputs} parameter looks much like the @cite{Outputs} parameter,
35920 but with an @cite{Asm_Input} attribute.
35921 The @cite{"="} constraint, indicating an output value, is not present.
35923 You can have multiple input variables, in the same way that you can have more
35924 than one output variable.
35926 The parameter count (%0, %1) etc, still starts at the first output statement,
35927 and continues with the input statements.
35929 Just as the @cite{Outputs} parameter causes the register to be stored into the
35930 target variable after execution of the assembler statements, so does the
35931 @cite{Inputs} parameter cause its variable to be loaded into the register
35932 before execution of the assembler statements.
35934 Thus the effect of the @cite{Asm} invocation is:
35940 load the 32-bit value of @cite{Value} into eax
35943 execute the @cite{incl %eax} instruction
35946 store the contents of eax into the @cite{Result} variable
35949 The resulting assembler file (with @emph{-O2} optimization) contains:
35954 _increment__incr.1:
35967 @node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
35968 @anchor{gnat_ugn/inline_assembler id6}@anchor{2e3}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{2e4}
35969 @section Inlining Inline Assembler Code
35972 For a short subprogram such as the @cite{Incr} function in the previous
35973 section, the overhead of the call and return (creating / deleting the stack
35974 frame) can be significant, compared to the amount of code in the subprogram
35975 body. A solution is to apply Ada's @cite{Inline} pragma to the subprogram,
35976 which directs the compiler to expand invocations of the subprogram at the
35977 point(s) of call, instead of setting up a stack frame for out-of-line calls.
35978 Here is the resulting program:
35983 with Interfaces; use Interfaces;
35984 with Ada.Text_IO; use Ada.Text_IO;
35985 with System.Machine_Code; use System.Machine_Code;
35986 procedure Increment_2 is
35988 function Incr (Value : Unsigned_32) return Unsigned_32 is
35989 Result : Unsigned_32;
35992 Outputs => Unsigned_32'Asm_Output ("=a", Result),
35993 Inputs => Unsigned_32'Asm_Input ("a", Value));
35996 pragma Inline (Increment);
35998 Value : Unsigned_32;
36002 Put_Line ("Value before is" & Value'Img);
36003 Value := Increment (Value);
36004 Put_Line ("Value after is" & Value'Img);
36009 Compile the program with both optimization (@emph{-O2}) and inlining
36010 (@emph{-gnatn}) enabled.
36012 The @cite{Incr} function is still compiled as usual, but at the
36013 point in @cite{Increment} where our function used to be called:
36019 call _increment__incr.1
36023 the code for the function body directly appears:
36036 thus saving the overhead of stack frame setup and an out-of-line call.
36038 @node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
36039 @anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{2e5}@anchor{gnat_ugn/inline_assembler id7}@anchor{2e6}
36040 @section Other @cite{Asm} Functionality
36043 This section describes two important parameters to the @cite{Asm}
36044 procedure: @cite{Clobber}, which identifies register usage;
36045 and @cite{Volatile}, which inhibits unwanted optimizations.
36048 * The Clobber Parameter::
36049 * The Volatile Parameter::
36053 @node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
36054 @anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{2e7}@anchor{gnat_ugn/inline_assembler id8}@anchor{2e8}
36055 @subsection The @cite{Clobber} Parameter
36058 One of the dangers of intermixing assembly language and a compiled language
36059 such as Ada is that the compiler needs to be aware of which registers are
36060 being used by the assembly code. In some cases, such as the earlier examples,
36061 the constraint string is sufficient to indicate register usage (e.g.,
36063 the eax register). But more generally, the compiler needs an explicit
36064 identification of the registers that are used by the Inline Assembly
36067 Using a register that the compiler doesn't know about
36068 could be a side effect of an instruction (like @cite{mull}
36069 storing its result in both eax and edx).
36070 It can also arise from explicit register usage in your
36071 assembly code; for example:
36076 Asm ("movl %0, %%ebx" & LF & HT &
36078 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
36079 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
36083 where the compiler (since it does not analyze the @cite{Asm} template string)
36084 does not know you are using the ebx register.
36086 In such cases you need to supply the @cite{Clobber} parameter to @cite{Asm},
36087 to identify the registers that will be used by your assembly code:
36092 Asm ("movl %0, %%ebx" & LF & HT &
36094 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
36095 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
36100 The Clobber parameter is a static string expression specifying the
36101 register(s) you are using. Note that register names are @emph{not} prefixed
36102 by a percent sign. Also, if more than one register is used then their names
36103 are separated by commas; e.g., @cite{"eax@comma{} ebx"}
36105 The @cite{Clobber} parameter has several additional uses:
36111 Use 'register' name @cite{cc} to indicate that flags might have changed
36114 Use 'register' name @cite{memory} if you changed a memory location
36117 @node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
36118 @anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{2e9}@anchor{gnat_ugn/inline_assembler id9}@anchor{2ea}
36119 @subsection The @cite{Volatile} Parameter
36122 @geindex Volatile parameter
36124 Compiler optimizations in the presence of Inline Assembler may sometimes have
36125 unwanted effects. For example, when an @cite{Asm} invocation with an input
36126 variable is inside a loop, the compiler might move the loading of the input
36127 variable outside the loop, regarding it as a one-time initialization.
36129 If this effect is not desired, you can disable such optimizations by setting
36130 the @cite{Volatile} parameter to @cite{True}; for example:
36135 Asm ("movl %0, %%ebx" & LF & HT &
36137 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
36138 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
36144 By default, @cite{Volatile} is set to @cite{False} unless there is no
36145 @cite{Outputs} parameter.
36147 Although setting @cite{Volatile} to @cite{True} prevents unwanted
36148 optimizations, it will also disable other optimizations that might be
36149 important for efficiency. In general, you should set @cite{Volatile}
36150 to @cite{True} only if the compiler's optimizations have created
36153 @node GNU Free Documentation License,Index,Inline Assembler,Top
36154 @anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license doc}@anchor{2eb}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{2ec}
36155 @chapter GNU Free Documentation License
36158 Version 1.3, 3 November 2008
36160 Copyright 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc
36161 @indicateurl{http://fsf.org/}
36163 Everyone is permitted to copy and distribute verbatim copies of this
36164 license document, but changing it is not allowed.
36168 The purpose of this License is to make a manual, textbook, or other
36169 functional and useful document "free" in the sense of freedom: to
36170 assure everyone the effective freedom to copy and redistribute it,
36171 with or without modifying it, either commercially or noncommercially.
36172 Secondarily, this License preserves for the author and publisher a way
36173 to get credit for their work, while not being considered responsible
36174 for modifications made by others.
36176 This License is a kind of "copyleft", which means that derivative
36177 works of the document must themselves be free in the same sense. It
36178 complements the GNU General Public License, which is a copyleft
36179 license designed for free software.
36181 We have designed this License in order to use it for manuals for free
36182 software, because free software needs free documentation: a free
36183 program should come with manuals providing the same freedoms that the
36184 software does. But this License is not limited to software manuals;
36185 it can be used for any textual work, regardless of subject matter or
36186 whether it is published as a printed book. We recommend this License
36187 principally for works whose purpose is instruction or reference.
36189 @strong{1. APPLICABILITY AND DEFINITIONS}
36191 This License applies to any manual or other work, in any medium, that
36192 contains a notice placed by the copyright holder saying it can be
36193 distributed under the terms of this License. Such a notice grants a
36194 world-wide, royalty-free license, unlimited in duration, to use that
36195 work under the conditions stated herein. The @strong{Document}, below,
36196 refers to any such manual or work. Any member of the public is a
36197 licensee, and is addressed as "@strong{you}". You accept the license if you
36198 copy, modify or distribute the work in a way requiring permission
36199 under copyright law.
36201 A "@strong{Modified Version}" of the Document means any work containing the
36202 Document or a portion of it, either copied verbatim, or with
36203 modifications and/or translated into another language.
36205 A "@strong{Secondary Section}" is a named appendix or a front-matter section of
36206 the Document that deals exclusively with the relationship of the
36207 publishers or authors of the Document to the Document's overall subject
36208 (or to related matters) and contains nothing that could fall directly
36209 within that overall subject. (Thus, if the Document is in part a
36210 textbook of mathematics, a Secondary Section may not explain any
36211 mathematics.) The relationship could be a matter of historical
36212 connection with the subject or with related matters, or of legal,
36213 commercial, philosophical, ethical or political position regarding
36216 The "@strong{Invariant Sections}" are certain Secondary Sections whose titles
36217 are designated, as being those of Invariant Sections, in the notice
36218 that says that the Document is released under this License. If a
36219 section does not fit the above definition of Secondary then it is not
36220 allowed to be designated as Invariant. The Document may contain zero
36221 Invariant Sections. If the Document does not identify any Invariant
36222 Sections then there are none.
36224 The "@strong{Cover Texts}" are certain short passages of text that are listed,
36225 as Front-Cover Texts or Back-Cover Texts, in the notice that says that
36226 the Document is released under this License. A Front-Cover Text may
36227 be at most 5 words, and a Back-Cover Text may be at most 25 words.
36229 A "@strong{Transparent}" copy of the Document means a machine-readable copy,
36230 represented in a format whose specification is available to the
36231 general public, that is suitable for revising the document
36232 straightforwardly with generic text editors or (for images composed of
36233 pixels) generic paint programs or (for drawings) some widely available
36234 drawing editor, and that is suitable for input to text formatters or
36235 for automatic translation to a variety of formats suitable for input
36236 to text formatters. A copy made in an otherwise Transparent file
36237 format whose markup, or absence of markup, has been arranged to thwart
36238 or discourage subsequent modification by readers is not Transparent.
36239 An image format is not Transparent if used for any substantial amount
36240 of text. A copy that is not "Transparent" is called @strong{Opaque}.
36242 Examples of suitable formats for Transparent copies include plain
36243 ASCII without markup, Texinfo input format, LaTeX input format, SGML
36244 or XML using a publicly available DTD, and standard-conforming simple
36245 HTML, PostScript or PDF designed for human modification. Examples of
36246 transparent image formats include PNG, XCF and JPG. Opaque formats
36247 include proprietary formats that can be read and edited only by
36248 proprietary word processors, SGML or XML for which the DTD and/or
36249 processing tools are not generally available, and the
36250 machine-generated HTML, PostScript or PDF produced by some word
36251 processors for output purposes only.
36253 The "@strong{Title Page}" means, for a printed book, the title page itself,
36254 plus such following pages as are needed to hold, legibly, the material
36255 this License requires to appear in the title page. For works in
36256 formats which do not have any title page as such, "Title Page" means
36257 the text near the most prominent appearance of the work's title,
36258 preceding the beginning of the body of the text.
36260 The "@strong{publisher}" means any person or entity that distributes
36261 copies of the Document to the public.
36263 A section "@strong{Entitled XYZ}" means a named subunit of the Document whose
36264 title either is precisely XYZ or contains XYZ in parentheses following
36265 text that translates XYZ in another language. (Here XYZ stands for a
36266 specific section name mentioned below, such as "@strong{Acknowledgements}",
36267 "@strong{Dedications}", "@strong{Endorsements}", or "@strong{History}".)
36268 To "@strong{Preserve the Title}"
36269 of such a section when you modify the Document means that it remains a
36270 section "Entitled XYZ" according to this definition.
36272 The Document may include Warranty Disclaimers next to the notice which
36273 states that this License applies to the Document. These Warranty
36274 Disclaimers are considered to be included by reference in this
36275 License, but only as regards disclaiming warranties: any other
36276 implication that these Warranty Disclaimers may have is void and has
36277 no effect on the meaning of this License.
36279 @strong{2. VERBATIM COPYING}
36281 You may copy and distribute the Document in any medium, either
36282 commercially or noncommercially, provided that this License, the
36283 copyright notices, and the license notice saying this License applies
36284 to the Document are reproduced in all copies, and that you add no other
36285 conditions whatsoever to those of this License. You may not use
36286 technical measures to obstruct or control the reading or further
36287 copying of the copies you make or distribute. However, you may accept
36288 compensation in exchange for copies. If you distribute a large enough
36289 number of copies you must also follow the conditions in section 3.
36291 You may also lend copies, under the same conditions stated above, and
36292 you may publicly display copies.
36294 @strong{3. COPYING IN QUANTITY}
36296 If you publish printed copies (or copies in media that commonly have
36297 printed covers) of the Document, numbering more than 100, and the
36298 Document's license notice requires Cover Texts, you must enclose the
36299 copies in covers that carry, clearly and legibly, all these Cover
36300 Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
36301 the back cover. Both covers must also clearly and legibly identify
36302 you as the publisher of these copies. The front cover must present
36303 the full title with all words of the title equally prominent and
36304 visible. You may add other material on the covers in addition.
36305 Copying with changes limited to the covers, as long as they preserve
36306 the title of the Document and satisfy these conditions, can be treated
36307 as verbatim copying in other respects.
36309 If the required texts for either cover are too voluminous to fit
36310 legibly, you should put the first ones listed (as many as fit
36311 reasonably) on the actual cover, and continue the rest onto adjacent
36314 If you publish or distribute Opaque copies of the Document numbering
36315 more than 100, you must either include a machine-readable Transparent
36316 copy along with each Opaque copy, or state in or with each Opaque copy
36317 a computer-network location from which the general network-using
36318 public has access to download using public-standard network protocols
36319 a complete Transparent copy of the Document, free of added material.
36320 If you use the latter option, you must take reasonably prudent steps,
36321 when you begin distribution of Opaque copies in quantity, to ensure
36322 that this Transparent copy will remain thus accessible at the stated
36323 location until at least one year after the last time you distribute an
36324 Opaque copy (directly or through your agents or retailers) of that
36325 edition to the public.
36327 It is requested, but not required, that you contact the authors of the
36328 Document well before redistributing any large number of copies, to give
36329 them a chance to provide you with an updated version of the Document.
36331 @strong{4. MODIFICATIONS}
36333 You may copy and distribute a Modified Version of the Document under
36334 the conditions of sections 2 and 3 above, provided that you release
36335 the Modified Version under precisely this License, with the Modified
36336 Version filling the role of the Document, thus licensing distribution
36337 and modification of the Modified Version to whoever possesses a copy
36338 of it. In addition, you must do these things in the Modified Version:
36344 Use in the Title Page (and on the covers, if any) a title distinct
36345 from that of the Document, and from those of previous versions
36346 (which should, if there were any, be listed in the History section
36347 of the Document). You may use the same title as a previous version
36348 if the original publisher of that version gives permission.
36351 List on the Title Page, as authors, one or more persons or entities
36352 responsible for authorship of the modifications in the Modified
36353 Version, together with at least five of the principal authors of the
36354 Document (all of its principal authors, if it has fewer than five),
36355 unless they release you from this requirement.
36358 State on the Title page the name of the publisher of the
36359 Modified Version, as the publisher.
36362 Preserve all the copyright notices of the Document.
36365 Add an appropriate copyright notice for your modifications
36366 adjacent to the other copyright notices.
36369 Include, immediately after the copyright notices, a license notice
36370 giving the public permission to use the Modified Version under the
36371 terms of this License, in the form shown in the Addendum below.
36374 Preserve in that license notice the full lists of Invariant Sections
36375 and required Cover Texts given in the Document's license notice.
36378 Include an unaltered copy of this License.
36381 Preserve the section Entitled "History", Preserve its Title, and add
36382 to it an item stating at least the title, year, new authors, and
36383 publisher of the Modified Version as given on the Title Page. If
36384 there is no section Entitled "History" in the Document, create one
36385 stating the title, year, authors, and publisher of the Document as
36386 given on its Title Page, then add an item describing the Modified
36387 Version as stated in the previous sentence.
36390 Preserve the network location, if any, given in the Document for
36391 public access to a Transparent copy of the Document, and likewise
36392 the network locations given in the Document for previous versions
36393 it was based on. These may be placed in the "History" section.
36394 You may omit a network location for a work that was published at
36395 least four years before the Document itself, or if the original
36396 publisher of the version it refers to gives permission.
36399 For any section Entitled "Acknowledgements" or "Dedications",
36400 Preserve the Title of the section, and preserve in the section all
36401 the substance and tone of each of the contributor acknowledgements
36402 and/or dedications given therein.
36405 Preserve all the Invariant Sections of the Document,
36406 unaltered in their text and in their titles. Section numbers
36407 or the equivalent are not considered part of the section titles.
36410 Delete any section Entitled "Endorsements". Such a section
36411 may not be included in the Modified Version.
36414 Do not retitle any existing section to be Entitled "Endorsements"
36415 or to conflict in title with any Invariant Section.
36418 Preserve any Warranty Disclaimers.
36421 If the Modified Version includes new front-matter sections or
36422 appendices that qualify as Secondary Sections and contain no material
36423 copied from the Document, you may at your option designate some or all
36424 of these sections as invariant. To do this, add their titles to the
36425 list of Invariant Sections in the Modified Version's license notice.
36426 These titles must be distinct from any other section titles.
36428 You may add a section Entitled "Endorsements", provided it contains
36429 nothing but endorsements of your Modified Version by various
36430 parties---for example, statements of peer review or that the text has
36431 been approved by an organization as the authoritative definition of a
36434 You may add a passage of up to five words as a Front-Cover Text, and a
36435 passage of up to 25 words as a Back-Cover Text, to the end of the list
36436 of Cover Texts in the Modified Version. Only one passage of
36437 Front-Cover Text and one of Back-Cover Text may be added by (or
36438 through arrangements made by) any one entity. If the Document already
36439 includes a cover text for the same cover, previously added by you or
36440 by arrangement made by the same entity you are acting on behalf of,
36441 you may not add another; but you may replace the old one, on explicit
36442 permission from the previous publisher that added the old one.
36444 The author(s) and publisher(s) of the Document do not by this License
36445 give permission to use their names for publicity for or to assert or
36446 imply endorsement of any Modified Version.
36448 @strong{5. COMBINING DOCUMENTS}
36450 You may combine the Document with other documents released under this
36451 License, under the terms defined in section 4 above for modified
36452 versions, provided that you include in the combination all of the
36453 Invariant Sections of all of the original documents, unmodified, and
36454 list them all as Invariant Sections of your combined work in its
36455 license notice, and that you preserve all their Warranty Disclaimers.
36457 The combined work need only contain one copy of this License, and
36458 multiple identical Invariant Sections may be replaced with a single
36459 copy. If there are multiple Invariant Sections with the same name but
36460 different contents, make the title of each such section unique by
36461 adding at the end of it, in parentheses, the name of the original
36462 author or publisher of that section if known, or else a unique number.
36463 Make the same adjustment to the section titles in the list of
36464 Invariant Sections in the license notice of the combined work.
36466 In the combination, you must combine any sections Entitled "History"
36467 in the various original documents, forming one section Entitled
36468 "History"; likewise combine any sections Entitled "Acknowledgements",
36469 and any sections Entitled "Dedications". You must delete all sections
36470 Entitled "Endorsements".
36472 @strong{6. COLLECTIONS OF DOCUMENTS}
36474 You may make a collection consisting of the Document and other documents
36475 released under this License, and replace the individual copies of this
36476 License in the various documents with a single copy that is included in
36477 the collection, provided that you follow the rules of this License for
36478 verbatim copying of each of the documents in all other respects.
36480 You may extract a single document from such a collection, and distribute
36481 it individually under this License, provided you insert a copy of this
36482 License into the extracted document, and follow this License in all
36483 other respects regarding verbatim copying of that document.
36485 @strong{7. AGGREGATION WITH INDEPENDENT WORKS}
36487 A compilation of the Document or its derivatives with other separate
36488 and independent documents or works, in or on a volume of a storage or
36489 distribution medium, is called an "aggregate" if the copyright
36490 resulting from the compilation is not used to limit the legal rights
36491 of the compilation's users beyond what the individual works permit.
36492 When the Document is included in an aggregate, this License does not
36493 apply to the other works in the aggregate which are not themselves
36494 derivative works of the Document.
36496 If the Cover Text requirement of section 3 is applicable to these
36497 copies of the Document, then if the Document is less than one half of
36498 the entire aggregate, the Document's Cover Texts may be placed on
36499 covers that bracket the Document within the aggregate, or the
36500 electronic equivalent of covers if the Document is in electronic form.
36501 Otherwise they must appear on printed covers that bracket the whole
36504 @strong{8. TRANSLATION}
36506 Translation is considered a kind of modification, so you may
36507 distribute translations of the Document under the terms of section 4.
36508 Replacing Invariant Sections with translations requires special
36509 permission from their copyright holders, but you may include
36510 translations of some or all Invariant Sections in addition to the
36511 original versions of these Invariant Sections. You may include a
36512 translation of this License, and all the license notices in the
36513 Document, and any Warranty Disclaimers, provided that you also include
36514 the original English version of this License and the original versions
36515 of those notices and disclaimers. In case of a disagreement between
36516 the translation and the original version of this License or a notice
36517 or disclaimer, the original version will prevail.
36519 If a section in the Document is Entitled "Acknowledgements",
36520 "Dedications", or "History", the requirement (section 4) to Preserve
36521 its Title (section 1) will typically require changing the actual
36524 @strong{9. TERMINATION}
36526 You may not copy, modify, sublicense, or distribute the Document
36527 except as expressly provided under this License. Any attempt
36528 otherwise to copy, modify, sublicense, or distribute it is void, and
36529 will automatically terminate your rights under this License.
36531 However, if you cease all violation of this License, then your license
36532 from a particular copyright holder is reinstated (a) provisionally,
36533 unless and until the copyright holder explicitly and finally
36534 terminates your license, and (b) permanently, if the copyright holder
36535 fails to notify you of the violation by some reasonable means prior to
36536 60 days after the cessation.
36538 Moreover, your license from a particular copyright holder is
36539 reinstated permanently if the copyright holder notifies you of the
36540 violation by some reasonable means, this is the first time you have
36541 received notice of violation of this License (for any work) from that
36542 copyright holder, and you cure the violation prior to 30 days after
36543 your receipt of the notice.
36545 Termination of your rights under this section does not terminate the
36546 licenses of parties who have received copies or rights from you under
36547 this License. If your rights have been terminated and not permanently
36548 reinstated, receipt of a copy of some or all of the same material does
36549 not give you any rights to use it.
36551 @strong{10. FUTURE REVISIONS OF THIS LICENSE}
36553 The Free Software Foundation may publish new, revised versions
36554 of the GNU Free Documentation License from time to time. Such new
36555 versions will be similar in spirit to the present version, but may
36556 differ in detail to address new problems or concerns. See
36557 @indicateurl{http://www.gnu.org/copyleft/}.
36559 Each version of the License is given a distinguishing version number.
36560 If the Document specifies that a particular numbered version of this
36561 License "or any later version" applies to it, you have the option of
36562 following the terms and conditions either of that specified version or
36563 of any later version that has been published (not as a draft) by the
36564 Free Software Foundation. If the Document does not specify a version
36565 number of this License, you may choose any version ever published (not
36566 as a draft) by the Free Software Foundation. If the Document
36567 specifies that a proxy can decide which future versions of this
36568 License can be used, that proxy's public statement of acceptance of a
36569 version permanently authorizes you to choose that version for the
36572 @strong{11. RELICENSING}
36574 "Massive Multiauthor Collaboration Site" (or "MMC Site") means any
36575 World Wide Web server that publishes copyrightable works and also
36576 provides prominent facilities for anybody to edit those works. A
36577 public wiki that anybody can edit is an example of such a server. A
36578 "Massive Multiauthor Collaboration" (or "MMC") contained in the
36579 site means any set of copyrightable works thus published on the MMC
36582 "CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0
36583 license published by Creative Commons Corporation, a not-for-profit
36584 corporation with a principal place of business in San Francisco,
36585 California, as well as future copyleft versions of that license
36586 published by that same organization.
36588 "Incorporate" means to publish or republish a Document, in whole or
36589 in part, as part of another Document.
36591 An MMC is "eligible for relicensing" if it is licensed under this
36592 License, and if all works that were first published under this License
36593 somewhere other than this MMC, and subsequently incorporated in whole
36594 or in part into the MMC, (1) had no cover texts or invariant sections,
36595 and (2) were thus incorporated prior to November 1, 2008.
36597 The operator of an MMC Site may republish an MMC contained in the site
36598 under CC-BY-SA on the same site at any time before August 1, 2009,
36599 provided the MMC is eligible for relicensing.
36601 @strong{ADDENDUM: How to use this License for your documents}
36603 To use this License in a document you have written, include a copy of
36604 the License in the document and put the following copyright and
36605 license notices just after the title page:
36609 Copyright © YEAR YOUR NAME.
36610 Permission is granted to copy, distribute and/or modify this document
36611 under the terms of the GNU Free Documentation License, Version 1.3
36612 or any later version published by the Free Software Foundation;
36613 with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
36614 A copy of the license is included in the section entitled "GNU
36615 Free Documentation License".
36618 If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
36619 replace the "with ... Texts." line with this:
36623 with the Invariant Sections being LIST THEIR TITLES, with the
36624 Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
36627 If you have Invariant Sections without Cover Texts, or some other
36628 combination of the three, merge those two alternatives to suit the
36631 If your document contains nontrivial examples of program code, we
36632 recommend releasing these examples in parallel under your choice of
36633 free software license, such as the GNU General Public License,
36634 to permit their use in free software.
36636 @node Index,,GNU Free Documentation License,Top