1\input texinfo   @c -*-texinfo-*-
2@c %**start of header
3@setfilename gnat_ugn.info
4@documentencoding UTF-8
5@ifinfo
6@*Generated by Sphinx 1.4.6.@*
7@end ifinfo
8@settitle GNAT User's Guide for Native Platforms
9@defindex ge
10@paragraphindent 0
11@exampleindent 4
12@finalout
13@dircategory GNU Ada Tools
14@direntry
15* gnat_ugn: (gnat_ugn.info). gnat_ugn
16@end direntry
17
18@definfoenclose strong,`,'
19@definfoenclose emph,`,'
20@c %**end of header
21
22@copying
23@quotation
24GNAT User's Guide for Native Platforms , Dec 05, 2018
25
26AdaCore
27
28Copyright @copyright{} 2008-2019, Free Software Foundation
29@end quotation
30
31@end copying
32
33@titlepage
34@title GNAT User's Guide for Native Platforms
35@insertcopying
36@end titlepage
37@contents
38
39@c %** start of user preamble
40
41@c %** end of user preamble
42
43@ifnottex
44@node Top
45@top GNAT User's Guide for Native Platforms
46@insertcopying
47@end ifnottex
48
49@c %**start of body
50@anchor{gnat_ugn doc}@anchor{0}
51@emph{GNAT, The GNU Ada Development Environment}
52
53
54@include gcc-common.texi
55GCC version @value{version-GCC}@*
56AdaCore
57
58Permission is granted to copy, distribute and/or modify this document
59under the terms of the GNU Free Documentation License, Version 1.3 or
60any later version published by the Free Software Foundation; with no
61Invariant Sections, with the Front-Cover Texts being
62"GNAT User's Guide for Native Platforms",
63and with no Back-Cover Texts.  A copy of the license is
64included in the section entitled @ref{1,,GNU Free Documentation License}.
65
66@menu
67* About This Guide::
68* Getting Started with GNAT::
69* The GNAT Compilation Model::
70* Building Executable Programs with GNAT::
71* GNAT Utility Programs::
72* GNAT and Program Execution::
73* Platform-Specific Information::
74* Example of Binder Output File::
75* Elaboration Order Handling in GNAT::
76* Inline Assembler::
77* GNU Free Documentation License::
78* Index::
79
80@detailmenu
81 --- The Detailed Node Listing ---
82
83About This Guide
84
85* What This Guide Contains::
86* What You Should Know before Reading This Guide::
87* Related Information::
88* A Note to Readers of Previous Versions of the Manual::
89* Conventions::
90
91Getting Started with GNAT
92
93* Running GNAT::
94* Running a Simple Ada Program::
95* Running a Program with Multiple Units::
96* Using the gnatmake Utility::
97
98The GNAT Compilation Model
99
100* Source Representation::
101* Foreign Language Representation::
102* File Naming Topics and Utilities::
103* Configuration Pragmas::
104* Generating Object Files::
105* Source Dependencies::
106* The Ada Library Information Files::
107* Binding an Ada Program::
108* GNAT and Libraries::
109* Conditional Compilation::
110* Mixed Language Programming::
111* GNAT and Other Compilation Models::
112* Using GNAT Files with External Tools::
113
114Foreign Language Representation
115
116* Latin-1::
117* Other 8-Bit Codes::
118* Wide_Character Encodings::
119* Wide_Wide_Character Encodings::
120
121File Naming Topics and Utilities
122
123* File Naming Rules::
124* Using Other File Names::
125* Alternative File Naming Schemes::
126* Handling Arbitrary File Naming Conventions with gnatname::
127* File Name Krunching with gnatkr::
128* Renaming Files with gnatchop::
129
130Handling Arbitrary File Naming Conventions with gnatname
131
132* Arbitrary File Naming Conventions::
133* Running gnatname::
134* Switches for gnatname::
135* Examples of gnatname Usage::
136
137File Name Krunching with gnatkr
138
139* About gnatkr::
140* Using gnatkr::
141* Krunching Method::
142* Examples of gnatkr Usage::
143
144Renaming Files with gnatchop
145
146* Handling Files with Multiple Units::
147* Operating gnatchop in Compilation Mode::
148* Command Line for gnatchop::
149* Switches for gnatchop::
150* Examples of gnatchop Usage::
151
152Configuration Pragmas
153
154* Handling of Configuration Pragmas::
155* The Configuration Pragmas Files::
156
157GNAT and Libraries
158
159* Introduction to Libraries in GNAT::
160* General Ada Libraries::
161* Stand-alone Ada Libraries::
162* Rebuilding the GNAT Run-Time Library::
163
164General Ada Libraries
165
166* Building a library::
167* Installing a library::
168* Using a library::
169
170Stand-alone Ada Libraries
171
172* Introduction to Stand-alone Libraries::
173* Building a Stand-alone Library::
174* Creating a Stand-alone Library to be used in a non-Ada context::
175* Restrictions in Stand-alone Libraries::
176
177Conditional Compilation
178
179* Modeling Conditional Compilation in Ada::
180* Preprocessing with gnatprep::
181* Integrated Preprocessing::
182
183Modeling Conditional Compilation in Ada
184
185* Use of Boolean Constants::
186* Debugging - A Special Case::
187* Conditionalizing Declarations::
188* Use of Alternative Implementations::
189* Preprocessing::
190
191Preprocessing with gnatprep
192
193* Preprocessing Symbols::
194* Using gnatprep::
195* Switches for gnatprep::
196* Form of Definitions File::
197* Form of Input Text for gnatprep::
198
199Mixed Language Programming
200
201* Interfacing to C::
202* Calling Conventions::
203* Building Mixed Ada and C++ Programs::
204* Generating Ada Bindings for C and C++ headers::
205* Generating C Headers for Ada Specifications::
206
207Building Mixed Ada and C++ Programs
208
209* Interfacing to C++::
210* Linking a Mixed C++ & Ada Program::
211* A Simple Example::
212* Interfacing with C++ constructors::
213* Interfacing with C++ at the Class Level::
214
215Generating Ada Bindings for C and C++ headers
216
217* Running the Binding Generator::
218* Generating Bindings for C++ Headers::
219* Switches::
220
221Generating C Headers for Ada Specifications
222
223* Running the C Header Generator::
224
225GNAT and Other Compilation Models
226
227* Comparison between GNAT and C/C++ Compilation Models::
228* Comparison between GNAT and Conventional Ada Library Models::
229
230Using GNAT Files with External Tools
231
232* Using Other Utility Programs with GNAT::
233* The External Symbol Naming Scheme of GNAT::
234
235Building Executable Programs with GNAT
236
237* Building with gnatmake::
238* Compiling with gcc::
239* Compiler Switches::
240* Linker Switches::
241* Binding with gnatbind::
242* Linking with gnatlink::
243* Using the GNU make Utility::
244
245Building with gnatmake
246
247* Running gnatmake::
248* Switches for gnatmake::
249* Mode Switches for gnatmake::
250* Notes on the Command Line::
251* How gnatmake Works::
252* Examples of gnatmake Usage::
253
254Compiling with gcc
255
256* Compiling Programs::
257* Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL.
258* Order of Compilation Issues::
259* Examples::
260
261Compiler Switches
262
263* Alphabetical List of All Switches::
264* Output and Error Message Control::
265* Warning Message Control::
266* Debugging and Assertion Control::
267* Validity Checking::
268* Style Checking::
269* Run-Time Checks::
270* Using gcc for Syntax Checking::
271* Using gcc for Semantic Checking::
272* Compiling Different Versions of Ada::
273* Character Set Control::
274* File Naming Control::
275* Subprogram Inlining Control::
276* Auxiliary Output Control::
277* Debugging Control::
278* Exception Handling Control::
279* Units to Sources Mapping Files::
280* Code Generation Control::
281
282Binding with gnatbind
283
284* Running gnatbind::
285* Switches for gnatbind::
286* Command-Line Access::
287* Search Paths for gnatbind::
288* Examples of gnatbind Usage::
289
290Switches for gnatbind
291
292* Consistency-Checking Modes::
293* Binder Error Message Control::
294* Elaboration Control::
295* Output Control::
296* Dynamic Allocation Control::
297* Binding with Non-Ada Main Programs::
298* Binding Programs with No Main Subprogram::
299
300Linking with gnatlink
301
302* Running gnatlink::
303* Switches for gnatlink::
304
305Using the GNU make Utility
306
307* Using gnatmake in a Makefile::
308* Automatically Creating a List of Directories::
309* Generating the Command Line Switches::
310* Overcoming Command Line Length Limits::
311
312GNAT Utility Programs
313
314* The File Cleanup Utility gnatclean::
315* The GNAT Library Browser gnatls::
316* The Cross-Referencing Tools gnatxref and gnatfind::
317* The Ada to HTML Converter gnathtml::
318
319The File Cleanup Utility gnatclean
320
321* Running gnatclean::
322* Switches for gnatclean::
323
324The GNAT Library Browser gnatls
325
326* Running gnatls::
327* Switches for gnatls::
328* Example of gnatls Usage::
329
330The Cross-Referencing Tools gnatxref and gnatfind
331
332* gnatxref Switches::
333* gnatfind Switches::
334* Configuration Files for gnatxref and gnatfind::
335* Regular Expressions in gnatfind and gnatxref::
336* Examples of gnatxref Usage::
337* Examples of gnatfind Usage::
338
339Examples of gnatxref Usage
340
341* General Usage::
342* Using gnatxref with vi::
343
344The Ada to HTML Converter gnathtml
345
346* Invoking gnathtml::
347* Installing gnathtml::
348
349GNAT and Program Execution
350
351* Running and Debugging Ada Programs::
352* Profiling::
353* Improving Performance::
354* Overflow Check Handling in GNAT::
355* Performing Dimensionality Analysis in GNAT::
356* Stack Related Facilities::
357* Memory Management Issues::
358
359Running and Debugging Ada Programs
360
361* The GNAT Debugger GDB::
362* Running GDB::
363* Introduction to GDB Commands::
364* Using Ada Expressions::
365* Calling User-Defined Subprograms::
366* Using the next Command in a Function::
367* Stopping When Ada Exceptions Are Raised::
368* Ada Tasks::
369* Debugging Generic Units::
370* Remote Debugging with gdbserver::
371* GNAT Abnormal Termination or Failure to Terminate::
372* Naming Conventions for GNAT Source Files::
373* Getting Internal Debugging Information::
374* Stack Traceback::
375* Pretty-Printers for the GNAT runtime::
376
377Stack Traceback
378
379* Non-Symbolic Traceback::
380* Symbolic Traceback::
381
382Profiling
383
384* Profiling an Ada Program with gprof::
385
386Profiling an Ada Program with gprof
387
388* Compilation for profiling::
389* Program execution::
390* Running gprof::
391* Interpretation of profiling results::
392
393Improving Performance
394
395* Performance Considerations::
396* Text_IO Suggestions::
397* Reducing Size of Executables with Unused Subprogram/Data Elimination::
398
399Performance Considerations
400
401* Controlling Run-Time Checks::
402* Use of Restrictions::
403* Optimization Levels::
404* Debugging Optimized Code::
405* Inlining of Subprograms::
406* Floating_Point_Operations::
407* Vectorization of loops::
408* Other Optimization Switches::
409* Optimization and Strict Aliasing::
410* Aliased Variables and Optimization::
411* Atomic Variables and Optimization::
412* Passive Task Optimization::
413
414Reducing Size of Executables with Unused Subprogram/Data Elimination
415
416* About unused subprogram/data elimination::
417* Compilation options::
418* Example of unused subprogram/data elimination::
419
420Overflow Check Handling in GNAT
421
422* Background::
423* Management of Overflows in GNAT::
424* Specifying the Desired Mode::
425* Default Settings::
426* Implementation Notes::
427
428Stack Related Facilities
429
430* Stack Overflow Checking::
431* Static Stack Usage Analysis::
432* Dynamic Stack Usage Analysis::
433
434Memory Management Issues
435
436* Some Useful Memory Pools::
437* The GNAT Debug Pool Facility::
438
439Platform-Specific Information
440
441* Run-Time Libraries::
442* Specifying a Run-Time Library::
443* GNU/Linux Topics::
444* Microsoft Windows Topics::
445* Mac OS Topics::
446
447Run-Time Libraries
448
449* Summary of Run-Time Configurations::
450
451Specifying a Run-Time Library
452
453* Choosing the Scheduling Policy::
454
455GNU/Linux Topics
456
457* Required Packages on GNU/Linux::
458
459Microsoft Windows Topics
460
461* Using GNAT on Windows::
462* Using a network installation of GNAT::
463* CONSOLE and WINDOWS subsystems::
464* Temporary Files::
465* Disabling Command Line Argument Expansion::
466* Mixed-Language Programming on Windows::
467* Windows Specific Add-Ons::
468
469Mixed-Language Programming on Windows
470
471* Windows Calling Conventions::
472* Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs.
473* Using DLLs with GNAT::
474* Building DLLs with GNAT Project files::
475* Building DLLs with GNAT::
476* Building DLLs with gnatdll::
477* Ada DLLs and Finalization::
478* Creating a Spec for Ada DLLs::
479* GNAT and Windows Resources::
480* Using GNAT DLLs from Microsoft Visual Studio Applications::
481* Debugging a DLL::
482* Setting Stack Size from gnatlink::
483* Setting Heap Size from gnatlink::
484
485Windows Calling Conventions
486
487* C Calling Convention::
488* Stdcall Calling Convention::
489* Win32 Calling Convention::
490* DLL Calling Convention::
491
492Using DLLs with GNAT
493
494* Creating an Ada Spec for the DLL Services::
495* Creating an Import Library::
496
497Building DLLs with gnatdll
498
499* Limitations When Using Ada DLLs from Ada::
500* Exporting Ada Entities::
501* Ada DLLs and Elaboration::
502
503Creating a Spec for Ada DLLs
504
505* Creating the Definition File::
506* Using gnatdll::
507
508GNAT and Windows Resources
509
510* Building Resources::
511* Compiling Resources::
512* Using Resources::
513
514Debugging a DLL
515
516* Program and DLL Both Built with GCC/GNAT::
517* Program Built with Foreign Tools and DLL Built with GCC/GNAT::
518
519Windows Specific Add-Ons
520
521* Win32Ada::
522* wPOSIX::
523
524Mac OS Topics
525
526* Codesigning the Debugger::
527
528Elaboration Order Handling in GNAT
529
530* Elaboration Code::
531* Elaboration Order::
532* Checking the Elaboration Order::
533* Controlling the Elaboration Order in Ada::
534* Controlling the Elaboration Order in GNAT::
535* Common Elaboration-model Traits::
536* Dynamic Elaboration Model in GNAT::
537* Static Elaboration Model in GNAT::
538* SPARK Elaboration Model in GNAT::
539* Legacy Elaboration Model in GNAT::
540* Mixing Elaboration Models::
541* Elaboration Circularities::
542* Resolving Elaboration Circularities::
543* Resolving Task Issues::
544* Elaboration-related Compiler Switches::
545* Summary of Procedures for Elaboration Control::
546* Inspecting the Chosen Elaboration Order::
547
548Inline Assembler
549
550* Basic Assembler Syntax::
551* A Simple Example of Inline Assembler::
552* Output Variables in Inline Assembler::
553* Input Variables in Inline Assembler::
554* Inlining Inline Assembler Code::
555* Other Asm Functionality::
556
557Other Asm Functionality
558
559* The Clobber Parameter::
560* The Volatile Parameter::
561
562@end detailmenu
563@end menu
564
565@node About This Guide,Getting Started with GNAT,Top,Top
566@anchor{gnat_ugn/about_this_guide about-this-guide}@anchor{2}@anchor{gnat_ugn/about_this_guide doc}@anchor{3}@anchor{gnat_ugn/about_this_guide gnat-user-s-guide-for-native-platforms}@anchor{4}@anchor{gnat_ugn/about_this_guide id1}@anchor{5}
567@chapter About This Guide
568
569
570
571This guide describes the use of GNAT,
572a compiler and software development
573toolset for the full Ada programming language.
574It documents the features of the compiler and tools, and explains
575how to use them to build Ada applications.
576
577GNAT implements Ada 95, Ada 2005 and Ada 2012, and it may also be
578invoked in Ada 83 compatibility mode.
579By default, GNAT assumes Ada 2012, but you can override with a
580compiler switch (@ref{6,,Compiling Different Versions of Ada})
581to explicitly specify the language version.
582Throughout this manual, references to 'Ada' without a year suffix
583apply to all Ada 95/2005/2012 versions of the language.
584
585@menu
586* What This Guide Contains::
587* What You Should Know before Reading This Guide::
588* Related Information::
589* A Note to Readers of Previous Versions of the Manual::
590* Conventions::
591
592@end menu
593
594@node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
595@anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
596@section What This Guide Contains
597
598
599This guide contains the following chapters:
600
601
602@itemize *
603
604@item
605@ref{8,,Getting Started with GNAT} describes how to get started compiling
606and running Ada programs with the GNAT Ada programming environment.
607
608@item
609@ref{9,,The GNAT Compilation Model} describes the compilation model used
610by GNAT.
611
612@item
613@ref{a,,Building Executable Programs with GNAT} describes how to use the
614main GNAT tools to build executable programs, and it also gives examples of
615using the GNU make utility with GNAT.
616
617@item
618@ref{b,,GNAT Utility Programs} explains the various utility programs that
619are included in the GNAT environment
620
621@item
622@ref{c,,GNAT and Program Execution} covers a number of topics related to
623running, debugging, and tuning the performace of programs developed
624with GNAT
625@end itemize
626
627Appendices cover several additional topics:
628
629
630@itemize *
631
632@item
633@ref{d,,Platform-Specific Information} describes the different run-time
634library implementations and also presents information on how to use
635GNAT on several specific platforms
636
637@item
638@ref{e,,Example of Binder Output File} shows the source code for the binder
639output file for a sample program.
640
641@item
642@ref{f,,Elaboration Order Handling in GNAT} describes how GNAT helps
643you deal with elaboration order issues.
644
645@item
646@ref{10,,Inline Assembler} shows how to use the inline assembly facility
647in an Ada program.
648@end itemize
649
650@node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
651@anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{11}
652@section What You Should Know before Reading This Guide
653
654
655@geindex Ada 95 Language Reference Manual
656
657@geindex Ada 2005 Language Reference Manual
658
659This guide assumes a basic familiarity with the Ada 95 language, as
660described in the International Standard ANSI/ISO/IEC-8652:1995, January
6611995.
662It does not require knowledge of the features introduced by Ada 2005
663or Ada 2012.
664Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
665the GNAT documentation package.
666
667@node Related Information,A Note to Readers of Previous Versions of the Manual,What You Should Know before Reading This Guide,About This Guide
668@anchor{gnat_ugn/about_this_guide related-information}@anchor{12}
669@section Related Information
670
671
672For further information about Ada and related tools, please refer to the
673following documents:
674
675
676@itemize *
677
678@item
679@cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
680@cite{Ada 2012 Reference Manual}, which contain reference
681material for the several revisions of the Ada language standard.
682
683@item
684@cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
685implementation of Ada.
686
687@item
688@cite{Using the GNAT Programming Studio}, which describes the GPS
689Integrated Development Environment.
690
691@item
692@cite{GNAT Programming Studio Tutorial}, which introduces the
693main GPS features through examples.
694
695@item
696@cite{Debugging with GDB},
697for all details on the use of the GNU source-level debugger.
698
699@item
700@cite{GNU Emacs Manual},
701for full information on the extensible editor and programming
702environment Emacs.
703@end itemize
704
705@node A Note to Readers of Previous Versions of the Manual,Conventions,Related Information,About This Guide
706@anchor{gnat_ugn/about_this_guide a-note-to-readers-of-previous-versions-of-the-manual}@anchor{13}
707@section A Note to Readers of Previous Versions of the Manual
708
709
710In early 2015 the GNAT manuals were transitioned to the
711reStructuredText (rst) / Sphinx documentation generator technology.
712During that process the @cite{GNAT User's Guide} was reorganized
713so that related topics would be described together in the same chapter
714or appendix.  Here's a summary of the major changes realized in
715the new document structure.
716
717
718@itemize *
719
720@item
721@ref{9,,The GNAT Compilation Model} has been extended so that it now covers
722the following material:
723
724
725@itemize -
726
727@item
728The @code{gnatname}, @code{gnatkr}, and @code{gnatchop} tools
729
730@item
731@ref{14,,Configuration Pragmas}
732
733@item
734@ref{15,,GNAT and Libraries}
735
736@item
737@ref{16,,Conditional Compilation} including @ref{17,,Preprocessing with gnatprep}
738and @ref{18,,Integrated Preprocessing}
739
740@item
741@ref{19,,Generating Ada Bindings for C and C++ headers}
742
743@item
744@ref{1a,,Using GNAT Files with External Tools}
745@end itemize
746
747@item
748@ref{a,,Building Executable Programs with GNAT} is a new chapter consolidating
749the following content:
750
751
752@itemize -
753
754@item
755@ref{1b,,Building with gnatmake}
756
757@item
758@ref{1c,,Compiling with gcc}
759
760@item
761@ref{1d,,Binding with gnatbind}
762
763@item
764@ref{1e,,Linking with gnatlink}
765
766@item
767@ref{1f,,Using the GNU make Utility}
768@end itemize
769
770@item
771@ref{b,,GNAT Utility Programs} is a new chapter consolidating the information about several
772GNAT tools:
773
774
775
776@itemize -
777
778@item
779@ref{20,,The File Cleanup Utility gnatclean}
780
781@item
782@ref{21,,The GNAT Library Browser gnatls}
783
784@item
785@ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
786
787@item
788@ref{23,,The Ada to HTML Converter gnathtml}
789@end itemize
790
791@item
792@ref{c,,GNAT and Program Execution} is a new chapter consolidating the following:
793
794
795@itemize -
796
797@item
798@ref{24,,Running and Debugging Ada Programs}
799
800@item
801@ref{25,,Profiling}
802
803@item
804@ref{26,,Improving Performance}
805
806@item
807@ref{27,,Overflow Check Handling in GNAT}
808
809@item
810@ref{28,,Performing Dimensionality Analysis in GNAT}
811
812@item
813@ref{29,,Stack Related Facilities}
814
815@item
816@ref{2a,,Memory Management Issues}
817@end itemize
818
819@item
820@ref{d,,Platform-Specific Information} is a new appendix consolidating the following:
821
822
823@itemize -
824
825@item
826@ref{2b,,Run-Time Libraries}
827
828@item
829@ref{2c,,Microsoft Windows Topics}
830
831@item
832@ref{2d,,Mac OS Topics}
833@end itemize
834
835@item
836The @emph{Compatibility and Porting Guide} appendix has been moved to the
837@cite{GNAT Reference Manual}. It now includes a section
838@emph{Writing Portable Fixed-Point Declarations} which was previously
839a separate chapter in the @cite{GNAT User's Guide}.
840@end itemize
841
842@node Conventions,,A Note to Readers of Previous Versions of the Manual,About This Guide
843@anchor{gnat_ugn/about_this_guide conventions}@anchor{2e}
844@section Conventions
845
846
847@geindex Conventions
848@geindex typographical
849
850@geindex Typographical conventions
851
852Following are examples of the typographical and graphic conventions used
853in this guide:
854
855
856@itemize *
857
858@item
859@code{Functions}, @code{utility program names}, @code{standard names},
860and @code{classes}.
861
862@item
863@code{Option flags}
864
865@item
866@code{File names}
867
868@item
869@code{Variables}
870
871@item
872@emph{Emphasis}
873
874@item
875[optional information or parameters]
876
877@item
878Examples are described by text
879
880@example
881and then shown this way.
882@end example
883
884@item
885Commands that are entered by the user are shown as preceded by a prompt string
886comprising the @code{$} character followed by a space.
887
888@item
889Full file names are shown with the '/' character
890as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
891If you are using GNAT on a Windows platform, please note that
892the '\' character should be used instead.
893@end itemize
894
895@node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
896@anchor{gnat_ugn/getting_started_with_gnat getting-started-with-gnat}@anchor{8}@anchor{gnat_ugn/getting_started_with_gnat doc}@anchor{2f}@anchor{gnat_ugn/getting_started_with_gnat id1}@anchor{30}
897@chapter Getting Started with GNAT
898
899
900This chapter describes how to use GNAT's command line interface to build
901executable Ada programs.
902On most platforms a visually oriented Integrated Development Environment
903is also available, the GNAT Programming Studio (GPS).
904GPS offers a graphical "look and feel", support for development in
905other programming languages, comprehensive browsing features, and
906many other capabilities.
907For information on GPS please refer to
908@cite{Using the GNAT Programming Studio}.
909
910@menu
911* Running GNAT::
912* Running a Simple Ada Program::
913* Running a Program with Multiple Units::
914* Using the gnatmake Utility::
915
916@end menu
917
918@node Running GNAT,Running a Simple Ada Program,,Getting Started with GNAT
919@anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{31}@anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{32}
920@section Running GNAT
921
922
923Three steps are needed to create an executable file from an Ada source
924file:
925
926
927@itemize *
928
929@item
930The source file(s) must be compiled.
931
932@item
933The file(s) must be bound using the GNAT binder.
934
935@item
936All appropriate object files must be linked to produce an executable.
937@end itemize
938
939All three steps are most commonly handled by using the @code{gnatmake}
940utility program that, given the name of the main program, automatically
941performs the necessary compilation, binding and linking steps.
942
943@node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
944@anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{33}@anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{34}
945@section Running a Simple Ada Program
946
947
948Any text editor may be used to prepare an Ada program.
949(If Emacs is used, the optional Ada mode may be helpful in laying out the
950program.)
951The program text is a normal text file. We will assume in our initial
952example that you have used your editor to prepare the following
953standard format text file:
954
955@example
956with Ada.Text_IO; use Ada.Text_IO;
957procedure Hello is
958begin
959   Put_Line ("Hello WORLD!");
960end Hello;
961@end example
962
963This file should be named @code{hello.adb}.
964With the normal default file naming conventions, GNAT requires
965that each file
966contain a single compilation unit whose file name is the
967unit name,
968with periods replaced by hyphens; the
969extension is @code{ads} for a
970spec and @code{adb} for a body.
971You can override this default file naming convention by use of the
972special pragma @code{Source_File_Name} (for further information please
973see @ref{35,,Using Other File Names}).
974Alternatively, if you want to rename your files according to this default
975convention, which is probably more convenient if you will be using GNAT
976for all your compilations, then the @code{gnatchop} utility
977can be used to generate correctly-named source files
978(see @ref{36,,Renaming Files with gnatchop}).
979
980You can compile the program using the following command (@code{$} is used
981as the command prompt in the examples in this document):
982
983@example
984$ gcc -c hello.adb
985@end example
986
987@code{gcc} is the command used to run the compiler. This compiler is
988capable of compiling programs in several languages, including Ada and
989C. It assumes that you have given it an Ada program if the file extension is
990either @code{.ads} or @code{.adb}, and it will then call
991the GNAT compiler to compile the specified file.
992
993The @code{-c} switch is required. It tells @code{gcc} to only do a
994compilation. (For C programs, @code{gcc} can also do linking, but this
995capability is not used directly for Ada programs, so the @code{-c}
996switch must always be present.)
997
998This compile command generates a file
999@code{hello.o}, which is the object
1000file corresponding to your Ada program. It also generates
1001an 'Ada Library Information' file @code{hello.ali},
1002which contains additional information used to check
1003that an Ada program is consistent.
1004To build an executable file,
1005use @code{gnatbind} to bind the program
1006and @code{gnatlink} to link it. The
1007argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1008@code{ALI} file, but the default extension of @code{.ali} can
1009be omitted. This means that in the most common case, the argument
1010is simply the name of the main program:
1011
1012@example
1013$ gnatbind hello
1014$ gnatlink hello
1015@end example
1016
1017A simpler method of carrying out these steps is to use @code{gnatmake},
1018a master program that invokes all the required
1019compilation, binding and linking tools in the correct order. In particular,
1020@code{gnatmake} automatically recompiles any sources that have been
1021modified since they were last compiled, or sources that depend
1022on such modified sources, so that 'version skew' is avoided.
1023
1024@geindex Version skew (avoided by `@w{`}gnatmake`@w{`})
1025
1026@example
1027$ gnatmake hello.adb
1028@end example
1029
1030The result is an executable program called @code{hello}, which can be
1031run by entering:
1032
1033@example
1034$ hello
1035@end example
1036
1037assuming that the current directory is on the search path
1038for executable programs.
1039
1040and, if all has gone well, you will see:
1041
1042@example
1043Hello WORLD!
1044@end example
1045
1046appear in response to this command.
1047
1048@node Running a Program with Multiple Units,Using the gnatmake Utility,Running a Simple Ada Program,Getting Started with GNAT
1049@anchor{gnat_ugn/getting_started_with_gnat id4}@anchor{37}@anchor{gnat_ugn/getting_started_with_gnat running-a-program-with-multiple-units}@anchor{38}
1050@section Running a Program with Multiple Units
1051
1052
1053Consider a slightly more complicated example that has three files: a
1054main program, and the spec and body of a package:
1055
1056@example
1057package Greetings is
1058   procedure Hello;
1059   procedure Goodbye;
1060end Greetings;
1061
1062with Ada.Text_IO; use Ada.Text_IO;
1063package body Greetings is
1064   procedure Hello is
1065   begin
1066      Put_Line ("Hello WORLD!");
1067   end Hello;
1068
1069   procedure Goodbye is
1070   begin
1071      Put_Line ("Goodbye WORLD!");
1072   end Goodbye;
1073end Greetings;
1074
1075with Greetings;
1076procedure Gmain is
1077begin
1078   Greetings.Hello;
1079   Greetings.Goodbye;
1080end Gmain;
1081@end example
1082
1083Following the one-unit-per-file rule, place this program in the
1084following three separate files:
1085
1086
1087@table @asis
1088
1089@item @emph{greetings.ads}
1090
1091spec of package @code{Greetings}
1092
1093@item @emph{greetings.adb}
1094
1095body of package @code{Greetings}
1096
1097@item @emph{gmain.adb}
1098
1099body of main program
1100@end table
1101
1102To build an executable version of
1103this program, we could use four separate steps to compile, bind, and link
1104the program, as follows:
1105
1106@example
1107$ gcc -c gmain.adb
1108$ gcc -c greetings.adb
1109$ gnatbind gmain
1110$ gnatlink gmain
1111@end example
1112
1113Note that there is no required order of compilation when using GNAT.
1114In particular it is perfectly fine to compile the main program first.
1115Also, it is not necessary to compile package specs in the case where
1116there is an accompanying body; you only need to compile the body. If you want
1117to submit these files to the compiler for semantic checking and not code
1118generation, then use the @code{-gnatc} switch:
1119
1120@example
1121$ gcc -c greetings.ads -gnatc
1122@end example
1123
1124Although the compilation can be done in separate steps as in the
1125above example, in practice it is almost always more convenient
1126to use the @code{gnatmake} tool. All you need to know in this case
1127is the name of the main program's source file. The effect of the above four
1128commands can be achieved with a single one:
1129
1130@example
1131$ gnatmake gmain.adb
1132@end example
1133
1134In the next section we discuss the advantages of using @code{gnatmake} in
1135more detail.
1136
1137@node Using the gnatmake Utility,,Running a Program with Multiple Units,Getting Started with GNAT
1138@anchor{gnat_ugn/getting_started_with_gnat using-the-gnatmake-utility}@anchor{39}@anchor{gnat_ugn/getting_started_with_gnat id5}@anchor{3a}
1139@section Using the @code{gnatmake} Utility
1140
1141
1142If you work on a program by compiling single components at a time using
1143@code{gcc}, you typically keep track of the units you modify. In order to
1144build a consistent system, you compile not only these units, but also any
1145units that depend on the units you have modified.
1146For example, in the preceding case,
1147if you edit @code{gmain.adb}, you only need to recompile that file. But if
1148you edit @code{greetings.ads}, you must recompile both
1149@code{greetings.adb} and @code{gmain.adb}, because both files contain
1150units that depend on @code{greetings.ads}.
1151
1152@code{gnatbind} will warn you if you forget one of these compilation
1153steps, so that it is impossible to generate an inconsistent program as a
1154result of forgetting to do a compilation. Nevertheless it is tedious and
1155error-prone to keep track of dependencies among units.
1156One approach to handle the dependency-bookkeeping is to use a
1157makefile. However, makefiles present maintenance problems of their own:
1158if the dependencies change as you change the program, you must make
1159sure that the makefile is kept up-to-date manually, which is also an
1160error-prone process.
1161
1162The @code{gnatmake} utility takes care of these details automatically.
1163Invoke it using either one of the following forms:
1164
1165@example
1166$ gnatmake gmain.adb
1167$ gnatmake gmain
1168@end example
1169
1170The argument is the name of the file containing the main program;
1171you may omit the extension. @code{gnatmake}
1172examines the environment, automatically recompiles any files that need
1173recompiling, and binds and links the resulting set of object files,
1174generating the executable file, @code{gmain}.
1175In a large program, it
1176can be extremely helpful to use @code{gnatmake}, because working out by hand
1177what needs to be recompiled can be difficult.
1178
1179Note that @code{gnatmake} takes into account all the Ada rules that
1180establish dependencies among units. These include dependencies that result
1181from inlining subprogram bodies, and from
1182generic instantiation. Unlike some other
1183Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1184found by the compiler on a previous compilation, which may possibly
1185be wrong when sources change. @code{gnatmake} determines the exact set of
1186dependencies from scratch each time it is run.
1187
1188@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
1189
1190@node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
1191@anchor{gnat_ugn/the_gnat_compilation_model doc}@anchor{3b}@anchor{gnat_ugn/the_gnat_compilation_model the-gnat-compilation-model}@anchor{9}@anchor{gnat_ugn/the_gnat_compilation_model id1}@anchor{3c}
1192@chapter The GNAT Compilation Model
1193
1194
1195@geindex GNAT compilation model
1196
1197@geindex Compilation model
1198
1199This chapter describes the compilation model used by GNAT. Although
1200similar to that used by other languages such as C and C++, this model
1201is substantially different from the traditional Ada compilation models,
1202which are based on a centralized program library. The chapter covers
1203the following material:
1204
1205
1206@itemize *
1207
1208@item
1209Topics related to source file makeup and naming
1210
1211
1212@itemize *
1213
1214@item
1215@ref{3d,,Source Representation}
1216
1217@item
1218@ref{3e,,Foreign Language Representation}
1219
1220@item
1221@ref{3f,,File Naming Topics and Utilities}
1222@end itemize
1223
1224@item
1225@ref{14,,Configuration Pragmas}
1226
1227@item
1228@ref{40,,Generating Object Files}
1229
1230@item
1231@ref{41,,Source Dependencies}
1232
1233@item
1234@ref{42,,The Ada Library Information Files}
1235
1236@item
1237@ref{43,,Binding an Ada Program}
1238
1239@item
1240@ref{15,,GNAT and Libraries}
1241
1242@item
1243@ref{16,,Conditional Compilation}
1244
1245@item
1246@ref{44,,Mixed Language Programming}
1247
1248@item
1249@ref{45,,GNAT and Other Compilation Models}
1250
1251@item
1252@ref{1a,,Using GNAT Files with External Tools}
1253@end itemize
1254
1255@menu
1256* Source Representation::
1257* Foreign Language Representation::
1258* File Naming Topics and Utilities::
1259* Configuration Pragmas::
1260* Generating Object Files::
1261* Source Dependencies::
1262* The Ada Library Information Files::
1263* Binding an Ada Program::
1264* GNAT and Libraries::
1265* Conditional Compilation::
1266* Mixed Language Programming::
1267* GNAT and Other Compilation Models::
1268* Using GNAT Files with External Tools::
1269
1270@end menu
1271
1272@node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1273@anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{3d}@anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{46}
1274@section Source Representation
1275
1276
1277@geindex Latin-1
1278
1279@geindex VT
1280@geindex HT
1281@geindex CR
1282@geindex LF
1283@geindex FF
1284
1285Ada source programs are represented in standard text files, using
1286Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
12877-bit ASCII set, plus additional characters used for
1288representing foreign languages (see @ref{3e,,Foreign Language Representation}
1289for support of non-USA character sets). The format effector characters
1290are represented using their standard ASCII encodings, as follows:
1291
1292@quotation
1293
1294
1295@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxx}
1296@item
1297
1298Character
1299
1300@tab
1301
1302Effect
1303
1304@tab
1305
1306Code
1307
1308@item
1309
1310@code{VT}
1311
1312@tab
1313
1314Vertical tab
1315
1316@tab
1317
1318@code{16#0B#}
1319
1320@item
1321
1322@code{HT}
1323
1324@tab
1325
1326Horizontal tab
1327
1328@tab
1329
1330@code{16#09#}
1331
1332@item
1333
1334@code{CR}
1335
1336@tab
1337
1338Carriage return
1339
1340@tab
1341
1342@code{16#0D#}
1343
1344@item
1345
1346@code{LF}
1347
1348@tab
1349
1350Line feed
1351
1352@tab
1353
1354@code{16#0A#}
1355
1356@item
1357
1358@code{FF}
1359
1360@tab
1361
1362Form feed
1363
1364@tab
1365
1366@code{16#0C#}
1367
1368@end multitable
1369
1370@end quotation
1371
1372Source files are in standard text file format. In addition, GNAT will
1373recognize a wide variety of stream formats, in which the end of
1374physical lines is marked by any of the following sequences:
1375@code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1376in accommodating files that are imported from other operating systems.
1377
1378@geindex End of source file; Source file@comma{} end
1379
1380@geindex SUB (control character)
1381
1382The end of a source file is normally represented by the physical end of
1383file. However, the control character @code{16#1A#} (@code{SUB}) is also
1384recognized as signalling the end of the source file. Again, this is
1385provided for compatibility with other operating systems where this
1386code is used to represent the end of file.
1387
1388@geindex spec (definition)
1389@geindex compilation (definition)
1390
1391Each file contains a single Ada compilation unit, including any pragmas
1392associated with the unit. For example, this means you must place a
1393package declaration (a package @emph{spec}) and the corresponding body in
1394separate files. An Ada @emph{compilation} (which is a sequence of
1395compilation units) is represented using a sequence of files. Similarly,
1396you will place each subunit or child unit in a separate file.
1397
1398@node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1399@anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{3e}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{47}
1400@section Foreign Language Representation
1401
1402
1403GNAT supports the standard character sets defined in Ada as well as
1404several other non-standard character sets for use in localized versions
1405of the compiler (@ref{48,,Character Set Control}).
1406
1407@menu
1408* Latin-1::
1409* Other 8-Bit Codes::
1410* Wide_Character Encodings::
1411* Wide_Wide_Character Encodings::
1412
1413@end menu
1414
1415@node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1416@anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{49}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{4a}
1417@subsection Latin-1
1418
1419
1420@geindex Latin-1
1421
1422The basic character set is Latin-1. This character set is defined by ISO
1423standard 8859, part 1. The lower half (character codes @code{16#00#}
1424... @code{16#7F#)} is identical to standard ASCII coding, but the upper
1425half is used to represent additional characters. These include extended letters
1426used by European languages, such as French accents, the vowels with umlauts
1427used in German, and the extra letter A-ring used in Swedish.
1428
1429@geindex Ada.Characters.Latin_1
1430
1431For a complete list of Latin-1 codes and their encodings, see the source
1432file of library unit @code{Ada.Characters.Latin_1} in file
1433@code{a-chlat1.ads}.
1434You may use any of these extended characters freely in character or
1435string literals. In addition, the extended characters that represent
1436letters can be used in identifiers.
1437
1438@node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1439@anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{4b}@anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{4c}
1440@subsection Other 8-Bit Codes
1441
1442
1443GNAT also supports several other 8-bit coding schemes:
1444
1445@geindex Latin-2
1446
1447@geindex ISO 8859-2
1448
1449
1450@table @asis
1451
1452@item @emph{ISO 8859-2 (Latin-2)}
1453
1454Latin-2 letters allowed in identifiers, with uppercase and lowercase
1455equivalence.
1456@end table
1457
1458@geindex Latin-3
1459
1460@geindex ISO 8859-3
1461
1462
1463@table @asis
1464
1465@item @emph{ISO 8859-3 (Latin-3)}
1466
1467Latin-3 letters allowed in identifiers, with uppercase and lowercase
1468equivalence.
1469@end table
1470
1471@geindex Latin-4
1472
1473@geindex ISO 8859-4
1474
1475
1476@table @asis
1477
1478@item @emph{ISO 8859-4 (Latin-4)}
1479
1480Latin-4 letters allowed in identifiers, with uppercase and lowercase
1481equivalence.
1482@end table
1483
1484@geindex ISO 8859-5
1485
1486@geindex Cyrillic
1487
1488
1489@table @asis
1490
1491@item @emph{ISO 8859-5 (Cyrillic)}
1492
1493ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1494lowercase equivalence.
1495@end table
1496
1497@geindex ISO 8859-15
1498
1499@geindex Latin-9
1500
1501
1502@table @asis
1503
1504@item @emph{ISO 8859-15 (Latin-9)}
1505
1506ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1507lowercase equivalence
1508@end table
1509
1510@geindex code page 437 (IBM PC)
1511
1512
1513@table @asis
1514
1515@item @emph{IBM PC (code page 437)}
1516
1517This code page is the normal default for PCs in the U.S. It corresponds
1518to the original IBM PC character set. This set has some, but not all, of
1519the extended Latin-1 letters, but these letters do not have the same
1520encoding as Latin-1. In this mode, these letters are allowed in
1521identifiers with uppercase and lowercase equivalence.
1522@end table
1523
1524@geindex code page 850 (IBM PC)
1525
1526
1527@table @asis
1528
1529@item @emph{IBM PC (code page 850)}
1530
1531This code page is a modification of 437 extended to include all the
1532Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1533mode, all these letters are allowed in identifiers with uppercase and
1534lowercase equivalence.
1535
1536@item @emph{Full Upper 8-bit}
1537
1538Any character in the range 80-FF allowed in identifiers, and all are
1539considered distinct. In other words, there are no uppercase and lowercase
1540equivalences in this range. This is useful in conjunction with
1541certain encoding schemes used for some foreign character sets (e.g.,
1542the typical method of representing Chinese characters on the PC).
1543
1544@item @emph{No Upper-Half}
1545
1546No upper-half characters in the range 80-FF are allowed in identifiers.
1547This gives Ada 83 compatibility for identifier names.
1548@end table
1549
1550For precise data on the encodings permitted, and the uppercase and lowercase
1551equivalences that are recognized, see the file @code{csets.adb} in
1552the GNAT compiler sources. You will need to obtain a full source release
1553of GNAT to obtain this file.
1554
1555@node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1556@anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{4d}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{4e}
1557@subsection Wide_Character Encodings
1558
1559
1560GNAT allows wide character codes to appear in character and string
1561literals, and also optionally in identifiers, by means of the following
1562possible encoding schemes:
1563
1564
1565@table @asis
1566
1567@item @emph{Hex Coding}
1568
1569In this encoding, a wide character is represented by the following five
1570character sequence:
1571
1572@example
1573ESC a b c d
1574@end example
1575
1576where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1577characters (using uppercase letters) of the wide character code. For
1578example, ESC A345 is used to represent the wide character with code
1579@code{16#A345#}.
1580This scheme is compatible with use of the full Wide_Character set.
1581
1582@item @emph{Upper-Half Coding}
1583
1584@geindex Upper-Half Coding
1585
1586The wide character with encoding @code{16#abcd#} where the upper bit is on
1587(in other words, 'a' is in the range 8-F) is represented as two bytes,
1588@code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1589character, but is not required to be in the upper half. This method can
1590be also used for shift-JIS or EUC, where the internal coding matches the
1591external coding.
1592
1593@item @emph{Shift JIS Coding}
1594
1595@geindex Shift JIS Coding
1596
1597A wide character is represented by a two-character sequence,
1598@code{16#ab#} and
1599@code{16#cd#}, with the restrictions described for upper-half encoding as
1600described above. The internal character code is the corresponding JIS
1601character according to the standard algorithm for Shift-JIS
1602conversion. Only characters defined in the JIS code set table can be
1603used with this encoding method.
1604
1605@item @emph{EUC Coding}
1606
1607@geindex EUC Coding
1608
1609A wide character is represented by a two-character sequence
1610@code{16#ab#} and
1611@code{16#cd#}, with both characters being in the upper half. The internal
1612character code is the corresponding JIS character according to the EUC
1613encoding algorithm. Only characters defined in the JIS code set table
1614can be used with this encoding method.
1615
1616@item @emph{UTF-8 Coding}
1617
1618A wide character is represented using
1619UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
162010646-1/Am.2. Depending on the character value, the representation
1621is a one, two, or three byte sequence:
1622
1623@example
162416#0000#-16#007f#: 2#0xxxxxxx#
162516#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
162616#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1627@end example
1628
1629where the @code{xxx} bits correspond to the left-padded bits of the
163016-bit character value. Note that all lower half ASCII characters
1631are represented as ASCII bytes and all upper half characters and
1632other wide characters are represented as sequences of upper-half
1633(The full UTF-8 scheme allows for encoding 31-bit characters as
16346-byte sequences, and in the following section on wide wide
1635characters, the use of these sequences is documented).
1636
1637@item @emph{Brackets Coding}
1638
1639In this encoding, a wide character is represented by the following eight
1640character sequence:
1641
1642@example
1643[ " a b c d " ]
1644@end example
1645
1646where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1647characters (using uppercase letters) of the wide character code. For
1648example, ['A345'] is used to represent the wide character with code
1649@code{16#A345#}. It is also possible (though not required) to use the
1650Brackets coding for upper half characters. For example, the code
1651@code{16#A3#} can be represented as @code{['A3']}.
1652
1653This scheme is compatible with use of the full Wide_Character set,
1654and is also the method used for wide character encoding in some standard
1655ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1656@end table
1657
1658@cartouche
1659@quotation Note
1660Some of these coding schemes do not permit the full use of the
1661Ada character set. For example, neither Shift JIS nor EUC allow the
1662use of the upper half of the Latin-1 set.
1663@end quotation
1664@end cartouche
1665
1666@node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1667@anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{4f}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{50}
1668@subsection Wide_Wide_Character Encodings
1669
1670
1671GNAT allows wide wide character codes to appear in character and string
1672literals, and also optionally in identifiers, by means of the following
1673possible encoding schemes:
1674
1675
1676@table @asis
1677
1678@item @emph{UTF-8 Coding}
1679
1680A wide character is represented using
1681UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
168210646-1/Am.2. Depending on the character value, the representation
1683of character codes with values greater than 16#FFFF# is a
1684is a four, five, or six byte sequence:
1685
1686@example
168716#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1688                             10xxxxxx
168916#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1690                             10xxxxxx 10xxxxxx
169116#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1692                             10xxxxxx 10xxxxxx 10xxxxxx
1693@end example
1694
1695where the @code{xxx} bits correspond to the left-padded bits of the
169632-bit character value.
1697
1698@item @emph{Brackets Coding}
1699
1700In this encoding, a wide wide character is represented by the following ten or
1701twelve byte character sequence:
1702
1703@example
1704[ " a b c d e f " ]
1705[ " a b c d e f g h " ]
1706@end example
1707
1708where @code{a-h} are the six or eight hexadecimal
1709characters (using uppercase letters) of the wide wide character code. For
1710example, ["1F4567"] is used to represent the wide wide character with code
1711@code{16#001F_4567#}.
1712
1713This scheme is compatible with use of the full Wide_Wide_Character set,
1714and is also the method used for wide wide character encoding in some standard
1715ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1716@end table
1717
1718@node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1719@anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{3f}
1720@section File Naming Topics and Utilities
1721
1722
1723GNAT has a default file naming scheme and also provides the user with
1724a high degree of control over how the names and extensions of the
1725source files correspond to the Ada compilation units that they contain.
1726
1727@menu
1728* File Naming Rules::
1729* Using Other File Names::
1730* Alternative File Naming Schemes::
1731* Handling Arbitrary File Naming Conventions with gnatname::
1732* File Name Krunching with gnatkr::
1733* Renaming Files with gnatchop::
1734
1735@end menu
1736
1737@node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1738@anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{52}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{53}
1739@subsection File Naming Rules
1740
1741
1742The default file name is determined by the name of the unit that the
1743file contains. The name is formed by taking the full expanded name of
1744the unit and replacing the separating dots with hyphens and using
1745lowercase for all letters.
1746
1747An exception arises if the file name generated by the above rules starts
1748with one of the characters
1749@code{a}, @code{g}, @code{i}, or @code{s}, and the second character is a
1750minus. In this case, the character tilde is used in place
1751of the minus. The reason for this special rule is to avoid clashes with
1752the standard names for child units of the packages System, Ada,
1753Interfaces, and GNAT, which use the prefixes
1754@code{s-}, @code{a-}, @code{i-}, and @code{g-},
1755respectively.
1756
1757The file extension is @code{.ads} for a spec and
1758@code{.adb} for a body. The following table shows some
1759examples of these rules.
1760
1761@quotation
1762
1763
1764@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
1765@item
1766
1767Source File
1768
1769@tab
1770
1771Ada Compilation Unit
1772
1773@item
1774
1775@code{main.ads}
1776
1777@tab
1778
1779Main (spec)
1780
1781@item
1782
1783@code{main.adb}
1784
1785@tab
1786
1787Main (body)
1788
1789@item
1790
1791@code{arith_functions.ads}
1792
1793@tab
1794
1795Arith_Functions (package spec)
1796
1797@item
1798
1799@code{arith_functions.adb}
1800
1801@tab
1802
1803Arith_Functions (package body)
1804
1805@item
1806
1807@code{func-spec.ads}
1808
1809@tab
1810
1811Func.Spec (child package spec)
1812
1813@item
1814
1815@code{func-spec.adb}
1816
1817@tab
1818
1819Func.Spec (child package body)
1820
1821@item
1822
1823@code{main-sub.adb}
1824
1825@tab
1826
1827Sub (subunit of Main)
1828
1829@item
1830
1831@code{a~bad.adb}
1832
1833@tab
1834
1835A.Bad (child package body)
1836
1837@end multitable
1838
1839@end quotation
1840
1841Following these rules can result in excessively long
1842file names if corresponding
1843unit names are long (for example, if child units or subunits are
1844heavily nested). An option is available to shorten such long file names
1845(called file name 'krunching'). This may be particularly useful when
1846programs being developed with GNAT are to be used on operating systems
1847with limited file name lengths. @ref{54,,Using gnatkr}.
1848
1849Of course, no file shortening algorithm can guarantee uniqueness over
1850all possible unit names; if file name krunching is used, it is your
1851responsibility to ensure no name clashes occur. Alternatively you
1852can specify the exact file names that you want used, as described
1853in the next section. Finally, if your Ada programs are migrating from a
1854compiler with a different naming convention, you can use the gnatchop
1855utility to produce source files that follow the GNAT naming conventions.
1856(For details see @ref{36,,Renaming Files with gnatchop}.)
1857
1858Note: in the case of Windows or Mac OS operating systems, case is not
1859significant. So for example on Windows if the canonical name is
1860@code{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1861However, case is significant for other operating systems, so for example,
1862if you want to use other than canonically cased file names on a Unix system,
1863you need to follow the procedures described in the next section.
1864
1865@node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1866@anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{55}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{35}
1867@subsection Using Other File Names
1868
1869
1870@geindex File names
1871
1872In the previous section, we have described the default rules used by
1873GNAT to determine the file name in which a given unit resides. It is
1874often convenient to follow these default rules, and if you follow them,
1875the compiler knows without being explicitly told where to find all
1876the files it needs.
1877
1878@geindex Source_File_Name pragma
1879
1880However, in some cases, particularly when a program is imported from
1881another Ada compiler environment, it may be more convenient for the
1882programmer to specify which file names contain which units. GNAT allows
1883arbitrary file names to be used by means of the Source_File_Name pragma.
1884The form of this pragma is as shown in the following examples:
1885
1886@example
1887pragma Source_File_Name (My_Utilities.Stacks,
1888  Spec_File_Name => "myutilst_a.ada");
1889pragma Source_File_name (My_Utilities.Stacks,
1890  Body_File_Name => "myutilst.ada");
1891@end example
1892
1893As shown in this example, the first argument for the pragma is the unit
1894name (in this example a child unit). The second argument has the form
1895of a named association. The identifier
1896indicates whether the file name is for a spec or a body;
1897the file name itself is given by a string literal.
1898
1899The source file name pragma is a configuration pragma, which means that
1900normally it will be placed in the @code{gnat.adc}
1901file used to hold configuration
1902pragmas that apply to a complete compilation environment.
1903For more details on how the @code{gnat.adc} file is created and used
1904see @ref{56,,Handling of Configuration Pragmas}.
1905
1906@geindex gnat.adc
1907
1908GNAT allows completely arbitrary file names to be specified using the
1909source file name pragma. However, if the file name specified has an
1910extension other than @code{.ads} or @code{.adb} it is necessary to use
1911a special syntax when compiling the file. The name in this case must be
1912preceded by the special sequence @code{-x} followed by a space and the name
1913of the language, here @code{ada}, as in:
1914
1915@example
1916$ gcc -c -x ada peculiar_file_name.sim
1917@end example
1918
1919@code{gnatmake} handles non-standard file names in the usual manner (the
1920non-standard file name for the main program is simply used as the
1921argument to gnatmake). Note that if the extension is also non-standard,
1922then it must be included in the @code{gnatmake} command, it may not
1923be omitted.
1924
1925@node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
1926@anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{57}@anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{58}
1927@subsection Alternative File Naming Schemes
1928
1929
1930@geindex File naming schemes
1931@geindex alternative
1932
1933@geindex File names
1934
1935The previous section described the use of the @code{Source_File_Name}
1936pragma to allow arbitrary names to be assigned to individual source files.
1937However, this approach requires one pragma for each file, and especially in
1938large systems can result in very long @code{gnat.adc} files, and also create
1939a maintenance problem.
1940
1941@geindex Source_File_Name pragma
1942
1943GNAT also provides a facility for specifying systematic file naming schemes
1944other than the standard default naming scheme previously described. An
1945alternative scheme for naming is specified by the use of
1946@code{Source_File_Name} pragmas having the following format:
1947
1948@example
1949pragma Source_File_Name (
1950   Spec_File_Name  => FILE_NAME_PATTERN
1951 [ , Casing          => CASING_SPEC]
1952 [ , Dot_Replacement => STRING_LITERAL ] );
1953
1954pragma Source_File_Name (
1955   Body_File_Name  => FILE_NAME_PATTERN
1956 [ , Casing          => CASING_SPEC ]
1957 [ , Dot_Replacement => STRING_LITERAL ] ) ;
1958
1959pragma Source_File_Name (
1960   Subunit_File_Name  => FILE_NAME_PATTERN
1961 [ , Casing          => CASING_SPEC ]
1962 [ , Dot_Replacement => STRING_LITERAL ] ) ;
1963
1964FILE_NAME_PATTERN ::= STRING_LITERAL
1965CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1966@end example
1967
1968The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1969It contains a single asterisk character, and the unit name is substituted
1970systematically for this asterisk. The optional parameter
1971@code{Casing} indicates
1972whether the unit name is to be all upper-case letters, all lower-case letters,
1973or mixed-case. If no
1974@code{Casing} parameter is used, then the default is all
1975lower-case.
1976
1977The optional @code{Dot_Replacement} string is used to replace any periods
1978that occur in subunit or child unit names. If no @code{Dot_Replacement}
1979argument is used then separating dots appear unchanged in the resulting
1980file name.
1981Although the above syntax indicates that the
1982@code{Casing} argument must appear
1983before the @code{Dot_Replacement} argument, but it
1984is also permissible to write these arguments in the opposite order.
1985
1986As indicated, it is possible to specify different naming schemes for
1987bodies, specs, and subunits. Quite often the rule for subunits is the
1988same as the rule for bodies, in which case, there is no need to give
1989a separate @code{Subunit_File_Name} rule, and in this case the
1990@code{Body_File_name} rule is used for subunits as well.
1991
1992The separate rule for subunits can also be used to implement the rather
1993unusual case of a compilation environment (e.g., a single directory) which
1994contains a subunit and a child unit with the same unit name. Although
1995both units cannot appear in the same partition, the Ada Reference Manual
1996allows (but does not require) the possibility of the two units coexisting
1997in the same environment.
1998
1999The file name translation works in the following steps:
2000
2001
2002@itemize *
2003
2004@item
2005If there is a specific @code{Source_File_Name} pragma for the given unit,
2006then this is always used, and any general pattern rules are ignored.
2007
2008@item
2009If there is a pattern type @code{Source_File_Name} pragma that applies to
2010the unit, then the resulting file name will be used if the file exists. If
2011more than one pattern matches, the latest one will be tried first, and the
2012first attempt resulting in a reference to a file that exists will be used.
2013
2014@item
2015If no pattern type @code{Source_File_Name} pragma that applies to the unit
2016for which the corresponding file exists, then the standard GNAT default
2017naming rules are used.
2018@end itemize
2019
2020As an example of the use of this mechanism, consider a commonly used scheme
2021in which file names are all lower case, with separating periods copied
2022unchanged to the resulting file name, and specs end with @code{.1.ada}, and
2023bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
2024two pragmas appear:
2025
2026@example
2027pragma Source_File_Name
2028  (Spec_File_Name => ".1.ada");
2029pragma Source_File_Name
2030  (Body_File_Name => ".2.ada");
2031@end example
2032
2033The default GNAT scheme is actually implemented by providing the following
2034default pragmas internally:
2035
2036@example
2037pragma Source_File_Name
2038  (Spec_File_Name => ".ads", Dot_Replacement => "-");
2039pragma Source_File_Name
2040  (Body_File_Name => ".adb", Dot_Replacement => "-");
2041@end example
2042
2043Our final example implements a scheme typically used with one of the
2044Ada 83 compilers, where the separator character for subunits was '__'
2045(two underscores), specs were identified by adding @code{_.ADA}, bodies
2046by adding @code{.ADA}, and subunits by
2047adding @code{.SEP}. All file names were
2048upper case. Child units were not present of course since this was an
2049Ada 83 compiler, but it seems reasonable to extend this scheme to use
2050the same double underscore separator for child units.
2051
2052@example
2053pragma Source_File_Name
2054  (Spec_File_Name => "_.ADA",
2055   Dot_Replacement => "__",
2056   Casing = Uppercase);
2057pragma Source_File_Name
2058  (Body_File_Name => ".ADA",
2059   Dot_Replacement => "__",
2060   Casing = Uppercase);
2061pragma Source_File_Name
2062  (Subunit_File_Name => ".SEP",
2063   Dot_Replacement => "__",
2064   Casing = Uppercase);
2065@end example
2066
2067@geindex gnatname
2068
2069@node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
2070@anchor{gnat_ugn/the_gnat_compilation_model handling-arbitrary-file-naming-conventions-with-gnatname}@anchor{59}@anchor{gnat_ugn/the_gnat_compilation_model id12}@anchor{5a}
2071@subsection Handling Arbitrary File Naming Conventions with @code{gnatname}
2072
2073
2074@geindex File Naming Conventions
2075
2076@menu
2077* Arbitrary File Naming Conventions::
2078* Running gnatname::
2079* Switches for gnatname::
2080* Examples of gnatname Usage::
2081
2082@end menu
2083
2084@node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
2085@anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{5b}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{5c}
2086@subsubsection Arbitrary File Naming Conventions
2087
2088
2089The GNAT compiler must be able to know the source file name of a compilation
2090unit.  When using the standard GNAT default file naming conventions
2091(@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
2092does not need additional information.
2093
2094When the source file names do not follow the standard GNAT default file naming
2095conventions, the GNAT compiler must be given additional information through
2096a configuration pragmas file (@ref{14,,Configuration Pragmas})
2097or a project file.
2098When the non-standard file naming conventions are well-defined,
2099a small number of pragmas @code{Source_File_Name} specifying a naming pattern
2100(@ref{58,,Alternative File Naming Schemes}) may be sufficient. However,
2101if the file naming conventions are irregular or arbitrary, a number
2102of pragma @code{Source_File_Name} for individual compilation units
2103must be defined.
2104To help maintain the correspondence between compilation unit names and
2105source file names within the compiler,
2106GNAT provides a tool @code{gnatname} to generate the required pragmas for a
2107set of files.
2108
2109@node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
2110@anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{5d}@anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{5e}
2111@subsubsection Running @code{gnatname}
2112
2113
2114The usual form of the @code{gnatname} command is:
2115
2116@example
2117$ gnatname [ switches ]  naming_pattern  [ naming_patterns ]
2118    [--and [ switches ]  naming_pattern  [ naming_patterns ]]
2119@end example
2120
2121All of the arguments are optional. If invoked without any argument,
2122@code{gnatname} will display its usage.
2123
2124When used with at least one naming pattern, @code{gnatname} will attempt to
2125find all the compilation units in files that follow at least one of the
2126naming patterns. To find these compilation units,
2127@code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
2128regular files.
2129
2130One or several Naming Patterns may be given as arguments to @code{gnatname}.
2131Each Naming Pattern is enclosed between double quotes (or single
2132quotes on Windows).
2133A Naming Pattern is a regular expression similar to the wildcard patterns
2134used in file names by the Unix shells or the DOS prompt.
2135
2136@code{gnatname} may be called with several sections of directories/patterns.
2137Sections are separated by the switch @code{--and}. In each section, there must be
2138at least one pattern. If no directory is specified in a section, the current
2139directory (or the project directory if @code{-P} is used) is implied.
2140The options other that the directory switches and the patterns apply globally
2141even if they are in different sections.
2142
2143Examples of Naming Patterns are:
2144
2145@example
2146"*.[12].ada"
2147"*.ad[sb]*"
2148"body_*"    "spec_*"
2149@end example
2150
2151For a more complete description of the syntax of Naming Patterns,
2152see the second kind of regular expressions described in @code{g-regexp.ads}
2153(the 'Glob' regular expressions).
2154
2155When invoked without the switch @code{-P}, @code{gnatname} will create a
2156configuration pragmas file @code{gnat.adc} in the current working directory,
2157with pragmas @code{Source_File_Name} for each file that contains a valid Ada
2158unit.
2159
2160@node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
2161@anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{5f}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{60}
2162@subsubsection Switches for @code{gnatname}
2163
2164
2165Switches for @code{gnatname} must precede any specified Naming Pattern.
2166
2167You may specify any of the following switches to @code{gnatname}:
2168
2169@geindex --version (gnatname)
2170
2171
2172@table @asis
2173
2174@item @code{--version}
2175
2176Display Copyright and version, then exit disregarding all other options.
2177@end table
2178
2179@geindex --help (gnatname)
2180
2181
2182@table @asis
2183
2184@item @code{--help}
2185
2186If @code{--version} was not used, display usage, then exit disregarding
2187all other options.
2188
2189@item @code{--subdirs=@emph{dir}}
2190
2191Real object, library or exec directories are subdirectories <dir> of the
2192specified ones.
2193
2194@item @code{--no-backup}
2195
2196Do not create a backup copy of an existing project file.
2197
2198@item @code{--and}
2199
2200Start another section of directories/patterns.
2201@end table
2202
2203@geindex -c (gnatname)
2204
2205
2206@table @asis
2207
2208@item @code{-c@emph{filename}}
2209
2210Create a configuration pragmas file @code{filename} (instead of the default
2211@code{gnat.adc}).
2212There may be zero, one or more space between @code{-c} and
2213@code{filename}.
2214@code{filename} may include directory information. @code{filename} must be
2215writable. There may be only one switch @code{-c}.
2216When a switch @code{-c} is
2217specified, no switch @code{-P} may be specified (see below).
2218@end table
2219
2220@geindex -d (gnatname)
2221
2222
2223@table @asis
2224
2225@item @code{-d@emph{dir}}
2226
2227Look for source files in directory @code{dir}. There may be zero, one or more
2228spaces between @code{-d} and @code{dir}.
2229@code{dir} may end with @code{/**}, that is it may be of the form
2230@code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
2231subdirectories, recursively, have to be searched for sources.
2232When a switch @code{-d}
2233is specified, the current working directory will not be searched for source
2234files, unless it is explicitly specified with a @code{-d}
2235or @code{-D} switch.
2236Several switches @code{-d} may be specified.
2237If @code{dir} is a relative path, it is relative to the directory of
2238the configuration pragmas file specified with switch
2239@code{-c},
2240or to the directory of the project file specified with switch
2241@code{-P} or,
2242if neither switch @code{-c}
2243nor switch @code{-P} are specified, it is relative to the
2244current working directory. The directory
2245specified with switch @code{-d} must exist and be readable.
2246@end table
2247
2248@geindex -D (gnatname)
2249
2250
2251@table @asis
2252
2253@item @code{-D@emph{filename}}
2254
2255Look for source files in all directories listed in text file @code{filename}.
2256There may be zero, one or more spaces between @code{-D}
2257and @code{filename}.
2258@code{filename} must be an existing, readable text file.
2259Each nonempty line in @code{filename} must be a directory.
2260Specifying switch @code{-D} is equivalent to specifying as many
2261switches @code{-d} as there are nonempty lines in
2262@code{file}.
2263
2264@item @code{-eL}
2265
2266Follow symbolic links when processing project files.
2267
2268@geindex -f (gnatname)
2269
2270@item @code{-f@emph{pattern}}
2271
2272Foreign patterns. Using this switch, it is possible to add sources of languages
2273other than Ada to the list of sources of a project file.
2274It is only useful if a -P switch is used.
2275For example,
2276
2277@example
2278gnatname -Pprj -f"*.c" "*.ada"
2279@end example
2280
2281will look for Ada units in all files with the @code{.ada} extension,
2282and will add to the list of file for project @code{prj.gpr} the C files
2283with extension @code{.c}.
2284
2285@geindex -h (gnatname)
2286
2287@item @code{-h}
2288
2289Output usage (help) information. The output is written to @code{stdout}.
2290
2291@geindex -P (gnatname)
2292
2293@item @code{-P@emph{proj}}
2294
2295Create or update project file @code{proj}. There may be zero, one or more space
2296between @code{-P} and @code{proj}. @code{proj} may include directory
2297information. @code{proj} must be writable.
2298There may be only one switch @code{-P}.
2299When a switch @code{-P} is specified,
2300no switch @code{-c} may be specified.
2301On all platforms, except on VMS, when @code{gnatname} is invoked for an
2302existing project file <proj>.gpr, a backup copy of the project file is created
2303in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
2304non negative number that makes this backup copy a new file.
2305
2306@geindex -v (gnatname)
2307
2308@item @code{-v}
2309
2310Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2311This includes name of the file written, the name of the directories to search
2312and, for each file in those directories whose name matches at least one of
2313the Naming Patterns, an indication of whether the file contains a unit,
2314and if so the name of the unit.
2315@end table
2316
2317@geindex -v -v (gnatname)
2318
2319
2320@table @asis
2321
2322@item @code{-v -v}
2323
2324Very Verbose mode. In addition to the output produced in verbose mode,
2325for each file in the searched directories whose name matches none of
2326the Naming Patterns, an indication is given that there is no match.
2327
2328@geindex -x (gnatname)
2329
2330@item @code{-x@emph{pattern}}
2331
2332Excluded patterns. Using this switch, it is possible to exclude some files
2333that would match the name patterns. For example,
2334
2335@example
2336gnatname -x "*_nt.ada" "*.ada"
2337@end example
2338
2339will look for Ada units in all files with the @code{.ada} extension,
2340except those whose names end with @code{_nt.ada}.
2341@end table
2342
2343@node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2344@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{61}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{62}
2345@subsubsection Examples of @code{gnatname} Usage
2346
2347
2348@example
2349$ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2350@end example
2351
2352In this example, the directory @code{/home/me} must already exist
2353and be writable. In addition, the directory
2354@code{/home/me/sources} (specified by
2355@code{-d sources}) must exist and be readable.
2356
2357Note the optional spaces after @code{-c} and @code{-d}.
2358
2359@example
2360$ gnatname -P/home/me/proj -x "*_nt_body.ada"
2361-dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2362@end example
2363
2364Note that several switches @code{-d} may be used,
2365even in conjunction with one or several switches
2366@code{-D}. Several Naming Patterns and one excluded pattern
2367are used in this example.
2368
2369@node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2370@anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{63}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{64}
2371@subsection File Name Krunching with @code{gnatkr}
2372
2373
2374@geindex gnatkr
2375
2376This section discusses the method used by the compiler to shorten
2377the default file names chosen for Ada units so that they do not
2378exceed the maximum length permitted. It also describes the
2379@code{gnatkr} utility that can be used to determine the result of
2380applying this shortening.
2381
2382@menu
2383* About gnatkr::
2384* Using gnatkr::
2385* Krunching Method::
2386* Examples of gnatkr Usage::
2387
2388@end menu
2389
2390@node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2391@anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{66}
2392@subsubsection About @code{gnatkr}
2393
2394
2395The default file naming rule in GNAT
2396is that the file name must be derived from
2397the unit name. The exact default rule is as follows:
2398
2399
2400@itemize *
2401
2402@item
2403Take the unit name and replace all dots by hyphens.
2404
2405@item
2406If such a replacement occurs in the
2407second character position of a name, and the first character is
2408@code{a}, @code{g}, @code{s}, or @code{i},
2409then replace the dot by the character
2410@code{~} (tilde)
2411instead of a minus.
2412
2413The reason for this exception is to avoid clashes
2414with the standard names for children of System, Ada, Interfaces,
2415and GNAT, which use the prefixes
2416@code{s-}, @code{a-}, @code{i-}, and @code{g-},
2417respectively.
2418@end itemize
2419
2420The @code{-gnatk@emph{nn}}
2421switch of the compiler activates a 'krunching'
2422circuit that limits file names to nn characters (where nn is a decimal
2423integer).
2424
2425The @code{gnatkr} utility can be used to determine the krunched name for
2426a given file, when krunched to a specified maximum length.
2427
2428@node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2429@anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{67}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{54}
2430@subsubsection Using @code{gnatkr}
2431
2432
2433The @code{gnatkr} command has the form:
2434
2435@example
2436$ gnatkr name [ length ]
2437@end example
2438
2439@code{name} is the uncrunched file name, derived from the name of the unit
2440in the standard manner described in the previous section (i.e., in particular
2441all dots are replaced by hyphens). The file name may or may not have an
2442extension (defined as a suffix of the form period followed by arbitrary
2443characters other than period). If an extension is present then it will
2444be preserved in the output. For example, when krunching @code{hellofile.ads}
2445to eight characters, the result will be hellofil.ads.
2446
2447Note: for compatibility with previous versions of @code{gnatkr} dots may
2448appear in the name instead of hyphens, but the last dot will always be
2449taken as the start of an extension. So if @code{gnatkr} is given an argument
2450such as @code{Hello.World.adb} it will be treated exactly as if the first
2451period had been a hyphen, and for example krunching to eight characters
2452gives the result @code{hellworl.adb}.
2453
2454Note that the result is always all lower case.
2455Characters of the other case are folded as required.
2456
2457@code{length} represents the length of the krunched name. The default
2458when no argument is given is 8 characters. A length of zero stands for
2459unlimited, in other words do not chop except for system files where the
2460implied crunching length is always eight characters.
2461
2462The output is the krunched name. The output has an extension only if the
2463original argument was a file name with an extension.
2464
2465@node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2466@anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{68}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{69}
2467@subsubsection Krunching Method
2468
2469
2470The initial file name is determined by the name of the unit that the file
2471contains. The name is formed by taking the full expanded name of the
2472unit and replacing the separating dots with hyphens and
2473using lowercase
2474for all letters, except that a hyphen in the second character position is
2475replaced by a tilde if the first character is
2476@code{a}, @code{i}, @code{g}, or @code{s}.
2477The extension is @code{.ads} for a
2478spec and @code{.adb} for a body.
2479Krunching does not affect the extension, but the file name is shortened to
2480the specified length by following these rules:
2481
2482
2483@itemize *
2484
2485@item
2486The name is divided into segments separated by hyphens, tildes or
2487underscores and all hyphens, tildes, and underscores are
2488eliminated. If this leaves the name short enough, we are done.
2489
2490@item
2491If the name is too long, the longest segment is located (left-most
2492if there are two of equal length), and shortened by dropping
2493its last character. This is repeated until the name is short enough.
2494
2495As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2496to fit the name into 8 characters as required by some operating systems:
2497
2498@example
2499our-strings-wide_fixed 22
2500our strings wide fixed 19
2501our string  wide fixed 18
2502our strin   wide fixed 17
2503our stri    wide fixed 16
2504our stri    wide fixe  15
2505our str     wide fixe  14
2506our str     wid  fixe  13
2507our str     wid  fix   12
2508ou  str     wid  fix   11
2509ou  st      wid  fix   10
2510ou  st      wi   fix   9
2511ou  st      wi   fi    8
2512Final file name: oustwifi.adb
2513@end example
2514
2515@item
2516The file names for all predefined units are always krunched to eight
2517characters. The krunching of these predefined units uses the following
2518special prefix replacements:
2519
2520
2521@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx}
2522@item
2523
2524Prefix
2525
2526@tab
2527
2528Replacement
2529
2530@item
2531
2532@code{ada-}
2533
2534@tab
2535
2536@code{a-}
2537
2538@item
2539
2540@code{gnat-}
2541
2542@tab
2543
2544@code{g-}
2545
2546@item
2547
2548@code{interfac es-}
2549
2550@tab
2551
2552@code{i-}
2553
2554@item
2555
2556@code{system-}
2557
2558@tab
2559
2560@code{s-}
2561
2562@end multitable
2563
2564
2565These system files have a hyphen in the second character position. That
2566is why normal user files replace such a character with a
2567tilde, to avoid confusion with system file names.
2568
2569As an example of this special rule, consider
2570@code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2571
2572@example
2573ada-strings-wide_fixed 22
2574a-  strings wide fixed 18
2575a-  string  wide fixed 17
2576a-  strin   wide fixed 16
2577a-  stri    wide fixed 15
2578a-  stri    wide fixe  14
2579a-  str     wide fixe  13
2580a-  str     wid  fixe  12
2581a-  str     wid  fix   11
2582a-  st      wid  fix   10
2583a-  st      wi   fix   9
2584a-  st      wi   fi    8
2585Final file name: a-stwifi.adb
2586@end example
2587@end itemize
2588
2589Of course no file shortening algorithm can guarantee uniqueness over all
2590possible unit names, and if file name krunching is used then it is your
2591responsibility to ensure that no name clashes occur. The utility
2592program @code{gnatkr} is supplied for conveniently determining the
2593krunched name of a file.
2594
2595@node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2596@anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{6a}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{6b}
2597@subsubsection Examples of @code{gnatkr} Usage
2598
2599
2600@example
2601$ gnatkr very_long_unit_name.ads      --> velounna.ads
2602$ gnatkr grandparent-parent-child.ads --> grparchi.ads
2603$ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2604$ gnatkr grandparent-parent-child     --> grparchi
2605$ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2606$ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2607@end example
2608
2609@node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2610@anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{36}
2611@subsection Renaming Files with @code{gnatchop}
2612
2613
2614@geindex gnatchop
2615
2616This section discusses how to handle files with multiple units by using
2617the @code{gnatchop} utility. This utility is also useful in renaming
2618files to meet the standard GNAT default file naming conventions.
2619
2620@menu
2621* Handling Files with Multiple Units::
2622* Operating gnatchop in Compilation Mode::
2623* Command Line for gnatchop::
2624* Switches for gnatchop::
2625* Examples of gnatchop Usage::
2626
2627@end menu
2628
2629@node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2630@anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{6d}@anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{6e}
2631@subsubsection Handling Files with Multiple Units
2632
2633
2634The basic compilation model of GNAT requires that a file submitted to the
2635compiler have only one unit and there be a strict correspondence
2636between the file name and the unit name.
2637
2638The @code{gnatchop} utility allows both of these rules to be relaxed,
2639allowing GNAT to process files which contain multiple compilation units
2640and files with arbitrary file names. @code{gnatchop}
2641reads the specified file and generates one or more output files,
2642containing one unit per file. The unit and the file name correspond,
2643as required by GNAT.
2644
2645If you want to permanently restructure a set of 'foreign' files so that
2646they match the GNAT rules, and do the remaining development using the
2647GNAT structure, you can simply use @code{gnatchop} once, generate the
2648new set of files and work with them from that point on.
2649
2650Alternatively, if you want to keep your files in the 'foreign' format,
2651perhaps to maintain compatibility with some other Ada compilation
2652system, you can set up a procedure where you use @code{gnatchop} each
2653time you compile, regarding the source files that it writes as temporary
2654files that you throw away.
2655
2656Note that if your file containing multiple units starts with a byte order
2657mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2658will each start with a copy of this BOM, meaning that they can be compiled
2659automatically in UTF-8 mode without needing to specify an explicit encoding.
2660
2661@node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2662@anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{6f}@anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{70}
2663@subsubsection Operating gnatchop in Compilation Mode
2664
2665
2666The basic function of @code{gnatchop} is to take a file with multiple units
2667and split it into separate files. The boundary between files is reasonably
2668clear, except for the issue of comments and pragmas. In default mode, the
2669rule is that any pragmas between units belong to the previous unit, except
2670that configuration pragmas always belong to the following unit. Any comments
2671belong to the following unit. These rules
2672almost always result in the right choice of
2673the split point without needing to mark it explicitly and most users will
2674find this default to be what they want. In this default mode it is incorrect to
2675submit a file containing only configuration pragmas, or one that ends in
2676configuration pragmas, to @code{gnatchop}.
2677
2678However, using a special option to activate 'compilation mode',
2679@code{gnatchop}
2680can perform another function, which is to provide exactly the semantics
2681required by the RM for handling of configuration pragmas in a compilation.
2682In the absence of configuration pragmas (at the main file level), this
2683option has no effect, but it causes such configuration pragmas to be handled
2684in a quite different manner.
2685
2686First, in compilation mode, if @code{gnatchop} is given a file that consists of
2687only configuration pragmas, then this file is appended to the
2688@code{gnat.adc} file in the current directory. This behavior provides
2689the required behavior described in the RM for the actions to be taken
2690on submitting such a file to the compiler, namely that these pragmas
2691should apply to all subsequent compilations in the same compilation
2692environment. Using GNAT, the current directory, possibly containing a
2693@code{gnat.adc} file is the representation
2694of a compilation environment. For more information on the
2695@code{gnat.adc} file, see @ref{56,,Handling of Configuration Pragmas}.
2696
2697Second, in compilation mode, if @code{gnatchop}
2698is given a file that starts with
2699configuration pragmas, and contains one or more units, then these
2700configuration pragmas are prepended to each of the chopped files. This
2701behavior provides the required behavior described in the RM for the
2702actions to be taken on compiling such a file, namely that the pragmas
2703apply to all units in the compilation, but not to subsequently compiled
2704units.
2705
2706Finally, if configuration pragmas appear between units, they are appended
2707to the previous unit. This results in the previous unit being illegal,
2708since the compiler does not accept configuration pragmas that follow
2709a unit. This provides the required RM behavior that forbids configuration
2710pragmas other than those preceding the first compilation unit of a
2711compilation.
2712
2713For most purposes, @code{gnatchop} will be used in default mode. The
2714compilation mode described above is used only if you need exactly
2715accurate behavior with respect to compilations, and you have files
2716that contain multiple units and configuration pragmas. In this
2717circumstance the use of @code{gnatchop} with the compilation mode
2718switch provides the required behavior, and is for example the mode
2719in which GNAT processes the ACVC tests.
2720
2721@node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2722@anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{72}
2723@subsubsection Command Line for @code{gnatchop}
2724
2725
2726The @code{gnatchop} command has the form:
2727
2728@example
2729$ gnatchop switches file_name [file_name ...]
2730      [directory]
2731@end example
2732
2733The only required argument is the file name of the file to be chopped.
2734There are no restrictions on the form of this file name. The file itself
2735contains one or more Ada units, in normal GNAT format, concatenated
2736together. As shown, more than one file may be presented to be chopped.
2737
2738When run in default mode, @code{gnatchop} generates one output file in
2739the current directory for each unit in each of the files.
2740
2741@code{directory}, if specified, gives the name of the directory to which
2742the output files will be written. If it is not specified, all files are
2743written to the current directory.
2744
2745For example, given a
2746file called @code{hellofiles} containing
2747
2748@example
2749procedure Hello;
2750
2751with Ada.Text_IO; use Ada.Text_IO;
2752procedure Hello is
2753begin
2754   Put_Line ("Hello");
2755end Hello;
2756@end example
2757
2758the command
2759
2760@example
2761$ gnatchop hellofiles
2762@end example
2763
2764generates two files in the current directory, one called
2765@code{hello.ads} containing the single line that is the procedure spec,
2766and the other called @code{hello.adb} containing the remaining text. The
2767original file is not affected. The generated files can be compiled in
2768the normal manner.
2769
2770When gnatchop is invoked on a file that is empty or that contains only empty
2771lines and/or comments, gnatchop will not fail, but will not produce any
2772new sources.
2773
2774For example, given a
2775file called @code{toto.txt} containing
2776
2777@example
2778--  Just a comment
2779@end example
2780
2781the command
2782
2783@example
2784$ gnatchop toto.txt
2785@end example
2786
2787will not produce any new file and will result in the following warnings:
2788
2789@example
2790toto.txt:1:01: warning: empty file, contains no compilation units
2791no compilation units found
2792no source files written
2793@end example
2794
2795@node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2796@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{73}@anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{74}
2797@subsubsection Switches for @code{gnatchop}
2798
2799
2800@code{gnatchop} recognizes the following switches:
2801
2802@geindex --version (gnatchop)
2803
2804
2805@table @asis
2806
2807@item @code{--version}
2808
2809Display Copyright and version, then exit disregarding all other options.
2810@end table
2811
2812@geindex --help (gnatchop)
2813
2814
2815@table @asis
2816
2817@item @code{--help}
2818
2819If @code{--version} was not used, display usage, then exit disregarding
2820all other options.
2821@end table
2822
2823@geindex -c (gnatchop)
2824
2825
2826@table @asis
2827
2828@item @code{-c}
2829
2830Causes @code{gnatchop} to operate in compilation mode, in which
2831configuration pragmas are handled according to strict RM rules. See
2832previous section for a full description of this mode.
2833
2834@item @code{-gnat@emph{xxx}}
2835
2836This passes the given @code{-gnat@emph{xxx}} switch to @code{gnat} which is
2837used to parse the given file. Not all @emph{xxx} options make sense,
2838but for example, the use of @code{-gnati2} allows @code{gnatchop} to
2839process a source file that uses Latin-2 coding for identifiers.
2840
2841@item @code{-h}
2842
2843Causes @code{gnatchop} to generate a brief help summary to the standard
2844output file showing usage information.
2845@end table
2846
2847@geindex -k (gnatchop)
2848
2849
2850@table @asis
2851
2852@item @code{-k@emph{mm}}
2853
2854Limit generated file names to the specified number @code{mm}
2855of characters.
2856This is useful if the
2857resulting set of files is required to be interoperable with systems
2858which limit the length of file names.
2859No space is allowed between the @code{-k} and the numeric value. The numeric
2860value may be omitted in which case a default of @code{-k8},
2861suitable for use
2862with DOS-like file systems, is used. If no @code{-k} switch
2863is present then
2864there is no limit on the length of file names.
2865@end table
2866
2867@geindex -p (gnatchop)
2868
2869
2870@table @asis
2871
2872@item @code{-p}
2873
2874Causes the file modification time stamp of the input file to be
2875preserved and used for the time stamp of the output file(s). This may be
2876useful for preserving coherency of time stamps in an environment where
2877@code{gnatchop} is used as part of a standard build process.
2878@end table
2879
2880@geindex -q (gnatchop)
2881
2882
2883@table @asis
2884
2885@item @code{-q}
2886
2887Causes output of informational messages indicating the set of generated
2888files to be suppressed. Warnings and error messages are unaffected.
2889@end table
2890
2891@geindex -r (gnatchop)
2892
2893@geindex Source_Reference pragmas
2894
2895
2896@table @asis
2897
2898@item @code{-r}
2899
2900Generate @code{Source_Reference} pragmas. Use this switch if the output
2901files are regarded as temporary and development is to be done in terms
2902of the original unchopped file. This switch causes
2903@code{Source_Reference} pragmas to be inserted into each of the
2904generated files to refers back to the original file name and line number.
2905The result is that all error messages refer back to the original
2906unchopped file.
2907In addition, the debugging information placed into the object file (when
2908the @code{-g} switch of @code{gcc} or @code{gnatmake} is
2909specified)
2910also refers back to this original file so that tools like profilers and
2911debuggers will give information in terms of the original unchopped file.
2912
2913If the original file to be chopped itself contains
2914a @code{Source_Reference}
2915pragma referencing a third file, then gnatchop respects
2916this pragma, and the generated @code{Source_Reference} pragmas
2917in the chopped file refer to the original file, with appropriate
2918line numbers. This is particularly useful when @code{gnatchop}
2919is used in conjunction with @code{gnatprep} to compile files that
2920contain preprocessing statements and multiple units.
2921@end table
2922
2923@geindex -v (gnatchop)
2924
2925
2926@table @asis
2927
2928@item @code{-v}
2929
2930Causes @code{gnatchop} to operate in verbose mode. The version
2931number and copyright notice are output, as well as exact copies of
2932the gnat1 commands spawned to obtain the chop control information.
2933@end table
2934
2935@geindex -w (gnatchop)
2936
2937
2938@table @asis
2939
2940@item @code{-w}
2941
2942Overwrite existing file names. Normally @code{gnatchop} regards it as a
2943fatal error if there is already a file with the same name as a
2944file it would otherwise output, in other words if the files to be
2945chopped contain duplicated units. This switch bypasses this
2946check, and causes all but the last instance of such duplicated
2947units to be skipped.
2948@end table
2949
2950@geindex --GCC= (gnatchop)
2951
2952
2953@table @asis
2954
2955@item @code{--GCC=@emph{xxxx}}
2956
2957Specify the path of the GNAT parser to be used. When this switch is used,
2958no attempt is made to add the prefix to the GNAT parser executable.
2959@end table
2960
2961@node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
2962@anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{75}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{76}
2963@subsubsection Examples of @code{gnatchop} Usage
2964
2965
2966@example
2967$ gnatchop -w hello_s.ada prerelease/files
2968@end example
2969
2970Chops the source file @code{hello_s.ada}. The output files will be
2971placed in the directory @code{prerelease/files},
2972overwriting any
2973files with matching names in that directory (no files in the current
2974directory are modified).
2975
2976@example
2977$ gnatchop archive
2978@end example
2979
2980Chops the source file @code{archive}
2981into the current directory. One
2982useful application of @code{gnatchop} is in sending sets of sources
2983around, for example in email messages. The required sources are simply
2984concatenated (for example, using a Unix @code{cat}
2985command), and then
2986@code{gnatchop} is used at the other end to reconstitute the original
2987file names.
2988
2989@example
2990$ gnatchop file1 file2 file3 direc
2991@end example
2992
2993Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
2994the resulting files in the directory @code{direc}. Note that if any units
2995occur more than once anywhere within this set of files, an error message
2996is generated, and no files are written. To override this check, use the
2997@code{-w} switch,
2998in which case the last occurrence in the last file will
2999be the one that is output, and earlier duplicate occurrences for a given
3000unit will be skipped.
3001
3002@node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
3003@anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{14}
3004@section Configuration Pragmas
3005
3006
3007@geindex Configuration pragmas
3008
3009@geindex Pragmas
3010@geindex configuration
3011
3012Configuration pragmas include those pragmas described as
3013such in the Ada Reference Manual, as well as
3014implementation-dependent pragmas that are configuration pragmas.
3015See the @code{Implementation_Defined_Pragmas} chapter in the
3016@cite{GNAT_Reference_Manual} for details on these
3017additional GNAT-specific configuration pragmas.
3018Most notably, the pragma @code{Source_File_Name}, which allows
3019specifying non-default names for source files, is a configuration
3020pragma. The following is a complete list of configuration pragmas
3021recognized by GNAT:
3022
3023@example
3024Ada_83
3025Ada_95
3026Ada_05
3027Ada_2005
3028Ada_12
3029Ada_2012
3030Allow_Integer_Address
3031Annotate
3032Assertion_Policy
3033Assume_No_Invalid_Values
3034C_Pass_By_Copy
3035Check_Float_Overflow
3036Check_Name
3037Check_Policy
3038Compile_Time_Error
3039Compile_Time_Warning
3040Compiler_Unit
3041Compiler_Unit_Warning
3042Component_Alignment
3043Convention_Identifier
3044Debug_Policy
3045Detect_Blocking
3046Default_Scalar_Storage_Order
3047Default_Storage_Pool
3048Disable_Atomic_Synchronization
3049Discard_Names
3050Elaboration_Checks
3051Eliminate
3052Enable_Atomic_Synchronization
3053Extend_System
3054Extensions_Allowed
3055External_Name_Casing
3056Fast_Math
3057Favor_Top_Level
3058Ignore_Pragma
3059Implicit_Packing
3060Initialize_Scalars
3061Interrupt_State
3062License
3063Locking_Policy
3064No_Component_Reordering
3065No_Heap_Finalization
3066No_Run_Time
3067No_Strict_Aliasing
3068Normalize_Scalars
3069Optimize_Alignment
3070Overflow_Mode
3071Overriding_Renamings
3072Partition_Elaboration_Policy
3073Persistent_BSS
3074Polling
3075Prefix_Exception_Messages
3076Priority_Specific_Dispatching
3077Profile
3078Profile_Warnings
3079Propagate_Exceptions
3080Queuing_Policy
3081Rational
3082Ravenscar
3083Rename_Pragma
3084Restricted_Run_Time
3085Restrictions
3086Restrictions_Warnings
3087Reviewable
3088Short_Circuit_And_Or
3089Short_Descriptors
3090Source_File_Name
3091Source_File_Name_Project
3092SPARK_Mode
3093Style_Checks
3094Suppress
3095Suppress_Exception_Locations
3096Task_Dispatching_Policy
3097Unevaluated_Use_Of_Old
3098Universal_Data
3099Unsuppress
3100Use_VADS_Size
3101Validity_Checks
3102Warning_As_Error
3103Warnings
3104Wide_Character_Encoding
3105@end example
3106
3107@menu
3108* Handling of Configuration Pragmas::
3109* The Configuration Pragmas Files::
3110
3111@end menu
3112
3113@node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
3114@anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{78}@anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{56}
3115@subsection Handling of Configuration Pragmas
3116
3117
3118Configuration pragmas may either appear at the start of a compilation
3119unit, or they can appear in a configuration pragma file to apply to
3120all compilations performed in a given compilation environment.
3121
3122GNAT also provides the @code{gnatchop} utility to provide an automatic
3123way to handle configuration pragmas following the semantics for
3124compilations (that is, files with multiple units), described in the RM.
3125See @ref{6f,,Operating gnatchop in Compilation Mode} for details.
3126However, for most purposes, it will be more convenient to edit the
3127@code{gnat.adc} file that contains configuration pragmas directly,
3128as described in the following section.
3129
3130In the case of @code{Restrictions} pragmas appearing as configuration
3131pragmas in individual compilation units, the exact handling depends on
3132the type of restriction.
3133
3134Restrictions that require partition-wide consistency (like
3135@code{No_Tasking}) are
3136recognized wherever they appear
3137and can be freely inherited, e.g. from a @emph{with}ed unit to the @emph{with}ing
3138unit. This makes sense since the binder will in any case insist on seeing
3139consistent use, so any unit not conforming to any restrictions that are
3140anywhere in the partition will be rejected, and you might as well find
3141that out at compile time rather than at bind time.
3142
3143For restrictions that do not require partition-wide consistency, e.g.
3144SPARK or No_Implementation_Attributes, in general the restriction applies
3145only to the unit in which the pragma appears, and not to any other units.
3146
3147The exception is No_Elaboration_Code which always applies to the entire
3148object file from a compilation, i.e. to the body, spec, and all subunits.
3149This restriction can be specified in a configuration pragma file, or it
3150can be on the body and/or the spec (in eithe case it applies to all the
3151relevant units). It can appear on a subunit only if it has previously
3152appeared in the body of spec.
3153
3154@node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
3155@anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{79}@anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{7a}
3156@subsection The Configuration Pragmas Files
3157
3158
3159@geindex gnat.adc
3160
3161In GNAT a compilation environment is defined by the current
3162directory at the time that a compile command is given. This current
3163directory is searched for a file whose name is @code{gnat.adc}. If
3164this file is present, it is expected to contain one or more
3165configuration pragmas that will be applied to the current compilation.
3166However, if the switch @code{-gnatA} is used, @code{gnat.adc} is not
3167considered. When taken into account, @code{gnat.adc} is added to the
3168dependencies, so that if @code{gnat.adc} is modified later, an invocation of
3169@code{gnatmake} will recompile the source.
3170
3171Configuration pragmas may be entered into the @code{gnat.adc} file
3172either by running @code{gnatchop} on a source file that consists only of
3173configuration pragmas, or more conveniently by direct editing of the
3174@code{gnat.adc} file, which is a standard format source file.
3175
3176Besides @code{gnat.adc}, additional files containing configuration
3177pragmas may be applied to the current compilation using the switch
3178@code{-gnatec=@emph{path}} where @code{path} must designate an existing file that
3179contains only configuration pragmas. These configuration pragmas are
3180in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
3181is present and switch @code{-gnatA} is not used).
3182
3183It is allowable to specify several switches @code{-gnatec=}, all of which
3184will be taken into account.
3185
3186Files containing configuration pragmas specified with switches
3187@code{-gnatec=} are added to the dependencies, unless they are
3188temporary files. A file is considered temporary if its name ends in
3189@code{.tmp} or @code{.TMP}. Certain tools follow this naming
3190convention because they pass information to @code{gcc} via
3191temporary files that are immediately deleted; it doesn't make sense to
3192depend on a file that no longer exists. Such tools include
3193@code{gprbuild}, @code{gnatmake}, and @code{gnatcheck}.
3194
3195If you are using project file, a separate mechanism is provided using
3196project attributes.
3197
3198@c --Comment
3199@c See :ref:`Specifying_Configuration_Pragmas` for more details.
3200
3201@node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
3202@anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{7b}
3203@section Generating Object Files
3204
3205
3206An Ada program consists of a set of source files, and the first step in
3207compiling the program is to generate the corresponding object files.
3208These are generated by compiling a subset of these source files.
3209The files you need to compile are the following:
3210
3211
3212@itemize *
3213
3214@item
3215If a package spec has no body, compile the package spec to produce the
3216object file for the package.
3217
3218@item
3219If a package has both a spec and a body, compile the body to produce the
3220object file for the package. The source file for the package spec need
3221not be compiled in this case because there is only one object file, which
3222contains the code for both the spec and body of the package.
3223
3224@item
3225For a subprogram, compile the subprogram body to produce the object file
3226for the subprogram. The spec, if one is present, is as usual in a
3227separate file, and need not be compiled.
3228@end itemize
3229
3230@geindex Subunits
3231
3232
3233@itemize *
3234
3235@item
3236In the case of subunits, only compile the parent unit. A single object
3237file is generated for the entire subunit tree, which includes all the
3238subunits.
3239
3240@item
3241Compile child units independently of their parent units
3242(though, of course, the spec of all the ancestor unit must be present in order
3243to compile a child unit).
3244
3245@geindex Generics
3246
3247@item
3248Compile generic units in the same manner as any other units. The object
3249files in this case are small dummy files that contain at most the
3250flag used for elaboration checking. This is because GNAT always handles generic
3251instantiation by means of macro expansion. However, it is still necessary to
3252compile generic units, for dependency checking and elaboration purposes.
3253@end itemize
3254
3255The preceding rules describe the set of files that must be compiled to
3256generate the object files for a program. Each object file has the same
3257name as the corresponding source file, except that the extension is
3258@code{.o} as usual.
3259
3260You may wish to compile other files for the purpose of checking their
3261syntactic and semantic correctness. For example, in the case where a
3262package has a separate spec and body, you would not normally compile the
3263spec. However, it is convenient in practice to compile the spec to make
3264sure it is error-free before compiling clients of this spec, because such
3265compilations will fail if there is an error in the spec.
3266
3267GNAT provides an option for compiling such files purely for the
3268purposes of checking correctness; such compilations are not required as
3269part of the process of building a program. To compile a file in this
3270checking mode, use the @code{-gnatc} switch.
3271
3272@node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3273@anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{7c}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{41}
3274@section Source Dependencies
3275
3276
3277A given object file clearly depends on the source file which is compiled
3278to produce it. Here we are using "depends" in the sense of a typical
3279@code{make} utility; in other words, an object file depends on a source
3280file if changes to the source file require the object file to be
3281recompiled.
3282In addition to this basic dependency, a given object may depend on
3283additional source files as follows:
3284
3285
3286@itemize *
3287
3288@item
3289If a file being compiled @emph{with}s a unit @code{X}, the object file
3290depends on the file containing the spec of unit @code{X}. This includes
3291files that are @emph{with}ed implicitly either because they are parents
3292of @emph{with}ed child units or they are run-time units required by the
3293language constructs used in a particular unit.
3294
3295@item
3296If a file being compiled instantiates a library level generic unit, the
3297object file depends on both the spec and body files for this generic
3298unit.
3299
3300@item
3301If a file being compiled instantiates a generic unit defined within a
3302package, the object file depends on the body file for the package as
3303well as the spec file.
3304@end itemize
3305
3306@geindex Inline
3307
3308@geindex -gnatn switch
3309
3310
3311@itemize *
3312
3313@item
3314If a file being compiled contains a call to a subprogram for which
3315pragma @code{Inline} applies and inlining is activated with the
3316@code{-gnatn} switch, the object file depends on the file containing the
3317body of this subprogram as well as on the file containing the spec. Note
3318that for inlining to actually occur as a result of the use of this switch,
3319it is necessary to compile in optimizing mode.
3320
3321@geindex -gnatN switch
3322
3323The use of @code{-gnatN} activates  inlining optimization
3324that is performed by the front end of the compiler. This inlining does
3325not require that the code generation be optimized. Like @code{-gnatn},
3326the use of this switch generates additional dependencies.
3327
3328When using a gcc-based back end (in practice this means using any version
3329of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of
3330@code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
3331Historically front end inlining was more extensive than the gcc back end
3332inlining, but that is no longer the case.
3333
3334@item
3335If an object file @code{O} depends on the proper body of a subunit through
3336inlining or instantiation, it depends on the parent unit of the subunit.
3337This means that any modification of the parent unit or one of its subunits
3338affects the compilation of @code{O}.
3339
3340@item
3341The object file for a parent unit depends on all its subunit body files.
3342
3343@item
3344The previous two rules meant that for purposes of computing dependencies and
3345recompilation, a body and all its subunits are treated as an indivisible whole.
3346
3347These rules are applied transitively: if unit @code{A} @emph{with}s
3348unit @code{B}, whose elaboration calls an inlined procedure in package
3349@code{C}, the object file for unit @code{A} will depend on the body of
3350@code{C}, in file @code{c.adb}.
3351
3352The set of dependent files described by these rules includes all the
3353files on which the unit is semantically dependent, as dictated by the
3354Ada language standard. However, it is a superset of what the
3355standard describes, because it includes generic, inline, and subunit
3356dependencies.
3357
3358An object file must be recreated by recompiling the corresponding source
3359file if any of the source files on which it depends are modified. For
3360example, if the @code{make} utility is used to control compilation,
3361the rule for an Ada object file must mention all the source files on
3362which the object file depends, according to the above definition.
3363The determination of the necessary
3364recompilations is done automatically when one uses @code{gnatmake}.
3365@end itemize
3366
3367@node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3368@anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{7d}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{42}
3369@section The Ada Library Information Files
3370
3371
3372@geindex Ada Library Information files
3373
3374@geindex ALI files
3375
3376Each compilation actually generates two output files. The first of these
3377is the normal object file that has a @code{.o} extension. The second is a
3378text file containing full dependency information. It has the same
3379name as the source file, but an @code{.ali} extension.
3380This file is known as the Ada Library Information (@code{ALI}) file.
3381The following information is contained in the @code{ALI} file.
3382
3383
3384@itemize *
3385
3386@item
3387Version information (indicates which version of GNAT was used to compile
3388the unit(s) in question)
3389
3390@item
3391Main program information (including priority and time slice settings,
3392as well as the wide character encoding used during compilation).
3393
3394@item
3395List of arguments used in the @code{gcc} command for the compilation
3396
3397@item
3398Attributes of the unit, including configuration pragmas used, an indication
3399of whether the compilation was successful, exception model used etc.
3400
3401@item
3402A list of relevant restrictions applying to the unit (used for consistency)
3403checking.
3404
3405@item
3406Categorization information (e.g., use of pragma @code{Pure}).
3407
3408@item
3409Information on all @emph{with}ed units, including presence of
3410@code{Elaborate} or @code{Elaborate_All} pragmas.
3411
3412@item
3413Information from any @code{Linker_Options} pragmas used in the unit
3414
3415@item
3416Information on the use of @code{Body_Version} or @code{Version}
3417attributes in the unit.
3418
3419@item
3420Dependency information. This is a list of files, together with
3421time stamp and checksum information. These are files on which
3422the unit depends in the sense that recompilation is required
3423if any of these units are modified.
3424
3425@item
3426Cross-reference data. Contains information on all entities referenced
3427in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
3428provide cross-reference information.
3429@end itemize
3430
3431For a full detailed description of the format of the @code{ALI} file,
3432see the source of the body of unit @code{Lib.Writ}, contained in file
3433@code{lib-writ.adb} in the GNAT compiler sources.
3434
3435@node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3436@anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{7e}@anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{43}
3437@section Binding an Ada Program
3438
3439
3440When using languages such as C and C++, once the source files have been
3441compiled the only remaining step in building an executable program
3442is linking the object modules together. This means that it is possible to
3443link an inconsistent version of a program, in which two units have
3444included different versions of the same header.
3445
3446The rules of Ada do not permit such an inconsistent program to be built.
3447For example, if two clients have different versions of the same package,
3448it is illegal to build a program containing these two clients.
3449These rules are enforced by the GNAT binder, which also determines an
3450elaboration order consistent with the Ada rules.
3451
3452The GNAT binder is run after all the object files for a program have
3453been created. It is given the name of the main program unit, and from
3454this it determines the set of units required by the program, by reading the
3455corresponding ALI files. It generates error messages if the program is
3456inconsistent or if no valid order of elaboration exists.
3457
3458If no errors are detected, the binder produces a main program, in Ada by
3459default, that contains calls to the elaboration procedures of those
3460compilation unit that require them, followed by
3461a call to the main program. This Ada program is compiled to generate the
3462object file for the main program. The name of
3463the Ada file is @code{b~xxx}.adb` (with the corresponding spec
3464@code{b~xxx}.ads`) where @code{xxx} is the name of the
3465main program unit.
3466
3467Finally, the linker is used to build the resulting executable program,
3468using the object from the main program from the bind step as well as the
3469object files for the Ada units of the program.
3470
3471@node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3472@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{15}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{7f}
3473@section GNAT and Libraries
3474
3475
3476@geindex Library building and using
3477
3478This section describes how to build and use libraries with GNAT, and also shows
3479how to recompile the GNAT run-time library. You should be familiar with the
3480Project Manager facility (see the @emph{GNAT_Project_Manager} chapter of the
3481@emph{GPRbuild User's Guide}) before reading this chapter.
3482
3483@menu
3484* Introduction to Libraries in GNAT::
3485* General Ada Libraries::
3486* Stand-alone Ada Libraries::
3487* Rebuilding the GNAT Run-Time Library::
3488
3489@end menu
3490
3491@node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3492@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{80}@anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{81}
3493@subsection Introduction to Libraries in GNAT
3494
3495
3496A library is, conceptually, a collection of objects which does not have its
3497own main thread of execution, but rather provides certain services to the
3498applications that use it. A library can be either statically linked with the
3499application, in which case its code is directly included in the application,
3500or, on platforms that support it, be dynamically linked, in which case
3501its code is shared by all applications making use of this library.
3502
3503GNAT supports both types of libraries.
3504In the static case, the compiled code can be provided in different ways. The
3505simplest approach is to provide directly the set of objects resulting from
3506compilation of the library source files. Alternatively, you can group the
3507objects into an archive using whatever commands are provided by the operating
3508system. For the latter case, the objects are grouped into a shared library.
3509
3510In the GNAT environment, a library has three types of components:
3511
3512
3513@itemize *
3514
3515@item
3516Source files,
3517
3518@item
3519@code{ALI} files (see @ref{42,,The Ada Library Information Files}), and
3520
3521@item
3522Object files, an archive or a shared library.
3523@end itemize
3524
3525A GNAT library may expose all its source files, which is useful for
3526documentation purposes. Alternatively, it may expose only the units needed by
3527an external user to make use of the library. That is to say, the specs
3528reflecting the library services along with all the units needed to compile
3529those specs, which can include generic bodies or any body implementing an
3530inlined routine. In the case of @emph{stand-alone libraries} those exposed
3531units are called @emph{interface units} (@ref{82,,Stand-alone Ada Libraries}).
3532
3533All compilation units comprising an application, including those in a library,
3534need to be elaborated in an order partially defined by Ada's semantics. GNAT
3535computes the elaboration order from the @code{ALI} files and this is why they
3536constitute a mandatory part of GNAT libraries.
3537@emph{Stand-alone libraries} are the exception to this rule because a specific
3538library elaboration routine is produced independently of the application(s)
3539using the library.
3540
3541@node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3542@anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{83}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{84}
3543@subsection General Ada Libraries
3544
3545
3546@menu
3547* Building a library::
3548* Installing a library::
3549* Using a library::
3550
3551@end menu
3552
3553@node Building a library,Installing a library,,General Ada Libraries
3554@anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{85}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{86}
3555@subsubsection Building a library
3556
3557
3558The easiest way to build a library is to use the Project Manager,
3559which supports a special type of project called a @emph{Library Project}
3560(see the @emph{Library Projects} section in the @emph{GNAT Project Manager}
3561chapter of the @emph{GPRbuild User's Guide}).
3562
3563A project is considered a library project, when two project-level attributes
3564are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
3565control different aspects of library configuration, additional optional
3566project-level attributes can be specified:
3567
3568
3569@itemize *
3570
3571@item
3572
3573@table @asis
3574
3575@item @code{Library_Kind}
3576
3577This attribute controls whether the library is to be static or dynamic
3578@end table
3579
3580@item
3581
3582@table @asis
3583
3584@item @code{Library_Version}
3585
3586This attribute specifies the library version; this value is used
3587during dynamic linking of shared libraries to determine if the currently
3588installed versions of the binaries are compatible.
3589@end table
3590
3591@item
3592@code{Library_Options}
3593
3594@item
3595
3596@table @asis
3597
3598@item @code{Library_GCC}
3599
3600These attributes specify additional low-level options to be used during
3601library generation, and redefine the actual application used to generate
3602library.
3603@end table
3604@end itemize
3605
3606The GNAT Project Manager takes full care of the library maintenance task,
3607including recompilation of the source files for which objects do not exist
3608or are not up to date, assembly of the library archive, and installation of
3609the library (i.e., copying associated source, object and @code{ALI} files
3610to the specified location).
3611
3612Here is a simple library project file:
3613
3614@example
3615project My_Lib is
3616  for Source_Dirs use ("src1", "src2");
3617  for Object_Dir use "obj";
3618  for Library_Name use "mylib";
3619  for Library_Dir use "lib";
3620  for Library_Kind use "dynamic";
3621end My_lib;
3622@end example
3623
3624and the compilation command to build and install the library:
3625
3626@example
3627$ gnatmake -Pmy_lib
3628@end example
3629
3630It is not entirely trivial to perform manually all the steps required to
3631produce a library. We recommend that you use the GNAT Project Manager
3632for this task. In special cases where this is not desired, the necessary
3633steps are discussed below.
3634
3635There are various possibilities for compiling the units that make up the
3636library: for example with a Makefile (@ref{1f,,Using the GNU make Utility}) or
3637with a conventional script. For simple libraries, it is also possible to create
3638a dummy main program which depends upon all the packages that comprise the
3639interface of the library. This dummy main program can then be given to
3640@code{gnatmake}, which will ensure that all necessary objects are built.
3641
3642After this task is accomplished, you should follow the standard procedure
3643of the underlying operating system to produce the static or shared library.
3644
3645Here is an example of such a dummy program:
3646
3647@example
3648with My_Lib.Service1;
3649with My_Lib.Service2;
3650with My_Lib.Service3;
3651procedure My_Lib_Dummy is
3652begin
3653   null;
3654end;
3655@end example
3656
3657Here are the generic commands that will build an archive or a shared library.
3658
3659@example
3660# compiling the library
3661$ gnatmake -c my_lib_dummy.adb
3662
3663# we don't need the dummy object itself
3664$ rm my_lib_dummy.o my_lib_dummy.ali
3665
3666# create an archive with the remaining objects
3667$ ar rc libmy_lib.a *.o
3668# some systems may require "ranlib" to be run as well
3669
3670# or create a shared library
3671$ gcc -shared -o libmy_lib.so *.o
3672# some systems may require the code to have been compiled with -fPIC
3673
3674# remove the object files that are now in the library
3675$ rm *.o
3676
3677# Make the ALI files read-only so that gnatmake will not try to
3678# regenerate the objects that are in the library
3679$ chmod -w *.ali
3680@end example
3681
3682Please note that the library must have a name of the form @code{lib@emph{xxx}.a}
3683or @code{lib@emph{xxx}.so} (or @code{lib@emph{xxx}.dll} on Windows) in order to
3684be accessed by the directive @code{-l@emph{xxx}} at link time.
3685
3686@node Installing a library,Using a library,Building a library,General Ada Libraries
3687@anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{87}@anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{88}
3688@subsubsection Installing a library
3689
3690
3691@geindex ADA_PROJECT_PATH
3692
3693@geindex GPR_PROJECT_PATH
3694
3695If you use project files, library installation is part of the library build
3696process (see the @emph{Installing a Library with Project Files} section of the
3697@emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}).
3698
3699When project files are not an option, it is also possible, but not recommended,
3700to install the library so that the sources needed to use the library are on the
3701Ada source path and the ALI files & libraries be on the Ada Object path (see
3702@ref{89,,Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
3703administrator can place general-purpose libraries in the default compiler
3704paths, by specifying the libraries' location in the configuration files
3705@code{ada_source_path} and @code{ada_object_path}. These configuration files
3706must be located in the GNAT installation tree at the same place as the gcc spec
3707file. The location of the gcc spec file can be determined as follows:
3708
3709@example
3710$ gcc -v
3711@end example
3712
3713The configuration files mentioned above have a simple format: each line
3714must contain one unique directory name.
3715Those names are added to the corresponding path
3716in their order of appearance in the file. The names can be either absolute
3717or relative; in the latter case, they are relative to where theses files
3718are located.
3719
3720The files @code{ada_source_path} and @code{ada_object_path} might not be
3721present in a
3722GNAT installation, in which case, GNAT will look for its run-time library in
3723the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3724objects and @code{ALI} files). When the files exist, the compiler does not
3725look in @code{adainclude} and @code{adalib}, and thus the
3726@code{ada_source_path} file
3727must contain the location for the GNAT run-time sources (which can simply
3728be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3729contain the location for the GNAT run-time objects (which can simply
3730be @code{adalib}).
3731
3732You can also specify a new default path to the run-time library at compilation
3733time with the switch @code{--RTS=rts-path}. You can thus choose / change
3734the run-time library you want your program to be compiled with. This switch is
3735recognized by @code{gcc}, @code{gnatmake}, @code{gnatbind},
3736@code{gnatls}, @code{gnatfind} and @code{gnatxref}.
3737
3738It is possible to install a library before or after the standard GNAT
3739library, by reordering the lines in the configuration files. In general, a
3740library must be installed before the GNAT library if it redefines
3741any part of it.
3742
3743@node Using a library,,Installing a library,General Ada Libraries
3744@anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{8a}@anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{8b}
3745@subsubsection Using a library
3746
3747
3748Once again, the project facility greatly simplifies the use of
3749libraries. In this context, using a library is just a matter of adding a
3750@emph{with} clause in the user project. For instance, to make use of the
3751library @code{My_Lib} shown in examples in earlier sections, you can
3752write:
3753
3754@example
3755with "my_lib";
3756project My_Proj is
3757  ...
3758end My_Proj;
3759@end example
3760
3761Even if you have a third-party, non-Ada library, you can still use GNAT's
3762Project Manager facility to provide a wrapper for it. For example, the
3763following project, when @emph{with}ed by your main project, will link with the
3764third-party library @code{liba.a}:
3765
3766@example
3767project Liba is
3768   for Externally_Built use "true";
3769   for Source_Files use ();
3770   for Library_Dir use "lib";
3771   for Library_Name use "a";
3772   for Library_Kind use "static";
3773end Liba;
3774@end example
3775
3776This is an alternative to the use of @code{pragma Linker_Options}. It is
3777especially interesting in the context of systems with several interdependent
3778static libraries where finding a proper linker order is not easy and best be
3779left to the tools having visibility over project dependence information.
3780
3781In order to use an Ada library manually, you need to make sure that this
3782library is on both your source and object path
3783(see @ref{89,,Search Paths and the Run-Time Library (RTL)}
3784and @ref{8c,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3785in an archive or a shared library, you need to specify the desired
3786library at link time.
3787
3788For example, you can use the library @code{mylib} installed in
3789@code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3790
3791@example
3792$ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3793  -largs -lmy_lib
3794@end example
3795
3796This can be expressed more simply:
3797
3798@example
3799$ gnatmake my_appl
3800@end example
3801
3802when the following conditions are met:
3803
3804
3805@itemize *
3806
3807@item
3808@code{/dir/my_lib_src} has been added by the user to the environment
3809variable
3810@geindex ADA_INCLUDE_PATH
3811@geindex environment variable; ADA_INCLUDE_PATH
3812@code{ADA_INCLUDE_PATH}, or by the administrator to the file
3813@code{ada_source_path}
3814
3815@item
3816@code{/dir/my_lib_obj} has been added by the user to the environment
3817variable
3818@geindex ADA_OBJECTS_PATH
3819@geindex environment variable; ADA_OBJECTS_PATH
3820@code{ADA_OBJECTS_PATH}, or by the administrator to the file
3821@code{ada_object_path}
3822
3823@item
3824a pragma @code{Linker_Options} has been added to one of the sources.
3825For example:
3826
3827@example
3828pragma Linker_Options ("-lmy_lib");
3829@end example
3830@end itemize
3831
3832Note that you may also load a library dynamically at
3833run time given its filename, as illustrated in the GNAT @code{plugins} example
3834in the directory @code{share/examples/gnat/plugins} within the GNAT
3835install area.
3836
3837@node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3838@anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{82}@anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{8d}
3839@subsection Stand-alone Ada Libraries
3840
3841
3842@geindex Stand-alone libraries
3843
3844@menu
3845* Introduction to Stand-alone Libraries::
3846* Building a Stand-alone Library::
3847* Creating a Stand-alone Library to be used in a non-Ada context::
3848* Restrictions in Stand-alone Libraries::
3849
3850@end menu
3851
3852@node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3853@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{8e}@anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{8f}
3854@subsubsection Introduction to Stand-alone Libraries
3855
3856
3857A Stand-alone Library (abbreviated 'SAL') is a library that contains the
3858necessary code to
3859elaborate the Ada units that are included in the library. In contrast with
3860an ordinary library, which consists of all sources, objects and @code{ALI}
3861files of the
3862library, a SAL may specify a restricted subset of compilation units
3863to serve as a library interface. In this case, the fully
3864self-sufficient set of files will normally consist of an objects
3865archive, the sources of interface units' specs, and the @code{ALI}
3866files of interface units.
3867If an interface spec contains a generic unit or an inlined subprogram,
3868the body's
3869source must also be provided; if the units that must be provided in the source
3870form depend on other units, the source and @code{ALI} files of those must
3871also be provided.
3872
3873The main purpose of a SAL is to minimize the recompilation overhead of client
3874applications when a new version of the library is installed. Specifically,
3875if the interface sources have not changed, client applications do not need to
3876be recompiled. If, furthermore, a SAL is provided in the shared form and its
3877version, controlled by @code{Library_Version} attribute, is not changed,
3878then the clients do not need to be relinked.
3879
3880SALs also allow the library providers to minimize the amount of library source
3881text exposed to the clients.  Such 'information hiding' might be useful or
3882necessary for various reasons.
3883
3884Stand-alone libraries are also well suited to be used in an executable whose
3885main routine is not written in Ada.
3886
3887@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
3888@anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{90}@anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{91}
3889@subsubsection Building a Stand-alone Library
3890
3891
3892GNAT's Project facility provides a simple way of building and installing
3893stand-alone libraries; see the @emph{Stand-alone Library Projects} section
3894in the @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}.
3895To be a Stand-alone Library Project, in addition to the two attributes
3896that make a project a Library Project (@code{Library_Name} and
3897@code{Library_Dir}; see the @emph{Library Projects} section in the
3898@emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}),
3899the attribute @code{Library_Interface} must be defined.  For example:
3900
3901@example
3902for Library_Dir use "lib_dir";
3903for Library_Name use "dummy";
3904for Library_Interface use ("int1", "int1.child");
3905@end example
3906
3907Attribute @code{Library_Interface} has a non-empty string list value,
3908each string in the list designating a unit contained in an immediate source
3909of the project file.
3910
3911When a Stand-alone Library is built, first the binder is invoked to build
3912a package whose name depends on the library name
3913(@code{b~dummy.ads/b} in the example above).
3914This binder-generated package includes initialization and
3915finalization procedures whose
3916names depend on the library name (@code{dummyinit} and @code{dummyfinal}
3917in the example
3918above). The object corresponding to this package is included in the library.
3919
3920You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3921calling of these procedures if a static SAL is built, or if a shared SAL
3922is built
3923with the project-level attribute @code{Library_Auto_Init} set to
3924@code{"false"}.
3925
3926For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
3927(those that are listed in attribute @code{Library_Interface}) are copied to
3928the Library Directory. As a consequence, only the Interface Units may be
3929imported from Ada units outside of the library. If other units are imported,
3930the binding phase will fail.
3931
3932It is also possible to build an encapsulated library where not only
3933the code to elaborate and finalize the library is embedded but also
3934ensuring that the library is linked only against static
3935libraries. So an encapsulated library only depends on system
3936libraries, all other code, including the GNAT runtime, is embedded. To
3937build an encapsulated library the attribute
3938@code{Library_Standalone} must be set to @code{encapsulated}:
3939
3940@example
3941for Library_Dir use "lib_dir";
3942for Library_Name use "dummy";
3943for Library_Kind use "dynamic";
3944for Library_Interface use ("int1", "int1.child");
3945for Library_Standalone use "encapsulated";
3946@end example
3947
3948The default value for this attribute is @code{standard} in which case
3949a stand-alone library is built.
3950
3951The attribute @code{Library_Src_Dir} may be specified for a
3952Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
3953single string value. Its value must be the path (absolute or relative to the
3954project directory) of an existing directory. This directory cannot be the
3955object directory or one of the source directories, but it can be the same as
3956the library directory. The sources of the Interface
3957Units of the library that are needed by an Ada client of the library will be
3958copied to the designated directory, called the Interface Copy directory.
3959These sources include the specs of the Interface Units, but they may also
3960include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
3961are used, or when there is a generic unit in the spec. Before the sources
3962are copied to the Interface Copy directory, an attempt is made to delete all
3963files in the Interface Copy directory.
3964
3965Building stand-alone libraries by hand is somewhat tedious, but for those
3966occasions when it is necessary here are the steps that you need to perform:
3967
3968
3969@itemize *
3970
3971@item
3972Compile all library sources.
3973
3974@item
3975Invoke the binder with the switch @code{-n} (No Ada main program),
3976with all the @code{ALI} files of the interfaces, and
3977with the switch @code{-L} to give specific names to the @code{init}
3978and @code{final} procedures.  For example:
3979
3980@example
3981$ gnatbind -n int1.ali int2.ali -Lsal1
3982@end example
3983
3984@item
3985Compile the binder generated file:
3986
3987@example
3988$ gcc -c b~int2.adb
3989@end example
3990
3991@item
3992Link the dynamic library with all the necessary object files,
3993indicating to the linker the names of the @code{init} (and possibly
3994@code{final}) procedures for automatic initialization (and finalization).
3995The built library should be placed in a directory different from
3996the object directory.
3997
3998@item
3999Copy the @code{ALI} files of the interface to the library directory,
4000add in this copy an indication that it is an interface to a SAL
4001(i.e., add a word @code{SL} on the line in the @code{ALI} file that starts
4002with letter 'P') and make the modified copy of the @code{ALI} file
4003read-only.
4004@end itemize
4005
4006Using SALs is not different from using other libraries
4007(see @ref{8a,,Using a library}).
4008
4009@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
4010@anchor{gnat_ugn/the_gnat_compilation_model creating-a-stand-alone-library-to-be-used-in-a-non-ada-context}@anchor{92}@anchor{gnat_ugn/the_gnat_compilation_model id44}@anchor{93}
4011@subsubsection Creating a Stand-alone Library to be used in a non-Ada context
4012
4013
4014It is easy to adapt the SAL build procedure discussed above for use of a SAL in
4015a non-Ada context.
4016
4017The only extra step required is to ensure that library interface subprograms
4018are compatible with the main program, by means of @code{pragma Export}
4019or @code{pragma Convention}.
4020
4021Here is an example of simple library interface for use with C main program:
4022
4023@example
4024package My_Package is
4025
4026   procedure Do_Something;
4027   pragma Export (C, Do_Something, "do_something");
4028
4029   procedure Do_Something_Else;
4030   pragma Export (C, Do_Something_Else, "do_something_else");
4031
4032end My_Package;
4033@end example
4034
4035On the foreign language side, you must provide a 'foreign' view of the
4036library interface; remember that it should contain elaboration routines in
4037addition to interface subprograms.
4038
4039The example below shows the content of @code{mylib_interface.h} (note
4040that there is no rule for the naming of this file, any name can be used)
4041
4042@example
4043/* the library elaboration procedure */
4044extern void mylibinit (void);
4045
4046/* the library finalization procedure */
4047extern void mylibfinal (void);
4048
4049/* the interface exported by the library */
4050extern void do_something (void);
4051extern void do_something_else (void);
4052@end example
4053
4054Libraries built as explained above can be used from any program, provided
4055that the elaboration procedures (named @code{mylibinit} in the previous
4056example) are called before the library services are used. Any number of
4057libraries can be used simultaneously, as long as the elaboration
4058procedure of each library is called.
4059
4060Below is an example of a C program that uses the @code{mylib} library.
4061
4062@example
4063#include "mylib_interface.h"
4064
4065int
4066main (void)
4067@{
4068   /* First, elaborate the library before using it */
4069   mylibinit ();
4070
4071   /* Main program, using the library exported entities */
4072   do_something ();
4073   do_something_else ();
4074
4075   /* Library finalization at the end of the program */
4076   mylibfinal ();
4077   return 0;
4078@}
4079@end example
4080
4081Note that invoking any library finalization procedure generated by
4082@code{gnatbind} shuts down the Ada run-time environment.
4083Consequently, the
4084finalization of all Ada libraries must be performed at the end of the program.
4085No call to these libraries or to the Ada run-time library should be made
4086after the finalization phase.
4087
4088Note also that special care must be taken with multi-tasks
4089applications. The initialization and finalization routines are not
4090protected against concurrent access. If such requirement is needed it
4091must be ensured at the application level using a specific operating
4092system services like a mutex or a critical-section.
4093
4094@node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
4095@anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{94}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{95}
4096@subsubsection Restrictions in Stand-alone Libraries
4097
4098
4099The pragmas listed below should be used with caution inside libraries,
4100as they can create incompatibilities with other Ada libraries:
4101
4102
4103@itemize *
4104
4105@item
4106pragma @code{Locking_Policy}
4107
4108@item
4109pragma @code{Partition_Elaboration_Policy}
4110
4111@item
4112pragma @code{Queuing_Policy}
4113
4114@item
4115pragma @code{Task_Dispatching_Policy}
4116
4117@item
4118pragma @code{Unreserve_All_Interrupts}
4119@end itemize
4120
4121When using a library that contains such pragmas, the user must make sure
4122that all libraries use the same pragmas with the same values. Otherwise,
4123@code{Program_Error} will
4124be raised during the elaboration of the conflicting
4125libraries. The usage of these pragmas and its consequences for the user
4126should therefore be well documented.
4127
4128Similarly, the traceback in the exception occurrence mechanism should be
4129enabled or disabled in a consistent manner across all libraries.
4130Otherwise, Program_Error will be raised during the elaboration of the
4131conflicting libraries.
4132
4133If the @code{Version} or @code{Body_Version}
4134attributes are used inside a library, then you need to
4135perform a @code{gnatbind} step that specifies all @code{ALI} files in all
4136libraries, so that version identifiers can be properly computed.
4137In practice these attributes are rarely used, so this is unlikely
4138to be a consideration.
4139
4140@node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
4141@anchor{gnat_ugn/the_gnat_compilation_model id46}@anchor{96}@anchor{gnat_ugn/the_gnat_compilation_model rebuilding-the-gnat-run-time-library}@anchor{97}
4142@subsection Rebuilding the GNAT Run-Time Library
4143
4144
4145@geindex GNAT Run-Time Library
4146@geindex rebuilding
4147
4148@geindex Building the GNAT Run-Time Library
4149
4150@geindex Rebuilding the GNAT Run-Time Library
4151
4152@geindex Run-Time Library
4153@geindex rebuilding
4154
4155It may be useful to recompile the GNAT library in various contexts, the
4156most important one being the use of partition-wide configuration pragmas
4157such as @code{Normalize_Scalars}. A special Makefile called
4158@code{Makefile.adalib} is provided to that effect and can be found in
4159the directory containing the GNAT library. The location of this
4160directory depends on the way the GNAT environment has been installed and can
4161be determined by means of the command:
4162
4163@example
4164$ gnatls -v
4165@end example
4166
4167The last entry in the object search path usually contains the
4168gnat library. This Makefile contains its own documentation and in
4169particular the set of instructions needed to rebuild a new library and
4170to use it.
4171
4172@geindex Conditional compilation
4173
4174@node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
4175@anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{98}@anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{16}
4176@section Conditional Compilation
4177
4178
4179This section presents some guidelines for modeling conditional compilation in Ada and describes the
4180gnatprep preprocessor utility.
4181
4182@geindex Conditional compilation
4183
4184@menu
4185* Modeling Conditional Compilation in Ada::
4186* Preprocessing with gnatprep::
4187* Integrated Preprocessing::
4188
4189@end menu
4190
4191@node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
4192@anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{99}@anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{9a}
4193@subsection Modeling Conditional Compilation in Ada
4194
4195
4196It is often necessary to arrange for a single source program
4197to serve multiple purposes, where it is compiled in different
4198ways to achieve these different goals. Some examples of the
4199need for this feature are
4200
4201
4202@itemize *
4203
4204@item
4205Adapting a program to a different hardware environment
4206
4207@item
4208Adapting a program to a different target architecture
4209
4210@item
4211Turning debugging features on and off
4212
4213@item
4214Arranging for a program to compile with different compilers
4215@end itemize
4216
4217In C, or C++, the typical approach would be to use the preprocessor
4218that is defined as part of the language. The Ada language does not
4219contain such a feature. This is not an oversight, but rather a very
4220deliberate design decision, based on the experience that overuse of
4221the preprocessing features in C and C++ can result in programs that
4222are extremely difficult to maintain. For example, if we have ten
4223switches that can be on or off, this means that there are a thousand
4224separate programs, any one of which might not even be syntactically
4225correct, and even if syntactically correct, the resulting program
4226might not work correctly. Testing all combinations can quickly become
4227impossible.
4228
4229Nevertheless, the need to tailor programs certainly exists, and in
4230this section we will discuss how this can
4231be achieved using Ada in general, and GNAT in particular.
4232
4233@menu
4234* Use of Boolean Constants::
4235* Debugging - A Special Case::
4236* Conditionalizing Declarations::
4237* Use of Alternative Implementations::
4238* Preprocessing::
4239
4240@end menu
4241
4242@node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4243@anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{9b}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{9c}
4244@subsubsection Use of Boolean Constants
4245
4246
4247In the case where the difference is simply which code
4248sequence is executed, the cleanest solution is to use Boolean
4249constants to control which code is executed.
4250
4251@example
4252FP_Initialize_Required : constant Boolean := True;
4253...
4254if FP_Initialize_Required then
4255...
4256end if;
4257@end example
4258
4259Not only will the code inside the @code{if} statement not be executed if
4260the constant Boolean is @code{False}, but it will also be completely
4261deleted from the program.
4262However, the code is only deleted after the @code{if} statement
4263has been checked for syntactic and semantic correctness.
4264(In contrast, with preprocessors the code is deleted before the
4265compiler ever gets to see it, so it is not checked until the switch
4266is turned on.)
4267
4268@geindex Preprocessors (contrasted with conditional compilation)
4269
4270Typically the Boolean constants will be in a separate package,
4271something like:
4272
4273@example
4274package Config is
4275   FP_Initialize_Required : constant Boolean := True;
4276   Reset_Available        : constant Boolean := False;
4277   ...
4278end Config;
4279@end example
4280
4281The @code{Config} package exists in multiple forms for the various targets,
4282with an appropriate script selecting the version of @code{Config} needed.
4283Then any other unit requiring conditional compilation can do a @emph{with}
4284of @code{Config} to make the constants visible.
4285
4286@node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4287@anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{9d}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{9e}
4288@subsubsection Debugging - A Special Case
4289
4290
4291A common use of conditional code is to execute statements (for example
4292dynamic checks, or output of intermediate results) under control of a
4293debug switch, so that the debugging behavior can be turned on and off.
4294This can be done using a Boolean constant to control whether the code
4295is active:
4296
4297@example
4298if Debugging then
4299   Put_Line ("got to the first stage!");
4300end if;
4301@end example
4302
4303or
4304
4305@example
4306if Debugging and then Temperature > 999.0 then
4307   raise Temperature_Crazy;
4308end if;
4309@end example
4310
4311@geindex pragma Assert
4312
4313Since this is a common case, there are special features to deal with
4314this in a convenient manner. For the case of tests, Ada 2005 has added
4315a pragma @code{Assert} that can be used for such tests. This pragma is modeled
4316on the @code{Assert} pragma that has always been available in GNAT, so this
4317feature may be used with GNAT even if you are not using Ada 2005 features.
4318The use of pragma @code{Assert} is described in the
4319@cite{GNAT_Reference_Manual}, but as an
4320example, the last test could be written:
4321
4322@example
4323pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4324@end example
4325
4326or simply
4327
4328@example
4329pragma Assert (Temperature <= 999.0);
4330@end example
4331
4332In both cases, if assertions are active and the temperature is excessive,
4333the exception @code{Assert_Failure} will be raised, with the given string in
4334the first case or a string indicating the location of the pragma in the second
4335case used as the exception message.
4336
4337@geindex pragma Assertion_Policy
4338
4339You can turn assertions on and off by using the @code{Assertion_Policy}
4340pragma.
4341
4342@geindex -gnata switch
4343
4344This is an Ada 2005 pragma which is implemented in all modes by
4345GNAT. Alternatively, you can use the @code{-gnata} switch
4346to enable assertions from the command line, which applies to
4347all versions of Ada.
4348
4349@geindex pragma Debug
4350
4351For the example above with the @code{Put_Line}, the GNAT-specific pragma
4352@code{Debug} can be used:
4353
4354@example
4355pragma Debug (Put_Line ("got to the first stage!"));
4356@end example
4357
4358If debug pragmas are enabled, the argument, which must be of the form of
4359a procedure call, is executed (in this case, @code{Put_Line} will be called).
4360Only one call can be present, but of course a special debugging procedure
4361containing any code you like can be included in the program and then
4362called in a pragma @code{Debug} argument as needed.
4363
4364One advantage of pragma @code{Debug} over the @code{if Debugging then}
4365construct is that pragma @code{Debug} can appear in declarative contexts,
4366such as at the very beginning of a procedure, before local declarations have
4367been elaborated.
4368
4369@geindex pragma Debug_Policy
4370
4371Debug pragmas are enabled using either the @code{-gnata} switch that also
4372controls assertions, or with a separate Debug_Policy pragma.
4373
4374The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4375in Ada 95 and Ada 83 programs as well), and is analogous to
4376pragma @code{Assertion_Policy} to control assertions.
4377
4378@code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
4379and thus they can appear in @code{gnat.adc} if you are not using a
4380project file, or in the file designated to contain configuration pragmas
4381in a project file.
4382They then apply to all subsequent compilations. In practice the use of
4383the @code{-gnata} switch is often the most convenient method of controlling
4384the status of these pragmas.
4385
4386Note that a pragma is not a statement, so in contexts where a statement
4387sequence is required, you can't just write a pragma on its own. You have
4388to add a @code{null} statement.
4389
4390@example
4391if ... then
4392   ... -- some statements
4393else
4394   pragma Assert (Num_Cases < 10);
4395   null;
4396end if;
4397@end example
4398
4399@node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4400@anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{a0}
4401@subsubsection Conditionalizing Declarations
4402
4403
4404In some cases it may be necessary to conditionalize declarations to meet
4405different requirements. For example we might want a bit string whose length
4406is set to meet some hardware message requirement.
4407
4408This may be possible using declare blocks controlled
4409by conditional constants:
4410
4411@example
4412if Small_Machine then
4413   declare
4414      X : Bit_String (1 .. 10);
4415   begin
4416      ...
4417   end;
4418else
4419   declare
4420      X : Large_Bit_String (1 .. 1000);
4421   begin
4422      ...
4423   end;
4424end if;
4425@end example
4426
4427Note that in this approach, both declarations are analyzed by the
4428compiler so this can only be used where both declarations are legal,
4429even though one of them will not be used.
4430
4431Another approach is to define integer constants, e.g., @code{Bits_Per_Word},
4432or Boolean constants, e.g., @code{Little_Endian}, and then write declarations
4433that are parameterized by these constants. For example
4434
4435@example
4436for Rec use
4437  Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4438end record;
4439@end example
4440
4441If @code{Bits_Per_Word} is set to 32, this generates either
4442
4443@example
4444for Rec use
4445  Field1 at 0 range 0 .. 32;
4446end record;
4447@end example
4448
4449for the big endian case, or
4450
4451@example
4452for Rec use record
4453    Field1 at 0 range 10 .. 32;
4454end record;
4455@end example
4456
4457for the little endian case. Since a powerful subset of Ada expression
4458notation is usable for creating static constants, clever use of this
4459feature can often solve quite difficult problems in conditionalizing
4460compilation (note incidentally that in Ada 95, the little endian
4461constant was introduced as @code{System.Default_Bit_Order}, so you do not
4462need to define this one yourself).
4463
4464@node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4465@anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{a2}
4466@subsubsection Use of Alternative Implementations
4467
4468
4469In some cases, none of the approaches described above are adequate. This
4470can occur for example if the set of declarations required is radically
4471different for two different configurations.
4472
4473In this situation, the official Ada way of dealing with conditionalizing
4474such code is to write separate units for the different cases. As long as
4475this does not result in excessive duplication of code, this can be done
4476without creating maintenance problems. The approach is to share common
4477code as far as possible, and then isolate the code and declarations
4478that are different. Subunits are often a convenient method for breaking
4479out a piece of a unit that is to be conditionalized, with separate files
4480for different versions of the subunit for different targets, where the
4481build script selects the right one to give to the compiler.
4482
4483@geindex Subunits (and conditional compilation)
4484
4485As an example, consider a situation where a new feature in Ada 2005
4486allows something to be done in a really nice way. But your code must be able
4487to compile with an Ada 95 compiler. Conceptually you want to say:
4488
4489@example
4490if Ada_2005 then
4491   ... neat Ada 2005 code
4492else
4493   ... not quite as neat Ada 95 code
4494end if;
4495@end example
4496
4497where @code{Ada_2005} is a Boolean constant.
4498
4499But this won't work when @code{Ada_2005} is set to @code{False},
4500since the @code{then} clause will be illegal for an Ada 95 compiler.
4501(Recall that although such unreachable code would eventually be deleted
4502by the compiler, it still needs to be legal.  If it uses features
4503introduced in Ada 2005, it will be illegal in Ada 95.)
4504
4505So instead we write
4506
4507@example
4508procedure Insert is separate;
4509@end example
4510
4511Then we have two files for the subunit @code{Insert}, with the two sets of
4512code.
4513If the package containing this is called @code{File_Queries}, then we might
4514have two files
4515
4516
4517@itemize *
4518
4519@item
4520@code{file_queries-insert-2005.adb}
4521
4522@item
4523@code{file_queries-insert-95.adb}
4524@end itemize
4525
4526and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4527
4528This can also be done with project files' naming schemes. For example:
4529
4530@example
4531for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4532@end example
4533
4534Note also that with project files it is desirable to use a different extension
4535than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4536conflict may arise through another commonly used feature: to declare as part
4537of the project a set of directories containing all the sources obeying the
4538default naming scheme.
4539
4540The use of alternative units is certainly feasible in all situations,
4541and for example the Ada part of the GNAT run-time is conditionalized
4542based on the target architecture using this approach. As a specific example,
4543consider the implementation of the AST feature in VMS. There is one
4544spec: @code{s-asthan.ads} which is the same for all architectures, and three
4545bodies:
4546
4547
4548@itemize *
4549
4550@item
4551
4552@table @asis
4553
4554@item @code{s-asthan.adb}
4555
4556used for all non-VMS operating systems
4557@end table
4558
4559@item
4560
4561@table @asis
4562
4563@item @code{s-asthan-vms-alpha.adb}
4564
4565used for VMS on the Alpha
4566@end table
4567
4568@item
4569
4570@table @asis
4571
4572@item @code{s-asthan-vms-ia64.adb}
4573
4574used for VMS on the ia64
4575@end table
4576@end itemize
4577
4578The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4579this operating system feature is not available, and the two remaining
4580versions interface with the corresponding versions of VMS to provide
4581VMS-compatible AST handling. The GNAT build script knows the architecture
4582and operating system, and automatically selects the right version,
4583renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4584
4585Another style for arranging alternative implementations is through Ada's
4586access-to-subprogram facility.
4587In case some functionality is to be conditionally included,
4588you can declare an access-to-procedure variable @code{Ref} that is initialized
4589to designate a 'do nothing' procedure, and then invoke @code{Ref.all}
4590when appropriate.
4591In some library package, set @code{Ref} to @code{Proc'Access} for some
4592procedure @code{Proc} that performs the relevant processing.
4593The initialization only occurs if the library package is included in the
4594program.
4595The same idea can also be implemented using tagged types and dispatching
4596calls.
4597
4598@node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4599@anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{a4}
4600@subsubsection Preprocessing
4601
4602
4603@geindex Preprocessing
4604
4605Although it is quite possible to conditionalize code without the use of
4606C-style preprocessing, as described earlier in this section, it is
4607nevertheless convenient in some cases to use the C approach. Moreover,
4608older Ada compilers have often provided some preprocessing capability,
4609so legacy code may depend on this approach, even though it is not
4610standard.
4611
4612To accommodate such use, GNAT provides a preprocessor (modeled to a large
4613extent on the various preprocessors that have been used
4614with legacy code on other compilers, to enable easier transition).
4615
4616@geindex gnatprep
4617
4618The preprocessor may be used in two separate modes. It can be used quite
4619separately from the compiler, to generate a separate output source file
4620that is then fed to the compiler as a separate step. This is the
4621@code{gnatprep} utility, whose use is fully described in
4622@ref{17,,Preprocessing with gnatprep}.
4623
4624The preprocessing language allows such constructs as
4625
4626@example
4627#if DEBUG or else (PRIORITY > 4) then
4628   sequence of declarations
4629#else
4630   completely different sequence of declarations
4631#end if;
4632@end example
4633
4634The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
4635defined either on the command line or in a separate file.
4636
4637The other way of running the preprocessor is even closer to the C style and
4638often more convenient. In this approach the preprocessing is integrated into
4639the compilation process. The compiler is given the preprocessor input which
4640includes @code{#if} lines etc, and then the compiler carries out the
4641preprocessing internally and processes the resulting output.
4642For more details on this approach, see @ref{18,,Integrated Preprocessing}.
4643
4644@node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4645@anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{17}
4646@subsection Preprocessing with @code{gnatprep}
4647
4648
4649@geindex gnatprep
4650
4651@geindex Preprocessing (gnatprep)
4652
4653This section discusses how to use GNAT's @code{gnatprep} utility for simple
4654preprocessing.
4655Although designed for use with GNAT, @code{gnatprep} does not depend on any
4656special GNAT features.
4657For further discussion of conditional compilation in general, see
4658@ref{16,,Conditional Compilation}.
4659
4660@menu
4661* Preprocessing Symbols::
4662* Using gnatprep::
4663* Switches for gnatprep::
4664* Form of Definitions File::
4665* Form of Input Text for gnatprep::
4666
4667@end menu
4668
4669@node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4670@anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{a6}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{a7}
4671@subsubsection Preprocessing Symbols
4672
4673
4674Preprocessing symbols are defined in @emph{definition files} and referenced in the
4675sources to be preprocessed. A preprocessing symbol is an identifier, following
4676normal Ada (case-insensitive) rules for its syntax, with the restriction that
4677all characters need to be in the ASCII set (no accented letters).
4678
4679@node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4680@anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{a8}@anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{a9}
4681@subsubsection Using @code{gnatprep}
4682
4683
4684To call @code{gnatprep} use:
4685
4686@example
4687$ gnatprep [ switches ] infile outfile [ deffile ]
4688@end example
4689
4690where
4691
4692
4693@itemize *
4694
4695@item
4696
4697@table @asis
4698
4699@item @emph{switches}
4700
4701is an optional sequence of switches as described in the next section.
4702@end table
4703
4704@item
4705
4706@table @asis
4707
4708@item @emph{infile}
4709
4710is the full name of the input file, which is an Ada source
4711file containing preprocessor directives.
4712@end table
4713
4714@item
4715
4716@table @asis
4717
4718@item @emph{outfile}
4719
4720is the full name of the output file, which is an Ada source
4721in standard Ada form. When used with GNAT, this file name will
4722normally have an @code{ads} or @code{adb} suffix.
4723@end table
4724
4725@item
4726
4727@table @asis
4728
4729@item @code{deffile}
4730
4731is the full name of a text file containing definitions of
4732preprocessing symbols to be referenced by the preprocessor. This argument is
4733optional, and can be replaced by the use of the @code{-D} switch.
4734@end table
4735@end itemize
4736
4737@node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4738@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{aa}@anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{ab}
4739@subsubsection Switches for @code{gnatprep}
4740
4741
4742@geindex --version (gnatprep)
4743
4744
4745@table @asis
4746
4747@item @code{--version}
4748
4749Display Copyright and version, then exit disregarding all other options.
4750@end table
4751
4752@geindex --help (gnatprep)
4753
4754
4755@table @asis
4756
4757@item @code{--help}
4758
4759If @code{--version} was not used, display usage and then exit disregarding
4760all other options.
4761@end table
4762
4763@geindex -b (gnatprep)
4764
4765
4766@table @asis
4767
4768@item @code{-b}
4769
4770Causes both preprocessor lines and the lines deleted by
4771preprocessing to be replaced by blank lines in the output source file,
4772preserving line numbers in the output file.
4773@end table
4774
4775@geindex -c (gnatprep)
4776
4777
4778@table @asis
4779
4780@item @code{-c}
4781
4782Causes both preprocessor lines and the lines deleted
4783by preprocessing to be retained in the output source as comments marked
4784with the special string @code{"--! "}. This option will result in line numbers
4785being preserved in the output file.
4786@end table
4787
4788@geindex -C (gnatprep)
4789
4790
4791@table @asis
4792
4793@item @code{-C}
4794
4795Causes comments to be scanned. Normally comments are ignored by gnatprep.
4796If this option is specified, then comments are scanned and any $symbol
4797substitutions performed as in program text. This is particularly useful
4798when structured comments are used (e.g., for programs written in a
4799pre-2014 version of the SPARK Ada subset). Note that this switch is not
4800available when  doing integrated preprocessing (it would be useless in
4801this context since comments are ignored by the compiler in any case).
4802@end table
4803
4804@geindex -D (gnatprep)
4805
4806
4807@table @asis
4808
4809@item @code{-D@emph{symbol}[=@emph{value}]}
4810
4811Defines a new preprocessing symbol with the specified value. If no value is given
4812on the command line, then symbol is considered to be @code{True}. This switch
4813can be used in place of a definition file.
4814@end table
4815
4816@geindex -r (gnatprep)
4817
4818
4819@table @asis
4820
4821@item @code{-r}
4822
4823Causes a @code{Source_Reference} pragma to be generated that
4824references the original input file, so that error messages will use
4825the file name of this original file. The use of this switch implies
4826that preprocessor lines are not to be removed from the file, so its
4827use will force @code{-b} mode if @code{-c}
4828has not been specified explicitly.
4829
4830Note that if the file to be preprocessed contains multiple units, then
4831it will be necessary to @code{gnatchop} the output file from
4832@code{gnatprep}. If a @code{Source_Reference} pragma is present
4833in the preprocessed file, it will be respected by
4834@code{gnatchop -r}
4835so that the final chopped files will correctly refer to the original
4836input source file for @code{gnatprep}.
4837@end table
4838
4839@geindex -s (gnatprep)
4840
4841
4842@table @asis
4843
4844@item @code{-s}
4845
4846Causes a sorted list of symbol names and values to be
4847listed on the standard output file.
4848@end table
4849
4850@geindex -T (gnatprep)
4851
4852
4853@table @asis
4854
4855@item @code{-T}
4856
4857Use LF as line terminators when writing files. By default the line terminator
4858of the host (LF under unix, CR/LF under Windows) is used.
4859@end table
4860
4861@geindex -u (gnatprep)
4862
4863
4864@table @asis
4865
4866@item @code{-u}
4867
4868Causes undefined symbols to be treated as having the value FALSE in the context
4869of a preprocessor test. In the absence of this option, an undefined symbol in
4870a @code{#if} or @code{#elsif} test will be treated as an error.
4871@end table
4872
4873@geindex -v (gnatprep)
4874
4875
4876@table @asis
4877
4878@item @code{-v}
4879
4880Verbose mode: generates more output about work done.
4881@end table
4882
4883Note: if neither @code{-b} nor @code{-c} is present,
4884then preprocessor lines and
4885deleted lines are completely removed from the output, unless -r is
4886specified, in which case -b is assumed.
4887
4888@node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4889@anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{ad}
4890@subsubsection Form of Definitions File
4891
4892
4893The definitions file contains lines of the form:
4894
4895@example
4896symbol := value
4897@end example
4898
4899where @code{symbol} is a preprocessing symbol, and @code{value} is one of the following:
4900
4901
4902@itemize *
4903
4904@item
4905Empty, corresponding to a null substitution,
4906
4907@item
4908A string literal using normal Ada syntax, or
4909
4910@item
4911Any sequence of characters from the set @{letters, digits, period, underline@}.
4912@end itemize
4913
4914Comment lines may also appear in the definitions file, starting with
4915the usual @code{--},
4916and comments may be added to the definitions lines.
4917
4918@node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4919@anchor{gnat_ugn/the_gnat_compilation_model id59}@anchor{ae}@anchor{gnat_ugn/the_gnat_compilation_model form-of-input-text-for-gnatprep}@anchor{af}
4920@subsubsection Form of Input Text for @code{gnatprep}
4921
4922
4923The input text may contain preprocessor conditional inclusion lines,
4924as well as general symbol substitution sequences.
4925
4926The preprocessor conditional inclusion commands have the form:
4927
4928@example
4929#if <expression> [then]
4930   lines
4931#elsif <expression> [then]
4932   lines
4933#elsif <expression> [then]
4934   lines
4935...
4936#else
4937   lines
4938#end if;
4939@end example
4940
4941In this example, <expression> is defined by the following grammar:
4942
4943@example
4944<expression> ::=  <symbol>
4945<expression> ::=  <symbol> = "<value>"
4946<expression> ::=  <symbol> = <symbol>
4947<expression> ::=  <symbol> = <integer>
4948<expression> ::=  <symbol> > <integer>
4949<expression> ::=  <symbol> >= <integer>
4950<expression> ::=  <symbol> < <integer>
4951<expression> ::=  <symbol> <= <integer>
4952<expression> ::=  <symbol> 'Defined
4953<expression> ::=  not <expression>
4954<expression> ::=  <expression> and <expression>
4955<expression> ::=  <expression> or <expression>
4956<expression> ::=  <expression> and then <expression>
4957<expression> ::=  <expression> or else <expression>
4958<expression> ::=  ( <expression> )
4959@end example
4960
4961Note the following restriction: it is not allowed to have "and" or "or"
4962following "not" in the same expression without parentheses. For example, this
4963is not allowed:
4964
4965@example
4966not X or Y
4967@end example
4968
4969This can be expressed instead as one of the following forms:
4970
4971@example
4972(not X) or Y
4973not (X or Y)
4974@end example
4975
4976For the first test (<expression> ::= <symbol>) the symbol must have
4977either the value true or false, that is to say the right-hand of the
4978symbol definition must be one of the (case-insensitive) literals
4979@code{True} or @code{False}. If the value is true, then the
4980corresponding lines are included, and if the value is false, they are
4981excluded.
4982
4983When comparing a symbol to an integer, the integer is any non negative
4984literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
49852#11#. The symbol value must also be a non negative integer. Integer values
4986in the range 0 .. 2**31-1 are supported.
4987
4988The test (<expression> ::= <symbol>'Defined) is true only if
4989the symbol has been defined in the definition file or by a @code{-D}
4990switch on the command line. Otherwise, the test is false.
4991
4992The equality tests are case insensitive, as are all the preprocessor lines.
4993
4994If the symbol referenced is not defined in the symbol definitions file,
4995then the effect depends on whether or not switch @code{-u}
4996is specified. If so, then the symbol is treated as if it had the value
4997false and the test fails. If this switch is not specified, then
4998it is an error to reference an undefined symbol. It is also an error to
4999reference a symbol that is defined with a value other than @code{True}
5000or @code{False}.
5001
5002The use of the @code{not} operator inverts the sense of this logical test.
5003The @code{not} operator cannot be combined with the @code{or} or @code{and}
5004operators, without parentheses. For example, "if not X or Y then" is not
5005allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
5006
5007The @code{then} keyword is optional as shown
5008
5009The @code{#} must be the first non-blank character on a line, but
5010otherwise the format is free form. Spaces or tabs may appear between
5011the @code{#} and the keyword. The keywords and the symbols are case
5012insensitive as in normal Ada code. Comments may be used on a
5013preprocessor line, but other than that, no other tokens may appear on a
5014preprocessor line. Any number of @code{elsif} clauses can be present,
5015including none at all. The @code{else} is optional, as in Ada.
5016
5017The @code{#} marking the start of a preprocessor line must be the first
5018non-blank character on the line, i.e., it must be preceded only by
5019spaces or horizontal tabs.
5020
5021Symbol substitution outside of preprocessor lines is obtained by using
5022the sequence:
5023
5024@example
5025$symbol
5026@end example
5027
5028anywhere within a source line, except in a comment or within a
5029string literal. The identifier
5030following the @code{$} must match one of the symbols defined in the symbol
5031definition file, and the result is to substitute the value of the
5032symbol in place of @code{$symbol} in the output file.
5033
5034Note that although the substitution of strings within a string literal
5035is not possible, it is possible to have a symbol whose defined value is
5036a string literal. So instead of setting XYZ to @code{hello} and writing:
5037
5038@example
5039Header : String := "$XYZ";
5040@end example
5041
5042you should set XYZ to @code{"hello"} and write:
5043
5044@example
5045Header : String := $XYZ;
5046@end example
5047
5048and then the substitution will occur as desired.
5049
5050@node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
5051@anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{18}
5052@subsection Integrated Preprocessing
5053
5054
5055As noted above, a file to be preprocessed consists of Ada source code
5056in which preprocessing lines have been inserted. However,
5057instead of using @code{gnatprep} to explicitly preprocess a file as a separate
5058step before compilation, you can carry out the preprocessing implicitly
5059as part of compilation. Such @emph{integrated preprocessing}, which is the common
5060style with C, is performed when either or both of the following switches
5061are passed to the compiler:
5062
5063@quotation
5064
5065
5066@itemize *
5067
5068@item
5069@code{-gnatep}, which specifies the @emph{preprocessor data file}.
5070This file dictates how the source files will be preprocessed (e.g., which
5071symbol definition files apply to which sources).
5072
5073@item
5074@code{-gnateD}, which defines values for preprocessing symbols.
5075@end itemize
5076@end quotation
5077
5078Integrated preprocessing applies only to Ada source files, it is
5079not available for configuration pragma files.
5080
5081With integrated preprocessing, the output from the preprocessor is not,
5082by default, written to any external file. Instead it is passed
5083internally to the compiler. To preserve the result of
5084preprocessing in a file, either run @code{gnatprep}
5085in standalone mode or else supply the @code{-gnateG} switch
5086(described below) to the compiler.
5087
5088When using project files:
5089
5090@quotation
5091
5092
5093@itemize *
5094
5095@item
5096the builder switch @code{-x} should be used if any Ada source is
5097compiled with @code{gnatep=}, so that the compiler finds the
5098@emph{preprocessor data file}.
5099
5100@item
5101the preprocessing data file and the symbol definition files should be
5102located in the source directories of the project.
5103@end itemize
5104@end quotation
5105
5106Note that the @code{gnatmake} switch @code{-m} will almost
5107always trigger recompilation for sources that are preprocessed,
5108because @code{gnatmake} cannot compute the checksum of the source after
5109preprocessing.
5110
5111The actual preprocessing function is described in detail in
5112@ref{17,,Preprocessing with gnatprep}. This section explains the switches
5113that relate to integrated preprocessing.
5114
5115@geindex -gnatep (gcc)
5116
5117
5118@table @asis
5119
5120@item @code{-gnatep=@emph{preprocessor_data_file}}
5121
5122This switch specifies the file name (without directory
5123information) of the preprocessor data file. Either place this file
5124in one of the source directories, or, when using project
5125files, reference the project file's directory via the
5126@code{project_name'Project_Dir} project attribute; e.g:
5127
5128@quotation
5129
5130@example
5131project Prj is
5132   package Compiler is
5133      for Switches ("Ada") use
5134        ("-gnatep=" & Prj'Project_Dir & "prep.def");
5135   end Compiler;
5136end Prj;
5137@end example
5138@end quotation
5139
5140A preprocessor data file is a text file that contains @emph{preprocessor
5141control lines}.  A preprocessor control line directs the preprocessing of
5142either a particular source file, or, analogous to @code{others} in Ada,
5143all sources not specified elsewhere in  the preprocessor data file.
5144A preprocessor control line
5145can optionally identify a @emph{definition file} that assigns values to
5146preprocessor symbols, as well as a list of switches that relate to
5147preprocessing.
5148Empty lines and comments (using Ada syntax) are also permitted, with no
5149semantic effect.
5150
5151Here's an example of a preprocessor data file:
5152
5153@quotation
5154
5155@example
5156"toto.adb"  "prep.def" -u
5157--  Preprocess toto.adb, using definition file prep.def
5158--  Undefined symbols are treated as False
5159
5160* -c -DVERSION=V101
5161--  Preprocess all other sources without using a definition file
5162--  Suppressed lined are commented
5163--  Symbol VERSION has the value V101
5164
5165"tata.adb" "prep2.def" -s
5166--  Preprocess tata.adb, using definition file prep2.def
5167--  List all symbols with their values
5168@end example
5169@end quotation
5170
5171A preprocessor control line has the following syntax:
5172
5173@quotation
5174
5175@example
5176<preprocessor_control_line> ::=
5177   <preprocessor_input> [ <definition_file_name> ] @{ <switch> @}
5178
5179<preprocessor_input> ::= <source_file_name> | '*'
5180
5181<definition_file_name> ::= <string_literal>
5182
5183<source_file_name> := <string_literal>
5184
5185<switch> := (See below for list)
5186@end example
5187@end quotation
5188
5189Thus  each preprocessor control line starts with either a literal string or
5190the character '*':
5191
5192
5193@itemize *
5194
5195@item
5196A literal string is the file name (without directory information) of the source
5197file that will be input to the preprocessor.
5198
5199@item
5200The character '*' is a wild-card indicator; the additional parameters on the line
5201indicate the preprocessing for all the sources
5202that are not specified explicitly on other lines (the order of the lines is not
5203significant).
5204@end itemize
5205
5206It is an error to have two lines with the same file name or two
5207lines starting with the character '*'.
5208
5209After the file name or '*', an optional literal string specifies the name of
5210the definition file to be used for preprocessing
5211(@ref{ac,,Form of Definitions File}). The definition files are found by the
5212compiler in one of the source directories. In some cases, when compiling
5213a source in a directory other than the current directory, if the definition
5214file is in the current directory, it may be necessary to add the current
5215directory as a source directory through the @code{-I} switch; otherwise
5216the compiler would not find the definition file.
5217
5218Finally, switches similar to those of @code{gnatprep} may optionally appear:
5219
5220
5221@table @asis
5222
5223@item @code{-b}
5224
5225Causes both preprocessor lines and the lines deleted by
5226preprocessing to be replaced by blank lines, preserving the line number.
5227This switch is always implied; however, if specified after @code{-c}
5228it cancels the effect of @code{-c}.
5229
5230@item @code{-c}
5231
5232Causes both preprocessor lines and the lines deleted
5233by preprocessing to be retained as comments marked
5234with the special string '@cite{--!}'.
5235
5236@item @code{-D@emph{symbol}=@emph{new_value}}
5237
5238Define or redefine @code{symbol} to have @code{new_value} as its value.
5239The permitted form for @code{symbol} is either an Ada identifier, or any Ada reserved word
5240aside from @code{if},
5241@code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5242The permitted form for @code{new_value} is a literal string, an Ada identifier or any Ada reserved
5243word. A symbol declared with this switch replaces a symbol with the
5244same name defined in a definition file.
5245
5246@item @code{-s}
5247
5248Causes a sorted list of symbol names and values to be
5249listed on the standard output file.
5250
5251@item @code{-u}
5252
5253Causes undefined symbols to be treated as having the value @code{FALSE}
5254in the context
5255of a preprocessor test. In the absence of this option, an undefined symbol in
5256a @code{#if} or @code{#elsif} test will be treated as an error.
5257@end table
5258@end table
5259
5260@geindex -gnateD (gcc)
5261
5262
5263@table @asis
5264
5265@item @code{-gnateD@emph{symbol}[=@emph{new_value}]}
5266
5267Define or redefine @code{symbol} to have @code{new_value} as its value. If no value
5268is supplied, then the value of @code{symbol} is @code{True}.
5269The form of @code{symbol} is an identifier, following normal Ada (case-insensitive)
5270rules for its syntax, and @code{new_value} is either an arbitrary string between double
5271quotes or any sequence (including an empty sequence) of characters from the
5272set (letters, digits, period, underline).
5273Ada reserved words may be used as symbols, with the exceptions of @code{if},
5274@code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5275
5276Examples:
5277
5278@quotation
5279
5280@example
5281-gnateDToto=Tata
5282-gnateDFoo
5283-gnateDFoo=\"Foo-Bar\"
5284@end example
5285@end quotation
5286
5287A symbol declared with this switch on the command line replaces a
5288symbol with the same name either in a definition file or specified with a
5289switch @code{-D} in the preprocessor data file.
5290
5291This switch is similar to switch @code{-D} of @code{gnatprep}.
5292
5293@item @code{-gnateG}
5294
5295When integrated preprocessing is performed on source file @code{filename.extension},
5296create or overwrite @code{filename.extension.prep} to contain
5297the result of the preprocessing.
5298For example if the source file is @code{foo.adb} then
5299the output file will be @code{foo.adb.prep}.
5300@end table
5301
5302@node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5303@anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{44}@anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{b1}
5304@section Mixed Language Programming
5305
5306
5307@geindex Mixed Language Programming
5308
5309This section describes how to develop a mixed-language program,
5310with a focus on combining Ada with C or C++.
5311
5312@menu
5313* Interfacing to C::
5314* Calling Conventions::
5315* Building Mixed Ada and C++ Programs::
5316* Generating Ada Bindings for C and C++ headers::
5317* Generating C Headers for Ada Specifications::
5318
5319@end menu
5320
5321@node Interfacing to C,Calling Conventions,,Mixed Language Programming
5322@anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{b2}@anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{b3}
5323@subsection Interfacing to C
5324
5325
5326Interfacing Ada with a foreign language such as C involves using
5327compiler directives to import and/or export entity definitions in each
5328language -- using @code{extern} statements in C, for instance, and the
5329@code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
5330A full treatment of these topics is provided in Appendix B, section 1
5331of the Ada Reference Manual.
5332
5333There are two ways to build a program using GNAT that contains some Ada
5334sources and some foreign language sources, depending on whether or not
5335the main subprogram is written in Ada.  Here is a source example with
5336the main subprogram in Ada:
5337
5338@example
5339/* file1.c */
5340#include <stdio.h>
5341
5342void print_num (int num)
5343@{
5344  printf ("num is %d.\\n", num);
5345  return;
5346@}
5347@end example
5348
5349@example
5350/* file2.c */
5351
5352/* num_from_Ada is declared in my_main.adb */
5353extern int num_from_Ada;
5354
5355int get_num (void)
5356@{
5357  return num_from_Ada;
5358@}
5359@end example
5360
5361@example
5362--  my_main.adb
5363procedure My_Main is
5364
5365   --  Declare then export an Integer entity called num_from_Ada
5366   My_Num : Integer := 10;
5367   pragma Export (C, My_Num, "num_from_Ada");
5368
5369   --  Declare an Ada function spec for Get_Num, then use
5370   --  C function get_num for the implementation.
5371   function Get_Num return Integer;
5372   pragma Import (C, Get_Num, "get_num");
5373
5374   --  Declare an Ada procedure spec for Print_Num, then use
5375   --  C function print_num for the implementation.
5376   procedure Print_Num (Num : Integer);
5377   pragma Import (C, Print_Num, "print_num");
5378
5379begin
5380   Print_Num (Get_Num);
5381end My_Main;
5382@end example
5383
5384To build this example:
5385
5386
5387@itemize *
5388
5389@item
5390First compile the foreign language files to
5391generate object files:
5392
5393@example
5394$ gcc -c file1.c
5395$ gcc -c file2.c
5396@end example
5397
5398@item
5399Then, compile the Ada units to produce a set of object files and ALI
5400files:
5401
5402@example
5403$ gnatmake -c my_main.adb
5404@end example
5405
5406@item
5407Run the Ada binder on the Ada main program:
5408
5409@example
5410$ gnatbind my_main.ali
5411@end example
5412
5413@item
5414Link the Ada main program, the Ada objects and the other language
5415objects:
5416
5417@example
5418$ gnatlink my_main.ali file1.o file2.o
5419@end example
5420@end itemize
5421
5422The last three steps can be grouped in a single command:
5423
5424@example
5425$ gnatmake my_main.adb -largs file1.o file2.o
5426@end example
5427
5428@geindex Binder output file
5429
5430If the main program is in a language other than Ada, then you may have
5431more than one entry point into the Ada subsystem. You must use a special
5432binder option to generate callable routines that initialize and
5433finalize the Ada units (@ref{b4,,Binding with Non-Ada Main Programs}).
5434Calls to the initialization and finalization routines must be inserted
5435in the main program, or some other appropriate point in the code. The
5436call to initialize the Ada units must occur before the first Ada
5437subprogram is called, and the call to finalize the Ada units must occur
5438after the last Ada subprogram returns. The binder will place the
5439initialization and finalization subprograms into the
5440@code{b~xxx.adb} file where they can be accessed by your C
5441sources.  To illustrate, we have the following example:
5442
5443@example
5444/* main.c */
5445extern void adainit (void);
5446extern void adafinal (void);
5447extern int add (int, int);
5448extern int sub (int, int);
5449
5450int main (int argc, char *argv[])
5451@{
5452   int a = 21, b = 7;
5453
5454   adainit();
5455
5456   /* Should print "21 + 7 = 28" */
5457   printf ("%d + %d = %d\\n", a, b, add (a, b));
5458
5459   /* Should print "21 - 7 = 14" */
5460   printf ("%d - %d = %d\\n", a, b, sub (a, b));
5461
5462   adafinal();
5463@}
5464@end example
5465
5466@example
5467--  unit1.ads
5468package Unit1 is
5469   function Add (A, B : Integer) return Integer;
5470   pragma Export (C, Add, "add");
5471end Unit1;
5472@end example
5473
5474@example
5475--  unit1.adb
5476package body Unit1 is
5477   function Add (A, B : Integer) return Integer is
5478   begin
5479      return A + B;
5480   end Add;
5481end Unit1;
5482@end example
5483
5484@example
5485--  unit2.ads
5486package Unit2 is
5487   function Sub (A, B : Integer) return Integer;
5488   pragma Export (C, Sub, "sub");
5489end Unit2;
5490@end example
5491
5492@example
5493--  unit2.adb
5494package body Unit2 is
5495   function Sub (A, B : Integer) return Integer is
5496   begin
5497      return A - B;
5498   end Sub;
5499end Unit2;
5500@end example
5501
5502The build procedure for this application is similar to the last
5503example's:
5504
5505
5506@itemize *
5507
5508@item
5509First, compile the foreign language files to generate object files:
5510
5511@example
5512$ gcc -c main.c
5513@end example
5514
5515@item
5516Next, compile the Ada units to produce a set of object files and ALI
5517files:
5518
5519@example
5520$ gnatmake -c unit1.adb
5521$ gnatmake -c unit2.adb
5522@end example
5523
5524@item
5525Run the Ada binder on every generated ALI file.  Make sure to use the
5526@code{-n} option to specify a foreign main program:
5527
5528@example
5529$ gnatbind -n unit1.ali unit2.ali
5530@end example
5531
5532@item
5533Link the Ada main program, the Ada objects and the foreign language
5534objects. You need only list the last ALI file here:
5535
5536@example
5537$ gnatlink unit2.ali main.o -o exec_file
5538@end example
5539
5540This procedure yields a binary executable called @code{exec_file}.
5541@end itemize
5542
5543Depending on the circumstances (for example when your non-Ada main object
5544does not provide symbol @code{main}), you may also need to instruct the
5545GNAT linker not to include the standard startup objects by passing the
5546@code{-nostartfiles} switch to @code{gnatlink}.
5547
5548@node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5549@anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{b5}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{b6}
5550@subsection Calling Conventions
5551
5552
5553@geindex Foreign Languages
5554
5555@geindex Calling Conventions
5556
5557GNAT follows standard calling sequence conventions and will thus interface
5558to any other language that also follows these conventions. The following
5559Convention identifiers are recognized by GNAT:
5560
5561@geindex Interfacing to Ada
5562
5563@geindex Other Ada compilers
5564
5565@geindex Convention Ada
5566
5567
5568@table @asis
5569
5570@item @code{Ada}
5571
5572This indicates that the standard Ada calling sequence will be
5573used and all Ada data items may be passed without any limitations in the
5574case where GNAT is used to generate both the caller and callee. It is also
5575possible to mix GNAT generated code and code generated by another Ada
5576compiler. In this case, the data types should be restricted to simple
5577cases, including primitive types. Whether complex data types can be passed
5578depends on the situation. Probably it is safe to pass simple arrays, such
5579as arrays of integers or floats. Records may or may not work, depending
5580on whether both compilers lay them out identically. Complex structures
5581involving variant records, access parameters, tasks, or protected types,
5582are unlikely to be able to be passed.
5583
5584Note that in the case of GNAT running
5585on a platform that supports HP Ada 83, a higher degree of compatibility
5586can be guaranteed, and in particular records are laid out in an identical
5587manner in the two compilers. Note also that if output from two different
5588compilers is mixed, the program is responsible for dealing with elaboration
5589issues. Probably the safest approach is to write the main program in the
5590version of Ada other than GNAT, so that it takes care of its own elaboration
5591requirements, and then call the GNAT-generated adainit procedure to ensure
5592elaboration of the GNAT components. Consult the documentation of the other
5593Ada compiler for further details on elaboration.
5594
5595However, it is not possible to mix the tasking run time of GNAT and
5596HP Ada 83, All the tasking operations must either be entirely within
5597GNAT compiled sections of the program, or entirely within HP Ada 83
5598compiled sections of the program.
5599@end table
5600
5601@geindex Interfacing to Assembly
5602
5603@geindex Convention Assembler
5604
5605
5606@table @asis
5607
5608@item @code{Assembler}
5609
5610Specifies assembler as the convention. In practice this has the
5611same effect as convention Ada (but is not equivalent in the sense of being
5612considered the same convention).
5613@end table
5614
5615@geindex Convention Asm
5616
5617@geindex Asm
5618
5619
5620@table @asis
5621
5622@item @code{Asm}
5623
5624Equivalent to Assembler.
5625
5626@geindex Interfacing to COBOL
5627
5628@geindex Convention COBOL
5629@end table
5630
5631@geindex COBOL
5632
5633
5634@table @asis
5635
5636@item @code{COBOL}
5637
5638Data will be passed according to the conventions described
5639in section B.4 of the Ada Reference Manual.
5640@end table
5641
5642@geindex C
5643
5644@geindex Interfacing to C
5645
5646@geindex Convention C
5647
5648
5649@table @asis
5650
5651@item @code{C}
5652
5653Data will be passed according to the conventions described
5654in section B.3 of the Ada Reference Manual.
5655
5656A note on interfacing to a C 'varargs' function:
5657
5658@quotation
5659
5660@geindex C varargs function
5661
5662@geindex Interfacing to C varargs function
5663
5664@geindex varargs function interfaces
5665
5666In C, @code{varargs} allows a function to take a variable number of
5667arguments. There is no direct equivalent in this to Ada. One
5668approach that can be used is to create a C wrapper for each
5669different profile and then interface to this C wrapper. For
5670example, to print an @code{int} value using @code{printf},
5671create a C function @code{printfi} that takes two arguments, a
5672pointer to a string and an int, and calls @code{printf}.
5673Then in the Ada program, use pragma @code{Import} to
5674interface to @code{printfi}.
5675
5676It may work on some platforms to directly interface to
5677a @code{varargs} function by providing a specific Ada profile
5678for a particular call. However, this does not work on
5679all platforms, since there is no guarantee that the
5680calling sequence for a two argument normal C function
5681is the same as for calling a @code{varargs} C function with
5682the same two arguments.
5683@end quotation
5684@end table
5685
5686@geindex Convention Default
5687
5688@geindex Default
5689
5690
5691@table @asis
5692
5693@item @code{Default}
5694
5695Equivalent to C.
5696@end table
5697
5698@geindex Convention External
5699
5700@geindex External
5701
5702
5703@table @asis
5704
5705@item @code{External}
5706
5707Equivalent to C.
5708@end table
5709
5710@geindex C++
5711
5712@geindex Interfacing to C++
5713
5714@geindex Convention C++
5715
5716
5717@table @asis
5718
5719@item @code{C_Plus_Plus} (or @code{CPP})
5720
5721This stands for C++. For most purposes this is identical to C.
5722See the separate description of the specialized GNAT pragmas relating to
5723C++ interfacing for further details.
5724@end table
5725
5726@geindex Fortran
5727
5728@geindex Interfacing to Fortran
5729
5730@geindex Convention Fortran
5731
5732
5733@table @asis
5734
5735@item @code{Fortran}
5736
5737Data will be passed according to the conventions described
5738in section B.5 of the Ada Reference Manual.
5739
5740@item @code{Intrinsic}
5741
5742This applies to an intrinsic operation, as defined in the Ada
5743Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5744this means that the body of the subprogram is provided by the compiler itself,
5745usually by means of an efficient code sequence, and that the user does not
5746supply an explicit body for it. In an application program, the pragma may
5747be applied to the following sets of names:
5748
5749
5750@itemize *
5751
5752@item
5753Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5754The corresponding subprogram declaration must have
5755two formal parameters. The
5756first one must be a signed integer type or a modular type with a binary
5757modulus, and the second parameter must be of type Natural.
5758The return type must be the same as the type of the first argument. The size
5759of this type can only be 8, 16, 32, or 64.
5760
5761@item
5762Binary arithmetic operators: '+', '-', '*', '/'.
5763The corresponding operator declaration must have parameters and result type
5764that have the same root numeric type (for example, all three are long_float
5765types). This simplifies the definition of operations that use type checking
5766to perform dimensional checks:
5767@end itemize
5768
5769@example
5770  type Distance is new Long_Float;
5771  type Time     is new Long_Float;
5772  type Velocity is new Long_Float;
5773  function "/" (D : Distance; T : Time)
5774    return Velocity;
5775  pragma Import (Intrinsic, "/");
5776
5777This common idiom is often programmed with a generic definition and an
5778explicit body. The pragma makes it simpler to introduce such declarations.
5779It incurs no overhead in compilation time or code size, because it is
5780implemented as a single machine instruction.
5781@end example
5782
5783
5784@itemize *
5785
5786@item
5787General subprogram entities. This is used  to bind an Ada subprogram
5788declaration to
5789a compiler builtin by name with back-ends where such interfaces are
5790available. A typical example is the set of @code{__builtin} functions
5791exposed by the GCC back-end, as in the following example:
5792
5793@example
5794function builtin_sqrt (F : Float) return Float;
5795pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5796@end example
5797
5798Most of the GCC builtins are accessible this way, and as for other
5799import conventions (e.g. C), it is the user's responsibility to ensure
5800that the Ada subprogram profile matches the underlying builtin
5801expectations.
5802@end itemize
5803@end table
5804
5805@geindex Stdcall
5806
5807@geindex Convention Stdcall
5808
5809
5810@table @asis
5811
5812@item @code{Stdcall}
5813
5814This is relevant only to Windows implementations of GNAT,
5815and specifies that the @code{Stdcall} calling sequence will be used,
5816as defined by the NT API. Nevertheless, to ease building
5817cross-platform bindings this convention will be handled as a @code{C} calling
5818convention on non-Windows platforms.
5819@end table
5820
5821@geindex DLL
5822
5823@geindex Convention DLL
5824
5825
5826@table @asis
5827
5828@item @code{DLL}
5829
5830This is equivalent to @code{Stdcall}.
5831@end table
5832
5833@geindex Win32
5834
5835@geindex Convention Win32
5836
5837
5838@table @asis
5839
5840@item @code{Win32}
5841
5842This is equivalent to @code{Stdcall}.
5843@end table
5844
5845@geindex Stubbed
5846
5847@geindex Convention Stubbed
5848
5849
5850@table @asis
5851
5852@item @code{Stubbed}
5853
5854This is a special convention that indicates that the compiler
5855should provide a stub body that raises @code{Program_Error}.
5856@end table
5857
5858GNAT additionally provides a useful pragma @code{Convention_Identifier}
5859that can be used to parameterize conventions and allow additional synonyms
5860to be specified. For example if you have legacy code in which the convention
5861identifier Fortran77 was used for Fortran, you can use the configuration
5862pragma:
5863
5864@example
5865pragma Convention_Identifier (Fortran77, Fortran);
5866@end example
5867
5868And from now on the identifier Fortran77 may be used as a convention
5869identifier (for example in an @code{Import} pragma) with the same
5870meaning as Fortran.
5871
5872@node Building Mixed Ada and C++ Programs,Generating Ada Bindings for C and C++ headers,Calling Conventions,Mixed Language Programming
5873@anchor{gnat_ugn/the_gnat_compilation_model id64}@anchor{b7}@anchor{gnat_ugn/the_gnat_compilation_model building-mixed-ada-and-c-programs}@anchor{b8}
5874@subsection Building Mixed Ada and C++ Programs
5875
5876
5877A programmer inexperienced with mixed-language development may find that
5878building an application containing both Ada and C++ code can be a
5879challenge.  This section gives a few hints that should make this task easier.
5880
5881@menu
5882* Interfacing to C++::
5883* Linking a Mixed C++ & Ada Program::
5884* A Simple Example::
5885* Interfacing with C++ constructors::
5886* Interfacing with C++ at the Class Level::
5887
5888@end menu
5889
5890@node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5891@anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{b9}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{ba}
5892@subsubsection Interfacing to C++
5893
5894
5895GNAT supports interfacing with the G++ compiler (or any C++ compiler
5896generating code that is compatible with the G++ Application Binary
5897Interface ---see @indicateurl{http://www.codesourcery.com/archives/cxx-abi}).
5898
5899Interfacing can be done at 3 levels: simple data, subprograms, and
5900classes. In the first two cases, GNAT offers a specific @code{Convention C_Plus_Plus}
5901(or @code{CPP}) that behaves exactly like @code{Convention C}.
5902Usually, C++ mangles the names of subprograms. To generate proper mangled
5903names automatically, see @ref{19,,Generating Ada Bindings for C and C++ headers}).
5904This problem can also be addressed manually in two ways:
5905
5906
5907@itemize *
5908
5909@item
5910by modifying the C++ code in order to force a C convention using
5911the @code{extern "C"} syntax.
5912
5913@item
5914by figuring out the mangled name (using e.g. @code{nm}) and using it as the
5915Link_Name argument of the pragma import.
5916@end itemize
5917
5918Interfacing at the class level can be achieved by using the GNAT specific
5919pragmas such as @code{CPP_Constructor}.  See the @cite{GNAT_Reference_Manual} for additional information.
5920
5921@node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5922@anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-ada-program}@anchor{bb}@anchor{gnat_ugn/the_gnat_compilation_model linking-a-mixed-c-and-ada-program}@anchor{bc}
5923@subsubsection Linking a Mixed C++ & Ada Program
5924
5925
5926Usually the linker of the C++ development system must be used to link
5927mixed applications because most C++ systems will resolve elaboration
5928issues (such as calling constructors on global class instances)
5929transparently during the link phase. GNAT has been adapted to ease the
5930use of a foreign linker for the last phase. Three cases can be
5931considered:
5932
5933
5934@itemize *
5935
5936@item
5937Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5938The C++ linker can simply be called by using the C++ specific driver
5939called @code{g++}.
5940
5941Note that if the C++ code uses inline functions, you will need to
5942compile your C++ code with the @code{-fkeep-inline-functions} switch in
5943order to provide an existing function implementation that the Ada code can
5944link with.
5945
5946@example
5947$ g++ -c -fkeep-inline-functions file1.C
5948$ g++ -c -fkeep-inline-functions file2.C
5949$ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5950@end example
5951
5952@item
5953Using GNAT and G++ from two different GCC installations: If both
5954compilers are on the :envvar`PATH`, the previous method may be used. It is
5955important to note that environment variables such as
5956@geindex C_INCLUDE_PATH
5957@geindex environment variable; C_INCLUDE_PATH
5958@code{C_INCLUDE_PATH},
5959@geindex GCC_EXEC_PREFIX
5960@geindex environment variable; GCC_EXEC_PREFIX
5961@code{GCC_EXEC_PREFIX},
5962@geindex BINUTILS_ROOT
5963@geindex environment variable; BINUTILS_ROOT
5964@code{BINUTILS_ROOT}, and
5965@geindex GCC_ROOT
5966@geindex environment variable; GCC_ROOT
5967@code{GCC_ROOT} will affect both compilers
5968at the same time and may make one of the two compilers operate
5969improperly if set during invocation of the wrong compiler.  It is also
5970very important that the linker uses the proper @code{libgcc.a} GCC
5971library -- that is, the one from the C++ compiler installation. The
5972implicit link command as suggested in the @code{gnatmake} command
5973from the former example can be replaced by an explicit link command with
5974the full-verbosity option in order to verify which library is used:
5975
5976@example
5977$ gnatbind ada_unit
5978$ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5979@end example
5980
5981If there is a problem due to interfering environment variables, it can
5982be worked around by using an intermediate script. The following example
5983shows the proper script to use when GNAT has not been installed at its
5984default location and g++ has been installed at its default location:
5985
5986@example
5987$ cat ./my_script
5988#!/bin/sh
5989unset BINUTILS_ROOT
5990unset GCC_ROOT
5991c++ $*
5992$ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5993@end example
5994
5995@item
5996Using a non-GNU C++ compiler: The commands previously described can be
5997used to insure that the C++ linker is used. Nonetheless, you need to add
5998a few more parameters to the link command line, depending on the exception
5999mechanism used.
6000
6001If the @code{setjmp} / @code{longjmp} exception mechanism is used, only the paths
6002to the @code{libgcc} libraries are required:
6003
6004@example
6005$ cat ./my_script
6006#!/bin/sh
6007CC $* gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a
6008$ gnatlink ada_unit file1.o file2.o --LINK=./my_script
6009@end example
6010
6011where CC is the name of the non-GNU C++ compiler.
6012
6013If the "zero cost" exception mechanism is used, and the platform
6014supports automatic registration of exception tables (e.g., Solaris),
6015paths to more objects are required:
6016
6017@example
6018$ cat ./my_script
6019#!/bin/sh
6020CC gcc -print-file-name=crtbegin.o $* \\
6021gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a \\
6022gcc -print-file-name=crtend.o
6023$ gnatlink ada_unit file1.o file2.o --LINK=./my_script
6024@end example
6025
6026If the "zero cost exception" mechanism is used, and the platform
6027doesn't support automatic registration of exception tables (e.g., HP-UX
6028or AIX), the simple approach described above will not work and
6029a pre-linking phase using GNAT will be necessary.
6030@end itemize
6031
6032Another alternative is to use the @code{gprbuild} multi-language builder
6033which has a large knowledge base and knows how to link Ada and C++ code
6034together automatically in most cases.
6035
6036@node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
6037@anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{bd}@anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{be}
6038@subsubsection A Simple Example
6039
6040
6041The following example, provided as part of the GNAT examples, shows how
6042to achieve procedural interfacing between Ada and C++ in both
6043directions. The C++ class A has two methods. The first method is exported
6044to Ada by the means of an extern C wrapper function. The second method
6045calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
6046a limited record with a layout comparable to the C++ class. The Ada
6047subprogram, in turn, calls the C++ method. So, starting from the C++
6048main program, the process passes back and forth between the two
6049languages.
6050
6051Here are the compilation commands:
6052
6053@example
6054$ gnatmake -c simple_cpp_interface
6055$ g++ -c cpp_main.C
6056$ g++ -c ex7.C
6057$ gnatbind -n simple_cpp_interface
6058$ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
6059@end example
6060
6061Here are the corresponding sources:
6062
6063@example
6064//cpp_main.C
6065
6066#include "ex7.h"
6067
6068extern "C" @{
6069  void adainit (void);
6070  void adafinal (void);
6071  void method1 (A *t);
6072@}
6073
6074void method1 (A *t)
6075@{
6076  t->method1 ();
6077@}
6078
6079int main ()
6080@{
6081  A obj;
6082  adainit ();
6083  obj.method2 (3030);
6084  adafinal ();
6085@}
6086@end example
6087
6088@example
6089//ex7.h
6090
6091class Origin @{
6092 public:
6093  int o_value;
6094@};
6095class A : public Origin @{
6096 public:
6097  void method1 (void);
6098  void method2 (int v);
6099  A();
6100  int   a_value;
6101@};
6102@end example
6103
6104@example
6105//ex7.C
6106
6107#include "ex7.h"
6108#include <stdio.h>
6109
6110extern "C" @{ void ada_method2 (A *t, int v);@}
6111
6112void A::method1 (void)
6113@{
6114  a_value = 2020;
6115  printf ("in A::method1, a_value = %d \\n",a_value);
6116@}
6117
6118void A::method2 (int v)
6119@{
6120   ada_method2 (this, v);
6121   printf ("in A::method2, a_value = %d \\n",a_value);
6122@}
6123
6124A::A(void)
6125@{
6126   a_value = 1010;
6127  printf ("in A::A, a_value = %d \\n",a_value);
6128@}
6129@end example
6130
6131@example
6132-- simple_cpp_interface.ads
6133with System;
6134package Simple_Cpp_Interface is
6135   type A is limited
6136      record
6137         Vptr    : System.Address;
6138         O_Value : Integer;
6139         A_Value : Integer;
6140      end record;
6141   pragma Convention (C, A);
6142
6143   procedure Method1 (This : in out A);
6144   pragma Import (C, Method1);
6145
6146   procedure Ada_Method2 (This : in out A; V : Integer);
6147   pragma Export (C, Ada_Method2);
6148
6149end Simple_Cpp_Interface;
6150@end example
6151
6152@example
6153-- simple_cpp_interface.adb
6154package body Simple_Cpp_Interface is
6155
6156   procedure Ada_Method2 (This : in out A; V : Integer) is
6157   begin
6158      Method1 (This);
6159      This.A_Value := V;
6160   end Ada_Method2;
6161
6162end Simple_Cpp_Interface;
6163@end example
6164
6165@node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
6166@anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{bf}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{c0}
6167@subsubsection Interfacing with C++ constructors
6168
6169
6170In order to interface with C++ constructors GNAT provides the
6171@code{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
6172for additional information).
6173In this section we present some common uses of C++ constructors
6174in mixed-languages programs in GNAT.
6175
6176Let us assume that we need to interface with the following
6177C++ class:
6178
6179@example
6180class Root @{
6181public:
6182  int  a_value;
6183  int  b_value;
6184  virtual int Get_Value ();
6185  Root();              // Default constructor
6186  Root(int v);         // 1st non-default constructor
6187  Root(int v, int w);  // 2nd non-default constructor
6188@};
6189@end example
6190
6191For this purpose we can write the following package spec (further
6192information on how to build this spec is available in
6193@ref{c1,,Interfacing with C++ at the Class Level} and
6194@ref{19,,Generating Ada Bindings for C and C++ headers}).
6195
6196@example
6197with Interfaces.C; use Interfaces.C;
6198package Pkg_Root is
6199  type Root is tagged limited record
6200     A_Value : int;
6201     B_Value : int;
6202  end record;
6203  pragma Import (CPP, Root);
6204
6205  function Get_Value (Obj : Root) return int;
6206  pragma Import (CPP, Get_Value);
6207
6208  function Constructor return Root;
6209  pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
6210
6211  function Constructor (v : Integer) return Root;
6212  pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
6213
6214  function Constructor (v, w : Integer) return Root;
6215  pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
6216end Pkg_Root;
6217@end example
6218
6219On the Ada side the constructor is represented by a function (whose
6220name is arbitrary) that returns the classwide type corresponding to
6221the imported C++ class. Although the constructor is described as a
6222function, it is typically a procedure with an extra implicit argument
6223(the object being initialized) at the implementation level. GNAT
6224issues the appropriate call, whatever it is, to get the object
6225properly initialized.
6226
6227Constructors can only appear in the following contexts:
6228
6229
6230@itemize *
6231
6232@item
6233On the right side of an initialization of an object of type @code{T}.
6234
6235@item
6236On the right side of an initialization of a record component of type @code{T}.
6237
6238@item
6239In an Ada 2005 limited aggregate.
6240
6241@item
6242In an Ada 2005 nested limited aggregate.
6243
6244@item
6245In an Ada 2005 limited aggregate that initializes an object built in
6246place by an extended return statement.
6247@end itemize
6248
6249In a declaration of an object whose type is a class imported from C++,
6250either the default C++ constructor is implicitly called by GNAT, or
6251else the required C++ constructor must be explicitly called in the
6252expression that initializes the object. For example:
6253
6254@example
6255Obj1 : Root;
6256Obj2 : Root := Constructor;
6257Obj3 : Root := Constructor (v => 10);
6258Obj4 : Root := Constructor (30, 40);
6259@end example
6260
6261The first two declarations are equivalent: in both cases the default C++
6262constructor is invoked (in the former case the call to the constructor is
6263implicit, and in the latter case the call is explicit in the object
6264declaration). @code{Obj3} is initialized by the C++ non-default constructor
6265that takes an integer argument, and @code{Obj4} is initialized by the
6266non-default C++ constructor that takes two integers.
6267
6268Let us derive the imported C++ class in the Ada side. For example:
6269
6270@example
6271type DT is new Root with record
6272   C_Value : Natural := 2009;
6273end record;
6274@end example
6275
6276In this case the components DT inherited from the C++ side must be
6277initialized by a C++ constructor, and the additional Ada components
6278of type DT are initialized by GNAT. The initialization of such an
6279object is done either by default, or by means of a function returning
6280an aggregate of type DT, or by means of an extension aggregate.
6281
6282@example
6283Obj5 : DT;
6284Obj6 : DT := Function_Returning_DT (50);
6285Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6286@end example
6287
6288The declaration of @code{Obj5} invokes the default constructors: the
6289C++ default constructor of the parent type takes care of the initialization
6290of the components inherited from Root, and GNAT takes care of the default
6291initialization of the additional Ada components of type DT (that is,
6292@code{C_Value} is initialized to value 2009). The order of invocation of
6293the constructors is consistent with the order of elaboration required by
6294Ada and C++. That is, the constructor of the parent type is always called
6295before the constructor of the derived type.
6296
6297Let us now consider a record that has components whose type is imported
6298from C++. For example:
6299
6300@example
6301type Rec1 is limited record
6302   Data1 : Root := Constructor (10);
6303   Value : Natural := 1000;
6304end record;
6305
6306type Rec2 (D : Integer := 20) is limited record
6307   Rec   : Rec1;
6308   Data2 : Root := Constructor (D, 30);
6309end record;
6310@end example
6311
6312The initialization of an object of type @code{Rec2} will call the
6313non-default C++ constructors specified for the imported components.
6314For example:
6315
6316@example
6317Obj8 : Rec2 (40);
6318@end example
6319
6320Using Ada 2005 we can use limited aggregates to initialize an object
6321invoking C++ constructors that differ from those specified in the type
6322declarations. For example:
6323
6324@example
6325Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6326                        others => <>),
6327                others => <>);
6328@end example
6329
6330The above declaration uses an Ada 2005 limited aggregate to
6331initialize @code{Obj9}, and the C++ constructor that has two integer
6332arguments is invoked to initialize the @code{Data1} component instead
6333of the constructor specified in the declaration of type @code{Rec1}. In
6334Ada 2005 the box in the aggregate indicates that unspecified components
6335are initialized using the expression (if any) available in the component
6336declaration. That is, in this case discriminant @code{D} is initialized
6337to value @code{20}, @code{Value} is initialized to value 1000, and the
6338non-default C++ constructor that handles two integers takes care of
6339initializing component @code{Data2} with values @code{20,30}.
6340
6341In Ada 2005 we can use the extended return statement to build the Ada
6342equivalent to C++ non-default constructors. For example:
6343
6344@example
6345function Constructor (V : Integer) return Rec2 is
6346begin
6347   return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
6348                                 others => <>),
6349                         others => <>) do
6350      --  Further actions required for construction of
6351      --  objects of type Rec2
6352      ...
6353   end record;
6354end Constructor;
6355@end example
6356
6357In this example the extended return statement construct is used to
6358build in place the returned object whose components are initialized
6359by means of a limited aggregate. Any further action associated with
6360the constructor can be placed inside the construct.
6361
6362@node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6363@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-at-the-class-level}@anchor{c1}@anchor{gnat_ugn/the_gnat_compilation_model id69}@anchor{c2}
6364@subsubsection Interfacing with C++ at the Class Level
6365
6366
6367In this section we demonstrate the GNAT features for interfacing with
6368C++ by means of an example making use of Ada 2005 abstract interface
6369types. This example consists of a classification of animals; classes
6370have been used to model our main classification of animals, and
6371interfaces provide support for the management of secondary
6372classifications. We first demonstrate a case in which the types and
6373constructors are defined on the C++ side and imported from the Ada
6374side, and latter the reverse case.
6375
6376The root of our derivation will be the @code{Animal} class, with a
6377single private attribute (the @code{Age} of the animal), a constructor,
6378and two public primitives to set and get the value of this attribute.
6379
6380@example
6381class Animal @{
6382 public:
6383   virtual void Set_Age (int New_Age);
6384   virtual int Age ();
6385   Animal() @{Age_Count = 0;@};
6386 private:
6387   int Age_Count;
6388@};
6389@end example
6390
6391Abstract interface types are defined in C++ by means of classes with pure
6392virtual functions and no data members. In our example we will use two
6393interfaces that provide support for the common management of @code{Carnivore}
6394and @code{Domestic} animals:
6395
6396@example
6397class Carnivore @{
6398public:
6399   virtual int Number_Of_Teeth () = 0;
6400@};
6401
6402class Domestic @{
6403public:
6404   virtual void Set_Owner (char* Name) = 0;
6405@};
6406@end example
6407
6408Using these declarations, we can now say that a @code{Dog} is an animal that is
6409both Carnivore and Domestic, that is:
6410
6411@example
6412class Dog : Animal, Carnivore, Domestic @{
6413 public:
6414   virtual int  Number_Of_Teeth ();
6415   virtual void Set_Owner (char* Name);
6416
6417   Dog(); // Constructor
6418 private:
6419   int  Tooth_Count;
6420   char *Owner;
6421@};
6422@end example
6423
6424In the following examples we will assume that the previous declarations are
6425located in a file named @code{animals.h}. The following package demonstrates
6426how to import these C++ declarations from the Ada side:
6427
6428@example
6429with Interfaces.C.Strings; use Interfaces.C.Strings;
6430package Animals is
6431  type Carnivore is limited interface;
6432  pragma Convention (C_Plus_Plus, Carnivore);
6433  function Number_Of_Teeth (X : Carnivore)
6434     return Natural is abstract;
6435
6436  type Domestic is limited interface;
6437  pragma Convention (C_Plus_Plus, Domestic);
6438  procedure Set_Owner
6439    (X    : in out Domestic;
6440     Name : Chars_Ptr) is abstract;
6441
6442  type Animal is tagged limited record
6443    Age : Natural;
6444  end record;
6445  pragma Import (C_Plus_Plus, Animal);
6446
6447  procedure Set_Age (X : in out Animal; Age : Integer);
6448  pragma Import (C_Plus_Plus, Set_Age);
6449
6450  function Age (X : Animal) return Integer;
6451  pragma Import (C_Plus_Plus, Age);
6452
6453  function New_Animal return Animal;
6454  pragma CPP_Constructor (New_Animal);
6455  pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6456
6457  type Dog is new Animal and Carnivore and Domestic with record
6458    Tooth_Count : Natural;
6459    Owner       : Chars_Ptr;
6460  end record;
6461  pragma Import (C_Plus_Plus, Dog);
6462
6463  function Number_Of_Teeth (A : Dog) return Natural;
6464  pragma Import (C_Plus_Plus, Number_Of_Teeth);
6465
6466  procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6467  pragma Import (C_Plus_Plus, Set_Owner);
6468
6469  function New_Dog return Dog;
6470  pragma CPP_Constructor (New_Dog);
6471  pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6472end Animals;
6473@end example
6474
6475Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6476interfacing with these C++ classes is easy. The only requirement is that all
6477the primitives and components must be declared exactly in the same order in
6478the two languages.
6479
6480Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6481means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
6482the arguments to the called primitives will be the same as for C++. For the
6483imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
6484to indicate that they have been defined on the C++ side; this is required
6485because the dispatch table associated with these tagged types will be built
6486in the C++ side and therefore will not contain the predefined Ada primitives
6487which Ada would otherwise expect.
6488
6489As the reader can see there is no need to indicate the C++ mangled names
6490associated with each subprogram because it is assumed that all the calls to
6491these primitives will be dispatching calls. The only exception is the
6492constructor, which must be registered with the compiler by means of
6493@code{pragma CPP_Constructor} and needs to provide its associated C++
6494mangled name because the Ada compiler generates direct calls to it.
6495
6496With the above packages we can now declare objects of type Dog on the Ada side
6497and dispatch calls to the corresponding subprograms on the C++ side. We can
6498also extend the tagged type Dog with further fields and primitives, and
6499override some of its C++ primitives on the Ada side. For example, here we have
6500a type derivation defined on the Ada side that inherits all the dispatching
6501primitives of the ancestor from the C++ side.
6502
6503@example
6504with Animals; use Animals;
6505package Vaccinated_Animals is
6506  type Vaccinated_Dog is new Dog with null record;
6507  function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6508end Vaccinated_Animals;
6509@end example
6510
6511It is important to note that, because of the ABI compatibility, the programmer
6512does not need to add any further information to indicate either the object
6513layout or the dispatch table entry associated with each dispatching operation.
6514
6515Now let us define all the types and constructors on the Ada side and export
6516them to C++, using the same hierarchy of our previous example:
6517
6518@example
6519with Interfaces.C.Strings;
6520use Interfaces.C.Strings;
6521package Animals is
6522  type Carnivore is limited interface;
6523  pragma Convention (C_Plus_Plus, Carnivore);
6524  function Number_Of_Teeth (X : Carnivore)
6525     return Natural is abstract;
6526
6527  type Domestic is limited interface;
6528  pragma Convention (C_Plus_Plus, Domestic);
6529  procedure Set_Owner
6530    (X    : in out Domestic;
6531     Name : Chars_Ptr) is abstract;
6532
6533  type Animal is tagged record
6534    Age : Natural;
6535  end record;
6536  pragma Convention (C_Plus_Plus, Animal);
6537
6538  procedure Set_Age (X : in out Animal; Age : Integer);
6539  pragma Export (C_Plus_Plus, Set_Age);
6540
6541  function Age (X : Animal) return Integer;
6542  pragma Export (C_Plus_Plus, Age);
6543
6544  function New_Animal return Animal'Class;
6545  pragma Export (C_Plus_Plus, New_Animal);
6546
6547  type Dog is new Animal and Carnivore and Domestic with record
6548    Tooth_Count : Natural;
6549    Owner       : String (1 .. 30);
6550  end record;
6551  pragma Convention (C_Plus_Plus, Dog);
6552
6553  function Number_Of_Teeth (A : Dog) return Natural;
6554  pragma Export (C_Plus_Plus, Number_Of_Teeth);
6555
6556  procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6557  pragma Export (C_Plus_Plus, Set_Owner);
6558
6559  function New_Dog return Dog'Class;
6560  pragma Export (C_Plus_Plus, New_Dog);
6561end Animals;
6562@end example
6563
6564Compared with our previous example the only differences are the use of
6565@code{pragma Convention} (instead of @code{pragma Import}), and the use of
6566@code{pragma Export} to indicate to the GNAT compiler that the primitives will
6567be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6568nothing else to be done; as explained above, the only requirement is that all
6569the primitives and components are declared in exactly the same order.
6570
6571For completeness, let us see a brief C++ main program that uses the
6572declarations available in @code{animals.h} (presented in our first example) to
6573import and use the declarations from the Ada side, properly initializing and
6574finalizing the Ada run-time system along the way:
6575
6576@example
6577#include "animals.h"
6578#include <iostream>
6579using namespace std;
6580
6581void Check_Carnivore (Carnivore *obj) @{...@}
6582void Check_Domestic (Domestic *obj)   @{...@}
6583void Check_Animal (Animal *obj)       @{...@}
6584void Check_Dog (Dog *obj)             @{...@}
6585
6586extern "C" @{
6587  void adainit (void);
6588  void adafinal (void);
6589  Dog* new_dog ();
6590@}
6591
6592void test ()
6593@{
6594  Dog *obj = new_dog();  // Ada constructor
6595  Check_Carnivore (obj); // Check secondary DT
6596  Check_Domestic (obj);  // Check secondary DT
6597  Check_Animal (obj);    // Check primary DT
6598  Check_Dog (obj);       // Check primary DT
6599@}
6600
6601int main ()
6602@{
6603  adainit ();  test();  adafinal ();
6604  return 0;
6605@}
6606@end example
6607
6608@node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Building Mixed Ada and C++ Programs,Mixed Language Programming
6609@anchor{gnat_ugn/the_gnat_compilation_model id70}@anchor{c3}@anchor{gnat_ugn/the_gnat_compilation_model generating-ada-bindings-for-c-and-c-headers}@anchor{19}
6610@subsection Generating Ada Bindings for C and C++ headers
6611
6612
6613@geindex Binding generation (for C and C++ headers)
6614
6615@geindex C headers (binding generation)
6616
6617@geindex C++ headers (binding generation)
6618
6619GNAT includes a binding generator for C and C++ headers which is
6620intended to do 95% of the tedious work of generating Ada specs from C
6621or C++ header files.
6622
6623Note that this capability is not intended to generate 100% correct Ada specs,
6624and will is some cases require manual adjustments, although it can often
6625be used out of the box in practice.
6626
6627Some of the known limitations include:
6628
6629
6630@itemize *
6631
6632@item
6633only very simple character constant macros are translated into Ada
6634constants. Function macros (macros with arguments) are partially translated
6635as comments, to be completed manually if needed.
6636
6637@item
6638some extensions (e.g. vector types) are not supported
6639
6640@item
6641pointers to pointers or complex structures are mapped to System.Address
6642
6643@item
6644identifiers with identical name (except casing) will generate compilation
6645errors (e.g. @code{shm_get} vs @code{SHM_GET}).
6646@end itemize
6647
6648The code generated is using the Ada 2005 syntax, which makes it
6649easier to interface with other languages than previous versions of Ada.
6650
6651@menu
6652* Running the Binding Generator::
6653* Generating Bindings for C++ Headers::
6654* Switches::
6655
6656@end menu
6657
6658@node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6659@anchor{gnat_ugn/the_gnat_compilation_model id71}@anchor{c4}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{c5}
6660@subsubsection Running the Binding Generator
6661
6662
6663The binding generator is part of the @code{gcc} compiler and can be
6664invoked via the @code{-fdump-ada-spec} switch, which will generate Ada
6665spec files for the header files specified on the command line, and all
6666header files needed by these files transitively. For example:
6667
6668@example
6669$ g++ -c -fdump-ada-spec -C /usr/include/time.h
6670$ gcc -c -gnat05 *.ads
6671@end example
6672
6673will generate, under GNU/Linux, the following files: @code{time_h.ads},
6674@code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6675correspond to the files @code{/usr/include/time.h},
6676@code{/usr/include/bits/time.h}, etc..., and will then compile these Ada specs
6677in Ada 2005 mode.
6678
6679The @code{-C} switch tells @code{gcc} to extract comments from headers,
6680and will attempt to generate corresponding Ada comments.
6681
6682If you want to generate a single Ada file and not the transitive closure, you
6683can use instead the @code{-fdump-ada-spec-slim} switch.
6684
6685You can optionally specify a parent unit, of which all generated units will
6686be children, using @code{-fada-spec-parent=@emph{unit}}.
6687
6688Note that we recommend when possible to use the @emph{g++} driver to
6689generate bindings, even for most C headers, since this will in general
6690generate better Ada specs. For generating bindings for C++ headers, it is
6691mandatory to use the @emph{g++} command, or @emph{gcc -x c++} which
6692is equivalent in this case. If @emph{g++} cannot work on your C headers
6693because of incompatibilities between C and C++, then you can fallback to
6694@code{gcc} instead.
6695
6696For an example of better bindings generated from the C++ front-end,
6697the name of the parameters (when available) are actually ignored by the C
6698front-end. Consider the following C header:
6699
6700@example
6701extern void foo (int variable);
6702@end example
6703
6704with the C front-end, @code{variable} is ignored, and the above is handled as:
6705
6706@example
6707extern void foo (int);
6708@end example
6709
6710generating a generic:
6711
6712@example
6713procedure foo (param1 : int);
6714@end example
6715
6716with the C++ front-end, the name is available, and we generate:
6717
6718@example
6719procedure foo (variable : int);
6720@end example
6721
6722In some cases, the generated bindings will be more complete or more meaningful
6723when defining some macros, which you can do via the @code{-D} switch. This
6724is for example the case with @code{Xlib.h} under GNU/Linux:
6725
6726@example
6727$ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6728@end example
6729
6730The above will generate more complete bindings than a straight call without
6731the @code{-DXLIB_ILLEGAL_ACCESS} switch.
6732
6733In other cases, it is not possible to parse a header file in a stand-alone
6734manner, because other include files need to be included first. In this
6735case, the solution is to create a small header file including the needed
6736@code{#include} and possible @code{#define} directives. For example, to
6737generate Ada bindings for @code{readline/readline.h}, you need to first
6738include @code{stdio.h}, so you can create a file with the following two
6739lines in e.g. @code{readline1.h}:
6740
6741@example
6742#include <stdio.h>
6743#include <readline/readline.h>
6744@end example
6745
6746and then generate Ada bindings from this file:
6747
6748@example
6749$ g++ -c -fdump-ada-spec readline1.h
6750@end example
6751
6752@node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6753@anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{c6}@anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{c7}
6754@subsubsection Generating Bindings for C++ Headers
6755
6756
6757Generating bindings for C++ headers is done using the same options, always
6758with the @emph{g++} compiler. Note that generating Ada spec from C++ headers is a
6759much more complex job and support for C++ headers is much more limited that
6760support for C headers. As a result, you will need to modify the resulting
6761bindings by hand more extensively when using C++ headers.
6762
6763In this mode, C++ classes will be mapped to Ada tagged types, constructors
6764will be mapped using the @code{CPP_Constructor} pragma, and when possible,
6765multiple inheritance of abstract classes will be mapped to Ada interfaces
6766(see the @emph{Interfacing to C++} section in the @cite{GNAT Reference Manual}
6767for additional information on interfacing to C++).
6768
6769For example, given the following C++ header file:
6770
6771@example
6772class Carnivore @{
6773public:
6774   virtual int Number_Of_Teeth () = 0;
6775@};
6776
6777class Domestic @{
6778public:
6779   virtual void Set_Owner (char* Name) = 0;
6780@};
6781
6782class Animal @{
6783public:
6784  int Age_Count;
6785  virtual void Set_Age (int New_Age);
6786@};
6787
6788class Dog : Animal, Carnivore, Domestic @{
6789 public:
6790  int  Tooth_Count;
6791  char *Owner;
6792
6793  virtual int  Number_Of_Teeth ();
6794  virtual void Set_Owner (char* Name);
6795
6796  Dog();
6797@};
6798@end example
6799
6800The corresponding Ada code is generated:
6801
6802@example
6803package Class_Carnivore is
6804  type Carnivore is limited interface;
6805  pragma Import (CPP, Carnivore);
6806
6807  function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6808end;
6809use Class_Carnivore;
6810
6811package Class_Domestic is
6812  type Domestic is limited interface;
6813  pragma Import (CPP, Domestic);
6814
6815  procedure Set_Owner
6816    (this : access Domestic;
6817     Name : Interfaces.C.Strings.chars_ptr) is abstract;
6818end;
6819use Class_Domestic;
6820
6821package Class_Animal is
6822  type Animal is tagged limited record
6823    Age_Count : aliased int;
6824  end record;
6825  pragma Import (CPP, Animal);
6826
6827  procedure Set_Age (this : access Animal; New_Age : int);
6828  pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6829end;
6830use Class_Animal;
6831
6832package Class_Dog is
6833  type Dog is new Animal and Carnivore and Domestic with record
6834    Tooth_Count : aliased int;
6835    Owner : Interfaces.C.Strings.chars_ptr;
6836  end record;
6837  pragma Import (CPP, Dog);
6838
6839  function Number_Of_Teeth (this : access Dog) return int;
6840  pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6841
6842  procedure Set_Owner
6843    (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6844  pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6845
6846  function New_Dog return Dog;
6847  pragma CPP_Constructor (New_Dog);
6848  pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6849end;
6850use Class_Dog;
6851@end example
6852
6853@node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6854@anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{c8}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{c9}
6855@subsubsection Switches
6856
6857
6858@geindex -fdump-ada-spec (gcc)
6859
6860
6861@table @asis
6862
6863@item @code{-fdump-ada-spec}
6864
6865Generate Ada spec files for the given header files transitively (including
6866all header files that these headers depend upon).
6867@end table
6868
6869@geindex -fdump-ada-spec-slim (gcc)
6870
6871
6872@table @asis
6873
6874@item @code{-fdump-ada-spec-slim}
6875
6876Generate Ada spec files for the header files specified on the command line
6877only.
6878@end table
6879
6880@geindex -fada-spec-parent (gcc)
6881
6882
6883@table @asis
6884
6885@item @code{-fada-spec-parent=@emph{unit}}
6886
6887Specifies that all files generated by @code{-fdump-ada-spec} are
6888to be child units of the specified parent unit.
6889@end table
6890
6891@geindex -C (gcc)
6892
6893
6894@table @asis
6895
6896@item @code{-C}
6897
6898Extract comments from headers and generate Ada comments in the Ada spec files.
6899@end table
6900
6901@node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6902@anchor{gnat_ugn/the_gnat_compilation_model generating-c-headers-for-ada-specifications}@anchor{ca}@anchor{gnat_ugn/the_gnat_compilation_model id73}@anchor{cb}
6903@subsection Generating C Headers for Ada Specifications
6904
6905
6906@geindex Binding generation (for Ada specs)
6907
6908@geindex C headers (binding generation)
6909
6910GNAT includes a C header generator for Ada specifications which supports
6911Ada types that have a direct mapping to C types. This includes in particular
6912support for:
6913
6914
6915@itemize *
6916
6917@item
6918Scalar types
6919
6920@item
6921Constrained arrays
6922
6923@item
6924Records (untagged)
6925
6926@item
6927Composition of the above types
6928
6929@item
6930Constant declarations
6931
6932@item
6933Object declarations
6934
6935@item
6936Subprogram declarations
6937@end itemize
6938
6939@menu
6940* Running the C Header Generator::
6941
6942@end menu
6943
6944@node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6945@anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{cc}
6946@subsubsection Running the C Header Generator
6947
6948
6949The C header generator is part of the GNAT compiler and can be invoked via
6950the @code{-gnatceg} combination of switches, which will generate a @code{.h}
6951file corresponding to the given input file (Ada spec or body). Note that
6952only spec files are processed in any case, so giving a spec or a body file
6953as input is equivalent. For example:
6954
6955@example
6956$ gcc -c -gnatceg pack1.ads
6957@end example
6958
6959will generate a self-contained file called @code{pack1.h} including
6960common definitions from the Ada Standard package, followed by the
6961definitions included in @code{pack1.ads}, as well as all the other units
6962withed by this file.
6963
6964For instance, given the following Ada files:
6965
6966@example
6967package Pack2 is
6968   type Int is range 1 .. 10;
6969end Pack2;
6970@end example
6971
6972@example
6973with Pack2;
6974
6975package Pack1 is
6976   type Rec is record
6977      Field1, Field2 : Pack2.Int;
6978   end record;
6979
6980   Global : Rec := (1, 2);
6981
6982   procedure Proc1 (R : Rec);
6983   procedure Proc2 (R : in out Rec);
6984end Pack1;
6985@end example
6986
6987The above @code{gcc} command will generate the following @code{pack1.h} file:
6988
6989@example
6990/* Standard definitions skipped */
6991#ifndef PACK2_ADS
6992#define PACK2_ADS
6993typedef short_short_integer pack2__TintB;
6994typedef pack2__TintB pack2__int;
6995#endif /* PACK2_ADS */
6996
6997#ifndef PACK1_ADS
6998#define PACK1_ADS
6999typedef struct _pack1__rec @{
7000  pack2__int field1;
7001  pack2__int field2;
7002@} pack1__rec;
7003extern pack1__rec pack1__global;
7004extern void pack1__proc1(const pack1__rec r);
7005extern void pack1__proc2(pack1__rec *r);
7006#endif /* PACK1_ADS */
7007@end example
7008
7009You can then @code{include} @code{pack1.h} from a C source file and use the types,
7010call subprograms, reference objects, and constants.
7011
7012@node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
7013@anchor{gnat_ugn/the_gnat_compilation_model id74}@anchor{cd}@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{45}
7014@section GNAT and Other Compilation Models
7015
7016
7017This section compares the GNAT model with the approaches taken in
7018other environents, first the C/C++ model and then the mechanism that
7019has been used in other Ada systems, in particular those traditionally
7020used for Ada 83.
7021
7022@menu
7023* Comparison between GNAT and C/C++ Compilation Models::
7024* Comparison between GNAT and Conventional Ada Library Models::
7025
7026@end menu
7027
7028@node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
7029@anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-c-c-compilation-models}@anchor{ce}@anchor{gnat_ugn/the_gnat_compilation_model id75}@anchor{cf}
7030@subsection Comparison between GNAT and C/C++ Compilation Models
7031
7032
7033The GNAT model of compilation is close to the C and C++ models. You can
7034think of Ada specs as corresponding to header files in C. As in C, you
7035don't need to compile specs; they are compiled when they are used. The
7036Ada @emph{with} is similar in effect to the @code{#include} of a C
7037header.
7038
7039One notable difference is that, in Ada, you may compile specs separately
7040to check them for semantic and syntactic accuracy. This is not always
7041possible with C headers because they are fragments of programs that have
7042less specific syntactic or semantic rules.
7043
7044The other major difference is the requirement for running the binder,
7045which performs two important functions. First, it checks for
7046consistency. In C or C++, the only defense against assembling
7047inconsistent programs lies outside the compiler, in a makefile, for
7048example. The binder satisfies the Ada requirement that it be impossible
7049to construct an inconsistent program when the compiler is used in normal
7050mode.
7051
7052@geindex Elaboration order control
7053
7054The other important function of the binder is to deal with elaboration
7055issues. There are also elaboration issues in C++ that are handled
7056automatically. This automatic handling has the advantage of being
7057simpler to use, but the C++ programmer has no control over elaboration.
7058Where @code{gnatbind} might complain there was no valid order of
7059elaboration, a C++ compiler would simply construct a program that
7060malfunctioned at run time.
7061
7062@node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
7063@anchor{gnat_ugn/the_gnat_compilation_model comparison-between-gnat-and-conventional-ada-library-models}@anchor{d0}@anchor{gnat_ugn/the_gnat_compilation_model id76}@anchor{d1}
7064@subsection Comparison between GNAT and Conventional Ada Library Models
7065
7066
7067This section is intended for Ada programmers who have
7068used an Ada compiler implementing the traditional Ada library
7069model, as described in the Ada Reference Manual.
7070
7071@geindex GNAT library
7072
7073In GNAT, there is no 'library' in the normal sense. Instead, the set of
7074source files themselves acts as the library. Compiling Ada programs does
7075not generate any centralized information, but rather an object file and
7076a ALI file, which are of interest only to the binder and linker.
7077In a traditional system, the compiler reads information not only from
7078the source file being compiled, but also from the centralized library.
7079This means that the effect of a compilation depends on what has been
7080previously compiled. In particular:
7081
7082
7083@itemize *
7084
7085@item
7086When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7087to the version of the unit most recently compiled into the library.
7088
7089@item
7090Inlining is effective only if the necessary body has already been
7091compiled into the library.
7092
7093@item
7094Compiling a unit may obsolete other units in the library.
7095@end itemize
7096
7097In GNAT, compiling one unit never affects the compilation of any other
7098units because the compiler reads only source files. Only changes to source
7099files can affect the results of a compilation. In particular:
7100
7101
7102@itemize *
7103
7104@item
7105When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7106to the source version of the unit that is currently accessible to the
7107compiler.
7108
7109@geindex Inlining
7110
7111@item
7112Inlining requires the appropriate source files for the package or
7113subprogram bodies to be available to the compiler. Inlining is always
7114effective, independent of the order in which units are compiled.
7115
7116@item
7117Compiling a unit never affects any other compilations. The editing of
7118sources may cause previous compilations to be out of date if they
7119depended on the source file being modified.
7120@end itemize
7121
7122The most important result of these differences is that order of compilation
7123is never significant in GNAT. There is no situation in which one is
7124required to do one compilation before another. What shows up as order of
7125compilation requirements in the traditional Ada library becomes, in
7126GNAT, simple source dependencies; in other words, there is only a set
7127of rules saying what source files must be present when a file is
7128compiled.
7129
7130@node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
7131@anchor{gnat_ugn/the_gnat_compilation_model using-gnat-files-with-external-tools}@anchor{1a}@anchor{gnat_ugn/the_gnat_compilation_model id77}@anchor{d2}
7132@section Using GNAT Files with External Tools
7133
7134
7135This section explains how files that are produced by GNAT may be
7136used with tools designed for other languages.
7137
7138@menu
7139* Using Other Utility Programs with GNAT::
7140* The External Symbol Naming Scheme of GNAT::
7141
7142@end menu
7143
7144@node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
7145@anchor{gnat_ugn/the_gnat_compilation_model using-other-utility-programs-with-gnat}@anchor{d3}@anchor{gnat_ugn/the_gnat_compilation_model id78}@anchor{d4}
7146@subsection Using Other Utility Programs with GNAT
7147
7148
7149The object files generated by GNAT are in standard system format and in
7150particular the debugging information uses this format. This means
7151programs generated by GNAT can be used with existing utilities that
7152depend on these formats.
7153
7154In general, any utility program that works with C will also often work with
7155Ada programs generated by GNAT. This includes software utilities such as
7156gprof (a profiling program), gdb (the FSF debugger), and utilities such
7157as Purify.
7158
7159@node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
7160@anchor{gnat_ugn/the_gnat_compilation_model the-external-symbol-naming-scheme-of-gnat}@anchor{d5}@anchor{gnat_ugn/the_gnat_compilation_model id79}@anchor{d6}
7161@subsection The External Symbol Naming Scheme of GNAT
7162
7163
7164In order to interpret the output from GNAT, when using tools that are
7165originally intended for use with other languages, it is useful to
7166understand the conventions used to generate link names from the Ada
7167entity names.
7168
7169All link names are in all lowercase letters. With the exception of library
7170procedure names, the mechanism used is simply to use the full expanded
7171Ada name with dots replaced by double underscores. For example, suppose
7172we have the following package spec:
7173
7174@example
7175package QRS is
7176   MN : Integer;
7177end QRS;
7178@end example
7179
7180@geindex pragma Export
7181
7182The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
7183the corresponding link name is @code{qrs__mn}.
7184Of course if a @code{pragma Export} is used this may be overridden:
7185
7186@example
7187package Exports is
7188   Var1 : Integer;
7189   pragma Export (Var1, C, External_Name => "var1_name");
7190   Var2 : Integer;
7191   pragma Export (Var2, C, Link_Name => "var2_link_name");
7192end Exports;
7193@end example
7194
7195In this case, the link name for @code{Var1} is whatever link name the
7196C compiler would assign for the C function @code{var1_name}. This typically
7197would be either @code{var1_name} or @code{_var1_name}, depending on operating
7198system conventions, but other possibilities exist. The link name for
7199@code{Var2} is @code{var2_link_name}, and this is not operating system
7200dependent.
7201
7202One exception occurs for library level procedures. A potential ambiguity
7203arises between the required name @code{_main} for the C main program,
7204and the name we would otherwise assign to an Ada library level procedure
7205called @code{Main} (which might well not be the main program).
7206
7207To avoid this ambiguity, we attach the prefix @code{_ada_} to such
7208names. So if we have a library level procedure such as:
7209
7210@example
7211procedure Hello (S : String);
7212@end example
7213
7214the external name of this procedure will be @code{_ada_hello}.
7215
7216@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7217
7218@node Building Executable Programs with GNAT,GNAT Utility Programs,The GNAT Compilation Model,Top
7219@anchor{gnat_ugn/building_executable_programs_with_gnat building-executable-programs-with-gnat}@anchor{a}@anchor{gnat_ugn/building_executable_programs_with_gnat doc}@anchor{d7}@anchor{gnat_ugn/building_executable_programs_with_gnat id1}@anchor{d8}
7220@chapter Building Executable Programs with GNAT
7221
7222
7223This chapter describes first the gnatmake tool
7224(@ref{1b,,Building with gnatmake}),
7225which automatically determines the set of sources
7226needed by an Ada compilation unit and executes the necessary
7227(re)compilations, binding and linking.
7228It also explains how to use each tool individually: the
7229compiler (gcc, see @ref{1c,,Compiling with gcc}),
7230binder (gnatbind, see @ref{1d,,Binding with gnatbind}),
7231and linker (gnatlink, see @ref{1e,,Linking with gnatlink})
7232to build executable programs.
7233Finally, this chapter provides examples of
7234how to make use of the general GNU make mechanism
7235in a GNAT context (see @ref{1f,,Using the GNU make Utility}).
7236
7237
7238@menu
7239* Building with gnatmake::
7240* Compiling with gcc::
7241* Compiler Switches::
7242* Linker Switches::
7243* Binding with gnatbind::
7244* Linking with gnatlink::
7245* Using the GNU make Utility::
7246
7247@end menu
7248
7249@node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7250@anchor{gnat_ugn/building_executable_programs_with_gnat the-gnat-make-program-gnatmake}@anchor{1b}@anchor{gnat_ugn/building_executable_programs_with_gnat building-with-gnatmake}@anchor{d9}
7251@section Building with @code{gnatmake}
7252
7253
7254@geindex gnatmake
7255
7256A typical development cycle when working on an Ada program consists of
7257the following steps:
7258
7259
7260@enumerate
7261
7262@item
7263Edit some sources to fix bugs;
7264
7265@item
7266Add enhancements;
7267
7268@item
7269Compile all sources affected;
7270
7271@item
7272Rebind and relink; and
7273
7274@item
7275Test.
7276@end enumerate
7277
7278@geindex Dependency rules (compilation)
7279
7280The third step in particular can be tricky, because not only do the modified
7281files have to be compiled, but any files depending on these files must also be
7282recompiled. The dependency rules in Ada can be quite complex, especially
7283in the presence of overloading, @code{use} clauses, generics and inlined
7284subprograms.
7285
7286@code{gnatmake} automatically takes care of the third and fourth steps
7287of this process. It determines which sources need to be compiled,
7288compiles them, and binds and links the resulting object files.
7289
7290Unlike some other Ada make programs, the dependencies are always
7291accurately recomputed from the new sources. The source based approach of
7292the GNAT compilation model makes this possible. This means that if
7293changes to the source program cause corresponding changes in
7294dependencies, they will always be tracked exactly correctly by
7295@code{gnatmake}.
7296
7297Note that for advanced forms of project structure, we recommend creating
7298a project file as explained in the @emph{GNAT_Project_Manager} chapter in the
7299@emph{GPRbuild User's Guide}, and using the
7300@code{gprbuild} tool which supports building with project files and works similarly
7301to @code{gnatmake}.
7302
7303@menu
7304* Running gnatmake::
7305* Switches for gnatmake::
7306* Mode Switches for gnatmake::
7307* Notes on the Command Line::
7308* How gnatmake Works::
7309* Examples of gnatmake Usage::
7310
7311@end menu
7312
7313@node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7314@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{da}@anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{db}
7315@subsection Running @code{gnatmake}
7316
7317
7318The usual form of the @code{gnatmake} command is
7319
7320@example
7321$ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7322@end example
7323
7324The only required argument is one @code{file_name}, which specifies
7325a compilation unit that is a main program. Several @code{file_names} can be
7326specified: this will result in several executables being built.
7327If @code{switches} are present, they can be placed before the first
7328@code{file_name}, between @code{file_names} or after the last @code{file_name}.
7329If @code{mode_switches} are present, they must always be placed after
7330the last @code{file_name} and all @code{switches}.
7331
7332If you are using standard file extensions (@code{.adb} and
7333@code{.ads}), then the
7334extension may be omitted from the @code{file_name} arguments. However, if
7335you are using non-standard extensions, then it is required that the
7336extension be given. A relative or absolute directory path can be
7337specified in a @code{file_name}, in which case, the input source file will
7338be searched for in the specified directory only. Otherwise, the input
7339source file will first be searched in the directory where
7340@code{gnatmake} was invoked and if it is not found, it will be search on
7341the source path of the compiler as described in
7342@ref{89,,Search Paths and the Run-Time Library (RTL)}.
7343
7344All @code{gnatmake} output (except when you specify @code{-M}) is sent to
7345@code{stderr}. The output produced by the
7346@code{-M} switch is sent to @code{stdout}.
7347
7348@node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7349@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{dc}@anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{dd}
7350@subsection Switches for @code{gnatmake}
7351
7352
7353You may specify any of the following switches to @code{gnatmake}:
7354
7355@geindex --version (gnatmake)
7356
7357
7358@table @asis
7359
7360@item @code{--version}
7361
7362Display Copyright and version, then exit disregarding all other options.
7363@end table
7364
7365@geindex --help (gnatmake)
7366
7367
7368@table @asis
7369
7370@item @code{--help}
7371
7372If @code{--version} was not used, display usage, then exit disregarding
7373all other options.
7374@end table
7375
7376@geindex --GCC=compiler_name (gnatmake)
7377
7378
7379@table @asis
7380
7381@item @code{--GCC=@emph{compiler_name}}
7382
7383Program used for compiling. The default is @code{gcc}. You need to use
7384quotes around @code{compiler_name} if @code{compiler_name} contains
7385spaces or other separator characters.
7386As an example @code{--GCC="foo -x  -y"}
7387will instruct @code{gnatmake} to use @code{foo -x -y} as your
7388compiler. A limitation of this syntax is that the name and path name of
7389the executable itself must not include any embedded spaces. Note that
7390switch @code{-c} is always inserted after your command name. Thus in the
7391above example the compiler command that will be used by @code{gnatmake}
7392will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7393used, only the last @code{compiler_name} is taken into account. However,
7394all the additional switches are also taken into account. Thus,
7395@code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7396@code{--GCC="bar -x -y -z -t"}.
7397@end table
7398
7399@geindex --GNATBIND=binder_name (gnatmake)
7400
7401
7402@table @asis
7403
7404@item @code{--GNATBIND=@emph{binder_name}}
7405
7406Program used for binding. The default is @code{gnatbind}. You need to
7407use quotes around @code{binder_name} if @code{binder_name} contains spaces
7408or other separator characters.
7409As an example @code{--GNATBIND="bar -x  -y"}
7410will instruct @code{gnatmake} to use @code{bar -x -y} as your
7411binder. Binder switches that are normally appended by @code{gnatmake}
7412to @code{gnatbind} are now appended to the end of @code{bar -x -y}.
7413A limitation of this syntax is that the name and path name of the executable
7414itself must not include any embedded spaces.
7415@end table
7416
7417@geindex --GNATLINK=linker_name (gnatmake)
7418
7419
7420@table @asis
7421
7422@item @code{--GNATLINK=@emph{linker_name}}
7423
7424Program used for linking. The default is @code{gnatlink}. You need to
7425use quotes around @code{linker_name} if @code{linker_name} contains spaces
7426or other separator characters.
7427As an example @code{--GNATLINK="lan -x  -y"}
7428will instruct @code{gnatmake} to use @code{lan -x -y} as your
7429linker. Linker switches that are normally appended by @code{gnatmake} to
7430@code{gnatlink} are now appended to the end of @code{lan -x -y}.
7431A limitation of this syntax is that the name and path name of the executable
7432itself must not include any embedded spaces.
7433
7434@item @code{--create-map-file}
7435
7436When linking an executable, create a map file. The name of the map file
7437has the same name as the executable with extension ".map".
7438
7439@item @code{--create-map-file=@emph{mapfile}}
7440
7441When linking an executable, create a map file with the specified name.
7442@end table
7443
7444@geindex --create-missing-dirs (gnatmake)
7445
7446
7447@table @asis
7448
7449@item @code{--create-missing-dirs}
7450
7451When using project files (@code{-P@emph{project}}), automatically create
7452missing object directories, library directories and exec
7453directories.
7454
7455@item @code{--single-compile-per-obj-dir}
7456
7457Disallow simultaneous compilations in the same object directory when
7458project files are used.
7459
7460@item @code{--subdirs=@emph{subdir}}
7461
7462Actual object directory of each project file is the subdirectory subdir of the
7463object directory specified or defaulted in the project file.
7464
7465@item @code{--unchecked-shared-lib-imports}
7466
7467By default, shared library projects are not allowed to import static library
7468projects. When this switch is used on the command line, this restriction is
7469relaxed.
7470
7471@item @code{--source-info=@emph{source info file}}
7472
7473Specify a source info file. This switch is active only when project files
7474are used. If the source info file is specified as a relative path, then it is
7475relative to the object directory of the main project. If the source info file
7476does not exist, then after the Project Manager has successfully parsed and
7477processed the project files and found the sources, it creates the source info
7478file. If the source info file already exists and can be read successfully,
7479then the Project Manager will get all the needed information about the sources
7480from the source info file and will not look for them. This reduces the time
7481to process the project files, especially when looking for sources that take a
7482long time. If the source info file exists but cannot be parsed successfully,
7483the Project Manager will attempt to recreate it. If the Project Manager fails
7484to create the source info file, a message is issued, but gnatmake does not
7485fail. @code{gnatmake} "trusts" the source info file. This means that
7486if the source files have changed (addition, deletion, moving to a different
7487source directory), then the source info file need to be deleted and recreated.
7488@end table
7489
7490@geindex -a (gnatmake)
7491
7492
7493@table @asis
7494
7495@item @code{-a}
7496
7497Consider all files in the make process, even the GNAT internal system
7498files (for example, the predefined Ada library files), as well as any
7499locked files. Locked files are files whose ALI file is write-protected.
7500By default,
7501@code{gnatmake} does not check these files,
7502because the assumption is that the GNAT internal files are properly up
7503to date, and also that any write protected ALI files have been properly
7504installed. Note that if there is an installation problem, such that one
7505of these files is not up to date, it will be properly caught by the
7506binder.
7507You may have to specify this switch if you are working on GNAT
7508itself. The switch @code{-a} is also useful
7509in conjunction with @code{-f}
7510if you need to recompile an entire application,
7511including run-time files, using special configuration pragmas,
7512such as a @code{Normalize_Scalars} pragma.
7513
7514By default
7515@code{gnatmake -a} compiles all GNAT
7516internal files with
7517@code{gcc -c -gnatpg} rather than @code{gcc -c}.
7518@end table
7519
7520@geindex -b (gnatmake)
7521
7522
7523@table @asis
7524
7525@item @code{-b}
7526
7527Bind only. Can be combined with @code{-c} to do
7528compilation and binding, but no link.
7529Can be combined with @code{-l}
7530to do binding and linking. When not combined with
7531@code{-c}
7532all the units in the closure of the main program must have been previously
7533compiled and must be up to date. The root unit specified by @code{file_name}
7534may be given without extension, with the source extension or, if no GNAT
7535Project File is specified, with the ALI file extension.
7536@end table
7537
7538@geindex -c (gnatmake)
7539
7540
7541@table @asis
7542
7543@item @code{-c}
7544
7545Compile only. Do not perform binding, except when @code{-b}
7546is also specified. Do not perform linking, except if both
7547@code{-b} and
7548@code{-l} are also specified.
7549If the root unit specified by @code{file_name} is not a main unit, this is the
7550default. Otherwise @code{gnatmake} will attempt binding and linking
7551unless all objects are up to date and the executable is more recent than
7552the objects.
7553@end table
7554
7555@geindex -C (gnatmake)
7556
7557
7558@table @asis
7559
7560@item @code{-C}
7561
7562Use a temporary mapping file. A mapping file is a way to communicate
7563to the compiler two mappings: from unit names to file names (without
7564any directory information) and from file names to path names (with
7565full directory information). A mapping file can make the compiler's
7566file searches faster, especially if there are many source directories,
7567or the sources are read over a slow network connection. If
7568@code{-P} is used, a mapping file is always used, so
7569@code{-C} is unnecessary; in this case the mapping file
7570is initially populated based on the project file. If
7571@code{-C} is used without
7572@code{-P},
7573the mapping file is initially empty. Each invocation of the compiler
7574will add any newly accessed sources to the mapping file.
7575@end table
7576
7577@geindex -C= (gnatmake)
7578
7579
7580@table @asis
7581
7582@item @code{-C=@emph{file}}
7583
7584Use a specific mapping file. The file, specified as a path name (absolute or
7585relative) by this switch, should already exist, otherwise the switch is
7586ineffective. The specified mapping file will be communicated to the compiler.
7587This switch is not compatible with a project file
7588(-P`file`) or with multiple compiling processes
7589(-jnnn, when nnn is greater than 1).
7590@end table
7591
7592@geindex -d (gnatmake)
7593
7594
7595@table @asis
7596
7597@item @code{-d}
7598
7599Display progress for each source, up to date or not, as a single line:
7600
7601@example
7602completed x out of y (zz%)
7603@end example
7604
7605If the file needs to be compiled this is displayed after the invocation of
7606the compiler. These lines are displayed even in quiet output mode.
7607@end table
7608
7609@geindex -D (gnatmake)
7610
7611
7612@table @asis
7613
7614@item @code{-D @emph{dir}}
7615
7616Put all object files and ALI file in directory @code{dir}.
7617If the @code{-D} switch is not used, all object files
7618and ALI files go in the current working directory.
7619
7620This switch cannot be used when using a project file.
7621@end table
7622
7623@geindex -eI (gnatmake)
7624
7625
7626@table @asis
7627
7628@item @code{-eI@emph{nnn}}
7629
7630Indicates that the main source is a multi-unit source and the rank of the unit
7631in the source file is nnn. nnn needs to be a positive number and a valid
7632index in the source. This switch cannot be used when @code{gnatmake} is
7633invoked for several mains.
7634@end table
7635
7636@geindex -eL (gnatmake)
7637
7638@geindex symbolic links
7639
7640
7641@table @asis
7642
7643@item @code{-eL}
7644
7645Follow all symbolic links when processing project files.
7646This should be used if your project uses symbolic links for files or
7647directories, but is not needed in other cases.
7648
7649@geindex naming scheme
7650
7651This also assumes that no directory matches the naming scheme for files (for
7652instance that you do not have a directory called "sources.ads" when using the
7653default GNAT naming scheme).
7654
7655When you do not have to use this switch (i.e., by default), gnatmake is able to
7656save a lot of system calls (several per source file and object file), which
7657can result in a significant speed up to load and manipulate a project file,
7658especially when using source files from a remote system.
7659@end table
7660
7661@geindex -eS (gnatmake)
7662
7663
7664@table @asis
7665
7666@item @code{-eS}
7667
7668Output the commands for the compiler, the binder and the linker
7669on standard output,
7670instead of standard error.
7671@end table
7672
7673@geindex -f (gnatmake)
7674
7675
7676@table @asis
7677
7678@item @code{-f}
7679
7680Force recompilations. Recompile all sources, even though some object
7681files may be up to date, but don't recompile predefined or GNAT internal
7682files or locked files (files with a write-protected ALI file),
7683unless the @code{-a} switch is also specified.
7684@end table
7685
7686@geindex -F (gnatmake)
7687
7688
7689@table @asis
7690
7691@item @code{-F}
7692
7693When using project files, if some errors or warnings are detected during
7694parsing and verbose mode is not in effect (no use of switch
7695-v), then error lines start with the full path name of the project
7696file, rather than its simple file name.
7697@end table
7698
7699@geindex -g (gnatmake)
7700
7701
7702@table @asis
7703
7704@item @code{-g}
7705
7706Enable debugging. This switch is simply passed to the compiler and to the
7707linker.
7708@end table
7709
7710@geindex -i (gnatmake)
7711
7712
7713@table @asis
7714
7715@item @code{-i}
7716
7717In normal mode, @code{gnatmake} compiles all object files and ALI files
7718into the current directory. If the @code{-i} switch is used,
7719then instead object files and ALI files that already exist are overwritten
7720in place. This means that once a large project is organized into separate
7721directories in the desired manner, then @code{gnatmake} will automatically
7722maintain and update this organization. If no ALI files are found on the
7723Ada object path (see @ref{89,,Search Paths and the Run-Time Library (RTL)}),
7724the new object and ALI files are created in the
7725directory containing the source being compiled. If another organization
7726is desired, where objects and sources are kept in different directories,
7727a useful technique is to create dummy ALI files in the desired directories.
7728When detecting such a dummy file, @code{gnatmake} will be forced to
7729recompile the corresponding source file, and it will be put the resulting
7730object and ALI files in the directory where it found the dummy file.
7731@end table
7732
7733@geindex -j (gnatmake)
7734
7735@geindex Parallel make
7736
7737
7738@table @asis
7739
7740@item @code{-j@emph{n}}
7741
7742Use @code{n} processes to carry out the (re)compilations. On a multiprocessor
7743machine compilations will occur in parallel. If @code{n} is 0, then the
7744maximum number of parallel compilations is the number of core processors
7745on the platform. In the event of compilation errors, messages from various
7746compilations might get interspersed (but @code{gnatmake} will give you the
7747full ordered list of failing compiles at the end). If this is problematic,
7748rerun the make process with n set to 1 to get a clean list of messages.
7749@end table
7750
7751@geindex -k (gnatmake)
7752
7753
7754@table @asis
7755
7756@item @code{-k}
7757
7758Keep going. Continue as much as possible after a compilation error. To
7759ease the programmer's task in case of compilation errors, the list of
7760sources for which the compile fails is given when @code{gnatmake}
7761terminates.
7762
7763If @code{gnatmake} is invoked with several @code{file_names} and with this
7764switch, if there are compilation errors when building an executable,
7765@code{gnatmake} will not attempt to build the following executables.
7766@end table
7767
7768@geindex -l (gnatmake)
7769
7770
7771@table @asis
7772
7773@item @code{-l}
7774
7775Link only. Can be combined with @code{-b} to binding
7776and linking. Linking will not be performed if combined with
7777@code{-c}
7778but not with @code{-b}.
7779When not combined with @code{-b}
7780all the units in the closure of the main program must have been previously
7781compiled and must be up to date, and the main program needs to have been bound.
7782The root unit specified by @code{file_name}
7783may be given without extension, with the source extension or, if no GNAT
7784Project File is specified, with the ALI file extension.
7785@end table
7786
7787@geindex -m (gnatmake)
7788
7789
7790@table @asis
7791
7792@item @code{-m}
7793
7794Specify that the minimum necessary amount of recompilations
7795be performed. In this mode @code{gnatmake} ignores time
7796stamp differences when the only
7797modifications to a source file consist in adding/removing comments,
7798empty lines, spaces or tabs. This means that if you have changed the
7799comments in a source file or have simply reformatted it, using this
7800switch will tell @code{gnatmake} not to recompile files that depend on it
7801(provided other sources on which these files depend have undergone no
7802semantic modifications). Note that the debugging information may be
7803out of date with respect to the sources if the @code{-m} switch causes
7804a compilation to be switched, so the use of this switch represents a
7805trade-off between compilation time and accurate debugging information.
7806@end table
7807
7808@geindex Dependencies
7809@geindex producing list
7810
7811@geindex -M (gnatmake)
7812
7813
7814@table @asis
7815
7816@item @code{-M}
7817
7818Check if all objects are up to date. If they are, output the object
7819dependences to @code{stdout} in a form that can be directly exploited in
7820a @code{Makefile}. By default, each source file is prefixed with its
7821(relative or absolute) directory name. This name is whatever you
7822specified in the various @code{-aI}
7823and @code{-I} switches. If you use
7824@code{gnatmake -M}  @code{-q}
7825(see below), only the source file names,
7826without relative paths, are output. If you just specify the  @code{-M}
7827switch, dependencies of the GNAT internal system files are omitted. This
7828is typically what you want. If you also specify
7829the @code{-a} switch,
7830dependencies of the GNAT internal files are also listed. Note that
7831dependencies of the objects in external Ada libraries (see
7832switch  @code{-aL@emph{dir}} in the following list)
7833are never reported.
7834@end table
7835
7836@geindex -n (gnatmake)
7837
7838
7839@table @asis
7840
7841@item @code{-n}
7842
7843Don't compile, bind, or link. Checks if all objects are up to date.
7844If they are not, the full name of the first file that needs to be
7845recompiled is printed.
7846Repeated use of this option, followed by compiling the indicated source
7847file, will eventually result in recompiling all required units.
7848@end table
7849
7850@geindex -o (gnatmake)
7851
7852
7853@table @asis
7854
7855@item @code{-o @emph{exec_name}}
7856
7857Output executable name. The name of the final executable program will be
7858@code{exec_name}. If the @code{-o} switch is omitted the default
7859name for the executable will be the name of the input file in appropriate form
7860for an executable file on the host system.
7861
7862This switch cannot be used when invoking @code{gnatmake} with several
7863@code{file_names}.
7864@end table
7865
7866@geindex -p (gnatmake)
7867
7868
7869@table @asis
7870
7871@item @code{-p}
7872
7873Same as @code{--create-missing-dirs}
7874@end table
7875
7876@geindex -P (gnatmake)
7877
7878
7879@table @asis
7880
7881@item @code{-P@emph{project}}
7882
7883Use project file @code{project}. Only one such switch can be used.
7884@end table
7885
7886@c -- Comment:
7887@c :ref:`gnatmake_and_Project_Files`.
7888
7889@geindex -q (gnatmake)
7890
7891
7892@table @asis
7893
7894@item @code{-q}
7895
7896Quiet. When this flag is not set, the commands carried out by
7897@code{gnatmake} are displayed.
7898@end table
7899
7900@geindex -s (gnatmake)
7901
7902
7903@table @asis
7904
7905@item @code{-s}
7906
7907Recompile if compiler switches have changed since last compilation.
7908All compiler switches but -I and -o are taken into account in the
7909following way:
7910orders between different 'first letter' switches are ignored, but
7911orders between same switches are taken into account. For example,
7912@code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O}
7913is equivalent to @code{-O -g}.
7914
7915This switch is recommended when Integrated Preprocessing is used.
7916@end table
7917
7918@geindex -u (gnatmake)
7919
7920
7921@table @asis
7922
7923@item @code{-u}
7924
7925Unique. Recompile at most the main files. It implies -c. Combined with
7926-f, it is equivalent to calling the compiler directly. Note that using
7927-u with a project file and no main has a special meaning.
7928@end table
7929
7930@c --Comment
7931@c (See :ref:`Project_Files_and_Main_Subprograms`.)
7932
7933@geindex -U (gnatmake)
7934
7935
7936@table @asis
7937
7938@item @code{-U}
7939
7940When used without a project file or with one or several mains on the command
7941line, is equivalent to -u. When used with a project file and no main
7942on the command line, all sources of all project files are checked and compiled
7943if not up to date, and libraries are rebuilt, if necessary.
7944@end table
7945
7946@geindex -v (gnatmake)
7947
7948
7949@table @asis
7950
7951@item @code{-v}
7952
7953Verbose. Display the reason for all recompilations @code{gnatmake}
7954decides are necessary, with the highest verbosity level.
7955@end table
7956
7957@geindex -vl (gnatmake)
7958
7959
7960@table @asis
7961
7962@item @code{-vl}
7963
7964Verbosity level Low. Display fewer lines than in verbosity Medium.
7965@end table
7966
7967@geindex -vm (gnatmake)
7968
7969
7970@table @asis
7971
7972@item @code{-vm}
7973
7974Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7975@end table
7976
7977@geindex -vm (gnatmake)
7978
7979
7980@table @asis
7981
7982@item @code{-vh}
7983
7984Verbosity level High. Equivalent to -v.
7985
7986@item @code{-vP@emph{x}}
7987
7988Indicate the verbosity of the parsing of GNAT project files.
7989See @ref{de,,Switches Related to Project Files}.
7990@end table
7991
7992@geindex -x (gnatmake)
7993
7994
7995@table @asis
7996
7997@item @code{-x}
7998
7999Indicate that sources that are not part of any Project File may be compiled.
8000Normally, when using Project Files, only sources that are part of a Project
8001File may be compile. When this switch is used, a source outside of all Project
8002Files may be compiled. The ALI file and the object file will be put in the
8003object directory of the main Project. The compilation switches used will only
8004be those specified on the command line. Even when
8005@code{-x} is used, mains specified on the
8006command line need to be sources of a project file.
8007
8008@item @code{-X@emph{name}=@emph{value}}
8009
8010Indicate that external variable @code{name} has the value @code{value}.
8011The Project Manager will use this value for occurrences of
8012@code{external(name)} when parsing the project file.
8013@ref{de,,Switches Related to Project Files}.
8014@end table
8015
8016@geindex -z (gnatmake)
8017
8018
8019@table @asis
8020
8021@item @code{-z}
8022
8023No main subprogram. Bind and link the program even if the unit name
8024given on the command line is a package name. The resulting executable
8025will execute the elaboration routines of the package and its closure,
8026then the finalization routines.
8027@end table
8028
8029@subsubheading GCC switches
8030
8031
8032Any uppercase or multi-character switch that is not a @code{gnatmake} switch
8033is passed to @code{gcc} (e.g., @code{-O}, @code{-gnato,} etc.)
8034
8035@subsubheading Source and library search path switches
8036
8037
8038@geindex -aI (gnatmake)
8039
8040
8041@table @asis
8042
8043@item @code{-aI@emph{dir}}
8044
8045When looking for source files also look in directory @code{dir}.
8046The order in which source files search is undertaken is
8047described in @ref{89,,Search Paths and the Run-Time Library (RTL)}.
8048@end table
8049
8050@geindex -aL (gnatmake)
8051
8052
8053@table @asis
8054
8055@item @code{-aL@emph{dir}}
8056
8057Consider @code{dir} as being an externally provided Ada library.
8058Instructs @code{gnatmake} to skip compilation units whose @code{.ALI}
8059files have been located in directory @code{dir}. This allows you to have
8060missing bodies for the units in @code{dir} and to ignore out of date bodies
8061for the same units. You still need to specify
8062the location of the specs for these units by using the switches
8063@code{-aI@emph{dir}}  or @code{-I@emph{dir}}.
8064Note: this switch is provided for compatibility with previous versions
8065of @code{gnatmake}. The easier method of causing standard libraries
8066to be excluded from consideration is to write-protect the corresponding
8067ALI files.
8068@end table
8069
8070@geindex -aO (gnatmake)
8071
8072
8073@table @asis
8074
8075@item @code{-aO@emph{dir}}
8076
8077When searching for library and object files, look in directory
8078@code{dir}. The order in which library files are searched is described in
8079@ref{8c,,Search Paths for gnatbind}.
8080@end table
8081
8082@geindex Search paths
8083@geindex for gnatmake
8084
8085@geindex -A (gnatmake)
8086
8087
8088@table @asis
8089
8090@item @code{-A@emph{dir}}
8091
8092Equivalent to @code{-aL@emph{dir}} @code{-aI@emph{dir}}.
8093
8094@geindex -I (gnatmake)
8095
8096@item @code{-I@emph{dir}}
8097
8098Equivalent to @code{-aO@emph{dir} -aI@emph{dir}}.
8099@end table
8100
8101@geindex -I- (gnatmake)
8102
8103@geindex Source files
8104@geindex suppressing search
8105
8106
8107@table @asis
8108
8109@item @code{-I-}
8110
8111Do not look for source files in the directory containing the source
8112file named in the command line.
8113Do not look for ALI or object files in the directory
8114where @code{gnatmake} was invoked.
8115@end table
8116
8117@geindex -L (gnatmake)
8118
8119@geindex Linker libraries
8120
8121
8122@table @asis
8123
8124@item @code{-L@emph{dir}}
8125
8126Add directory @code{dir} to the list of directories in which the linker
8127will search for libraries. This is equivalent to
8128@code{-largs} @code{-L@emph{dir}}.
8129Furthermore, under Windows, the sources pointed to by the libraries path
8130set in the registry are not searched for.
8131@end table
8132
8133@geindex -nostdinc (gnatmake)
8134
8135
8136@table @asis
8137
8138@item @code{-nostdinc}
8139
8140Do not look for source files in the system default directory.
8141@end table
8142
8143@geindex -nostdlib (gnatmake)
8144
8145
8146@table @asis
8147
8148@item @code{-nostdlib}
8149
8150Do not look for library files in the system default directory.
8151@end table
8152
8153@geindex --RTS (gnatmake)
8154
8155
8156@table @asis
8157
8158@item @code{--RTS=@emph{rts-path}}
8159
8160Specifies the default location of the run-time library. GNAT looks for the
8161run-time
8162in the following directories, and stops as soon as a valid run-time is found
8163(@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
8164@code{ada_object_path} present):
8165
8166
8167@itemize *
8168
8169@item
8170@emph{<current directory>/$rts_path}
8171
8172@item
8173@emph{<default-search-dir>/$rts_path}
8174
8175@item
8176@emph{<default-search-dir>/rts-$rts_path}
8177
8178@item
8179The selected path is handled like a normal RTS path.
8180@end itemize
8181@end table
8182
8183@node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
8184@anchor{gnat_ugn/building_executable_programs_with_gnat id4}@anchor{df}@anchor{gnat_ugn/building_executable_programs_with_gnat mode-switches-for-gnatmake}@anchor{e0}
8185@subsection Mode Switches for @code{gnatmake}
8186
8187
8188The mode switches (referred to as @code{mode_switches}) allow the
8189inclusion of switches that are to be passed to the compiler itself, the
8190binder or the linker. The effect of a mode switch is to cause all
8191subsequent switches up to the end of the switch list, or up to the next
8192mode switch, to be interpreted as switches to be passed on to the
8193designated component of GNAT.
8194
8195@geindex -cargs (gnatmake)
8196
8197
8198@table @asis
8199
8200@item @code{-cargs @emph{switches}}
8201
8202Compiler switches. Here @code{switches} is a list of switches
8203that are valid switches for @code{gcc}. They will be passed on to
8204all compile steps performed by @code{gnatmake}.
8205@end table
8206
8207@geindex -bargs (gnatmake)
8208
8209
8210@table @asis
8211
8212@item @code{-bargs @emph{switches}}
8213
8214Binder switches. Here @code{switches} is a list of switches
8215that are valid switches for @code{gnatbind}. They will be passed on to
8216all bind steps performed by @code{gnatmake}.
8217@end table
8218
8219@geindex -largs (gnatmake)
8220
8221
8222@table @asis
8223
8224@item @code{-largs @emph{switches}}
8225
8226Linker switches. Here @code{switches} is a list of switches
8227that are valid switches for @code{gnatlink}. They will be passed on to
8228all link steps performed by @code{gnatmake}.
8229@end table
8230
8231@geindex -margs (gnatmake)
8232
8233
8234@table @asis
8235
8236@item @code{-margs @emph{switches}}
8237
8238Make switches. The switches are directly interpreted by @code{gnatmake},
8239regardless of any previous occurrence of @code{-cargs}, @code{-bargs}
8240or @code{-largs}.
8241@end table
8242
8243@node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8244@anchor{gnat_ugn/building_executable_programs_with_gnat id5}@anchor{e1}@anchor{gnat_ugn/building_executable_programs_with_gnat notes-on-the-command-line}@anchor{e2}
8245@subsection Notes on the Command Line
8246
8247
8248This section contains some additional useful notes on the operation
8249of the @code{gnatmake} command.
8250
8251@geindex Recompilation (by gnatmake)
8252
8253
8254@itemize *
8255
8256@item
8257If @code{gnatmake} finds no ALI files, it recompiles the main program
8258and all other units required by the main program.
8259This means that @code{gnatmake}
8260can be used for the initial compile, as well as during subsequent steps of
8261the development cycle.
8262
8263@item
8264If you enter @code{gnatmake foo.adb}, where @code{foo}
8265is a subunit or body of a generic unit, @code{gnatmake} recompiles
8266@code{foo.adb} (because it finds no ALI) and stops, issuing a
8267warning.
8268
8269@item
8270In @code{gnatmake} the switch @code{-I}
8271is used to specify both source and
8272library file paths. Use @code{-aI}
8273instead if you just want to specify
8274source paths only and @code{-aO}
8275if you want to specify library paths
8276only.
8277
8278@item
8279@code{gnatmake} will ignore any files whose ALI file is write-protected.
8280This may conveniently be used to exclude standard libraries from
8281consideration and in particular it means that the use of the
8282@code{-f} switch will not recompile these files
8283unless @code{-a} is also specified.
8284
8285@item
8286@code{gnatmake} has been designed to make the use of Ada libraries
8287particularly convenient. Assume you have an Ada library organized
8288as follows: @emph{obj-dir} contains the objects and ALI files for
8289of your Ada compilation units,
8290whereas @emph{include-dir} contains the
8291specs of these units, but no bodies. Then to compile a unit
8292stored in @code{main.adb}, which uses this Ada library you would just type:
8293
8294@example
8295$ gnatmake -aI`include-dir`  -aL`obj-dir`  main
8296@end example
8297
8298@item
8299Using @code{gnatmake} along with the @code{-m (minimal recompilation)}
8300switch provides a mechanism for avoiding unnecessary recompilations. Using
8301this switch,
8302you can update the comments/format of your
8303source files without having to recompile everything. Note, however, that
8304adding or deleting lines in a source files may render its debugging
8305info obsolete. If the file in question is a spec, the impact is rather
8306limited, as that debugging info will only be useful during the
8307elaboration phase of your program. For bodies the impact can be more
8308significant. In all events, your debugger will warn you if a source file
8309is more recent than the corresponding object, and alert you to the fact
8310that the debugging information may be out of date.
8311@end itemize
8312
8313@node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8314@anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{e3}@anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{e4}
8315@subsection How @code{gnatmake} Works
8316
8317
8318Generally @code{gnatmake} automatically performs all necessary
8319recompilations and you don't need to worry about how it works. However,
8320it may be useful to have some basic understanding of the @code{gnatmake}
8321approach and in particular to understand how it uses the results of
8322previous compilations without incorrectly depending on them.
8323
8324First a definition: an object file is considered @emph{up to date} if the
8325corresponding ALI file exists and if all the source files listed in the
8326dependency section of this ALI file have time stamps matching those in
8327the ALI file. This means that neither the source file itself nor any
8328files that it depends on have been modified, and hence there is no need
8329to recompile this file.
8330
8331@code{gnatmake} works by first checking if the specified main unit is up
8332to date. If so, no compilations are required for the main unit. If not,
8333@code{gnatmake} compiles the main program to build a new ALI file that
8334reflects the latest sources. Then the ALI file of the main unit is
8335examined to find all the source files on which the main program depends,
8336and @code{gnatmake} recursively applies the above procedure on all these
8337files.
8338
8339This process ensures that @code{gnatmake} only trusts the dependencies
8340in an existing ALI file if they are known to be correct. Otherwise it
8341always recompiles to determine a new, guaranteed accurate set of
8342dependencies. As a result the program is compiled 'upside down' from what may
8343be more familiar as the required order of compilation in some other Ada
8344systems. In particular, clients are compiled before the units on which
8345they depend. The ability of GNAT to compile in any order is critical in
8346allowing an order of compilation to be chosen that guarantees that
8347@code{gnatmake} will recompute a correct set of new dependencies if
8348necessary.
8349
8350When invoking @code{gnatmake} with several @code{file_names}, if a unit is
8351imported by several of the executables, it will be recompiled at most once.
8352
8353Note: when using non-standard naming conventions
8354(@ref{35,,Using Other File Names}), changing through a configuration pragmas
8355file the version of a source and invoking @code{gnatmake} to recompile may
8356have no effect, if the previous version of the source is still accessible
8357by @code{gnatmake}. It may be necessary to use the switch
8358-f.
8359
8360@node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8361@anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatmake-usage}@anchor{e5}@anchor{gnat_ugn/building_executable_programs_with_gnat id7}@anchor{e6}
8362@subsection Examples of @code{gnatmake} Usage
8363
8364
8365
8366@table @asis
8367
8368@item @emph{gnatmake hello.adb}
8369
8370Compile all files necessary to bind and link the main program
8371@code{hello.adb} (containing unit @code{Hello}) and bind and link the
8372resulting object files to generate an executable file @code{hello}.
8373
8374@item @emph{gnatmake main1 main2 main3}
8375
8376Compile all files necessary to bind and link the main programs
8377@code{main1.adb} (containing unit @code{Main1}), @code{main2.adb}
8378(containing unit @code{Main2}) and @code{main3.adb}
8379(containing unit @code{Main3}) and bind and link the resulting object files
8380to generate three executable files @code{main1},
8381@code{main2}  and @code{main3}.
8382
8383@item @emph{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8384
8385Compile all files necessary to bind and link the main program unit
8386@code{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8387be done with optimization level 2 and the order of elaboration will be
8388listed by the binder. @code{gnatmake} will operate in quiet mode, not
8389displaying commands it is executing.
8390@end table
8391
8392@node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8393@anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{1c}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{e7}
8394@section Compiling with @code{gcc}
8395
8396
8397This section discusses how to compile Ada programs using the @code{gcc}
8398command. It also describes the set of switches
8399that can be used to control the behavior of the compiler.
8400
8401@menu
8402* Compiling Programs::
8403* Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL.
8404* Order of Compilation Issues::
8405* Examples::
8406
8407@end menu
8408
8409@node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8410@anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{e8}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{e9}
8411@subsection Compiling Programs
8412
8413
8414The first step in creating an executable program is to compile the units
8415of the program using the @code{gcc} command. You must compile the
8416following files:
8417
8418
8419@itemize *
8420
8421@item
8422the body file (@code{.adb}) for a library level subprogram or generic
8423subprogram
8424
8425@item
8426the spec file (@code{.ads}) for a library level package or generic
8427package that has no body
8428
8429@item
8430the body file (@code{.adb}) for a library level package
8431or generic package that has a body
8432@end itemize
8433
8434You need @emph{not} compile the following files
8435
8436
8437@itemize *
8438
8439@item
8440the spec of a library unit which has a body
8441
8442@item
8443subunits
8444@end itemize
8445
8446because they are compiled as part of compiling related units. GNAT
8447package specs
8448when the corresponding body is compiled, and subunits when the parent is
8449compiled.
8450
8451@geindex cannot generate code
8452
8453If you attempt to compile any of these files, you will get one of the
8454following error messages (where @code{fff} is the name of the file you
8455compiled):
8456
8457@quotation
8458
8459@example
8460cannot generate code for file `@w{`}fff`@w{`} (package spec)
8461to check package spec, use -gnatc
8462
8463cannot generate code for file `@w{`}fff`@w{`} (missing subunits)
8464to check parent unit, use -gnatc
8465
8466cannot generate code for file `@w{`}fff`@w{`} (subprogram spec)
8467to check subprogram spec, use -gnatc
8468
8469cannot generate code for file `@w{`}fff`@w{`} (subunit)
8470to check subunit, use -gnatc
8471@end example
8472@end quotation
8473
8474As indicated by the above error messages, if you want to submit
8475one of these files to the compiler to check for correct semantics
8476without generating code, then use the @code{-gnatc} switch.
8477
8478The basic command for compiling a file containing an Ada unit is:
8479
8480@example
8481$ gcc -c [switches] <file name>
8482@end example
8483
8484where @code{file name} is the name of the Ada file (usually
8485having an extension @code{.ads} for a spec or @code{.adb} for a body).
8486You specify the
8487@code{-c} switch to tell @code{gcc} to compile, but not link, the file.
8488The result of a successful compilation is an object file, which has the
8489same name as the source file but an extension of @code{.o} and an Ada
8490Library Information (ALI) file, which also has the same name as the
8491source file, but with @code{.ali} as the extension. GNAT creates these
8492two output files in the current directory, but you may specify a source
8493file in any directory using an absolute or relative path specification
8494containing the directory information.
8495
8496TESTING: the @code{--foobar@emph{NN}} switch
8497
8498@geindex gnat1
8499
8500@code{gcc} is actually a driver program that looks at the extensions of
8501the file arguments and loads the appropriate compiler. For example, the
8502GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8503These programs are in directories known to the driver program (in some
8504configurations via environment variables you set), but need not be in
8505your path. The @code{gcc} driver also calls the assembler and any other
8506utilities needed to complete the generation of the required object
8507files.
8508
8509It is possible to supply several file names on the same @code{gcc}
8510command. This causes @code{gcc} to call the appropriate compiler for
8511each file. For example, the following command lists two separate
8512files to be compiled:
8513
8514@example
8515$ gcc -c x.adb y.adb
8516@end example
8517
8518calls @code{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8519@code{y.adb}.
8520The compiler generates two object files @code{x.o} and @code{y.o}
8521and the two ALI files @code{x.ali} and @code{y.ali}.
8522
8523Any switches apply to all the files listed, see @ref{ea,,Compiler Switches} for a
8524list of available @code{gcc} switches.
8525
8526@node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8527@anchor{gnat_ugn/building_executable_programs_with_gnat id10}@anchor{eb}@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-and-the-run-time-library-rtl}@anchor{89}
8528@subsection Search Paths and the Run-Time Library (RTL)
8529
8530
8531With the GNAT source-based library system, the compiler must be able to
8532find source files for units that are needed by the unit being compiled.
8533Search paths are used to guide this process.
8534
8535The compiler compiles one source file whose name must be given
8536explicitly on the command line. In other words, no searching is done
8537for this file. To find all other source files that are needed (the most
8538common being the specs of units), the compiler examines the following
8539directories, in the following order:
8540
8541
8542@itemize *
8543
8544@item
8545The directory containing the source file of the main unit being compiled
8546(the file name on the command line).
8547
8548@item
8549Each directory named by an @code{-I} switch given on the @code{gcc}
8550command line, in the order given.
8551
8552@geindex ADA_PRJ_INCLUDE_FILE
8553
8554@item
8555Each of the directories listed in the text file whose name is given
8556by the
8557@geindex ADA_PRJ_INCLUDE_FILE
8558@geindex environment variable; ADA_PRJ_INCLUDE_FILE
8559@code{ADA_PRJ_INCLUDE_FILE} environment variable.
8560@geindex ADA_PRJ_INCLUDE_FILE
8561@geindex environment variable; ADA_PRJ_INCLUDE_FILE
8562@code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8563driver when project files are used. It should not normally be set
8564by other means.
8565
8566@geindex ADA_INCLUDE_PATH
8567
8568@item
8569Each of the directories listed in the value of the
8570@geindex ADA_INCLUDE_PATH
8571@geindex environment variable; ADA_INCLUDE_PATH
8572@code{ADA_INCLUDE_PATH} environment variable.
8573Construct this value
8574exactly as the
8575@geindex PATH
8576@geindex environment variable; PATH
8577@code{PATH} environment variable: a list of directory
8578names separated by colons (semicolons when working with the NT version).
8579
8580@item
8581The content of the @code{ada_source_path} file which is part of the GNAT
8582installation tree and is used to store standard libraries such as the
8583GNAT Run Time Library (RTL) source files.
8584@ref{87,,Installing a library}
8585@end itemize
8586
8587Specifying the switch @code{-I-}
8588inhibits the use of the directory
8589containing the source file named in the command line. You can still
8590have this directory on your search path, but in this case it must be
8591explicitly requested with a @code{-I} switch.
8592
8593Specifying the switch @code{-nostdinc}
8594inhibits the search of the default location for the GNAT Run Time
8595Library (RTL) source files.
8596
8597The compiler outputs its object files and ALI files in the current
8598working directory.
8599Caution: The object file can be redirected with the @code{-o} switch;
8600however, @code{gcc} and @code{gnat1} have not been coordinated on this
8601so the @code{ALI} file will not go to the right place. Therefore, you should
8602avoid using the @code{-o} switch.
8603
8604@geindex System.IO
8605
8606The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8607children make up the GNAT RTL, together with the simple @code{System.IO}
8608package used in the @code{"Hello World"} example. The sources for these units
8609are needed by the compiler and are kept together in one directory. Not
8610all of the bodies are needed, but all of the sources are kept together
8611anyway. In a normal installation, you need not specify these directory
8612names when compiling or binding. Either the environment variables or
8613the built-in defaults cause these files to be found.
8614
8615In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8616@code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8617consisting of child units of @code{GNAT}. This is a collection of generally
8618useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8619for further details.
8620
8621Besides simplifying access to the RTL, a major use of search paths is
8622in compiling sources from multiple directories. This can make
8623development environments much more flexible.
8624
8625@node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8626@anchor{gnat_ugn/building_executable_programs_with_gnat id11}@anchor{ec}@anchor{gnat_ugn/building_executable_programs_with_gnat order-of-compilation-issues}@anchor{ed}
8627@subsection Order of Compilation Issues
8628
8629
8630If, in our earlier example, there was a spec for the @code{hello}
8631procedure, it would be contained in the file @code{hello.ads}; yet this
8632file would not have to be explicitly compiled. This is the result of the
8633model we chose to implement library management. Some of the consequences
8634of this model are as follows:
8635
8636
8637@itemize *
8638
8639@item
8640There is no point in compiling specs (except for package
8641specs with no bodies) because these are compiled as needed by clients. If
8642you attempt a useless compilation, you will receive an error message.
8643It is also useless to compile subunits because they are compiled as needed
8644by the parent.
8645
8646@item
8647There are no order of compilation requirements: performing a
8648compilation never obsoletes anything. The only way you can obsolete
8649something and require recompilations is to modify one of the
8650source files on which it depends.
8651
8652@item
8653There is no library as such, apart from the ALI files
8654(@ref{42,,The Ada Library Information Files}, for information on the format
8655of these files). For now we find it convenient to create separate ALI files,
8656but eventually the information therein may be incorporated into the object
8657file directly.
8658
8659@item
8660When you compile a unit, the source files for the specs of all units
8661that it @emph{with}s, all its subunits, and the bodies of any generics it
8662instantiates must be available (reachable by the search-paths mechanism
8663described above), or you will receive a fatal error message.
8664@end itemize
8665
8666@node Examples,,Order of Compilation Issues,Compiling with gcc
8667@anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{ee}@anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{ef}
8668@subsection Examples
8669
8670
8671The following are some typical Ada compilation command line examples:
8672
8673@example
8674$ gcc -c xyz.adb
8675@end example
8676
8677Compile body in file @code{xyz.adb} with all default options.
8678
8679@example
8680$ gcc -c -O2 -gnata xyz-def.adb
8681@end example
8682
8683Compile the child unit package in file @code{xyz-def.adb} with extensive
8684optimizations, and pragma @code{Assert}/@cite{Debug} statements
8685enabled.
8686
8687@example
8688$ gcc -c -gnatc abc-def.adb
8689@end example
8690
8691Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8692mode.
8693
8694@node Compiler Switches,Linker Switches,Compiling with gcc,Building Executable Programs with GNAT
8695@anchor{gnat_ugn/building_executable_programs_with_gnat compiler-switches}@anchor{f0}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gcc}@anchor{ea}
8696@section Compiler Switches
8697
8698
8699The @code{gcc} command accepts switches that control the
8700compilation process. These switches are fully described in this section:
8701first an alphabetical listing of all switches with a brief description,
8702and then functionally grouped sets of switches with more detailed
8703information.
8704
8705More switches exist for GCC than those documented here, especially
8706for specific targets. However, their use is not recommended as
8707they may change code generation in ways that are incompatible with
8708the Ada run-time library, or can cause inconsistencies between
8709compilation units.
8710
8711@menu
8712* Alphabetical List of All Switches::
8713* Output and Error Message Control::
8714* Warning Message Control::
8715* Debugging and Assertion Control::
8716* Validity Checking::
8717* Style Checking::
8718* Run-Time Checks::
8719* Using gcc for Syntax Checking::
8720* Using gcc for Semantic Checking::
8721* Compiling Different Versions of Ada::
8722* Character Set Control::
8723* File Naming Control::
8724* Subprogram Inlining Control::
8725* Auxiliary Output Control::
8726* Debugging Control::
8727* Exception Handling Control::
8728* Units to Sources Mapping Files::
8729* Code Generation Control::
8730
8731@end menu
8732
8733@node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8734@anchor{gnat_ugn/building_executable_programs_with_gnat id13}@anchor{f1}@anchor{gnat_ugn/building_executable_programs_with_gnat alphabetical-list-of-all-switches}@anchor{f2}
8735@subsection Alphabetical List of All Switches
8736
8737
8738@geindex -b (gcc)
8739
8740
8741@table @asis
8742
8743@item @code{-b @emph{target}}
8744
8745Compile your program to run on @code{target}, which is the name of a
8746system configuration. You must have a GNAT cross-compiler built if
8747@code{target} is not the same as your host system.
8748@end table
8749
8750@geindex -B (gcc)
8751
8752
8753@table @asis
8754
8755@item @code{-B@emph{dir}}
8756
8757Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8758from @code{dir} instead of the default location. Only use this switch
8759when multiple versions of the GNAT compiler are available.
8760See the "Options for Directory Search" section in the
8761@cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8762You would normally use the @code{-b} or @code{-V} switch instead.
8763@end table
8764
8765@geindex -c (gcc)
8766
8767
8768@table @asis
8769
8770@item @code{-c}
8771
8772Compile. Always use this switch when compiling Ada programs.
8773
8774Note: for some other languages when using @code{gcc}, notably in
8775the case of C and C++, it is possible to use
8776use @code{gcc} without a @code{-c} switch to
8777compile and link in one step. In the case of GNAT, you
8778cannot use this approach, because the binder must be run
8779and @code{gcc} cannot be used to run the GNAT binder.
8780@end table
8781
8782@geindex -fcallgraph-info (gcc)
8783
8784
8785@table @asis
8786
8787@item @code{-fcallgraph-info[=su,da]}
8788
8789Makes the compiler output callgraph information for the program, on a
8790per-file basis. The information is generated in the VCG format.  It can
8791be decorated with additional, per-node and/or per-edge information, if a
8792list of comma-separated markers is additionally specified. When the
8793@code{su} marker is specified, the callgraph is decorated with stack usage
8794information; it is equivalent to @code{-fstack-usage}. When the @code{da}
8795marker is specified, the callgraph is decorated with information about
8796dynamically allocated objects.
8797@end table
8798
8799@geindex -fdump-scos (gcc)
8800
8801
8802@table @asis
8803
8804@item @code{-fdump-scos}
8805
8806Generates SCO (Source Coverage Obligation) information in the ALI file.
8807This information is used by advanced coverage tools. See unit @code{SCOs}
8808in the compiler sources for details in files @code{scos.ads} and
8809@code{scos.adb}.
8810@end table
8811
8812@geindex -fgnat-encodings (gcc)
8813
8814
8815@table @asis
8816
8817@item @code{-fgnat-encodings=[all|gdb|minimal]}
8818
8819This switch controls the balance between GNAT encodings and standard DWARF
8820emitted in the debug information.
8821@end table
8822
8823@geindex -flto (gcc)
8824
8825
8826@table @asis
8827
8828@item @code{-flto[=@emph{n}]}
8829
8830Enables Link Time Optimization. This switch must be used in conjunction
8831with the @code{-Ox} switches (but not with the @code{-gnatn} switch
8832since it is a full replacement for the latter) and instructs the compiler
8833to defer most optimizations until the link stage. The advantage of this
8834approach is that the compiler can do a whole-program analysis and choose
8835the best interprocedural optimization strategy based on a complete view
8836of the program, instead of a fragmentary view with the usual approach.
8837This can also speed up the compilation of big programs and reduce the
8838size of the executable, compared with a traditional per-unit compilation
8839with inlining across units enabled by the @code{-gnatn} switch.
8840The drawback of this approach is that it may require more memory and that
8841the debugging information generated by -g with it might be hardly usable.
8842The switch, as well as the accompanying @code{-Ox} switches, must be
8843specified both for the compilation and the link phases.
8844If the @code{n} parameter is specified, the optimization and final code
8845generation at link time are executed using @code{n} parallel jobs by
8846means of an installed @code{make} program.
8847@end table
8848
8849@geindex -fno-inline (gcc)
8850
8851
8852@table @asis
8853
8854@item @code{-fno-inline}
8855
8856Suppresses all inlining, unless requested with pragma @code{Inline_Always}. The
8857effect is enforced regardless of other optimization or inlining switches.
8858Note that inlining can also be suppressed on a finer-grained basis with
8859pragma @code{No_Inline}.
8860@end table
8861
8862@geindex -fno-inline-functions (gcc)
8863
8864
8865@table @asis
8866
8867@item @code{-fno-inline-functions}
8868
8869Suppresses automatic inlining of subprograms, which is enabled
8870if @code{-O3} is used.
8871@end table
8872
8873@geindex -fno-inline-small-functions (gcc)
8874
8875
8876@table @asis
8877
8878@item @code{-fno-inline-small-functions}
8879
8880Suppresses automatic inlining of small subprograms, which is enabled
8881if @code{-O2} is used.
8882@end table
8883
8884@geindex -fno-inline-functions-called-once (gcc)
8885
8886
8887@table @asis
8888
8889@item @code{-fno-inline-functions-called-once}
8890
8891Suppresses inlining of subprograms local to the unit and called once
8892from within it, which is enabled if @code{-O1} is used.
8893@end table
8894
8895@geindex -fno-ivopts (gcc)
8896
8897
8898@table @asis
8899
8900@item @code{-fno-ivopts}
8901
8902Suppresses high-level loop induction variable optimizations, which are
8903enabled if @code{-O1} is used. These optimizations are generally
8904profitable but, for some specific cases of loops with numerous uses
8905of the iteration variable that follow a common pattern, they may end
8906up destroying the regularity that could be exploited at a lower level
8907and thus producing inferior code.
8908@end table
8909
8910@geindex -fno-strict-aliasing (gcc)
8911
8912
8913@table @asis
8914
8915@item @code{-fno-strict-aliasing}
8916
8917Causes the compiler to avoid assumptions regarding non-aliasing
8918of objects of different types. See
8919@ref{f3,,Optimization and Strict Aliasing} for details.
8920@end table
8921
8922@geindex -fno-strict-overflow (gcc)
8923
8924
8925@table @asis
8926
8927@item @code{-fno-strict-overflow}
8928
8929Causes the compiler to avoid assumptions regarding the rules of signed
8930integer overflow. These rules specify that signed integer overflow will
8931result in a Constraint_Error exception at run time and are enforced in
8932default mode by the compiler, so this switch should not be necessary in
8933normal operating mode. It might be useful in conjunction with @code{-gnato0}
8934for very peculiar cases of low-level programming.
8935@end table
8936
8937@geindex -fstack-check (gcc)
8938
8939
8940@table @asis
8941
8942@item @code{-fstack-check}
8943
8944Activates stack checking.
8945See @ref{f4,,Stack Overflow Checking} for details.
8946@end table
8947
8948@geindex -fstack-usage (gcc)
8949
8950
8951@table @asis
8952
8953@item @code{-fstack-usage}
8954
8955Makes the compiler output stack usage information for the program, on a
8956per-subprogram basis. See @ref{f5,,Static Stack Usage Analysis} for details.
8957@end table
8958
8959@geindex -g (gcc)
8960
8961
8962@table @asis
8963
8964@item @code{-g}
8965
8966Generate debugging information. This information is stored in the object
8967file and copied from there to the final executable file by the linker,
8968where it can be read by the debugger. You must use the
8969@code{-g} switch if you plan on using the debugger.
8970@end table
8971
8972@geindex -gnat05 (gcc)
8973
8974
8975@table @asis
8976
8977@item @code{-gnat05}
8978
8979Allow full Ada 2005 features.
8980@end table
8981
8982@geindex -gnat12 (gcc)
8983
8984
8985@table @asis
8986
8987@item @code{-gnat12}
8988
8989Allow full Ada 2012 features.
8990@end table
8991
8992@geindex -gnat83 (gcc)
8993
8994@geindex -gnat2005 (gcc)
8995
8996
8997@table @asis
8998
8999@item @code{-gnat2005}
9000
9001Allow full Ada 2005 features (same as @code{-gnat05})
9002@end table
9003
9004@geindex -gnat2012 (gcc)
9005
9006
9007@table @asis
9008
9009@item @code{-gnat2012}
9010
9011Allow full Ada 2012 features (same as @code{-gnat12})
9012
9013@item @code{-gnat83}
9014
9015Enforce Ada 83 restrictions.
9016@end table
9017
9018@geindex -gnat95 (gcc)
9019
9020
9021@table @asis
9022
9023@item @code{-gnat95}
9024
9025Enforce Ada 95 restrictions.
9026
9027Note: for compatibility with some Ada 95 compilers which support only
9028the @code{overriding} keyword of Ada 2005, the @code{-gnatd.D} switch can
9029be used along with @code{-gnat95} to achieve a similar effect with GNAT.
9030
9031@code{-gnatd.D} instructs GNAT to consider @code{overriding} as a keyword
9032and handle its associated semantic checks, even in Ada 95 mode.
9033@end table
9034
9035@geindex -gnata (gcc)
9036
9037
9038@table @asis
9039
9040@item @code{-gnata}
9041
9042Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
9043activated. Note that these pragmas can also be controlled using the
9044configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
9045It also activates pragmas @code{Check}, @code{Precondition}, and
9046@code{Postcondition}. Note that these pragmas can also be controlled
9047using the configuration pragma @code{Check_Policy}. In Ada 2012, it
9048also activates all assertions defined in the RM as aspects: preconditions,
9049postconditions, type invariants and (sub)type predicates. In all Ada modes,
9050corresponding pragmas for type invariants and (sub)type predicates are
9051also activated. The default is that all these assertions are disabled,
9052and have no effect, other than being checked for syntactic validity, and
9053in the case of subtype predicates, constructions such as membership tests
9054still test predicates even if assertions are turned off.
9055@end table
9056
9057@geindex -gnatA (gcc)
9058
9059
9060@table @asis
9061
9062@item @code{-gnatA}
9063
9064Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
9065it will be ignored.
9066@end table
9067
9068@geindex -gnatb (gcc)
9069
9070
9071@table @asis
9072
9073@item @code{-gnatb}
9074
9075Generate brief messages to @code{stderr} even if verbose mode set.
9076@end table
9077
9078@geindex -gnatB (gcc)
9079
9080
9081@table @asis
9082
9083@item @code{-gnatB}
9084
9085Assume no invalid (bad) values except for 'Valid attribute use
9086(@ref{f6,,Validity Checking}).
9087@end table
9088
9089@geindex -gnatc (gcc)
9090
9091
9092@table @asis
9093
9094@item @code{-gnatc}
9095
9096Check syntax and semantics only (no code generation attempted). When the
9097compiler is invoked by @code{gnatmake}, if the switch @code{-gnatc} is
9098only given to the compiler (after @code{-cargs} or in package Compiler of
9099the project file, @code{gnatmake} will fail because it will not find the
9100object file after compilation. If @code{gnatmake} is called with
9101@code{-gnatc} as a builder switch (before @code{-cargs} or in package
9102Builder of the project file) then @code{gnatmake} will not fail because
9103it will not look for the object files after compilation, and it will not try
9104to build and link.
9105@end table
9106
9107@geindex -gnatC (gcc)
9108
9109
9110@table @asis
9111
9112@item @code{-gnatC}
9113
9114Generate CodePeer intermediate format (no code generation attempted).
9115This switch will generate an intermediate representation suitable for
9116use by CodePeer (@code{.scil} files). This switch is not compatible with
9117code generation (it will, among other things, disable some switches such
9118as -gnatn, and enable others such as -gnata).
9119@end table
9120
9121@geindex -gnatd (gcc)
9122
9123
9124@table @asis
9125
9126@item @code{-gnatd}
9127
9128Specify debug options for the compiler. The string of characters after
9129the @code{-gnatd} specify the specific debug options. The possible
9130characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
9131compiler source file @code{debug.adb} for details of the implemented
9132debug options. Certain debug options are relevant to applications
9133programmers, and these are documented at appropriate points in this
9134users guide.
9135@end table
9136
9137@geindex -gnatD[nn] (gcc)
9138
9139
9140@table @asis
9141
9142@item @code{-gnatD}
9143
9144Create expanded source files for source level debugging. This switch
9145also suppresses generation of cross-reference information
9146(see @code{-gnatx}). Note that this switch is not allowed if a previous
9147-gnatR switch has been given, since these two switches are not compatible.
9148@end table
9149
9150@geindex -gnateA (gcc)
9151
9152
9153@table @asis
9154
9155@item @code{-gnateA}
9156
9157Check that the actual parameters of a subprogram call are not aliases of one
9158another. To qualify as aliasing, the actuals must denote objects of a composite
9159type, their memory locations must be identical or overlapping, and at least one
9160of the corresponding formal parameters must be of mode OUT or IN OUT.
9161
9162@example
9163type Rec_Typ is record
9164   Data : Integer := 0;
9165end record;
9166
9167function Self (Val : Rec_Typ) return Rec_Typ is
9168begin
9169   return Val;
9170end Self;
9171
9172procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
9173begin
9174   null;
9175end Detect_Aliasing;
9176
9177Obj : Rec_Typ;
9178
9179Detect_Aliasing (Obj, Obj);
9180Detect_Aliasing (Obj, Self (Obj));
9181@end example
9182
9183In the example above, the first call to @code{Detect_Aliasing} fails with a
9184@code{Program_Error} at run time because the actuals for @code{Val_1} and
9185@code{Val_2} denote the same object. The second call executes without raising
9186an exception because @code{Self(Obj)} produces an anonymous object which does
9187not share the memory location of @code{Obj}.
9188@end table
9189
9190@geindex -gnatec (gcc)
9191
9192
9193@table @asis
9194
9195@item @code{-gnatec=@emph{path}}
9196
9197Specify a configuration pragma file
9198(the equal sign is optional)
9199(@ref{79,,The Configuration Pragmas Files}).
9200@end table
9201
9202@geindex -gnateC (gcc)
9203
9204
9205@table @asis
9206
9207@item @code{-gnateC}
9208
9209Generate CodePeer messages in a compiler-like format. This switch is only
9210effective if @code{-gnatcC} is also specified and requires an installation
9211of CodePeer.
9212@end table
9213
9214@geindex -gnated (gcc)
9215
9216
9217@table @asis
9218
9219@item @code{-gnated}
9220
9221Disable atomic synchronization
9222@end table
9223
9224@geindex -gnateD (gcc)
9225
9226
9227@table @asis
9228
9229@item @code{-gnateDsymbol[=@emph{value}]}
9230
9231Defines a symbol, associated with @code{value}, for preprocessing.
9232(@ref{18,,Integrated Preprocessing}).
9233@end table
9234
9235@geindex -gnateE (gcc)
9236
9237
9238@table @asis
9239
9240@item @code{-gnateE}
9241
9242Generate extra information in exception messages. In particular, display
9243extra column information and the value and range associated with index and
9244range check failures, and extra column information for access checks.
9245In cases where the compiler is able to determine at compile time that
9246a check will fail, it gives a warning, and the extra information is not
9247produced at run time.
9248@end table
9249
9250@geindex -gnatef (gcc)
9251
9252
9253@table @asis
9254
9255@item @code{-gnatef}
9256
9257Display full source path name in brief error messages.
9258@end table
9259
9260@geindex -gnateF (gcc)
9261
9262
9263@table @asis
9264
9265@item @code{-gnateF}
9266
9267Check for overflow on all floating-point operations, including those
9268for unconstrained predefined types. See description of pragma
9269@code{Check_Float_Overflow} in GNAT RM.
9270@end table
9271
9272@geindex -gnateg (gcc)
9273
9274@code{-gnateg}
9275@code{-gnatceg}
9276
9277@quotation
9278
9279The @code{-gnatc} switch must always be specified before this switch, e.g.
9280@code{-gnatceg}. Generate a C header from the Ada input file. See
9281@ref{ca,,Generating C Headers for Ada Specifications} for more
9282information.
9283@end quotation
9284
9285@geindex -gnateG (gcc)
9286
9287
9288@table @asis
9289
9290@item @code{-gnateG}
9291
9292Save result of preprocessing in a text file.
9293@end table
9294
9295@geindex -gnatei (gcc)
9296
9297
9298@table @asis
9299
9300@item @code{-gnatei@emph{nnn}}
9301
9302Set maximum number of instantiations during compilation of a single unit to
9303@code{nnn}. This may be useful in increasing the default maximum of 8000 for
9304the rare case when a single unit legitimately exceeds this limit.
9305@end table
9306
9307@geindex -gnateI (gcc)
9308
9309
9310@table @asis
9311
9312@item @code{-gnateI@emph{nnn}}
9313
9314Indicates that the source is a multi-unit source and that the index of the
9315unit to compile is @code{nnn}. @code{nnn} needs to be a positive number and need
9316to be a valid index in the multi-unit source.
9317@end table
9318
9319@geindex -gnatel (gcc)
9320
9321
9322@table @asis
9323
9324@item @code{-gnatel}
9325
9326This switch can be used with the static elaboration model to issue info
9327messages showing
9328where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
9329are generated. This is useful in diagnosing elaboration circularities
9330caused by these implicit pragmas when using the static elaboration
9331model. See See the section in this guide on elaboration checking for
9332further details. These messages are not generated by default, and are
9333intended only for temporary use when debugging circularity problems.
9334@end table
9335
9336@geindex -gnatel (gcc)
9337
9338
9339@table @asis
9340
9341@item @code{-gnateL}
9342
9343This switch turns off the info messages about implicit elaboration pragmas.
9344@end table
9345
9346@geindex -gnatem (gcc)
9347
9348
9349@table @asis
9350
9351@item @code{-gnatem=@emph{path}}
9352
9353Specify a mapping file
9354(the equal sign is optional)
9355(@ref{f7,,Units to Sources Mapping Files}).
9356@end table
9357
9358@geindex -gnatep (gcc)
9359
9360
9361@table @asis
9362
9363@item @code{-gnatep=@emph{file}}
9364
9365Specify a preprocessing data file
9366(the equal sign is optional)
9367(@ref{18,,Integrated Preprocessing}).
9368@end table
9369
9370@geindex -gnateP (gcc)
9371
9372
9373@table @asis
9374
9375@item @code{-gnateP}
9376
9377Turn categorization dependency errors into warnings.
9378Ada requires that units that WITH one another have compatible categories, for
9379example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9380these errors become warnings (which can be ignored, or suppressed in the usual
9381manner). This can be useful in some specialized circumstances such as the
9382temporary use of special test software.
9383@end table
9384
9385@geindex -gnateS (gcc)
9386
9387
9388@table @asis
9389
9390@item @code{-gnateS}
9391
9392Synonym of @code{-fdump-scos}, kept for backwards compatibility.
9393@end table
9394
9395@geindex -gnatet=file (gcc)
9396
9397
9398@table @asis
9399
9400@item @code{-gnatet=@emph{path}}
9401
9402Generate target dependent information. The format of the output file is
9403described in the section about switch @code{-gnateT}.
9404@end table
9405
9406@geindex -gnateT (gcc)
9407
9408
9409@table @asis
9410
9411@item @code{-gnateT=@emph{path}}
9412
9413Read target dependent information, such as endianness or sizes and alignments
9414of base type. If this switch is passed, the default target dependent
9415information of the compiler is replaced by the one read from the input file.
9416This is used by tools other than the compiler, e.g. to do
9417semantic analysis of programs that will run on some other target than
9418the machine on which the tool is run.
9419
9420The following target dependent values should be defined,
9421where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
9422positive integer value, and fields marked with a question mark are
9423boolean fields, where a value of 0 is False, and a value of 1 is True:
9424
9425@example
9426Bits_BE                    : Nat; -- Bits stored big-endian?
9427Bits_Per_Unit              : Pos; -- Bits in a storage unit
9428Bits_Per_Word              : Pos; -- Bits in a word
9429Bytes_BE                   : Nat; -- Bytes stored big-endian?
9430Char_Size                  : Pos; -- Standard.Character'Size
9431Double_Float_Alignment     : Nat; -- Alignment of double float
9432Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
9433Double_Size                : Pos; -- Standard.Long_Float'Size
9434Float_Size                 : Pos; -- Standard.Float'Size
9435Float_Words_BE             : Nat; -- Float words stored big-endian?
9436Int_Size                   : Pos; -- Standard.Integer'Size
9437Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
9438Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
9439Long_Size                  : Pos; -- Standard.Long_Integer'Size
9440Maximum_Alignment          : Pos; -- Maximum permitted alignment
9441Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
9442Pointer_Size               : Pos; -- System.Address'Size
9443Short_Enums                : Nat; -- Foreign enums use short size?
9444Short_Size                 : Pos; -- Standard.Short_Integer'Size
9445Strict_Alignment           : Nat; -- Strict alignment?
9446System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9447Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
9448Words_BE                   : Nat; -- Words stored big-endian?
9449@end example
9450
9451@code{Bits_Per_Unit} is the number of bits in a storage unit, the equivalent of
9452GCC macro @code{BITS_PER_UNIT} documented as follows: @cite{Define this macro to be the number of bits in an addressable storage unit (byte); normally 8.}
9453
9454@code{Bits_Per_Word} is the number of bits in a machine word, the equivalent of
9455GCC macro @code{BITS_PER_WORD} documented as follows: @cite{Number of bits in a word; normally 32.}
9456
9457@code{Double_Scalar_Alignment} is the alignment for a scalar whose size is two
9458machine words. It should be the same as the alignment for C @code{long_long} on
9459most targets.
9460
9461@code{Maximum_Alignment} is the maximum alignment that the compiler might choose
9462by default for a type or object, which is also the maximum alignment that can
9463be specified in GNAT. It is computed for GCC backends as @code{BIGGEST_ALIGNMENT
9464/ BITS_PER_UNIT} where GCC macro @code{BIGGEST_ALIGNMENT} is documented as
9465follows: @cite{Biggest alignment that any data type can require on this machine@comma{} in bits.}
9466
9467@code{Max_Unaligned_Field} is the maximum size for unaligned bit field, which is
946864 for the majority of GCC targets (but can be different on some targets like
9469AAMP).
9470
9471@code{Strict_Alignment} is the equivalent of GCC macro @code{STRICT_ALIGNMENT}
9472documented as follows: @cite{Define this macro to be the value 1 if instructions will fail to work if given data not on the nominal alignment. If instructions will merely go slower in that case@comma{} define this macro as 0.}
9473
9474@code{System_Allocator_Alignment} is the guaranteed alignment of data returned
9475by calls to @code{malloc}.
9476
9477The format of the input file is as follows. First come the values of
9478the variables defined above, with one line per value:
9479
9480@example
9481name  value
9482@end example
9483
9484where @code{name} is the name of the parameter, spelled out in full,
9485and cased as in the above list, and @code{value} is an unsigned decimal
9486integer. Two or more blanks separates the name from the value.
9487
9488All the variables must be present, in alphabetical order (i.e. the
9489same order as the list above).
9490
9491Then there is a blank line to separate the two parts of the file. Then
9492come the lines showing the floating-point types to be registered, with
9493one line per registered mode:
9494
9495@example
9496name  digs float_rep size alignment
9497@end example
9498
9499where @code{name} is the string name of the type (which can have
9500single spaces embedded in the name (e.g. long double), @code{digs} is
9501the number of digits for the floating-point type, @code{float_rep} is
9502the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
9503AAMP), @code{size} is the size in bits, @code{alignment} is the
9504alignment in bits. The name is followed by at least two blanks, fields
9505are separated by at least one blank, and a LF character immediately
9506follows the alignment field.
9507
9508Here is an example of a target parameterization file:
9509
9510@example
9511Bits_BE                       0
9512Bits_Per_Unit                 8
9513Bits_Per_Word                64
9514Bytes_BE                      0
9515Char_Size                     8
9516Double_Float_Alignment        0
9517Double_Scalar_Alignment       0
9518Double_Size                  64
9519Float_Size                   32
9520Float_Words_BE                0
9521Int_Size                     64
9522Long_Double_Size            128
9523Long_Long_Size               64
9524Long_Size                    64
9525Maximum_Alignment            16
9526Max_Unaligned_Field          64
9527Pointer_Size                 64
9528Short_Size                   16
9529Strict_Alignment              0
9530System_Allocator_Alignment   16
9531Wchar_T_Size                 32
9532Words_BE                      0
9533
9534float         15  I  64  64
9535double        15  I  64  64
9536long double   18  I  80 128
9537TF            33  I 128 128
9538@end example
9539@end table
9540
9541@geindex -gnateu (gcc)
9542
9543
9544@table @asis
9545
9546@item @code{-gnateu}
9547
9548Ignore unrecognized validity, warning, and style switches that
9549appear after this switch is given. This may be useful when
9550compiling sources developed on a later version of the compiler
9551with an earlier version. Of course the earlier version must
9552support this switch.
9553@end table
9554
9555@geindex -gnateV (gcc)
9556
9557
9558@table @asis
9559
9560@item @code{-gnateV}
9561
9562Check that all actual parameters of a subprogram call are valid according to
9563the rules of validity checking (@ref{f6,,Validity Checking}).
9564@end table
9565
9566@geindex -gnateY (gcc)
9567
9568
9569@table @asis
9570
9571@item @code{-gnateY}
9572
9573Ignore all STYLE_CHECKS pragmas. Full legality checks
9574are still carried out, but the pragmas have no effect
9575on what style checks are active. This allows all style
9576checking options to be controlled from the command line.
9577@end table
9578
9579@geindex -gnatE (gcc)
9580
9581
9582@table @asis
9583
9584@item @code{-gnatE}
9585
9586Full dynamic elaboration checks.
9587@end table
9588
9589@geindex -gnatf (gcc)
9590
9591
9592@table @asis
9593
9594@item @code{-gnatf}
9595
9596Full errors. Multiple errors per line, all undefined references, do not
9597attempt to suppress cascaded errors.
9598@end table
9599
9600@geindex -gnatF (gcc)
9601
9602
9603@table @asis
9604
9605@item @code{-gnatF}
9606
9607Externals names are folded to all uppercase.
9608@end table
9609
9610@geindex -gnatg (gcc)
9611
9612
9613@table @asis
9614
9615@item @code{-gnatg}
9616
9617Internal GNAT implementation mode. This should not be used for applications
9618programs, it is intended only for use by the compiler and its run-time
9619library. For documentation, see the GNAT sources. Note that @code{-gnatg}
9620implies @code{-gnatw.ge} and @code{-gnatyg} so that all standard
9621warnings and all standard style options are turned on. All warnings and style
9622messages are treated as errors.
9623@end table
9624
9625@geindex -gnatG[nn] (gcc)
9626
9627
9628@table @asis
9629
9630@item @code{-gnatG=nn}
9631
9632List generated expanded code in source form.
9633@end table
9634
9635@geindex -gnath (gcc)
9636
9637
9638@table @asis
9639
9640@item @code{-gnath}
9641
9642Output usage information. The output is written to @code{stdout}.
9643@end table
9644
9645@geindex -gnatH (gcc)
9646
9647
9648@table @asis
9649
9650@item @code{-gnatH}
9651
9652Legacy elaboration-checking mode enabled. When this switch is in effect, the
9653pre-18.x access-before-elaboration model becomes the de facto model.
9654@end table
9655
9656@geindex -gnati (gcc)
9657
9658
9659@table @asis
9660
9661@item @code{-gnati@emph{c}}
9662
9663Identifier character set (@code{c} = 1/2/3/4/8/9/p/f/n/w).
9664For details of the possible selections for @code{c},
9665see @ref{48,,Character Set Control}.
9666@end table
9667
9668@geindex -gnatI (gcc)
9669
9670
9671@table @asis
9672
9673@item @code{-gnatI}
9674
9675Ignore representation clauses. When this switch is used,
9676representation clauses are treated as comments. This is useful
9677when initially porting code where you want to ignore rep clause
9678problems, and also for compiling foreign code (particularly
9679for use with ASIS). The representation clauses that are ignored
9680are: enumeration_representation_clause, record_representation_clause,
9681and attribute_definition_clause for the following attributes:
9682Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9683Object_Size, Scalar_Storage_Order, Size, Small, Stream_Size,
9684and Value_Size. Pragma Default_Scalar_Storage_Order is also ignored.
9685Note that this option should be used only for compiling -- the
9686code is likely to malfunction at run time.
9687
9688Note that when @code{-gnatct} is used to generate trees for input
9689into ASIS tools, these representation clauses are removed
9690from the tree and ignored. This means that the tool will not see them.
9691@end table
9692
9693@geindex -gnatjnn (gcc)
9694
9695
9696@table @asis
9697
9698@item @code{-gnatj@emph{nn}}
9699
9700Reformat error messages to fit on @code{nn} character lines
9701@end table
9702
9703@geindex -gnatJ (gcc)
9704
9705
9706@table @asis
9707
9708@item @code{-gnatJ}
9709
9710Permissive elaboration-checking mode enabled. When this switch is in effect,
9711the post-18.x access-before-elaboration model ignores potential issues with:
9712
9713
9714@itemize -
9715
9716@item
9717Accept statements
9718
9719@item
9720Activations of tasks defined in instances
9721
9722@item
9723Assertion pragmas
9724
9725@item
9726Calls from within an instance to its enclosing context
9727
9728@item
9729Calls through generic formal parameters
9730
9731@item
9732Calls to subprograms defined in instances
9733
9734@item
9735Entry calls
9736
9737@item
9738Indirect calls using 'Access
9739
9740@item
9741Requeue statements
9742
9743@item
9744Select statements
9745
9746@item
9747Synchronous task suspension
9748@end itemize
9749
9750and does not emit compile-time diagnostics or run-time checks.
9751@end table
9752
9753@geindex -gnatk (gcc)
9754
9755
9756@table @asis
9757
9758@item @code{-gnatk=@emph{n}}
9759
9760Limit file names to @code{n} (1-999) characters (@code{k} = krunch).
9761@end table
9762
9763@geindex -gnatl (gcc)
9764
9765
9766@table @asis
9767
9768@item @code{-gnatl}
9769
9770Output full source listing with embedded error messages.
9771@end table
9772
9773@geindex -gnatL (gcc)
9774
9775
9776@table @asis
9777
9778@item @code{-gnatL}
9779
9780Used in conjunction with -gnatG or -gnatD to intersperse original
9781source lines (as comment lines with line numbers) in the expanded
9782source output.
9783@end table
9784
9785@geindex -gnatm (gcc)
9786
9787
9788@table @asis
9789
9790@item @code{-gnatm=@emph{n}}
9791
9792Limit number of detected error or warning messages to @code{n}
9793where @code{n} is in the range 1..999999. The default setting if
9794no switch is given is 9999. If the number of warnings reaches this
9795limit, then a message is output and further warnings are suppressed,
9796but the compilation is continued. If the number of error messages
9797reaches this limit, then a message is output and the compilation
9798is abandoned. The equal sign here is optional. A value of zero
9799means that no limit applies.
9800@end table
9801
9802@geindex -gnatn (gcc)
9803
9804
9805@table @asis
9806
9807@item @code{-gnatn[12]}
9808
9809Activate inlining across units for subprograms for which pragma @code{Inline}
9810is specified. This inlining is performed by the GCC back-end. An optional
9811digit sets the inlining level: 1 for moderate inlining across units
9812or 2 for full inlining across units. If no inlining level is specified,
9813the compiler will pick it based on the optimization level.
9814@end table
9815
9816@geindex -gnatN (gcc)
9817
9818
9819@table @asis
9820
9821@item @code{-gnatN}
9822
9823Activate front end inlining for subprograms for which
9824pragma @code{Inline} is specified. This inlining is performed
9825by the front end and will be visible in the
9826@code{-gnatG} output.
9827
9828When using a gcc-based back end (in practice this means using any version
9829of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
9830@code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
9831Historically front end inlining was more extensive than the gcc back end
9832inlining, but that is no longer the case.
9833@end table
9834
9835@geindex -gnato0 (gcc)
9836
9837
9838@table @asis
9839
9840@item @code{-gnato0}
9841
9842Suppresses overflow checking. This causes the behavior of the compiler to
9843match the default for older versions where overflow checking was suppressed
9844by default. This is equivalent to having
9845@code{pragma Suppress (Overflow_Check)} in a configuration pragma file.
9846@end table
9847
9848@geindex -gnato?? (gcc)
9849
9850
9851@table @asis
9852
9853@item @code{-gnato??}
9854
9855Set default mode for handling generation of code to avoid intermediate
9856arithmetic overflow. Here @code{??} is two digits, a
9857single digit, or nothing. Each digit is one of the digits @code{1}
9858through @code{3}:
9859
9860
9861@multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
9862@item
9863
9864Digit
9865
9866@tab
9867
9868Interpretation
9869
9870@item
9871
9872@emph{1}
9873
9874@tab
9875
9876All intermediate overflows checked against base type (@code{STRICT})
9877
9878@item
9879
9880@emph{2}
9881
9882@tab
9883
9884Minimize intermediate overflows (@code{MINIMIZED})
9885
9886@item
9887
9888@emph{3}
9889
9890@tab
9891
9892Eliminate intermediate overflows (@code{ELIMINATED})
9893
9894@end multitable
9895
9896
9897If only one digit appears, then it applies to all
9898cases; if two digits are given, then the first applies outside
9899assertions, pre/postconditions, and type invariants, and the second
9900applies within assertions, pre/postconditions, and type invariants.
9901
9902If no digits follow the @code{-gnato}, then it is equivalent to
9903@code{-gnato11},
9904causing all intermediate overflows to be handled in strict
9905mode.
9906
9907This switch also causes arithmetic overflow checking to be performed
9908(as though @code{pragma Unsuppress (Overflow_Check)} had been specified).
9909
9910The default if no option @code{-gnato} is given is that overflow handling
9911is in @code{STRICT} mode (computations done using the base type), and that
9912overflow checking is enabled.
9913
9914Note that division by zero is a separate check that is not
9915controlled by this switch (divide-by-zero checking is on by default).
9916
9917See also @ref{f8,,Specifying the Desired Mode}.
9918@end table
9919
9920@geindex -gnatp (gcc)
9921
9922
9923@table @asis
9924
9925@item @code{-gnatp}
9926
9927Suppress all checks. See @ref{f9,,Run-Time Checks} for details. This switch
9928has no effect if cancelled by a subsequent @code{-gnat-p} switch.
9929@end table
9930
9931@geindex -gnat-p (gcc)
9932
9933
9934@table @asis
9935
9936@item @code{-gnat-p}
9937
9938Cancel effect of previous @code{-gnatp} switch.
9939@end table
9940
9941@geindex -gnatP (gcc)
9942
9943
9944@table @asis
9945
9946@item @code{-gnatP}
9947
9948Enable polling. This is required on some systems (notably Windows NT) to
9949obtain asynchronous abort and asynchronous transfer of control capability.
9950See @code{Pragma_Polling} in the @cite{GNAT_Reference_Manual} for full
9951details.
9952@end table
9953
9954@geindex -gnatq (gcc)
9955
9956
9957@table @asis
9958
9959@item @code{-gnatq}
9960
9961Don't quit. Try semantics, even if parse errors.
9962@end table
9963
9964@geindex -gnatQ (gcc)
9965
9966
9967@table @asis
9968
9969@item @code{-gnatQ}
9970
9971Don't quit. Generate @code{ALI} and tree files even if illegalities.
9972Note that code generation is still suppressed in the presence of any
9973errors, so even with @code{-gnatQ} no object file is generated.
9974@end table
9975
9976@geindex -gnatr (gcc)
9977
9978
9979@table @asis
9980
9981@item @code{-gnatr}
9982
9983Treat pragma Restrictions as Restriction_Warnings.
9984@end table
9985
9986@geindex -gnatR (gcc)
9987
9988
9989@table @asis
9990
9991@item @code{-gnatR[0|1|2|3|4][e][j][m][s]}
9992
9993Output representation information for declared types, objects and
9994subprograms. Note that this switch is not allowed if a previous
9995@code{-gnatD} switch has been given, since these two switches
9996are not compatible.
9997@end table
9998
9999@geindex -gnats (gcc)
10000
10001
10002@table @asis
10003
10004@item @code{-gnats}
10005
10006Syntax check only.
10007@end table
10008
10009@geindex -gnatS (gcc)
10010
10011
10012@table @asis
10013
10014@item @code{-gnatS}
10015
10016Print package Standard.
10017@end table
10018
10019@geindex -gnatt (gcc)
10020
10021
10022@table @asis
10023
10024@item @code{-gnatt}
10025
10026Generate tree output file.
10027@end table
10028
10029@geindex -gnatT (gcc)
10030
10031
10032@table @asis
10033
10034@item @code{-gnatT@emph{nnn}}
10035
10036All compiler tables start at @code{nnn} times usual starting size.
10037@end table
10038
10039@geindex -gnatu (gcc)
10040
10041
10042@table @asis
10043
10044@item @code{-gnatu}
10045
10046List units for this compilation.
10047@end table
10048
10049@geindex -gnatU (gcc)
10050
10051
10052@table @asis
10053
10054@item @code{-gnatU}
10055
10056Tag all error messages with the unique string 'error:'
10057@end table
10058
10059@geindex -gnatv (gcc)
10060
10061
10062@table @asis
10063
10064@item @code{-gnatv}
10065
10066Verbose mode. Full error output with source lines to @code{stdout}.
10067@end table
10068
10069@geindex -gnatV (gcc)
10070
10071
10072@table @asis
10073
10074@item @code{-gnatV}
10075
10076Control level of validity checking (@ref{f6,,Validity Checking}).
10077@end table
10078
10079@geindex -gnatw (gcc)
10080
10081
10082@table @asis
10083
10084@item @code{-gnatw@emph{xxx}}
10085
10086Warning mode where
10087@code{xxx} is a string of option letters that denotes
10088the exact warnings that
10089are enabled or disabled (@ref{fa,,Warning Message Control}).
10090@end table
10091
10092@geindex -gnatW (gcc)
10093
10094
10095@table @asis
10096
10097@item @code{-gnatW@emph{e}}
10098
10099Wide character encoding method
10100(@code{e}=n/h/u/s/e/8).
10101@end table
10102
10103@geindex -gnatx (gcc)
10104
10105
10106@table @asis
10107
10108@item @code{-gnatx}
10109
10110Suppress generation of cross-reference information.
10111@end table
10112
10113@geindex -gnatX (gcc)
10114
10115
10116@table @asis
10117
10118@item @code{-gnatX}
10119
10120Enable GNAT implementation extensions and latest Ada version.
10121@end table
10122
10123@geindex -gnaty (gcc)
10124
10125
10126@table @asis
10127
10128@item @code{-gnaty}
10129
10130Enable built-in style checks (@ref{fb,,Style Checking}).
10131@end table
10132
10133@geindex -gnatz (gcc)
10134
10135
10136@table @asis
10137
10138@item @code{-gnatz@emph{m}}
10139
10140Distribution stub generation and compilation
10141(@code{m}=r/c for receiver/caller stubs).
10142@end table
10143
10144@geindex -I (gcc)
10145
10146
10147@table @asis
10148
10149@item @code{-I@emph{dir}}
10150
10151@geindex RTL
10152
10153Direct GNAT to search the @code{dir} directory for source files needed by
10154the current compilation
10155(see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
10156@end table
10157
10158@geindex -I- (gcc)
10159
10160
10161@table @asis
10162
10163@item @code{-I-}
10164
10165@geindex RTL
10166
10167Except for the source file named in the command line, do not look for source
10168files in the directory containing the source file named in the command line
10169(see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
10170@end table
10171
10172@geindex -o (gcc)
10173
10174
10175@table @asis
10176
10177@item @code{-o @emph{file}}
10178
10179This switch is used in @code{gcc} to redirect the generated object file
10180and its associated ALI file. Beware of this switch with GNAT, because it may
10181cause the object file and ALI file to have different names which in turn
10182may confuse the binder and the linker.
10183@end table
10184
10185@geindex -nostdinc (gcc)
10186
10187
10188@table @asis
10189
10190@item @code{-nostdinc}
10191
10192Inhibit the search of the default location for the GNAT Run Time
10193Library (RTL) source files.
10194@end table
10195
10196@geindex -nostdlib (gcc)
10197
10198
10199@table @asis
10200
10201@item @code{-nostdlib}
10202
10203Inhibit the search of the default location for the GNAT Run Time
10204Library (RTL) ALI files.
10205@end table
10206
10207@geindex -O (gcc)
10208
10209
10210@table @asis
10211
10212@item @code{-O[@emph{n}]}
10213
10214@code{n} controls the optimization level:
10215
10216
10217@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
10218@item
10219
10220@emph{n}
10221
10222@tab
10223
10224Effect
10225
10226@item
10227
10228@emph{0}
10229
10230@tab
10231
10232No optimization, the default setting if no @code{-O} appears
10233
10234@item
10235
10236@emph{1}
10237
10238@tab
10239
10240Normal optimization, the default if you specify @code{-O} without an
10241operand. A good compromise between code quality and compilation
10242time.
10243
10244@item
10245
10246@emph{2}
10247
10248@tab
10249
10250Extensive optimization, may improve execution time, possibly at
10251the cost of substantially increased compilation time.
10252
10253@item
10254
10255@emph{3}
10256
10257@tab
10258
10259Same as @code{-O2}, and also includes inline expansion for small
10260subprograms in the same unit.
10261
10262@item
10263
10264@emph{s}
10265
10266@tab
10267
10268Optimize space usage
10269
10270@end multitable
10271
10272
10273See also @ref{fc,,Optimization Levels}.
10274@end table
10275
10276@geindex -pass-exit-codes (gcc)
10277
10278
10279@table @asis
10280
10281@item @code{-pass-exit-codes}
10282
10283Catch exit codes from the compiler and use the most meaningful as
10284exit status.
10285@end table
10286
10287@geindex --RTS (gcc)
10288
10289
10290@table @asis
10291
10292@item @code{--RTS=@emph{rts-path}}
10293
10294Specifies the default location of the run-time library. Same meaning as the
10295equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
10296@end table
10297
10298@geindex -S (gcc)
10299
10300
10301@table @asis
10302
10303@item @code{-S}
10304
10305Used in place of @code{-c} to
10306cause the assembler source file to be
10307generated, using @code{.s} as the extension,
10308instead of the object file.
10309This may be useful if you need to examine the generated assembly code.
10310@end table
10311
10312@geindex -fverbose-asm (gcc)
10313
10314
10315@table @asis
10316
10317@item @code{-fverbose-asm}
10318
10319Used in conjunction with @code{-S}
10320to cause the generated assembly code file to be annotated with variable
10321names, making it significantly easier to follow.
10322@end table
10323
10324@geindex -v (gcc)
10325
10326
10327@table @asis
10328
10329@item @code{-v}
10330
10331Show commands generated by the @code{gcc} driver. Normally used only for
10332debugging purposes or if you need to be sure what version of the
10333compiler you are executing.
10334@end table
10335
10336@geindex -V (gcc)
10337
10338
10339@table @asis
10340
10341@item @code{-V @emph{ver}}
10342
10343Execute @code{ver} version of the compiler. This is the @code{gcc}
10344version, not the GNAT version.
10345@end table
10346
10347@geindex -w (gcc)
10348
10349
10350@table @asis
10351
10352@item @code{-w}
10353
10354Turn off warnings generated by the back end of the compiler. Use of
10355this switch also causes the default for front end warnings to be set
10356to suppress (as though @code{-gnatws} had appeared at the start of
10357the options).
10358@end table
10359
10360@geindex Combining GNAT switches
10361
10362You may combine a sequence of GNAT switches into a single switch. For
10363example, the combined switch
10364
10365@quotation
10366
10367@example
10368-gnatofi3
10369@end example
10370@end quotation
10371
10372is equivalent to specifying the following sequence of switches:
10373
10374@quotation
10375
10376@example
10377-gnato -gnatf -gnati3
10378@end example
10379@end quotation
10380
10381The following restrictions apply to the combination of switches
10382in this manner:
10383
10384
10385@itemize *
10386
10387@item
10388The switch @code{-gnatc} if combined with other switches must come
10389first in the string.
10390
10391@item
10392The switch @code{-gnats} if combined with other switches must come
10393first in the string.
10394
10395@item
10396The switches
10397@code{-gnatzc} and @code{-gnatzr} may not be combined with any other
10398switches, and only one of them may appear in the command line.
10399
10400@item
10401The switch @code{-gnat-p} may not be combined with any other switch.
10402
10403@item
10404Once a 'y' appears in the string (that is a use of the @code{-gnaty}
10405switch), then all further characters in the switch are interpreted
10406as style modifiers (see description of @code{-gnaty}).
10407
10408@item
10409Once a 'd' appears in the string (that is a use of the @code{-gnatd}
10410switch), then all further characters in the switch are interpreted
10411as debug flags (see description of @code{-gnatd}).
10412
10413@item
10414Once a 'w' appears in the string (that is a use of the @code{-gnatw}
10415switch), then all further characters in the switch are interpreted
10416as warning mode modifiers (see description of @code{-gnatw}).
10417
10418@item
10419Once a 'V' appears in the string (that is a use of the @code{-gnatV}
10420switch), then all further characters in the switch are interpreted
10421as validity checking options (@ref{f6,,Validity Checking}).
10422
10423@item
10424Option 'em', 'ec', 'ep', 'l=' and 'R' must be the last options in
10425a combined list of options.
10426@end itemize
10427
10428@node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10429@anchor{gnat_ugn/building_executable_programs_with_gnat id14}@anchor{fd}@anchor{gnat_ugn/building_executable_programs_with_gnat output-and-error-message-control}@anchor{fe}
10430@subsection Output and Error Message Control
10431
10432
10433@geindex stderr
10434
10435The standard default format for error messages is called 'brief format'.
10436Brief format messages are written to @code{stderr} (the standard error
10437file) and have the following form:
10438
10439@example
10440e.adb:3:04: Incorrect spelling of keyword "function"
10441e.adb:4:20: ";" should be "is"
10442@end example
10443
10444The first integer after the file name is the line number in the file,
10445and the second integer is the column number within the line.
10446@code{GPS} can parse the error messages
10447and point to the referenced character.
10448The following switches provide control over the error message
10449format:
10450
10451@geindex -gnatv (gcc)
10452
10453
10454@table @asis
10455
10456@item @code{-gnatv}
10457
10458The @code{v} stands for verbose.
10459The effect of this setting is to write long-format error
10460messages to @code{stdout} (the standard output file.
10461The same program compiled with the
10462@code{-gnatv} switch would generate:
10463
10464@example
104653. funcion X (Q : Integer)
10466   |
10467>>> Incorrect spelling of keyword "function"
104684. return Integer;
10469                 |
10470>>> ";" should be "is"
10471@end example
10472
10473The vertical bar indicates the location of the error, and the @code{>>>}
10474prefix can be used to search for error messages. When this switch is
10475used the only source lines output are those with errors.
10476@end table
10477
10478@geindex -gnatl (gcc)
10479
10480
10481@table @asis
10482
10483@item @code{-gnatl}
10484
10485The @code{l} stands for list.
10486This switch causes a full listing of
10487the file to be generated. In the case where a body is
10488compiled, the corresponding spec is also listed, along
10489with any subunits. Typical output from compiling a package
10490body @code{p.adb} might look like:
10491
10492@example
10493Compiling: p.adb
10494
10495     1. package body p is
10496     2.    procedure a;
10497     3.    procedure a is separate;
10498     4. begin
10499     5.    null
10500               |
10501        >>> missing ";"
10502
10503     6. end;
10504
10505Compiling: p.ads
10506
10507     1. package p is
10508     2.    pragma Elaborate_Body
10509                                |
10510        >>> missing ";"
10511
10512     3. end p;
10513
10514Compiling: p-a.adb
10515
10516     1. separate p
10517                |
10518        >>> missing "("
10519
10520     2. procedure a is
10521     3. begin
10522     4.    null
10523               |
10524        >>> missing ";"
10525
10526     5. end;
10527@end example
10528
10529When you specify the @code{-gnatv} or @code{-gnatl} switches and
10530standard output is redirected, a brief summary is written to
10531@code{stderr} (standard error) giving the number of error messages and
10532warning messages generated.
10533@end table
10534
10535@geindex -gnatl=fname (gcc)
10536
10537
10538@table @asis
10539
10540@item @code{-gnatl=@emph{fname}}
10541
10542This has the same effect as @code{-gnatl} except that the output is
10543written to a file instead of to standard output. If the given name
10544@code{fname} does not start with a period, then it is the full name
10545of the file to be written. If @code{fname} is an extension, it is
10546appended to the name of the file being compiled. For example, if
10547file @code{xyz.adb} is compiled with @code{-gnatl=.lst},
10548then the output is written to file xyz.adb.lst.
10549@end table
10550
10551@geindex -gnatU (gcc)
10552
10553
10554@table @asis
10555
10556@item @code{-gnatU}
10557
10558This switch forces all error messages to be preceded by the unique
10559string 'error:'. This means that error messages take a few more
10560characters in space, but allows easy searching for and identification
10561of error messages.
10562@end table
10563
10564@geindex -gnatb (gcc)
10565
10566
10567@table @asis
10568
10569@item @code{-gnatb}
10570
10571The @code{b} stands for brief.
10572This switch causes GNAT to generate the
10573brief format error messages to @code{stderr} (the standard error
10574file) as well as the verbose
10575format message or full listing (which as usual is written to
10576@code{stdout} (the standard output file).
10577@end table
10578
10579@geindex -gnatm (gcc)
10580
10581
10582@table @asis
10583
10584@item @code{-gnatm=@emph{n}}
10585
10586The @code{m} stands for maximum.
10587@code{n} is a decimal integer in the
10588range of 1 to 999999 and limits the number of error or warning
10589messages to be generated. For example, using
10590@code{-gnatm2} might yield
10591
10592@example
10593e.adb:3:04: Incorrect spelling of keyword "function"
10594e.adb:5:35: missing ".."
10595fatal error: maximum number of errors detected
10596compilation abandoned
10597@end example
10598
10599The default setting if
10600no switch is given is 9999. If the number of warnings reaches this
10601limit, then a message is output and further warnings are suppressed,
10602but the compilation is continued. If the number of error messages
10603reaches this limit, then a message is output and the compilation
10604is abandoned. A value of zero means that no limit applies.
10605
10606Note that the equal sign is optional, so the switches
10607@code{-gnatm2} and @code{-gnatm=2} are equivalent.
10608@end table
10609
10610@geindex -gnatf (gcc)
10611
10612
10613@table @asis
10614
10615@item @code{-gnatf}
10616
10617@geindex Error messages
10618@geindex suppressing
10619
10620The @code{f} stands for full.
10621Normally, the compiler suppresses error messages that are likely to be
10622redundant. This switch causes all error
10623messages to be generated. In particular, in the case of
10624references to undefined variables. If a given variable is referenced
10625several times, the normal format of messages is
10626
10627@example
10628e.adb:7:07: "V" is undefined (more references follow)
10629@end example
10630
10631where the parenthetical comment warns that there are additional
10632references to the variable @code{V}. Compiling the same program with the
10633@code{-gnatf} switch yields
10634
10635@example
10636e.adb:7:07: "V" is undefined
10637e.adb:8:07: "V" is undefined
10638e.adb:8:12: "V" is undefined
10639e.adb:8:16: "V" is undefined
10640e.adb:9:07: "V" is undefined
10641e.adb:9:12: "V" is undefined
10642@end example
10643
10644The @code{-gnatf} switch also generates additional information for
10645some error messages.  Some examples are:
10646
10647
10648@itemize *
10649
10650@item
10651Details on possibly non-portable unchecked conversion
10652
10653@item
10654List possible interpretations for ambiguous calls
10655
10656@item
10657Additional details on incorrect parameters
10658@end itemize
10659@end table
10660
10661@geindex -gnatjnn (gcc)
10662
10663
10664@table @asis
10665
10666@item @code{-gnatjnn}
10667
10668In normal operation mode (or if @code{-gnatj0} is used), then error messages
10669with continuation lines are treated as though the continuation lines were
10670separate messages (and so a warning with two continuation lines counts as
10671three warnings, and is listed as three separate messages).
10672
10673If the @code{-gnatjnn} switch is used with a positive value for nn, then
10674messages are output in a different manner. A message and all its continuation
10675lines are treated as a unit, and count as only one warning or message in the
10676statistics totals. Furthermore, the message is reformatted so that no line
10677is longer than nn characters.
10678@end table
10679
10680@geindex -gnatq (gcc)
10681
10682
10683@table @asis
10684
10685@item @code{-gnatq}
10686
10687The @code{q} stands for quit (really 'don't quit').
10688In normal operation mode, the compiler first parses the program and
10689determines if there are any syntax errors. If there are, appropriate
10690error messages are generated and compilation is immediately terminated.
10691This switch tells
10692GNAT to continue with semantic analysis even if syntax errors have been
10693found. This may enable the detection of more errors in a single run. On
10694the other hand, the semantic analyzer is more likely to encounter some
10695internal fatal error when given a syntactically invalid tree.
10696@end table
10697
10698@geindex -gnatQ (gcc)
10699
10700
10701@table @asis
10702
10703@item @code{-gnatQ}
10704
10705In normal operation mode, the @code{ALI} file is not generated if any
10706illegalities are detected in the program. The use of @code{-gnatQ} forces
10707generation of the @code{ALI} file. This file is marked as being in
10708error, so it cannot be used for binding purposes, but it does contain
10709reasonably complete cross-reference information, and thus may be useful
10710for use by tools (e.g., semantic browsing tools or integrated development
10711environments) that are driven from the @code{ALI} file. This switch
10712implies @code{-gnatq}, since the semantic phase must be run to get a
10713meaningful ALI file.
10714
10715In addition, if @code{-gnatt} is also specified, then the tree file is
10716generated even if there are illegalities. It may be useful in this case
10717to also specify @code{-gnatq} to ensure that full semantic processing
10718occurs. The resulting tree file can be processed by ASIS, for the purpose
10719of providing partial information about illegal units, but if the error
10720causes the tree to be badly malformed, then ASIS may crash during the
10721analysis.
10722
10723When @code{-gnatQ} is used and the generated @code{ALI} file is marked as
10724being in error, @code{gnatmake} will attempt to recompile the source when it
10725finds such an @code{ALI} file, including with switch @code{-gnatc}.
10726
10727Note that @code{-gnatQ} has no effect if @code{-gnats} is specified,
10728since ALI files are never generated if @code{-gnats} is set.
10729@end table
10730
10731@node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10732@anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{fa}@anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{ff}
10733@subsection Warning Message Control
10734
10735
10736@geindex Warning messages
10737
10738In addition to error messages, which correspond to illegalities as defined
10739in the Ada Reference Manual, the compiler detects two kinds of warning
10740situations.
10741
10742First, the compiler considers some constructs suspicious and generates a
10743warning message to alert you to a possible error. Second, if the
10744compiler detects a situation that is sure to raise an exception at
10745run time, it generates a warning message. The following shows an example
10746of warning messages:
10747
10748@example
10749e.adb:4:24: warning: creation of object may raise Storage_Error
10750e.adb:10:17: warning: static value out of range
10751e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10752@end example
10753
10754GNAT considers a large number of situations as appropriate
10755for the generation of warning messages. As always, warnings are not
10756definite indications of errors. For example, if you do an out-of-range
10757assignment with the deliberate intention of raising a
10758@code{Constraint_Error} exception, then the warning that may be
10759issued does not indicate an error. Some of the situations for which GNAT
10760issues warnings (at least some of the time) are given in the following
10761list. This list is not complete, and new warnings are often added to
10762subsequent versions of GNAT. The list is intended to give a general idea
10763of the kinds of warnings that are generated.
10764
10765
10766@itemize *
10767
10768@item
10769Possible infinitely recursive calls
10770
10771@item
10772Out-of-range values being assigned
10773
10774@item
10775Possible order of elaboration problems
10776
10777@item
10778Size not a multiple of alignment for a record type
10779
10780@item
10781Assertions (pragma Assert) that are sure to fail
10782
10783@item
10784Unreachable code
10785
10786@item
10787Address clauses with possibly unaligned values, or where an attempt is
10788made to overlay a smaller variable with a larger one.
10789
10790@item
10791Fixed-point type declarations with a null range
10792
10793@item
10794Direct_IO or Sequential_IO instantiated with a type that has access values
10795
10796@item
10797Variables that are never assigned a value
10798
10799@item
10800Variables that are referenced before being initialized
10801
10802@item
10803Task entries with no corresponding @code{accept} statement
10804
10805@item
10806Duplicate accepts for the same task entry in a @code{select}
10807
10808@item
10809Objects that take too much storage
10810
10811@item
10812Unchecked conversion between types of differing sizes
10813
10814@item
10815Missing @code{return} statement along some execution path in a function
10816
10817@item
10818Incorrect (unrecognized) pragmas
10819
10820@item
10821Incorrect external names
10822
10823@item
10824Allocation from empty storage pool
10825
10826@item
10827Potentially blocking operation in protected type
10828
10829@item
10830Suspicious parenthesization of expressions
10831
10832@item
10833Mismatching bounds in an aggregate
10834
10835@item
10836Attempt to return local value by reference
10837
10838@item
10839Premature instantiation of a generic body
10840
10841@item
10842Attempt to pack aliased components
10843
10844@item
10845Out of bounds array subscripts
10846
10847@item
10848Wrong length on string assignment
10849
10850@item
10851Violations of style rules if style checking is enabled
10852
10853@item
10854Unused @emph{with} clauses
10855
10856@item
10857@code{Bit_Order} usage that does not have any effect
10858
10859@item
10860@code{Standard.Duration} used to resolve universal fixed expression
10861
10862@item
10863Dereference of possibly null value
10864
10865@item
10866Declaration that is likely to cause storage error
10867
10868@item
10869Internal GNAT unit @emph{with}ed by application unit
10870
10871@item
10872Values known to be out of range at compile time
10873
10874@item
10875Unreferenced or unmodified variables. Note that a special
10876exemption applies to variables which contain any of the substrings
10877@code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
10878are considered likely to be intentionally used in a situation where
10879otherwise a warning would be given, so warnings of this kind are
10880always suppressed for such variables.
10881
10882@item
10883Address overlays that could clobber memory
10884
10885@item
10886Unexpected initialization when address clause present
10887
10888@item
10889Bad alignment for address clause
10890
10891@item
10892Useless type conversions
10893
10894@item
10895Redundant assignment statements and other redundant constructs
10896
10897@item
10898Useless exception handlers
10899
10900@item
10901Accidental hiding of name by child unit
10902
10903@item
10904Access before elaboration detected at compile time
10905
10906@item
10907A range in a @code{for} loop that is known to be null or might be null
10908@end itemize
10909
10910The following section lists compiler switches that are available
10911to control the handling of warning messages. It is also possible
10912to exercise much finer control over what warnings are issued and
10913suppressed using the GNAT pragma Warnings (see the description
10914of the pragma in the @cite{GNAT_Reference_manual}).
10915
10916@geindex -gnatwa (gcc)
10917
10918
10919@table @asis
10920
10921@item @code{-gnatwa}
10922
10923@emph{Activate most optional warnings.}
10924
10925This switch activates most optional warning messages.  See the remaining list
10926in this section for details on optional warning messages that can be
10927individually controlled.  The warnings that are not turned on by this
10928switch are:
10929
10930
10931@itemize *
10932
10933@item
10934@code{-gnatwd} (implicit dereferencing)
10935
10936@item
10937@code{-gnatw.d} (tag warnings with -gnatw switch)
10938
10939@item
10940@code{-gnatwh} (hiding)
10941
10942@item
10943@code{-gnatw.h} (holes in record layouts)
10944
10945@item
10946@code{-gnatw.j} (late primitives of tagged types)
10947
10948@item
10949@code{-gnatw.k} (redefinition of names in standard)
10950
10951@item
10952@code{-gnatwl} (elaboration warnings)
10953
10954@item
10955@code{-gnatw.l} (inherited aspects)
10956
10957@item
10958@code{-gnatw.n} (atomic synchronization)
10959
10960@item
10961@code{-gnatwo} (address clause overlay)
10962
10963@item
10964@code{-gnatw.o} (values set by out parameters ignored)
10965
10966@item
10967@code{-gnatw.q} (questionable layout of record types)
10968
10969@item
10970@code{-gnatw.s} (overridden size clause)
10971
10972@item
10973@code{-gnatwt} (tracking of deleted conditional code)
10974
10975@item
10976@code{-gnatw.u} (unordered enumeration)
10977
10978@item
10979@code{-gnatw.w} (use of Warnings Off)
10980
10981@item
10982@code{-gnatw.y} (reasons for package needing body)
10983@end itemize
10984
10985All other optional warnings are turned on.
10986@end table
10987
10988@geindex -gnatwA (gcc)
10989
10990
10991@table @asis
10992
10993@item @code{-gnatwA}
10994
10995@emph{Suppress all optional errors.}
10996
10997This switch suppresses all optional warning messages, see remaining list
10998in this section for details on optional warning messages that can be
10999individually controlled. Note that unlike switch @code{-gnatws}, the
11000use of switch @code{-gnatwA} does not suppress warnings that are
11001normally given unconditionally and cannot be individually controlled
11002(for example, the warning about a missing exit path in a function).
11003Also, again unlike switch @code{-gnatws}, warnings suppressed by
11004the use of switch @code{-gnatwA} can be individually turned back
11005on. For example the use of switch @code{-gnatwA} followed by
11006switch @code{-gnatwd} will suppress all optional warnings except
11007the warnings for implicit dereferencing.
11008@end table
11009
11010@geindex -gnatw.a (gcc)
11011
11012
11013@table @asis
11014
11015@item @code{-gnatw.a}
11016
11017@emph{Activate warnings on failing assertions.}
11018
11019@geindex Assert failures
11020
11021This switch activates warnings for assertions where the compiler can tell at
11022compile time that the assertion will fail. Note that this warning is given
11023even if assertions are disabled. The default is that such warnings are
11024generated.
11025@end table
11026
11027@geindex -gnatw.A (gcc)
11028
11029
11030@table @asis
11031
11032@item @code{-gnatw.A}
11033
11034@emph{Suppress warnings on failing assertions.}
11035
11036@geindex Assert failures
11037
11038This switch suppresses warnings for assertions where the compiler can tell at
11039compile time that the assertion will fail.
11040@end table
11041
11042@geindex -gnatwb (gcc)
11043
11044
11045@table @asis
11046
11047@item @code{-gnatwb}
11048
11049@emph{Activate warnings on bad fixed values.}
11050
11051@geindex Bad fixed values
11052
11053@geindex Fixed-point Small value
11054
11055@geindex Small value
11056
11057This switch activates warnings for static fixed-point expressions whose
11058value is not an exact multiple of Small. Such values are implementation
11059dependent, since an implementation is free to choose either of the multiples
11060that surround the value. GNAT always chooses the closer one, but this is not
11061required behavior, and it is better to specify a value that is an exact
11062multiple, ensuring predictable execution. The default is that such warnings
11063are not generated.
11064@end table
11065
11066@geindex -gnatwB (gcc)
11067
11068
11069@table @asis
11070
11071@item @code{-gnatwB}
11072
11073@emph{Suppress warnings on bad fixed values.}
11074
11075This switch suppresses warnings for static fixed-point expressions whose
11076value is not an exact multiple of Small.
11077@end table
11078
11079@geindex -gnatw.b (gcc)
11080
11081
11082@table @asis
11083
11084@item @code{-gnatw.b}
11085
11086@emph{Activate warnings on biased representation.}
11087
11088@geindex Biased representation
11089
11090This switch activates warnings when a size clause, value size clause, component
11091clause, or component size clause forces the use of biased representation for an
11092integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
11093to represent 10/11). The default is that such warnings are generated.
11094@end table
11095
11096@geindex -gnatwB (gcc)
11097
11098
11099@table @asis
11100
11101@item @code{-gnatw.B}
11102
11103@emph{Suppress warnings on biased representation.}
11104
11105This switch suppresses warnings for representation clauses that force the use
11106of biased representation.
11107@end table
11108
11109@geindex -gnatwc (gcc)
11110
11111
11112@table @asis
11113
11114@item @code{-gnatwc}
11115
11116@emph{Activate warnings on conditionals.}
11117
11118@geindex Conditionals
11119@geindex constant
11120
11121This switch activates warnings for conditional expressions used in
11122tests that are known to be True or False at compile time. The default
11123is that such warnings are not generated.
11124Note that this warning does
11125not get issued for the use of boolean variables or constants whose
11126values are known at compile time, since this is a standard technique
11127for conditional compilation in Ada, and this would generate too many
11128false positive warnings.
11129
11130This warning option also activates a special test for comparisons using
11131the operators '>=' and' <='.
11132If the compiler can tell that only the equality condition is possible,
11133then it will warn that the '>' or '<' part of the test
11134is useless and that the operator could be replaced by '='.
11135An example would be comparing a @code{Natural} variable <= 0.
11136
11137This warning option also generates warnings if
11138one or both tests is optimized away in a membership test for integer
11139values if the result can be determined at compile time. Range tests on
11140enumeration types are not included, since it is common for such tests
11141to include an end point.
11142
11143This warning can also be turned on using @code{-gnatwa}.
11144@end table
11145
11146@geindex -gnatwC (gcc)
11147
11148
11149@table @asis
11150
11151@item @code{-gnatwC}
11152
11153@emph{Suppress warnings on conditionals.}
11154
11155This switch suppresses warnings for conditional expressions used in
11156tests that are known to be True or False at compile time.
11157@end table
11158
11159@geindex -gnatw.c (gcc)
11160
11161
11162@table @asis
11163
11164@item @code{-gnatw.c}
11165
11166@emph{Activate warnings on missing component clauses.}
11167
11168@geindex Component clause
11169@geindex missing
11170
11171This switch activates warnings for record components where a record
11172representation clause is present and has component clauses for the
11173majority, but not all, of the components. A warning is given for each
11174component for which no component clause is present.
11175@end table
11176
11177@geindex -gnatwC (gcc)
11178
11179
11180@table @asis
11181
11182@item @code{-gnatw.C}
11183
11184@emph{Suppress warnings on missing component clauses.}
11185
11186This switch suppresses warnings for record components that are
11187missing a component clause in the situation described above.
11188@end table
11189
11190@geindex -gnatwd (gcc)
11191
11192
11193@table @asis
11194
11195@item @code{-gnatwd}
11196
11197@emph{Activate warnings on implicit dereferencing.}
11198
11199If this switch is set, then the use of a prefix of an access type
11200in an indexed component, slice, or selected component without an
11201explicit @code{.all} will generate a warning. With this warning
11202enabled, access checks occur only at points where an explicit
11203@code{.all} appears in the source code (assuming no warnings are
11204generated as a result of this switch). The default is that such
11205warnings are not generated.
11206@end table
11207
11208@geindex -gnatwD (gcc)
11209
11210
11211@table @asis
11212
11213@item @code{-gnatwD}
11214
11215@emph{Suppress warnings on implicit dereferencing.}
11216
11217@geindex Implicit dereferencing
11218
11219@geindex Dereferencing
11220@geindex implicit
11221
11222This switch suppresses warnings for implicit dereferences in
11223indexed components, slices, and selected components.
11224@end table
11225
11226@geindex -gnatw.d (gcc)
11227
11228
11229@table @asis
11230
11231@item @code{-gnatw.d}
11232
11233@emph{Activate tagging of warning and info messages.}
11234
11235If this switch is set, then warning messages are tagged, with one of the
11236following strings:
11237
11238@quotation
11239
11240
11241@itemize -
11242
11243@item
11244@emph{[-gnatw?]}
11245Used to tag warnings controlled by the switch @code{-gnatwx} where x
11246is a letter a-z.
11247
11248@item
11249@emph{[-gnatw.?]}
11250Used to tag warnings controlled by the switch @code{-gnatw.x} where x
11251is a letter a-z.
11252
11253@item
11254@emph{[-gnatel]}
11255Used to tag elaboration information (info) messages generated when the
11256static model of elaboration is used and the @code{-gnatel} switch is set.
11257
11258@item
11259@emph{[restriction warning]}
11260Used to tag warning messages for restriction violations, activated by use
11261of the pragma @code{Restriction_Warnings}.
11262
11263@item
11264@emph{[warning-as-error]}
11265Used to tag warning messages that have been converted to error messages by
11266use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11267the string "error: " rather than "warning: ".
11268
11269@item
11270@emph{[enabled by default]}
11271Used to tag all other warnings that are always given by default, unless
11272warnings are completely suppressed using pragma @emph{Warnings(Off)} or
11273the switch @code{-gnatws}.
11274@end itemize
11275@end quotation
11276@end table
11277
11278@geindex -gnatw.d (gcc)
11279
11280
11281@table @asis
11282
11283@item @code{-gnatw.D}
11284
11285@emph{Deactivate tagging of warning and info messages messages.}
11286
11287If this switch is set, then warning messages return to the default
11288mode in which warnings and info messages are not tagged as described above for
11289@code{-gnatw.d}.
11290@end table
11291
11292@geindex -gnatwe (gcc)
11293
11294@geindex Warnings
11295@geindex treat as error
11296
11297
11298@table @asis
11299
11300@item @code{-gnatwe}
11301
11302@emph{Treat warnings and style checks as errors.}
11303
11304This switch causes warning messages and style check messages to be
11305treated as errors.
11306The warning string still appears, but the warning messages are counted
11307as errors, and prevent the generation of an object file. Note that this
11308is the only -gnatw switch that affects the handling of style check messages.
11309Note also that this switch has no effect on info (information) messages, which
11310are not treated as errors if this switch is present.
11311@end table
11312
11313@geindex -gnatw.e (gcc)
11314
11315
11316@table @asis
11317
11318@item @code{-gnatw.e}
11319
11320@emph{Activate every optional warning.}
11321
11322@geindex Warnings
11323@geindex activate every optional warning
11324
11325This switch activates all optional warnings, including those which
11326are not activated by @code{-gnatwa}. The use of this switch is not
11327recommended for normal use. If you turn this switch on, it is almost
11328certain that you will get large numbers of useless warnings. The
11329warnings that are excluded from @code{-gnatwa} are typically highly
11330specialized warnings that are suitable for use only in code that has
11331been specifically designed according to specialized coding rules.
11332@end table
11333
11334@geindex -gnatwE (gcc)
11335
11336@geindex Warnings
11337@geindex treat as error
11338
11339
11340@table @asis
11341
11342@item @code{-gnatwE}
11343
11344@emph{Treat all run-time exception warnings as errors.}
11345
11346This switch causes warning messages regarding errors that will be raised
11347during run-time execution to be treated as errors.
11348@end table
11349
11350@geindex -gnatwf (gcc)
11351
11352
11353@table @asis
11354
11355@item @code{-gnatwf}
11356
11357@emph{Activate warnings on unreferenced formals.}
11358
11359@geindex Formals
11360@geindex unreferenced
11361
11362This switch causes a warning to be generated if a formal parameter
11363is not referenced in the body of the subprogram. This warning can
11364also be turned on using @code{-gnatwu}. The
11365default is that these warnings are not generated.
11366@end table
11367
11368@geindex -gnatwF (gcc)
11369
11370
11371@table @asis
11372
11373@item @code{-gnatwF}
11374
11375@emph{Suppress warnings on unreferenced formals.}
11376
11377This switch suppresses warnings for unreferenced formal
11378parameters. Note that the
11379combination @code{-gnatwu} followed by @code{-gnatwF} has the
11380effect of warning on unreferenced entities other than subprogram
11381formals.
11382@end table
11383
11384@geindex -gnatwg (gcc)
11385
11386
11387@table @asis
11388
11389@item @code{-gnatwg}
11390
11391@emph{Activate warnings on unrecognized pragmas.}
11392
11393@geindex Pragmas
11394@geindex unrecognized
11395
11396This switch causes a warning to be generated if an unrecognized
11397pragma is encountered. Apart from issuing this warning, the
11398pragma is ignored and has no effect. The default
11399is that such warnings are issued (satisfying the Ada Reference
11400Manual requirement that such warnings appear).
11401@end table
11402
11403@geindex -gnatwG (gcc)
11404
11405
11406@table @asis
11407
11408@item @code{-gnatwG}
11409
11410@emph{Suppress warnings on unrecognized pragmas.}
11411
11412This switch suppresses warnings for unrecognized pragmas.
11413@end table
11414
11415@geindex -gnatw.g (gcc)
11416
11417
11418@table @asis
11419
11420@item @code{-gnatw.g}
11421
11422@emph{Warnings used for GNAT sources.}
11423
11424This switch sets the warning categories that are used by the standard
11425GNAT style. Currently this is equivalent to
11426@code{-gnatwAao.q.s.CI.V.X.Z}
11427but more warnings may be added in the future without advanced notice.
11428@end table
11429
11430@geindex -gnatwh (gcc)
11431
11432
11433@table @asis
11434
11435@item @code{-gnatwh}
11436
11437@emph{Activate warnings on hiding.}
11438
11439@geindex Hiding of Declarations
11440
11441This switch activates warnings on hiding declarations that are considered
11442potentially confusing. Not all cases of hiding cause warnings; for example an
11443overriding declaration hides an implicit declaration, which is just normal
11444code. The default is that warnings on hiding are not generated.
11445@end table
11446
11447@geindex -gnatwH (gcc)
11448
11449
11450@table @asis
11451
11452@item @code{-gnatwH}
11453
11454@emph{Suppress warnings on hiding.}
11455
11456This switch suppresses warnings on hiding declarations.
11457@end table
11458
11459@geindex -gnatw.h (gcc)
11460
11461
11462@table @asis
11463
11464@item @code{-gnatw.h}
11465
11466@emph{Activate warnings on holes/gaps in records.}
11467
11468@geindex Record Representation (gaps)
11469
11470This switch activates warnings on component clauses in record
11471representation clauses that leave holes (gaps) in the record layout.
11472If this warning option is active, then record representation clauses
11473should specify a contiguous layout, adding unused fill fields if needed.
11474@end table
11475
11476@geindex -gnatw.H (gcc)
11477
11478
11479@table @asis
11480
11481@item @code{-gnatw.H}
11482
11483@emph{Suppress warnings on holes/gaps in records.}
11484
11485This switch suppresses warnings on component clauses in record
11486representation clauses that leave holes (haps) in the record layout.
11487@end table
11488
11489@geindex -gnatwi (gcc)
11490
11491
11492@table @asis
11493
11494@item @code{-gnatwi}
11495
11496@emph{Activate warnings on implementation units.}
11497
11498This switch activates warnings for a @emph{with} of an internal GNAT
11499implementation unit, defined as any unit from the @code{Ada},
11500@code{Interfaces}, @code{GNAT},
11501or @code{System}
11502hierarchies that is not
11503documented in either the Ada Reference Manual or the GNAT
11504Programmer's Reference Manual. Such units are intended only
11505for internal implementation purposes and should not be @emph{with}ed
11506by user programs. The default is that such warnings are generated
11507@end table
11508
11509@geindex -gnatwI (gcc)
11510
11511
11512@table @asis
11513
11514@item @code{-gnatwI}
11515
11516@emph{Disable warnings on implementation units.}
11517
11518This switch disables warnings for a @emph{with} of an internal GNAT
11519implementation unit.
11520@end table
11521
11522@geindex -gnatw.i (gcc)
11523
11524
11525@table @asis
11526
11527@item @code{-gnatw.i}
11528
11529@emph{Activate warnings on overlapping actuals.}
11530
11531This switch enables a warning on statically detectable overlapping actuals in
11532a subprogram call, when one of the actuals is an in-out parameter, and the
11533types of the actuals are not by-copy types. This warning is off by default.
11534@end table
11535
11536@geindex -gnatw.I (gcc)
11537
11538
11539@table @asis
11540
11541@item @code{-gnatw.I}
11542
11543@emph{Disable warnings on overlapping actuals.}
11544
11545This switch disables warnings on overlapping actuals in a call..
11546@end table
11547
11548@geindex -gnatwj (gcc)
11549
11550
11551@table @asis
11552
11553@item @code{-gnatwj}
11554
11555@emph{Activate warnings on obsolescent features (Annex J).}
11556
11557@geindex Features
11558@geindex obsolescent
11559
11560@geindex Obsolescent features
11561
11562If this warning option is activated, then warnings are generated for
11563calls to subprograms marked with @code{pragma Obsolescent} and
11564for use of features in Annex J of the Ada Reference Manual. In the
11565case of Annex J, not all features are flagged. In particular use
11566of the renamed packages (like @code{Text_IO}) and use of package
11567@code{ASCII} are not flagged, since these are very common and
11568would generate many annoying positive warnings. The default is that
11569such warnings are not generated.
11570
11571In addition to the above cases, warnings are also generated for
11572GNAT features that have been provided in past versions but which
11573have been superseded (typically by features in the new Ada standard).
11574For example, @code{pragma Ravenscar} will be flagged since its
11575function is replaced by @code{pragma Profile(Ravenscar)}, and
11576@code{pragma Interface_Name} will be flagged since its function
11577is replaced by @code{pragma Import}.
11578
11579Note that this warning option functions differently from the
11580restriction @code{No_Obsolescent_Features} in two respects.
11581First, the restriction applies only to annex J features.
11582Second, the restriction does flag uses of package @code{ASCII}.
11583@end table
11584
11585@geindex -gnatwJ (gcc)
11586
11587
11588@table @asis
11589
11590@item @code{-gnatwJ}
11591
11592@emph{Suppress warnings on obsolescent features (Annex J).}
11593
11594This switch disables warnings on use of obsolescent features.
11595@end table
11596
11597@geindex -gnatw.j (gcc)
11598
11599
11600@table @asis
11601
11602@item @code{-gnatw.j}
11603
11604@emph{Activate warnings on late declarations of tagged type primitives.}
11605
11606This switch activates warnings on visible primitives added to a
11607tagged type after deriving a private extension from it.
11608@end table
11609
11610@geindex -gnatw.J (gcc)
11611
11612
11613@table @asis
11614
11615@item @code{-gnatw.J}
11616
11617@emph{Suppress warnings on late declarations of tagged type primitives.}
11618
11619This switch suppresses warnings on visible primitives added to a
11620tagged type after deriving a private extension from it.
11621@end table
11622
11623@geindex -gnatwk (gcc)
11624
11625
11626@table @asis
11627
11628@item @code{-gnatwk}
11629
11630@emph{Activate warnings on variables that could be constants.}
11631
11632This switch activates warnings for variables that are initialized but
11633never modified, and then could be declared constants. The default is that
11634such warnings are not given.
11635@end table
11636
11637@geindex -gnatwK (gcc)
11638
11639
11640@table @asis
11641
11642@item @code{-gnatwK}
11643
11644@emph{Suppress warnings on variables that could be constants.}
11645
11646This switch disables warnings on variables that could be declared constants.
11647@end table
11648
11649@geindex -gnatw.k (gcc)
11650
11651
11652@table @asis
11653
11654@item @code{-gnatw.k}
11655
11656@emph{Activate warnings on redefinition of names in standard.}
11657
11658This switch activates warnings for declarations that declare a name that
11659is defined in package Standard. Such declarations can be confusing,
11660especially since the names in package Standard continue to be directly
11661visible, meaning that use visibiliy on such redeclared names does not
11662work as expected. Names of discriminants and components in records are
11663not included in this check.
11664@end table
11665
11666@geindex -gnatwK (gcc)
11667
11668
11669@table @asis
11670
11671@item @code{-gnatw.K}
11672
11673@emph{Suppress warnings on redefinition of names in standard.}
11674
11675This switch activates warnings for declarations that declare a name that
11676is defined in package Standard.
11677@end table
11678
11679@geindex -gnatwl (gcc)
11680
11681
11682@table @asis
11683
11684@item @code{-gnatwl}
11685
11686@emph{Activate warnings for elaboration pragmas.}
11687
11688@geindex Elaboration
11689@geindex warnings
11690
11691This switch activates warnings for possible elaboration problems,
11692including suspicious use
11693of @code{Elaborate} pragmas, when using the static elaboration model, and
11694possible situations that may raise @code{Program_Error} when using the
11695dynamic elaboration model.
11696See the section in this guide on elaboration checking for further details.
11697The default is that such warnings
11698are not generated.
11699@end table
11700
11701@geindex -gnatwL (gcc)
11702
11703
11704@table @asis
11705
11706@item @code{-gnatwL}
11707
11708@emph{Suppress warnings for elaboration pragmas.}
11709
11710This switch suppresses warnings for possible elaboration problems.
11711@end table
11712
11713@geindex -gnatw.l (gcc)
11714
11715
11716@table @asis
11717
11718@item @code{-gnatw.l}
11719
11720@emph{List inherited aspects.}
11721
11722This switch causes the compiler to list inherited invariants,
11723preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
11724Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
11725@end table
11726
11727@geindex -gnatw.L (gcc)
11728
11729
11730@table @asis
11731
11732@item @code{-gnatw.L}
11733
11734@emph{Suppress listing of inherited aspects.}
11735
11736This switch suppresses listing of inherited aspects.
11737@end table
11738
11739@geindex -gnatwm (gcc)
11740
11741
11742@table @asis
11743
11744@item @code{-gnatwm}
11745
11746@emph{Activate warnings on modified but unreferenced variables.}
11747
11748This switch activates warnings for variables that are assigned (using
11749an initialization value or with one or more assignment statements) but
11750whose value is never read. The warning is suppressed for volatile
11751variables and also for variables that are renamings of other variables
11752or for which an address clause is given.
11753The default is that these warnings are not given.
11754@end table
11755
11756@geindex -gnatwM (gcc)
11757
11758
11759@table @asis
11760
11761@item @code{-gnatwM}
11762
11763@emph{Disable warnings on modified but unreferenced variables.}
11764
11765This switch disables warnings for variables that are assigned or
11766initialized, but never read.
11767@end table
11768
11769@geindex -gnatw.m (gcc)
11770
11771
11772@table @asis
11773
11774@item @code{-gnatw.m}
11775
11776@emph{Activate warnings on suspicious modulus values.}
11777
11778This switch activates warnings for modulus values that seem suspicious.
11779The cases caught are where the size is the same as the modulus (e.g.
11780a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11781with no size clause. The guess in both cases is that 2**x was intended
11782rather than x. In addition expressions of the form 2*x for small x
11783generate a warning (the almost certainly accurate guess being that
117842**x was intended). The default is that these warnings are given.
11785@end table
11786
11787@geindex -gnatw.M (gcc)
11788
11789
11790@table @asis
11791
11792@item @code{-gnatw.M}
11793
11794@emph{Disable warnings on suspicious modulus values.}
11795
11796This switch disables warnings for suspicious modulus values.
11797@end table
11798
11799@geindex -gnatwn (gcc)
11800
11801
11802@table @asis
11803
11804@item @code{-gnatwn}
11805
11806@emph{Set normal warnings mode.}
11807
11808This switch sets normal warning mode, in which enabled warnings are
11809issued and treated as warnings rather than errors. This is the default
11810mode. the switch @code{-gnatwn} can be used to cancel the effect of
11811an explicit @code{-gnatws} or
11812@code{-gnatwe}. It also cancels the effect of the
11813implicit @code{-gnatwe} that is activated by the
11814use of @code{-gnatg}.
11815@end table
11816
11817@geindex -gnatw.n (gcc)
11818
11819@geindex Atomic Synchronization
11820@geindex warnings
11821
11822
11823@table @asis
11824
11825@item @code{-gnatw.n}
11826
11827@emph{Activate warnings on atomic synchronization.}
11828
11829This switch actives warnings when an access to an atomic variable
11830requires the generation of atomic synchronization code. These
11831warnings are off by default.
11832@end table
11833
11834@geindex -gnatw.N (gcc)
11835
11836
11837@table @asis
11838
11839@item @code{-gnatw.N}
11840
11841@emph{Suppress warnings on atomic synchronization.}
11842
11843@geindex Atomic Synchronization
11844@geindex warnings
11845
11846This switch suppresses warnings when an access to an atomic variable
11847requires the generation of atomic synchronization code.
11848@end table
11849
11850@geindex -gnatwo (gcc)
11851
11852@geindex Address Clauses
11853@geindex warnings
11854
11855
11856@table @asis
11857
11858@item @code{-gnatwo}
11859
11860@emph{Activate warnings on address clause overlays.}
11861
11862This switch activates warnings for possibly unintended initialization
11863effects of defining address clauses that cause one variable to overlap
11864another. The default is that such warnings are generated.
11865@end table
11866
11867@geindex -gnatwO (gcc)
11868
11869
11870@table @asis
11871
11872@item @code{-gnatwO}
11873
11874@emph{Suppress warnings on address clause overlays.}
11875
11876This switch suppresses warnings on possibly unintended initialization
11877effects of defining address clauses that cause one variable to overlap
11878another.
11879@end table
11880
11881@geindex -gnatw.o (gcc)
11882
11883
11884@table @asis
11885
11886@item @code{-gnatw.o}
11887
11888@emph{Activate warnings on modified but unreferenced out parameters.}
11889
11890This switch activates warnings for variables that are modified by using
11891them as actuals for a call to a procedure with an out mode formal, where
11892the resulting assigned value is never read. It is applicable in the case
11893where there is more than one out mode formal. If there is only one out
11894mode formal, the warning is issued by default (controlled by -gnatwu).
11895The warning is suppressed for volatile
11896variables and also for variables that are renamings of other variables
11897or for which an address clause is given.
11898The default is that these warnings are not given.
11899@end table
11900
11901@geindex -gnatw.O (gcc)
11902
11903
11904@table @asis
11905
11906@item @code{-gnatw.O}
11907
11908@emph{Disable warnings on modified but unreferenced out parameters.}
11909
11910This switch suppresses warnings for variables that are modified by using
11911them as actuals for a call to a procedure with an out mode formal, where
11912the resulting assigned value is never read.
11913@end table
11914
11915@geindex -gnatwp (gcc)
11916
11917@geindex Inlining
11918@geindex warnings
11919
11920
11921@table @asis
11922
11923@item @code{-gnatwp}
11924
11925@emph{Activate warnings on ineffective pragma Inlines.}
11926
11927This switch activates warnings for failure of front end inlining
11928(activated by @code{-gnatN}) to inline a particular call. There are
11929many reasons for not being able to inline a call, including most
11930commonly that the call is too complex to inline. The default is
11931that such warnings are not given.
11932Warnings on ineffective inlining by the gcc back-end can be activated
11933separately, using the gcc switch -Winline.
11934@end table
11935
11936@geindex -gnatwP (gcc)
11937
11938
11939@table @asis
11940
11941@item @code{-gnatwP}
11942
11943@emph{Suppress warnings on ineffective pragma Inlines.}
11944
11945This switch suppresses warnings on ineffective pragma Inlines. If the
11946inlining mechanism cannot inline a call, it will simply ignore the
11947request silently.
11948@end table
11949
11950@geindex -gnatw.p (gcc)
11951
11952@geindex Parameter order
11953@geindex warnings
11954
11955
11956@table @asis
11957
11958@item @code{-gnatw.p}
11959
11960@emph{Activate warnings on parameter ordering.}
11961
11962This switch activates warnings for cases of suspicious parameter
11963ordering when the list of arguments are all simple identifiers that
11964match the names of the formals, but are in a different order. The
11965warning is suppressed if any use of named parameter notation is used,
11966so this is the appropriate way to suppress a false positive (and
11967serves to emphasize that the "misordering" is deliberate). The
11968default is that such warnings are not given.
11969@end table
11970
11971@geindex -gnatw.P (gcc)
11972
11973
11974@table @asis
11975
11976@item @code{-gnatw.P}
11977
11978@emph{Suppress warnings on parameter ordering.}
11979
11980This switch suppresses warnings on cases of suspicious parameter
11981ordering.
11982@end table
11983
11984@geindex -gnatwq (gcc)
11985
11986@geindex Parentheses
11987@geindex warnings
11988
11989
11990@table @asis
11991
11992@item @code{-gnatwq}
11993
11994@emph{Activate warnings on questionable missing parentheses.}
11995
11996This switch activates warnings for cases where parentheses are not used and
11997the result is potential ambiguity from a readers point of view. For example
11998(not a > b) when a and b are modular means ((not a) > b) and very likely the
11999programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
12000quite likely ((-x) mod 5) was intended. In such situations it seems best to
12001follow the rule of always parenthesizing to make the association clear, and
12002this warning switch warns if such parentheses are not present. The default
12003is that these warnings are given.
12004@end table
12005
12006@geindex -gnatwQ (gcc)
12007
12008
12009@table @asis
12010
12011@item @code{-gnatwQ}
12012
12013@emph{Suppress warnings on questionable missing parentheses.}
12014
12015This switch suppresses warnings for cases where the association is not
12016clear and the use of parentheses is preferred.
12017@end table
12018
12019@geindex -gnatw.q (gcc)
12020
12021@geindex Layout
12022@geindex warnings
12023
12024
12025@table @asis
12026
12027@item @code{-gnatw.q}
12028
12029@emph{Activate warnings on questionable layout of record types.}
12030
12031This switch activates warnings for cases where the default layout of
12032a record type, that is to say the layout of its components in textual
12033order of the source code, would very likely cause inefficiencies in
12034the code generated by the compiler, both in terms of space and speed
12035during execution. One warning is issued for each problematic component
12036without representation clause in the nonvariant part and then in each
12037variant recursively, if any.
12038
12039The purpose of these warnings is neither to prescribe an optimal layout
12040nor to force the use of representation clauses, but rather to get rid of
12041the most blatant inefficiencies in the layout. Therefore, the default
12042layout is matched against the following synthetic ordered layout and
12043the deviations are flagged on a component-by-component basis:
12044
12045
12046@itemize *
12047
12048@item
12049first all components or groups of components whose length is fixed
12050and a multiple of the storage unit,
12051
12052@item
12053then the remaining components whose length is fixed and not a multiple
12054of the storage unit,
12055
12056@item
12057then the remaining components whose length doesn't depend on discriminants
12058(that is to say, with variable but uniform length for all objects),
12059
12060@item
12061then all components whose length depends on discriminants,
12062
12063@item
12064finally the variant part (if any),
12065@end itemize
12066
12067for the nonvariant part and for each variant recursively, if any.
12068
12069The exact wording of the warning depends on whether the compiler is allowed
12070to reorder the components in the record type or precluded from doing it by
12071means of pragma @code{No_Component_Reordering}.
12072
12073The default is that these warnings are not given.
12074@end table
12075
12076@geindex -gnatw.Q (gcc)
12077
12078
12079@table @asis
12080
12081@item @code{-gnatw.Q}
12082
12083@emph{Suppress warnings on questionable layout of record types.}
12084
12085This switch suppresses warnings for cases where the default layout of
12086a record type would very likely cause inefficiencies.
12087@end table
12088
12089@geindex -gnatwr (gcc)
12090
12091
12092@table @asis
12093
12094@item @code{-gnatwr}
12095
12096@emph{Activate warnings on redundant constructs.}
12097
12098This switch activates warnings for redundant constructs. The following
12099is the current list of constructs regarded as redundant:
12100
12101
12102@itemize *
12103
12104@item
12105Assignment of an item to itself.
12106
12107@item
12108Type conversion that converts an expression to its own type.
12109
12110@item
12111Use of the attribute @code{Base} where @code{typ'Base} is the same
12112as @code{typ}.
12113
12114@item
12115Use of pragma @code{Pack} when all components are placed by a record
12116representation clause.
12117
12118@item
12119Exception handler containing only a reraise statement (raise with no
12120operand) which has no effect.
12121
12122@item
12123Use of the operator abs on an operand that is known at compile time
12124to be non-negative
12125
12126@item
12127Comparison of an object or (unary or binary) operation of boolean type to
12128an explicit True value.
12129@end itemize
12130
12131The default is that warnings for redundant constructs are not given.
12132@end table
12133
12134@geindex -gnatwR (gcc)
12135
12136
12137@table @asis
12138
12139@item @code{-gnatwR}
12140
12141@emph{Suppress warnings on redundant constructs.}
12142
12143This switch suppresses warnings for redundant constructs.
12144@end table
12145
12146@geindex -gnatw.r (gcc)
12147
12148
12149@table @asis
12150
12151@item @code{-gnatw.r}
12152
12153@emph{Activate warnings for object renaming function.}
12154
12155This switch activates warnings for an object renaming that renames a
12156function call, which is equivalent to a constant declaration (as
12157opposed to renaming the function itself).  The default is that these
12158warnings are given.
12159@end table
12160
12161@geindex -gnatwT (gcc)
12162
12163
12164@table @asis
12165
12166@item @code{-gnatw.R}
12167
12168@emph{Suppress warnings for object renaming function.}
12169
12170This switch suppresses warnings for object renaming function.
12171@end table
12172
12173@geindex -gnatws (gcc)
12174
12175
12176@table @asis
12177
12178@item @code{-gnatws}
12179
12180@emph{Suppress all warnings.}
12181
12182This switch completely suppresses the
12183output of all warning messages from the GNAT front end, including
12184both warnings that can be controlled by switches described in this
12185section, and those that are normally given unconditionally. The
12186effect of this suppress action can only be cancelled by a subsequent
12187use of the switch @code{-gnatwn}.
12188
12189Note that switch @code{-gnatws} does not suppress
12190warnings from the @code{gcc} back end.
12191To suppress these back end warnings as well, use the switch @code{-w}
12192in addition to @code{-gnatws}. Also this switch has no effect on the
12193handling of style check messages.
12194@end table
12195
12196@geindex -gnatw.s (gcc)
12197
12198@geindex Record Representation (component sizes)
12199
12200
12201@table @asis
12202
12203@item @code{-gnatw.s}
12204
12205@emph{Activate warnings on overridden size clauses.}
12206
12207This switch activates warnings on component clauses in record
12208representation clauses where the length given overrides that
12209specified by an explicit size clause for the component type. A
12210warning is similarly given in the array case if a specified
12211component size overrides an explicit size clause for the array
12212component type.
12213@end table
12214
12215@geindex -gnatw.S (gcc)
12216
12217
12218@table @asis
12219
12220@item @code{-gnatw.S}
12221
12222@emph{Suppress warnings on overridden size clauses.}
12223
12224This switch suppresses warnings on component clauses in record
12225representation clauses that override size clauses, and similar
12226warnings when an array component size overrides a size clause.
12227@end table
12228
12229@geindex -gnatwt (gcc)
12230
12231@geindex Deactivated code
12232@geindex warnings
12233
12234@geindex Deleted code
12235@geindex warnings
12236
12237
12238@table @asis
12239
12240@item @code{-gnatwt}
12241
12242@emph{Activate warnings for tracking of deleted conditional code.}
12243
12244This switch activates warnings for tracking of code in conditionals (IF and
12245CASE statements) that is detected to be dead code which cannot be executed, and
12246which is removed by the front end. This warning is off by default. This may be
12247useful for detecting deactivated code in certified applications.
12248@end table
12249
12250@geindex -gnatwT (gcc)
12251
12252
12253@table @asis
12254
12255@item @code{-gnatwT}
12256
12257@emph{Suppress warnings for tracking of deleted conditional code.}
12258
12259This switch suppresses warnings for tracking of deleted conditional code.
12260@end table
12261
12262@geindex -gnatw.t (gcc)
12263
12264
12265@table @asis
12266
12267@item @code{-gnatw.t}
12268
12269@emph{Activate warnings on suspicious contracts.}
12270
12271This switch activates warnings on suspicious contracts. This includes
12272warnings on suspicious postconditions (whether a pragma @code{Postcondition} or a
12273@code{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
12274@code{Contract_Cases}). A function postcondition or contract case is suspicious
12275when no postcondition or contract case for this function mentions the result
12276of the function.  A procedure postcondition or contract case is suspicious
12277when it only refers to the pre-state of the procedure, because in that case
12278it should rather be expressed as a precondition. This switch also controls
12279warnings on suspicious cases of expressions typically found in contracts like
12280quantified expressions and uses of Update attribute. The default is that such
12281warnings are generated.
12282@end table
12283
12284@geindex -gnatw.T (gcc)
12285
12286
12287@table @asis
12288
12289@item @code{-gnatw.T}
12290
12291@emph{Suppress warnings on suspicious contracts.}
12292
12293This switch suppresses warnings on suspicious contracts.
12294@end table
12295
12296@geindex -gnatwu (gcc)
12297
12298
12299@table @asis
12300
12301@item @code{-gnatwu}
12302
12303@emph{Activate warnings on unused entities.}
12304
12305This switch activates warnings to be generated for entities that
12306are declared but not referenced, and for units that are @emph{with}ed
12307and not
12308referenced. In the case of packages, a warning is also generated if
12309no entities in the package are referenced. This means that if a with'ed
12310package is referenced but the only references are in @code{use}
12311clauses or @code{renames}
12312declarations, a warning is still generated. A warning is also generated
12313for a generic package that is @emph{with}ed but never instantiated.
12314In the case where a package or subprogram body is compiled, and there
12315is a @emph{with} on the corresponding spec
12316that is only referenced in the body,
12317a warning is also generated, noting that the
12318@emph{with} can be moved to the body. The default is that
12319such warnings are not generated.
12320This switch also activates warnings on unreferenced formals
12321(it includes the effect of @code{-gnatwf}).
12322@end table
12323
12324@geindex -gnatwU (gcc)
12325
12326
12327@table @asis
12328
12329@item @code{-gnatwU}
12330
12331@emph{Suppress warnings on unused entities.}
12332
12333This switch suppresses warnings for unused entities and packages.
12334It also turns off warnings on unreferenced formals (and thus includes
12335the effect of @code{-gnatwF}).
12336@end table
12337
12338@geindex -gnatw.u (gcc)
12339
12340
12341@table @asis
12342
12343@item @code{-gnatw.u}
12344
12345@emph{Activate warnings on unordered enumeration types.}
12346
12347This switch causes enumeration types to be considered as conceptually
12348unordered, unless an explicit pragma @code{Ordered} is given for the type.
12349The effect is to generate warnings in clients that use explicit comparisons
12350or subranges, since these constructs both treat objects of the type as
12351ordered. (A @emph{client} is defined as a unit that is other than the unit in
12352which the type is declared, or its body or subunits.) Please refer to
12353the description of pragma @code{Ordered} in the
12354@cite{GNAT Reference Manual} for further details.
12355The default is that such warnings are not generated.
12356@end table
12357
12358@geindex -gnatw.U (gcc)
12359
12360
12361@table @asis
12362
12363@item @code{-gnatw.U}
12364
12365@emph{Deactivate warnings on unordered enumeration types.}
12366
12367This switch causes all enumeration types to be considered as ordered, so
12368that no warnings are given for comparisons or subranges for any type.
12369@end table
12370
12371@geindex -gnatwv (gcc)
12372
12373@geindex Unassigned variable warnings
12374
12375
12376@table @asis
12377
12378@item @code{-gnatwv}
12379
12380@emph{Activate warnings on unassigned variables.}
12381
12382This switch activates warnings for access to variables which
12383may not be properly initialized. The default is that
12384such warnings are generated.
12385@end table
12386
12387@geindex -gnatwV (gcc)
12388
12389
12390@table @asis
12391
12392@item @code{-gnatwV}
12393
12394@emph{Suppress warnings on unassigned variables.}
12395
12396This switch suppresses warnings for access to variables which
12397may not be properly initialized.
12398For variables of a composite type, the warning can also be suppressed in
12399Ada 2005 by using a default initialization with a box. For example, if
12400Table is an array of records whose components are only partially uninitialized,
12401then the following code:
12402
12403@example
12404Tab : Table := (others => <>);
12405@end example
12406
12407will suppress warnings on subsequent statements that access components
12408of variable Tab.
12409@end table
12410
12411@geindex -gnatw.v (gcc)
12412
12413@geindex bit order warnings
12414
12415
12416@table @asis
12417
12418@item @code{-gnatw.v}
12419
12420@emph{Activate info messages for non-default bit order.}
12421
12422This switch activates messages (labeled "info", they are not warnings,
12423just informational messages) about the effects of non-default bit-order
12424on records to which a component clause is applied. The effect of specifying
12425non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12426these messages, which are given by default, are useful in understanding the
12427exact consequences of using this feature.
12428@end table
12429
12430@geindex -gnatw.V (gcc)
12431
12432
12433@table @asis
12434
12435@item @code{-gnatw.V}
12436
12437@emph{Suppress info messages for non-default bit order.}
12438
12439This switch suppresses information messages for the effects of specifying
12440non-default bit order on record components with component clauses.
12441@end table
12442
12443@geindex -gnatww (gcc)
12444
12445@geindex String indexing warnings
12446
12447
12448@table @asis
12449
12450@item @code{-gnatww}
12451
12452@emph{Activate warnings on wrong low bound assumption.}
12453
12454This switch activates warnings for indexing an unconstrained string parameter
12455with a literal or S'Length. This is a case where the code is assuming that the
12456low bound is one, which is in general not true (for example when a slice is
12457passed). The default is that such warnings are generated.
12458@end table
12459
12460@geindex -gnatwW (gcc)
12461
12462
12463@table @asis
12464
12465@item @code{-gnatwW}
12466
12467@emph{Suppress warnings on wrong low bound assumption.}
12468
12469This switch suppresses warnings for indexing an unconstrained string parameter
12470with a literal or S'Length. Note that this warning can also be suppressed
12471in a particular case by adding an assertion that the lower bound is 1,
12472as shown in the following example:
12473
12474@example
12475procedure K (S : String) is
12476   pragma Assert (S'First = 1);
12477   ...
12478@end example
12479@end table
12480
12481@geindex -gnatw.w (gcc)
12482
12483@geindex Warnings Off control
12484
12485
12486@table @asis
12487
12488@item @code{-gnatw.w}
12489
12490@emph{Activate warnings on Warnings Off pragmas.}
12491
12492This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
12493where either the pragma is entirely useless (because it suppresses no
12494warnings), or it could be replaced by @code{pragma Unreferenced} or
12495@code{pragma Unmodified}.
12496Also activates warnings for the case of
12497Warnings (Off, String), where either there is no matching
12498Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12499The default is that these warnings are not given.
12500@end table
12501
12502@geindex -gnatw.W (gcc)
12503
12504
12505@table @asis
12506
12507@item @code{-gnatw.W}
12508
12509@emph{Suppress warnings on unnecessary Warnings Off pragmas.}
12510
12511This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
12512@end table
12513
12514@geindex -gnatwx (gcc)
12515
12516@geindex Export/Import pragma warnings
12517
12518
12519@table @asis
12520
12521@item @code{-gnatwx}
12522
12523@emph{Activate warnings on Export/Import pragmas.}
12524
12525This switch activates warnings on Export/Import pragmas when
12526the compiler detects a possible conflict between the Ada and
12527foreign language calling sequences. For example, the use of
12528default parameters in a convention C procedure is dubious
12529because the C compiler cannot supply the proper default, so
12530a warning is issued. The default is that such warnings are
12531generated.
12532@end table
12533
12534@geindex -gnatwX (gcc)
12535
12536
12537@table @asis
12538
12539@item @code{-gnatwX}
12540
12541@emph{Suppress warnings on Export/Import pragmas.}
12542
12543This switch suppresses warnings on Export/Import pragmas.
12544The sense of this is that you are telling the compiler that
12545you know what you are doing in writing the pragma, and it
12546should not complain at you.
12547@end table
12548
12549@geindex -gnatwm (gcc)
12550
12551
12552@table @asis
12553
12554@item @code{-gnatw.x}
12555
12556@emph{Activate warnings for No_Exception_Propagation mode.}
12557
12558This switch activates warnings for exception usage when pragma Restrictions
12559(No_Exception_Propagation) is in effect. Warnings are given for implicit or
12560explicit exception raises which are not covered by a local handler, and for
12561exception handlers which do not cover a local raise. The default is that
12562these warnings are given for units that contain exception handlers.
12563
12564@item @code{-gnatw.X}
12565
12566@emph{Disable warnings for No_Exception_Propagation mode.}
12567
12568This switch disables warnings for exception usage when pragma Restrictions
12569(No_Exception_Propagation) is in effect.
12570@end table
12571
12572@geindex -gnatwy (gcc)
12573
12574@geindex Ada compatibility issues warnings
12575
12576
12577@table @asis
12578
12579@item @code{-gnatwy}
12580
12581@emph{Activate warnings for Ada compatibility issues.}
12582
12583For the most part, newer versions of Ada are upwards compatible
12584with older versions. For example, Ada 2005 programs will almost
12585always work when compiled as Ada 2012.
12586However there are some exceptions (for example the fact that
12587@code{some} is now a reserved word in Ada 2012). This
12588switch activates several warnings to help in identifying
12589and correcting such incompatibilities. The default is that
12590these warnings are generated. Note that at one point Ada 2005
12591was called Ada 0Y, hence the choice of character.
12592@end table
12593
12594@geindex -gnatwY (gcc)
12595
12596@geindex Ada compatibility issues warnings
12597
12598
12599@table @asis
12600
12601@item @code{-gnatwY}
12602
12603@emph{Disable warnings for Ada compatibility issues.}
12604
12605This switch suppresses the warnings intended to help in identifying
12606incompatibilities between Ada language versions.
12607@end table
12608
12609@geindex -gnatw.y (gcc)
12610
12611@geindex Package spec needing body
12612
12613
12614@table @asis
12615
12616@item @code{-gnatw.y}
12617
12618@emph{Activate information messages for why package spec needs body.}
12619
12620There are a number of cases in which a package spec needs a body.
12621For example, the use of pragma Elaborate_Body, or the declaration
12622of a procedure specification requiring a completion. This switch
12623causes information messages to be output showing why a package
12624specification requires a body. This can be useful in the case of
12625a large package specification which is unexpectedly requiring a
12626body. The default is that such information messages are not output.
12627@end table
12628
12629@geindex -gnatw.Y (gcc)
12630
12631@geindex No information messages for why package spec needs body
12632
12633
12634@table @asis
12635
12636@item @code{-gnatw.Y}
12637
12638@emph{Disable information messages for why package spec needs body.}
12639
12640This switch suppresses the output of information messages showing why
12641a package specification needs a body.
12642@end table
12643
12644@geindex -gnatwz (gcc)
12645
12646@geindex Unchecked_Conversion warnings
12647
12648
12649@table @asis
12650
12651@item @code{-gnatwz}
12652
12653@emph{Activate warnings on unchecked conversions.}
12654
12655This switch activates warnings for unchecked conversions
12656where the types are known at compile time to have different
12657sizes. The default is that such warnings are generated. Warnings are also
12658generated for subprogram pointers with different conventions.
12659@end table
12660
12661@geindex -gnatwZ (gcc)
12662
12663
12664@table @asis
12665
12666@item @code{-gnatwZ}
12667
12668@emph{Suppress warnings on unchecked conversions.}
12669
12670This switch suppresses warnings for unchecked conversions
12671where the types are known at compile time to have different
12672sizes or conventions.
12673@end table
12674
12675@geindex -gnatw.z (gcc)
12676
12677@geindex Size/Alignment warnings
12678
12679
12680@table @asis
12681
12682@item @code{-gnatw.z}
12683
12684@emph{Activate warnings for size not a multiple of alignment.}
12685
12686This switch activates warnings for cases of record types with
12687specified @code{Size} and @code{Alignment} attributes where the
12688size is not a multiple of the alignment, resulting in an object
12689size that is greater than the specified size. The default
12690is that such warnings are generated.
12691@end table
12692
12693@geindex -gnatw.Z (gcc)
12694
12695@geindex Size/Alignment warnings
12696
12697
12698@table @asis
12699
12700@item @code{-gnatw.Z}
12701
12702@emph{Suppress warnings for size not a multiple of alignment.}
12703
12704This switch suppresses warnings for cases of record types with
12705specified @code{Size} and @code{Alignment} attributes where the
12706size is not a multiple of the alignment, resulting in an object
12707size that is greater than the specified size.
12708The warning can also be
12709suppressed by giving an explicit @code{Object_Size} value.
12710@end table
12711
12712@geindex -Wunused (gcc)
12713
12714
12715@table @asis
12716
12717@item @code{-Wunused}
12718
12719The warnings controlled by the @code{-gnatw} switch are generated by
12720the front end of the compiler. The GCC back end can provide
12721additional warnings and they are controlled by the @code{-W} switch.
12722For example, @code{-Wunused} activates back end
12723warnings for entities that are declared but not referenced.
12724@end table
12725
12726@geindex -Wuninitialized (gcc)
12727
12728
12729@table @asis
12730
12731@item @code{-Wuninitialized}
12732
12733Similarly, @code{-Wuninitialized} activates
12734the back end warning for uninitialized variables. This switch must be
12735used in conjunction with an optimization level greater than zero.
12736@end table
12737
12738@geindex -Wstack-usage (gcc)
12739
12740
12741@table @asis
12742
12743@item @code{-Wstack-usage=@emph{len}}
12744
12745Warn if the stack usage of a subprogram might be larger than @code{len} bytes.
12746See @ref{f5,,Static Stack Usage Analysis} for details.
12747@end table
12748
12749@geindex -Wall (gcc)
12750
12751
12752@table @asis
12753
12754@item @code{-Wall}
12755
12756This switch enables most warnings from the GCC back end.
12757The code generator detects a number of warning situations that are missed
12758by the GNAT front end, and this switch can be used to activate them.
12759The use of this switch also sets the default front end warning mode to
12760@code{-gnatwa}, that is, most front end warnings activated as well.
12761@end table
12762
12763@geindex -w (gcc)
12764
12765
12766@table @asis
12767
12768@item @code{-w}
12769
12770Conversely, this switch suppresses warnings from the GCC back end.
12771The use of this switch also sets the default front end warning mode to
12772@code{-gnatws}, that is, front end warnings suppressed as well.
12773@end table
12774
12775@geindex -Werror (gcc)
12776
12777
12778@table @asis
12779
12780@item @code{-Werror}
12781
12782This switch causes warnings from the GCC back end to be treated as
12783errors.  The warning string still appears, but the warning messages are
12784counted as errors, and prevent the generation of an object file.
12785@end table
12786
12787A string of warning parameters can be used in the same parameter. For example:
12788
12789@example
12790-gnatwaGe
12791@end example
12792
12793will turn on all optional warnings except for unrecognized pragma warnings,
12794and also specify that warnings should be treated as errors.
12795
12796When no switch @code{-gnatw} is used, this is equivalent to:
12797
12798@quotation
12799
12800
12801@itemize *
12802
12803@item
12804@code{-gnatw.a}
12805
12806@item
12807@code{-gnatwB}
12808
12809@item
12810@code{-gnatw.b}
12811
12812@item
12813@code{-gnatwC}
12814
12815@item
12816@code{-gnatw.C}
12817
12818@item
12819@code{-gnatwD}
12820
12821@item
12822@code{-gnatw.D}
12823
12824@item
12825@code{-gnatwF}
12826
12827@item
12828@code{-gnatw.F}
12829
12830@item
12831@code{-gnatwg}
12832
12833@item
12834@code{-gnatwH}
12835
12836@item
12837@code{-gnatw.H}
12838
12839@item
12840@code{-gnatwi}
12841
12842@item
12843@code{-gnatwJ}
12844
12845@item
12846@code{-gnatw.J}
12847
12848@item
12849@code{-gnatwK}
12850
12851@item
12852@code{-gnatw.K}
12853
12854@item
12855@code{-gnatwL}
12856
12857@item
12858@code{-gnatw.L}
12859
12860@item
12861@code{-gnatwM}
12862
12863@item
12864@code{-gnatw.m}
12865
12866@item
12867@code{-gnatwn}
12868
12869@item
12870@code{-gnatw.N}
12871
12872@item
12873@code{-gnatwo}
12874
12875@item
12876@code{-gnatw.O}
12877
12878@item
12879@code{-gnatwP}
12880
12881@item
12882@code{-gnatw.P}
12883
12884@item
12885@code{-gnatwq}
12886
12887@item
12888@code{-gnatw.Q}
12889
12890@item
12891@code{-gnatwR}
12892
12893@item
12894@code{-gnatw.R}
12895
12896@item
12897@code{-gnatw.S}
12898
12899@item
12900@code{-gnatwT}
12901
12902@item
12903@code{-gnatw.t}
12904
12905@item
12906@code{-gnatwU}
12907
12908@item
12909@code{-gnatw.U}
12910
12911@item
12912@code{-gnatwv}
12913
12914@item
12915@code{-gnatw.v}
12916
12917@item
12918@code{-gnatww}
12919
12920@item
12921@code{-gnatw.W}
12922
12923@item
12924@code{-gnatwx}
12925
12926@item
12927@code{-gnatw.X}
12928
12929@item
12930@code{-gnatwy}
12931
12932@item
12933@code{-gnatw.Y}
12934
12935@item
12936@code{-gnatwz}
12937
12938@item
12939@code{-gnatw.z}
12940@end itemize
12941@end quotation
12942
12943@node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12944@anchor{gnat_ugn/building_executable_programs_with_gnat debugging-and-assertion-control}@anchor{100}@anchor{gnat_ugn/building_executable_programs_with_gnat id16}@anchor{101}
12945@subsection Debugging and Assertion Control
12946
12947
12948@geindex -gnata (gcc)
12949
12950
12951@table @asis
12952
12953@item @code{-gnata}
12954
12955@geindex Assert
12956
12957@geindex Debug
12958
12959@geindex Assertions
12960
12961@geindex Precondition
12962
12963@geindex Postcondition
12964
12965@geindex Type invariants
12966
12967@geindex Subtype predicates
12968
12969The @code{-gnata} option is equivalent to the following @code{Assertion_Policy} pragma:
12970
12971@example
12972pragma Assertion_Policy (Check);
12973@end example
12974
12975Which is a shorthand for:
12976
12977@example
12978pragma Assertion_Policy
12979  (Assert               => Check,
12980   Static_Predicate     => Check,
12981   Dynamic_Predicate    => Check,
12982   Pre                  => Check,
12983   Pre'Class            => Check,
12984   Post                 => Check,
12985   Post'Class           => Check,
12986   Type_Invariant       => Check,
12987   Type_Invariant'Class => Check);
12988@end example
12989
12990The pragmas @code{Assert} and @code{Debug} normally have no effect and
12991are ignored. This switch, where @code{a} stands for 'assert', causes
12992pragmas @code{Assert} and @code{Debug} to be activated. This switch also
12993causes preconditions, postconditions, subtype predicates, and
12994type invariants to be activated.
12995
12996The pragmas have the form:
12997
12998@example
12999pragma Assert (<Boolean-expression> [, <static-string-expression>])
13000pragma Debug (<procedure call>)
13001pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
13002pragma Predicate (<type-local-name>, <Boolean-expression>)
13003pragma Precondition (<Boolean-expression>, <string-expression>)
13004pragma Postcondition (<Boolean-expression>, <string-expression>)
13005@end example
13006
13007The aspects have the form:
13008
13009@example
13010with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
13011  => <Boolean-expression>;
13012@end example
13013
13014The @code{Assert} pragma causes @code{Boolean-expression} to be tested.
13015If the result is @code{True}, the pragma has no effect (other than
13016possible side effects from evaluating the expression). If the result is
13017@code{False}, the exception @code{Assert_Failure} declared in the package
13018@code{System.Assertions} is raised (passing @code{static-string-expression}, if
13019present, as the message associated with the exception). If no string
13020expression is given, the default is a string containing the file name and
13021line number of the pragma.
13022
13023The @code{Debug} pragma causes @code{procedure} to be called. Note that
13024@code{pragma Debug} may appear within a declaration sequence, allowing
13025debugging procedures to be called between declarations.
13026
13027For the aspect specification, the @code{Boolean-expression} is evaluated.
13028If the result is @code{True}, the aspect has no effect. If the result
13029is @code{False}, the exception @code{Assert_Failure} is raised.
13030@end table
13031
13032@node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
13033@anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{102}
13034@subsection Validity Checking
13035
13036
13037@geindex Validity Checking
13038
13039The Ada Reference Manual defines the concept of invalid values (see
13040RM 13.9.1). The primary source of invalid values is uninitialized
13041variables. A scalar variable that is left uninitialized may contain
13042an invalid value; the concept of invalid does not apply to access or
13043composite types.
13044
13045It is an error to read an invalid value, but the RM does not require
13046run-time checks to detect such errors, except for some minimal
13047checking to prevent erroneous execution (i.e. unpredictable
13048behavior). This corresponds to the @code{-gnatVd} switch below,
13049which is the default. For example, by default, if the expression of a
13050case statement is invalid, it will raise Constraint_Error rather than
13051causing a wild jump, and if an array index on the left-hand side of an
13052assignment is invalid, it will raise Constraint_Error rather than
13053overwriting an arbitrary memory location.
13054
13055The @code{-gnatVa} may be used to enable additional validity checks,
13056which are not required by the RM. These checks are often very
13057expensive (which is why the RM does not require them). These checks
13058are useful in tracking down uninitialized variables, but they are
13059not usually recommended for production builds, and in particular
13060we do not recommend using these extra validity checking options in
13061combination with optimization, since this can confuse the optimizer.
13062If performance is a consideration, leading to the need to optimize,
13063then the validity checking options should not be used.
13064
13065The other @code{-gnatV@emph{x}} switches below allow finer-grained
13066control; you can enable whichever validity checks you desire. However,
13067for most debugging purposes, @code{-gnatVa} is sufficient, and the
13068default @code{-gnatVd} (i.e. standard Ada behavior) is usually
13069sufficient for non-debugging use.
13070
13071The @code{-gnatB} switch tells the compiler to assume that all
13072values are valid (that is, within their declared subtype range)
13073except in the context of a use of the Valid attribute. This means
13074the compiler can generate more efficient code, since the range
13075of values is better known at compile time. However, an uninitialized
13076variable can cause wild jumps and memory corruption in this mode.
13077
13078The @code{-gnatV@emph{x}} switch allows control over the validity
13079checking mode as described below.
13080The @code{x} argument is a string of letters that
13081indicate validity checks that are performed or not performed in addition
13082to the default checks required by Ada as described above.
13083
13084@geindex -gnatVa (gcc)
13085
13086
13087@table @asis
13088
13089@item @code{-gnatVa}
13090
13091@emph{All validity checks.}
13092
13093All validity checks are turned on.
13094That is, @code{-gnatVa} is
13095equivalent to @code{gnatVcdfimorst}.
13096@end table
13097
13098@geindex -gnatVc (gcc)
13099
13100
13101@table @asis
13102
13103@item @code{-gnatVc}
13104
13105@emph{Validity checks for copies.}
13106
13107The right hand side of assignments, and the initializing values of
13108object declarations are validity checked.
13109@end table
13110
13111@geindex -gnatVd (gcc)
13112
13113
13114@table @asis
13115
13116@item @code{-gnatVd}
13117
13118@emph{Default (RM) validity checks.}
13119
13120Some validity checks are done by default following normal Ada semantics
13121(RM 13.9.1 (9-11)).
13122A check is done in case statements that the expression is within the range
13123of the subtype. If it is not, Constraint_Error is raised.
13124For assignments to array components, a check is done that the expression used
13125as index is within the range. If it is not, Constraint_Error is raised.
13126Both these validity checks may be turned off using switch @code{-gnatVD}.
13127They are turned on by default. If @code{-gnatVD} is specified, a subsequent
13128switch @code{-gnatVd} will leave the checks turned on.
13129Switch @code{-gnatVD} should be used only if you are sure that all such
13130expressions have valid values. If you use this switch and invalid values
13131are present, then the program is erroneous, and wild jumps or memory
13132overwriting may occur.
13133@end table
13134
13135@geindex -gnatVe (gcc)
13136
13137
13138@table @asis
13139
13140@item @code{-gnatVe}
13141
13142@emph{Validity checks for elementary components.}
13143
13144In the absence of this switch, assignments to record or array components are
13145not validity checked, even if validity checks for assignments generally
13146(@code{-gnatVc}) are turned on. In Ada, assignment of composite values do not
13147require valid data, but assignment of individual components does. So for
13148example, there is a difference between copying the elements of an array with a
13149slice assignment, compared to assigning element by element in a loop. This
13150switch allows you to turn off validity checking for components, even when they
13151are assigned component by component.
13152@end table
13153
13154@geindex -gnatVf (gcc)
13155
13156
13157@table @asis
13158
13159@item @code{-gnatVf}
13160
13161@emph{Validity checks for floating-point values.}
13162
13163In the absence of this switch, validity checking occurs only for discrete
13164values. If @code{-gnatVf} is specified, then validity checking also applies
13165for floating-point values, and NaNs and infinities are considered invalid,
13166as well as out of range values for constrained types. Note that this means
13167that standard IEEE infinity mode is not allowed. The exact contexts
13168in which floating-point values are checked depends on the setting of other
13169options. For example, @code{-gnatVif} or @code{-gnatVfi}
13170(the order does not matter) specifies that floating-point parameters of mode
13171@code{in} should be validity checked.
13172@end table
13173
13174@geindex -gnatVi (gcc)
13175
13176
13177@table @asis
13178
13179@item @code{-gnatVi}
13180
13181@emph{Validity checks for `@w{`}in`@w{`} mode parameters.}
13182
13183Arguments for parameters of mode @code{in} are validity checked in function
13184and procedure calls at the point of call.
13185@end table
13186
13187@geindex -gnatVm (gcc)
13188
13189
13190@table @asis
13191
13192@item @code{-gnatVm}
13193
13194@emph{Validity checks for `@w{`}in out`@w{`} mode parameters.}
13195
13196Arguments for parameters of mode @code{in out} are validity checked in
13197procedure calls at the point of call. The @code{'m'} here stands for
13198modify, since this concerns parameters that can be modified by the call.
13199Note that there is no specific option to test @code{out} parameters,
13200but any reference within the subprogram will be tested in the usual
13201manner, and if an invalid value is copied back, any reference to it
13202will be subject to validity checking.
13203@end table
13204
13205@geindex -gnatVn (gcc)
13206
13207
13208@table @asis
13209
13210@item @code{-gnatVn}
13211
13212@emph{No validity checks.}
13213
13214This switch turns off all validity checking, including the default checking
13215for case statements and left hand side subscripts. Note that the use of
13216the switch @code{-gnatp} suppresses all run-time checks, including
13217validity checks, and thus implies @code{-gnatVn}. When this switch
13218is used, it cancels any other @code{-gnatV} previously issued.
13219@end table
13220
13221@geindex -gnatVo (gcc)
13222
13223
13224@table @asis
13225
13226@item @code{-gnatVo}
13227
13228@emph{Validity checks for operator and attribute operands.}
13229
13230Arguments for predefined operators and attributes are validity checked.
13231This includes all operators in package @code{Standard},
13232the shift operators defined as intrinsic in package @code{Interfaces}
13233and operands for attributes such as @code{Pos}. Checks are also made
13234on individual component values for composite comparisons, and on the
13235expressions in type conversions and qualified expressions. Checks are
13236also made on explicit ranges using @code{..} (e.g., slices, loops etc).
13237@end table
13238
13239@geindex -gnatVp (gcc)
13240
13241
13242@table @asis
13243
13244@item @code{-gnatVp}
13245
13246@emph{Validity checks for parameters.}
13247
13248This controls the treatment of parameters within a subprogram (as opposed
13249to @code{-gnatVi} and @code{-gnatVm} which control validity testing
13250of parameters on a call. If either of these call options is used, then
13251normally an assumption is made within a subprogram that the input arguments
13252have been validity checking at the point of call, and do not need checking
13253again within a subprogram). If @code{-gnatVp} is set, then this assumption
13254is not made, and parameters are not assumed to be valid, so their validity
13255will be checked (or rechecked) within the subprogram.
13256@end table
13257
13258@geindex -gnatVr (gcc)
13259
13260
13261@table @asis
13262
13263@item @code{-gnatVr}
13264
13265@emph{Validity checks for function returns.}
13266
13267The expression in @code{return} statements in functions is validity
13268checked.
13269@end table
13270
13271@geindex -gnatVs (gcc)
13272
13273
13274@table @asis
13275
13276@item @code{-gnatVs}
13277
13278@emph{Validity checks for subscripts.}
13279
13280All subscripts expressions are checked for validity, whether they appear
13281on the right side or left side (in default mode only left side subscripts
13282are validity checked).
13283@end table
13284
13285@geindex -gnatVt (gcc)
13286
13287
13288@table @asis
13289
13290@item @code{-gnatVt}
13291
13292@emph{Validity checks for tests.}
13293
13294Expressions used as conditions in @code{if}, @code{while} or @code{exit}
13295statements are checked, as well as guard expressions in entry calls.
13296@end table
13297
13298The @code{-gnatV} switch may be followed by a string of letters
13299to turn on a series of validity checking options.
13300For example, @code{-gnatVcr}
13301specifies that in addition to the default validity checking, copies and
13302function return expressions are to be validity checked.
13303In order to make it easier to specify the desired combination of effects,
13304the upper case letters @code{CDFIMORST} may
13305be used to turn off the corresponding lower case option.
13306Thus @code{-gnatVaM} turns on all validity checking options except for
13307checking of @code{in out} parameters.
13308
13309The specification of additional validity checking generates extra code (and
13310in the case of @code{-gnatVa} the code expansion can be substantial).
13311However, these additional checks can be very useful in detecting
13312uninitialized variables, incorrect use of unchecked conversion, and other
13313errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
13314is useful in conjunction with the extra validity checking, since this
13315ensures that wherever possible uninitialized variables have invalid values.
13316
13317See also the pragma @code{Validity_Checks} which allows modification of
13318the validity checking mode at the program source level, and also allows for
13319temporary disabling of validity checks.
13320
13321@node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
13322@anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{103}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{fb}
13323@subsection Style Checking
13324
13325
13326@geindex Style checking
13327
13328@geindex -gnaty (gcc)
13329
13330The @code{-gnatyx} switch causes the compiler to
13331enforce specified style rules. A limited set of style rules has been used
13332in writing the GNAT sources themselves. This switch allows user programs
13333to activate all or some of these checks. If the source program fails a
13334specified style check, an appropriate message is given, preceded by
13335the character sequence '(style)'. This message does not prevent
13336successful compilation (unless the @code{-gnatwe} switch is used).
13337
13338Note that this is by no means intended to be a general facility for
13339checking arbitrary coding standards. It is simply an embedding of the
13340style rules we have chosen for the GNAT sources. If you are starting
13341a project which does not have established style standards, you may
13342find it useful to adopt the entire set of GNAT coding standards, or
13343some subset of them.
13344
13345
13346The string @code{x} is a sequence of letters or digits
13347indicating the particular style
13348checks to be performed. The following checks are defined:
13349
13350@geindex -gnaty[0-9] (gcc)
13351
13352
13353@table @asis
13354
13355@item @code{-gnaty0}
13356
13357@emph{Specify indentation level.}
13358
13359If a digit from 1-9 appears
13360in the string after @code{-gnaty}
13361then proper indentation is checked, with the digit indicating the
13362indentation level required. A value of zero turns off this style check.
13363The general style of required indentation is as specified by
13364the examples in the Ada Reference Manual. Full line comments must be
13365aligned with the @code{--} starting on a column that is a multiple of
13366the alignment level, or they may be aligned the same way as the following
13367non-blank line (this is useful when full line comments appear in the middle
13368of a statement, or they may be aligned with the source line on the previous
13369non-blank line.
13370@end table
13371
13372@geindex -gnatya (gcc)
13373
13374
13375@table @asis
13376
13377@item @code{-gnatya}
13378
13379@emph{Check attribute casing.}
13380
13381Attribute names, including the case of keywords such as @code{digits}
13382used as attributes names, must be written in mixed case, that is, the
13383initial letter and any letter following an underscore must be uppercase.
13384All other letters must be lowercase.
13385@end table
13386
13387@geindex -gnatyA (gcc)
13388
13389
13390@table @asis
13391
13392@item @code{-gnatyA}
13393
13394@emph{Use of array index numbers in array attributes.}
13395
13396When using the array attributes First, Last, Range,
13397or Length, the index number must be omitted for one-dimensional arrays
13398and is required for multi-dimensional arrays.
13399@end table
13400
13401@geindex -gnatyb (gcc)
13402
13403
13404@table @asis
13405
13406@item @code{-gnatyb}
13407
13408@emph{Blanks not allowed at statement end.}
13409
13410Trailing blanks are not allowed at the end of statements. The purpose of this
13411rule, together with h (no horizontal tabs), is to enforce a canonical format
13412for the use of blanks to separate source tokens.
13413@end table
13414
13415@geindex -gnatyB (gcc)
13416
13417
13418@table @asis
13419
13420@item @code{-gnatyB}
13421
13422@emph{Check Boolean operators.}
13423
13424The use of AND/OR operators is not permitted except in the cases of modular
13425operands, array operands, and simple stand-alone boolean variables or
13426boolean constants. In all other cases @code{and then}/@cite{or else} are
13427required.
13428@end table
13429
13430@geindex -gnatyc (gcc)
13431
13432
13433@table @asis
13434
13435@item @code{-gnatyc}
13436
13437@emph{Check comments, double space.}
13438
13439Comments must meet the following set of rules:
13440
13441
13442@itemize *
13443
13444@item
13445The @code{--} that starts the column must either start in column one,
13446or else at least one blank must precede this sequence.
13447
13448@item
13449Comments that follow other tokens on a line must have at least one blank
13450following the @code{--} at the start of the comment.
13451
13452@item
13453Full line comments must have at least two blanks following the
13454@code{--} that starts the comment, with the following exceptions.
13455
13456@item
13457A line consisting only of the @code{--} characters, possibly preceded
13458by blanks is permitted.
13459
13460@item
13461A comment starting with @code{--x} where @code{x} is a special character
13462is permitted.
13463This allows proper processing of the output from specialized tools
13464such as @code{gnatprep} (where @code{--!} is used) and in earlier versions of the SPARK
13465annotation
13466language (where @code{--#} is used). For the purposes of this rule, a
13467special character is defined as being in one of the ASCII ranges
13468@code{16#21#...16#2F#} or @code{16#3A#...16#3F#}.
13469Note that this usage is not permitted
13470in GNAT implementation units (i.e., when @code{-gnatg} is used).
13471
13472@item
13473A line consisting entirely of minus signs, possibly preceded by blanks, is
13474permitted. This allows the construction of box comments where lines of minus
13475signs are used to form the top and bottom of the box.
13476
13477@item
13478A comment that starts and ends with @code{--} is permitted as long as at
13479least one blank follows the initial @code{--}. Together with the preceding
13480rule, this allows the construction of box comments, as shown in the following
13481example:
13482
13483@example
13484---------------------------
13485-- This is a box comment --
13486-- with two text lines.  --
13487---------------------------
13488@end example
13489@end itemize
13490@end table
13491
13492@geindex -gnatyC (gcc)
13493
13494
13495@table @asis
13496
13497@item @code{-gnatyC}
13498
13499@emph{Check comments, single space.}
13500
13501This is identical to @code{c} except that only one space
13502is required following the @code{--} of a comment instead of two.
13503@end table
13504
13505@geindex -gnatyd (gcc)
13506
13507
13508@table @asis
13509
13510@item @code{-gnatyd}
13511
13512@emph{Check no DOS line terminators present.}
13513
13514All lines must be terminated by a single ASCII.LF
13515character (in particular the DOS line terminator sequence CR/LF is not
13516allowed).
13517@end table
13518
13519@geindex -gnatye (gcc)
13520
13521
13522@table @asis
13523
13524@item @code{-gnatye}
13525
13526@emph{Check end/exit labels.}
13527
13528Optional labels on @code{end} statements ending subprograms and on
13529@code{exit} statements exiting named loops, are required to be present.
13530@end table
13531
13532@geindex -gnatyf (gcc)
13533
13534
13535@table @asis
13536
13537@item @code{-gnatyf}
13538
13539@emph{No form feeds or vertical tabs.}
13540
13541Neither form feeds nor vertical tab characters are permitted
13542in the source text.
13543@end table
13544
13545@geindex -gnatyg (gcc)
13546
13547
13548@table @asis
13549
13550@item @code{-gnatyg}
13551
13552@emph{GNAT style mode.}
13553
13554The set of style check switches is set to match that used by the GNAT sources.
13555This may be useful when developing code that is eventually intended to be
13556incorporated into GNAT. Currently this is equivalent to @code{-gnatwydISux})
13557but additional style switches may be added to this set in the future without
13558advance notice.
13559@end table
13560
13561@geindex -gnatyh (gcc)
13562
13563
13564@table @asis
13565
13566@item @code{-gnatyh}
13567
13568@emph{No horizontal tabs.}
13569
13570Horizontal tab characters are not permitted in the source text.
13571Together with the b (no blanks at end of line) check, this
13572enforces a canonical form for the use of blanks to separate
13573source tokens.
13574@end table
13575
13576@geindex -gnatyi (gcc)
13577
13578
13579@table @asis
13580
13581@item @code{-gnatyi}
13582
13583@emph{Check if-then layout.}
13584
13585The keyword @code{then} must appear either on the same
13586line as corresponding @code{if}, or on a line on its own, lined
13587up under the @code{if}.
13588@end table
13589
13590@geindex -gnatyI (gcc)
13591
13592
13593@table @asis
13594
13595@item @code{-gnatyI}
13596
13597@emph{check mode IN keywords.}
13598
13599Mode @code{in} (the default mode) is not
13600allowed to be given explicitly. @code{in out} is fine,
13601but not @code{in} on its own.
13602@end table
13603
13604@geindex -gnatyk (gcc)
13605
13606
13607@table @asis
13608
13609@item @code{-gnatyk}
13610
13611@emph{Check keyword casing.}
13612
13613All keywords must be in lower case (with the exception of keywords
13614such as @code{digits} used as attribute names to which this check
13615does not apply).
13616@end table
13617
13618@geindex -gnatyl (gcc)
13619
13620
13621@table @asis
13622
13623@item @code{-gnatyl}
13624
13625@emph{Check layout.}
13626
13627Layout of statement and declaration constructs must follow the
13628recommendations in the Ada Reference Manual, as indicated by the
13629form of the syntax rules. For example an @code{else} keyword must
13630be lined up with the corresponding @code{if} keyword.
13631
13632There are two respects in which the style rule enforced by this check
13633option are more liberal than those in the Ada Reference Manual. First
13634in the case of record declarations, it is permissible to put the
13635@code{record} keyword on the same line as the @code{type} keyword, and
13636then the @code{end} in @code{end record} must line up under @code{type}.
13637This is also permitted when the type declaration is split on two lines.
13638For example, any of the following three layouts is acceptable:
13639
13640@example
13641type q is record
13642   a : integer;
13643   b : integer;
13644end record;
13645
13646type q is
13647   record
13648      a : integer;
13649      b : integer;
13650   end record;
13651
13652type q is
13653   record
13654      a : integer;
13655      b : integer;
13656end record;
13657@end example
13658
13659Second, in the case of a block statement, a permitted alternative
13660is to put the block label on the same line as the @code{declare} or
13661@code{begin} keyword, and then line the @code{end} keyword up under
13662the block label. For example both the following are permitted:
13663
13664@example
13665Block : declare
13666   A : Integer := 3;
13667begin
13668   Proc (A, A);
13669end Block;
13670
13671Block :
13672   declare
13673      A : Integer := 3;
13674   begin
13675      Proc (A, A);
13676   end Block;
13677@end example
13678
13679The same alternative format is allowed for loops. For example, both of
13680the following are permitted:
13681
13682@example
13683Clear : while J < 10 loop
13684   A (J) := 0;
13685end loop Clear;
13686
13687Clear :
13688   while J < 10 loop
13689      A (J) := 0;
13690   end loop Clear;
13691@end example
13692@end table
13693
13694@geindex -gnatyLnnn (gcc)
13695
13696
13697@table @asis
13698
13699@item @code{-gnatyL}
13700
13701@emph{Set maximum nesting level.}
13702
13703The maximum level of nesting of constructs (including subprograms, loops,
13704blocks, packages, and conditionals) may not exceed the given value
13705@emph{nnn}. A value of zero disconnects this style check.
13706@end table
13707
13708@geindex -gnatym (gcc)
13709
13710
13711@table @asis
13712
13713@item @code{-gnatym}
13714
13715@emph{Check maximum line length.}
13716
13717The length of source lines must not exceed 79 characters, including
13718any trailing blanks. The value of 79 allows convenient display on an
1371980 character wide device or window, allowing for possible special
13720treatment of 80 character lines. Note that this count is of
13721characters in the source text. This means that a tab character counts
13722as one character in this count and a wide character sequence counts as
13723a single character (however many bytes are needed in the encoding).
13724@end table
13725
13726@geindex -gnatyMnnn (gcc)
13727
13728
13729@table @asis
13730
13731@item @code{-gnatyM}
13732
13733@emph{Set maximum line length.}
13734
13735The length of lines must not exceed the
13736given value @emph{nnn}. The maximum value that can be specified is 32767.
13737If neither style option for setting the line length is used, then the
13738default is 255. This also controls the maximum length of lexical elements,
13739where the only restriction is that they must fit on a single line.
13740@end table
13741
13742@geindex -gnatyn (gcc)
13743
13744
13745@table @asis
13746
13747@item @code{-gnatyn}
13748
13749@emph{Check casing of entities in Standard.}
13750
13751Any identifier from Standard must be cased
13752to match the presentation in the Ada Reference Manual (for example,
13753@code{Integer} and @code{ASCII.NUL}).
13754@end table
13755
13756@geindex -gnatyN (gcc)
13757
13758
13759@table @asis
13760
13761@item @code{-gnatyN}
13762
13763@emph{Turn off all style checks.}
13764
13765All style check options are turned off.
13766@end table
13767
13768@geindex -gnatyo (gcc)
13769
13770
13771@table @asis
13772
13773@item @code{-gnatyo}
13774
13775@emph{Check order of subprogram bodies.}
13776
13777All subprogram bodies in a given scope
13778(e.g., a package body) must be in alphabetical order. The ordering
13779rule uses normal Ada rules for comparing strings, ignoring casing
13780of letters, except that if there is a trailing numeric suffix, then
13781the value of this suffix is used in the ordering (e.g., Junk2 comes
13782before Junk10).
13783@end table
13784
13785@geindex -gnatyO (gcc)
13786
13787
13788@table @asis
13789
13790@item @code{-gnatyO}
13791
13792@emph{Check that overriding subprograms are explicitly marked as such.}
13793
13794This applies to all subprograms of a derived type that override a primitive
13795operation of the type, for both tagged and untagged types. In particular,
13796the declaration of a primitive operation of a type extension that overrides
13797an inherited operation must carry an overriding indicator. Another case is
13798the declaration of a function that overrides a predefined operator (such
13799as an equality operator).
13800@end table
13801
13802@geindex -gnatyp (gcc)
13803
13804
13805@table @asis
13806
13807@item @code{-gnatyp}
13808
13809@emph{Check pragma casing.}
13810
13811Pragma names must be written in mixed case, that is, the
13812initial letter and any letter following an underscore must be uppercase.
13813All other letters must be lowercase. An exception is that SPARK_Mode is
13814allowed as an alternative for Spark_Mode.
13815@end table
13816
13817@geindex -gnatyr (gcc)
13818
13819
13820@table @asis
13821
13822@item @code{-gnatyr}
13823
13824@emph{Check references.}
13825
13826All identifier references must be cased in the same way as the
13827corresponding declaration. No specific casing style is imposed on
13828identifiers. The only requirement is for consistency of references
13829with declarations.
13830@end table
13831
13832@geindex -gnatys (gcc)
13833
13834
13835@table @asis
13836
13837@item @code{-gnatys}
13838
13839@emph{Check separate specs.}
13840
13841Separate declarations ('specs') are required for subprograms (a
13842body is not allowed to serve as its own declaration). The only
13843exception is that parameterless library level procedures are
13844not required to have a separate declaration. This exception covers
13845the most frequent form of main program procedures.
13846@end table
13847
13848@geindex -gnatyS (gcc)
13849
13850
13851@table @asis
13852
13853@item @code{-gnatyS}
13854
13855@emph{Check no statements after then/else.}
13856
13857No statements are allowed
13858on the same line as a @code{then} or @code{else} keyword following the
13859keyword in an @code{if} statement. @code{or else} and @code{and then} are not
13860affected, and a special exception allows a pragma to appear after @code{else}.
13861@end table
13862
13863@geindex -gnatyt (gcc)
13864
13865
13866@table @asis
13867
13868@item @code{-gnatyt}
13869
13870@emph{Check token spacing.}
13871
13872The following token spacing rules are enforced:
13873
13874
13875@itemize *
13876
13877@item
13878The keywords @code{abs} and @code{not} must be followed by a space.
13879
13880@item
13881The token @code{=>} must be surrounded by spaces.
13882
13883@item
13884The token @code{<>} must be preceded by a space or a left parenthesis.
13885
13886@item
13887Binary operators other than @code{**} must be surrounded by spaces.
13888There is no restriction on the layout of the @code{**} binary operator.
13889
13890@item
13891Colon must be surrounded by spaces.
13892
13893@item
13894Colon-equal (assignment, initialization) must be surrounded by spaces.
13895
13896@item
13897Comma must be the first non-blank character on the line, or be
13898immediately preceded by a non-blank character, and must be followed
13899by a space.
13900
13901@item
13902If the token preceding a left parenthesis ends with a letter or digit, then
13903a space must separate the two tokens.
13904
13905@item
13906If the token following a right parenthesis starts with a letter or digit, then
13907a space must separate the two tokens.
13908
13909@item
13910A right parenthesis must either be the first non-blank character on
13911a line, or it must be preceded by a non-blank character.
13912
13913@item
13914A semicolon must not be preceded by a space, and must not be followed by
13915a non-blank character.
13916
13917@item
13918A unary plus or minus may not be followed by a space.
13919
13920@item
13921A vertical bar must be surrounded by spaces.
13922@end itemize
13923
13924Exactly one blank (and no other white space) must appear between
13925a @code{not} token and a following @code{in} token.
13926@end table
13927
13928@geindex -gnatyu (gcc)
13929
13930
13931@table @asis
13932
13933@item @code{-gnatyu}
13934
13935@emph{Check unnecessary blank lines.}
13936
13937Unnecessary blank lines are not allowed. A blank line is considered
13938unnecessary if it appears at the end of the file, or if more than
13939one blank line occurs in sequence.
13940@end table
13941
13942@geindex -gnatyx (gcc)
13943
13944
13945@table @asis
13946
13947@item @code{-gnatyx}
13948
13949@emph{Check extra parentheses.}
13950
13951Unnecessary extra level of parentheses (C-style) are not allowed
13952around conditions in @code{if} statements, @code{while} statements and
13953@code{exit} statements.
13954@end table
13955
13956@geindex -gnatyy (gcc)
13957
13958
13959@table @asis
13960
13961@item @code{-gnatyy}
13962
13963@emph{Set all standard style check options.}
13964
13965This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
13966options enabled with the exception of @code{-gnatyB}, @code{-gnatyd},
13967@code{-gnatyI}, @code{-gnatyLnnn}, @code{-gnatyo}, @code{-gnatyO},
13968@code{-gnatyS}, @code{-gnatyu}, and @code{-gnatyx}.
13969@end table
13970
13971@geindex -gnaty- (gcc)
13972
13973
13974@table @asis
13975
13976@item @code{-gnaty-}
13977
13978@emph{Remove style check options.}
13979
13980This causes any subsequent options in the string to act as canceling the
13981corresponding style check option. To cancel maximum nesting level control,
13982use the @code{L} parameter without any integer value after that, because any
13983digit following @emph{-} in the parameter string of the @code{-gnaty}
13984option will be treated as canceling the indentation check. The same is true
13985for the @code{M} parameter. @code{y} and @code{N} parameters are not
13986allowed after @emph{-}.
13987@end table
13988
13989@geindex -gnaty+ (gcc)
13990
13991
13992@table @asis
13993
13994@item @code{-gnaty+}
13995
13996@emph{Enable style check options.}
13997
13998This causes any subsequent options in the string to enable the corresponding
13999style check option. That is, it cancels the effect of a previous -,
14000if any.
14001@end table
14002
14003@c end of switch description (leave this comment to ease automatic parsing for
14004
14005@c GPS
14006
14007In the above rules, appearing in column one is always permitted, that is,
14008counts as meeting either a requirement for a required preceding space,
14009or as meeting a requirement for no preceding space.
14010
14011Appearing at the end of a line is also always permitted, that is, counts
14012as meeting either a requirement for a following space, or as meeting
14013a requirement for no following space.
14014
14015If any of these style rules is violated, a message is generated giving
14016details on the violation. The initial characters of such messages are
14017always '@cite{(style)}'. Note that these messages are treated as warning
14018messages, so they normally do not prevent the generation of an object
14019file. The @code{-gnatwe} switch can be used to treat warning messages,
14020including style messages, as fatal errors.
14021
14022The switch @code{-gnaty} on its own (that is not
14023followed by any letters or digits) is equivalent
14024to the use of @code{-gnatyy} as described above, that is all
14025built-in standard style check options are enabled.
14026
14027The switch @code{-gnatyN} clears any previously set style checks.
14028
14029@node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
14030@anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{f9}@anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{104}
14031@subsection Run-Time Checks
14032
14033
14034@geindex Division by zero
14035
14036@geindex Access before elaboration
14037
14038@geindex Checks
14039@geindex division by zero
14040
14041@geindex Checks
14042@geindex access before elaboration
14043
14044@geindex Checks
14045@geindex stack overflow checking
14046
14047By default, the following checks are suppressed: stack overflow
14048checks, and checks for access before elaboration on subprogram
14049calls. All other checks, including overflow checks, range checks and
14050array bounds checks, are turned on by default. The following @code{gcc}
14051switches refine this default behavior.
14052
14053@geindex -gnatp (gcc)
14054
14055
14056@table @asis
14057
14058@item @code{-gnatp}
14059
14060@geindex Suppressing checks
14061
14062@geindex Checks
14063@geindex suppressing
14064
14065This switch causes the unit to be compiled
14066as though @code{pragma Suppress (All_checks)}
14067had been present in the source. Validity checks are also eliminated (in
14068other words @code{-gnatp} also implies @code{-gnatVn}.
14069Use this switch to improve the performance
14070of the code at the expense of safety in the presence of invalid data or
14071program bugs.
14072
14073Note that when checks are suppressed, the compiler is allowed, but not
14074required, to omit the checking code. If the run-time cost of the
14075checking code is zero or near-zero, the compiler will generate it even
14076if checks are suppressed. In particular, if the compiler can prove
14077that a certain check will necessarily fail, it will generate code to
14078do an unconditional 'raise', even if checks are suppressed. The
14079compiler warns in this case. Another case in which checks may not be
14080eliminated is when they are embedded in certain run-time routines such
14081as math library routines.
14082
14083Of course, run-time checks are omitted whenever the compiler can prove
14084that they will not fail, whether or not checks are suppressed.
14085
14086Note that if you suppress a check that would have failed, program
14087execution is erroneous, which means the behavior is totally
14088unpredictable. The program might crash, or print wrong answers, or
14089do anything else. It might even do exactly what you wanted it to do
14090(and then it might start failing mysteriously next week or next
14091year). The compiler will generate code based on the assumption that
14092the condition being checked is true, which can result in erroneous
14093execution if that assumption is wrong.
14094
14095The checks subject to suppression include all the checks defined by the Ada
14096standard, the additional implementation defined checks @code{Alignment_Check},
14097@code{Duplicated_Tag_Check}, @code{Predicate_Check}, @code{Container_Checks}, @code{Tampering_Check},
14098and @code{Validity_Check}, as well as any checks introduced using @code{pragma Check_Name}.
14099Note that @code{Atomic_Synchronization} is not automatically suppressed by use of this option.
14100
14101If the code depends on certain checks being active, you can use
14102pragma @code{Unsuppress} either as a configuration pragma or as
14103a local pragma to make sure that a specified check is performed
14104even if @code{gnatp} is specified.
14105
14106The @code{-gnatp} switch has no effect if a subsequent
14107@code{-gnat-p} switch appears.
14108@end table
14109
14110@geindex -gnat-p (gcc)
14111
14112@geindex Suppressing checks
14113
14114@geindex Checks
14115@geindex suppressing
14116
14117@geindex Suppress
14118
14119
14120@table @asis
14121
14122@item @code{-gnat-p}
14123
14124This switch cancels the effect of a previous @code{gnatp} switch.
14125@end table
14126
14127@geindex -gnato?? (gcc)
14128
14129@geindex Overflow checks
14130
14131@geindex Overflow mode
14132
14133@geindex Check
14134@geindex overflow
14135
14136
14137@table @asis
14138
14139@item @code{-gnato??}
14140
14141This switch controls the mode used for computing intermediate
14142arithmetic integer operations, and also enables overflow checking.
14143For a full description of overflow mode and checking control, see
14144the 'Overflow Check Handling in GNAT' appendix in this
14145User's Guide.
14146
14147Overflow checks are always enabled by this switch. The argument
14148controls the mode, using the codes
14149
14150
14151@table @asis
14152
14153@item @emph{1 = STRICT}
14154
14155In STRICT mode, intermediate operations are always done using the
14156base type, and overflow checking ensures that the result is within
14157the base type range.
14158
14159@item @emph{2 = MINIMIZED}
14160
14161In MINIMIZED mode, overflows in intermediate operations are avoided
14162where possible by using a larger integer type for the computation
14163(typically @code{Long_Long_Integer}). Overflow checking ensures that
14164the result fits in this larger integer type.
14165
14166@item @emph{3 = ELIMINATED}
14167
14168In ELIMINATED mode, overflows in intermediate operations are avoided
14169by using multi-precision arithmetic. In this case, overflow checking
14170has no effect on intermediate operations (since overflow is impossible).
14171@end table
14172
14173If two digits are present after @code{-gnato} then the first digit
14174sets the mode for expressions outside assertions, and the second digit
14175sets the mode for expressions within assertions. Here assertions is used
14176in the technical sense (which includes for example precondition and
14177postcondition expressions).
14178
14179If one digit is present, the corresponding mode is applicable to both
14180expressions within and outside assertion expressions.
14181
14182If no digits are present, the default is to enable overflow checks
14183and set STRICT mode for both kinds of expressions. This is compatible
14184with the use of @code{-gnato} in previous versions of GNAT.
14185
14186@geindex Machine_Overflows
14187
14188Note that the @code{-gnato??} switch does not affect the code generated
14189for any floating-point operations; it applies only to integer semantics.
14190For floating-point, GNAT has the @code{Machine_Overflows}
14191attribute set to @code{False} and the normal mode of operation is to
14192generate IEEE NaN and infinite values on overflow or invalid operations
14193(such as dividing 0.0 by 0.0).
14194
14195The reason that we distinguish overflow checking from other kinds of
14196range constraint checking is that a failure of an overflow check, unlike
14197for example the failure of a range check, can result in an incorrect
14198value, but cannot cause random memory destruction (like an out of range
14199subscript), or a wild jump (from an out of range case value). Overflow
14200checking is also quite expensive in time and space, since in general it
14201requires the use of double length arithmetic.
14202
14203Note again that the default is @code{-gnato11} (equivalent to @code{-gnato1}),
14204so overflow checking is performed in STRICT mode by default.
14205@end table
14206
14207@geindex -gnatE (gcc)
14208
14209@geindex Elaboration checks
14210
14211@geindex Check
14212@geindex elaboration
14213
14214
14215@table @asis
14216
14217@item @code{-gnatE}
14218
14219Enables dynamic checks for access-before-elaboration
14220on subprogram calls and generic instantiations.
14221Note that @code{-gnatE} is not necessary for safety, because in the
14222default mode, GNAT ensures statically that the checks would not fail.
14223For full details of the effect and use of this switch,
14224@ref{1c,,Compiling with gcc}.
14225@end table
14226
14227@geindex -fstack-check (gcc)
14228
14229@geindex Stack Overflow Checking
14230
14231@geindex Checks
14232@geindex stack overflow checking
14233
14234
14235@table @asis
14236
14237@item @code{-fstack-check}
14238
14239Activates stack overflow checking. For full details of the effect and use of
14240this switch see @ref{f4,,Stack Overflow Checking}.
14241@end table
14242
14243@geindex Unsuppress
14244
14245The setting of these switches only controls the default setting of the
14246checks. You may modify them using either @code{Suppress} (to remove
14247checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
14248the program source.
14249
14250@node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
14251@anchor{gnat_ugn/building_executable_programs_with_gnat id20}@anchor{105}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-syntax-checking}@anchor{106}
14252@subsection Using @code{gcc} for Syntax Checking
14253
14254
14255@geindex -gnats (gcc)
14256
14257
14258@table @asis
14259
14260@item @code{-gnats}
14261
14262The @code{s} stands for 'syntax'.
14263
14264Run GNAT in syntax checking only mode. For
14265example, the command
14266
14267@example
14268$ gcc -c -gnats x.adb
14269@end example
14270
14271compiles file @code{x.adb} in syntax-check-only mode. You can check a
14272series of files in a single command
14273, and can use wild cards to specify such a group of files.
14274Note that you must specify the @code{-c} (compile
14275only) flag in addition to the @code{-gnats} flag.
14276
14277You may use other switches in conjunction with @code{-gnats}. In
14278particular, @code{-gnatl} and @code{-gnatv} are useful to control the
14279format of any generated error messages.
14280
14281When the source file is empty or contains only empty lines and/or comments,
14282the output is a warning:
14283
14284@example
14285$ gcc -c -gnats -x ada toto.txt
14286toto.txt:1:01: warning: empty file, contains no compilation units
14287$
14288@end example
14289
14290Otherwise, the output is simply the error messages, if any. No object file or
14291ALI file is generated by a syntax-only compilation. Also, no units other
14292than the one specified are accessed. For example, if a unit @code{X}
14293@emph{with}s a unit @code{Y}, compiling unit @code{X} in syntax
14294check only mode does not access the source file containing unit
14295@code{Y}.
14296
14297@geindex Multiple units
14298@geindex syntax checking
14299
14300Normally, GNAT allows only a single unit in a source file. However, this
14301restriction does not apply in syntax-check-only mode, and it is possible
14302to check a file containing multiple compilation units concatenated
14303together. This is primarily used by the @code{gnatchop} utility
14304(@ref{36,,Renaming Files with gnatchop}).
14305@end table
14306
14307@node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
14308@anchor{gnat_ugn/building_executable_programs_with_gnat id21}@anchor{107}@anchor{gnat_ugn/building_executable_programs_with_gnat using-gcc-for-semantic-checking}@anchor{108}
14309@subsection Using @code{gcc} for Semantic Checking
14310
14311
14312@geindex -gnatc (gcc)
14313
14314
14315@table @asis
14316
14317@item @code{-gnatc}
14318
14319The @code{c} stands for 'check'.
14320Causes the compiler to operate in semantic check mode,
14321with full checking for all illegalities specified in the
14322Ada Reference Manual, but without generation of any object code
14323(no object file is generated).
14324
14325Because dependent files must be accessed, you must follow the GNAT
14326semantic restrictions on file structuring to operate in this mode:
14327
14328
14329@itemize *
14330
14331@item
14332The needed source files must be accessible
14333(see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
14334
14335@item
14336Each file must contain only one compilation unit.
14337
14338@item
14339The file name and unit name must match (@ref{52,,File Naming Rules}).
14340@end itemize
14341
14342The output consists of error messages as appropriate. No object file is
14343generated. An @code{ALI} file is generated for use in the context of
14344cross-reference tools, but this file is marked as not being suitable
14345for binding (since no object file is generated).
14346The checking corresponds exactly to the notion of
14347legality in the Ada Reference Manual.
14348
14349Any unit can be compiled in semantics-checking-only mode, including
14350units that would not normally be compiled (subunits,
14351and specifications where a separate body is present).
14352@end table
14353
14354@node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14355@anchor{gnat_ugn/building_executable_programs_with_gnat compiling-different-versions-of-ada}@anchor{6}@anchor{gnat_ugn/building_executable_programs_with_gnat id22}@anchor{109}
14356@subsection Compiling Different Versions of Ada
14357
14358
14359The switches described in this section allow you to explicitly specify
14360the version of the Ada language that your programs are written in.
14361The default mode is Ada 2012,
14362but you can also specify Ada 95, Ada 2005 mode, or
14363indicate Ada 83 compatibility mode.
14364
14365@geindex Compatibility with Ada 83
14366
14367@geindex -gnat83 (gcc)
14368
14369@geindex ACVC
14370@geindex Ada 83 tests
14371
14372@geindex Ada 83 mode
14373
14374
14375@table @asis
14376
14377@item @code{-gnat83} (Ada 83 Compatibility Mode)
14378
14379Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14380specifies that the program is to be compiled in Ada 83 mode. With
14381@code{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14382semantics where this can be done easily.
14383It is not possible to guarantee this switch does a perfect
14384job; some subtle tests, such as are
14385found in earlier ACVC tests (and that have been removed from the ACATS suite
14386for Ada 95), might not compile correctly.
14387Nevertheless, this switch may be useful in some circumstances, for example
14388where, due to contractual reasons, existing code needs to be maintained
14389using only Ada 83 features.
14390
14391With few exceptions (most notably the need to use @code{<>} on
14392unconstrained
14393@geindex Generic formal parameters
14394generic formal parameters,
14395the use of the new Ada 95 / Ada 2005
14396reserved words, and the use of packages
14397with optional bodies), it is not necessary to specify the
14398@code{-gnat83} switch when compiling Ada 83 programs, because, with rare
14399exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14400a correct Ada 83 program is usually also a correct program
14401in these later versions of the language standard. For further information
14402please refer to the @emph{Compatibility and Porting Guide} chapter in the
14403@cite{GNAT Reference Manual}.
14404@end table
14405
14406@geindex -gnat95 (gcc)
14407
14408@geindex Ada 95 mode
14409
14410
14411@table @asis
14412
14413@item @code{-gnat95} (Ada 95 mode)
14414
14415This switch directs the compiler to implement the Ada 95 version of the
14416language.
14417Since Ada 95 is almost completely upwards
14418compatible with Ada 83, Ada 83 programs may generally be compiled using
14419this switch (see the description of the @code{-gnat83} switch for further
14420information about Ada 83 mode).
14421If an Ada 2005 program is compiled in Ada 95 mode,
14422uses of the new Ada 2005 features will cause error
14423messages or warnings.
14424
14425This switch also can be used to cancel the effect of a previous
14426@code{-gnat83}, @code{-gnat05/2005}, or @code{-gnat12/2012}
14427switch earlier in the command line.
14428@end table
14429
14430@geindex -gnat05 (gcc)
14431
14432@geindex -gnat2005 (gcc)
14433
14434@geindex Ada 2005 mode
14435
14436
14437@table @asis
14438
14439@item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14440
14441This switch directs the compiler to implement the Ada 2005 version of the
14442language, as documented in the official Ada standards document.
14443Since Ada 2005 is almost completely upwards
14444compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14445may generally be compiled using this switch (see the description of the
14446@code{-gnat83} and @code{-gnat95} switches for further
14447information).
14448@end table
14449
14450@geindex -gnat12 (gcc)
14451
14452@geindex -gnat2012 (gcc)
14453
14454@geindex Ada 2012 mode
14455
14456
14457@table @asis
14458
14459@item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14460
14461This switch directs the compiler to implement the Ada 2012 version of the
14462language (also the default).
14463Since Ada 2012 is almost completely upwards
14464compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14465Ada 83 and Ada 95 programs
14466may generally be compiled using this switch (see the description of the
14467@code{-gnat83}, @code{-gnat95}, and @code{-gnat05/2005} switches
14468for further information).
14469@end table
14470
14471@geindex -gnatX (gcc)
14472
14473@geindex Ada language extensions
14474
14475@geindex GNAT extensions
14476
14477
14478@table @asis
14479
14480@item @code{-gnatX} (Enable GNAT Extensions)
14481
14482This switch directs the compiler to implement the latest version of the
14483language (currently Ada 2012) and also to enable certain GNAT implementation
14484extensions that are not part of any Ada standard. For a full list of these
14485extensions, see the GNAT reference manual.
14486@end table
14487
14488@node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14489@anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{48}
14490@subsection Character Set Control
14491
14492
14493@geindex -gnati (gcc)
14494
14495
14496@table @asis
14497
14498@item @code{-gnati@emph{c}}
14499
14500Normally GNAT recognizes the Latin-1 character set in source program
14501identifiers, as described in the Ada Reference Manual.
14502This switch causes
14503GNAT to recognize alternate character sets in identifiers. @code{c} is a
14504single character  indicating the character set, as follows:
14505
14506
14507@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14508@item
14509
14510@emph{1}
14511
14512@tab
14513
14514ISO 8859-1 (Latin-1) identifiers
14515
14516@item
14517
14518@emph{2}
14519
14520@tab
14521
14522ISO 8859-2 (Latin-2) letters allowed in identifiers
14523
14524@item
14525
14526@emph{3}
14527
14528@tab
14529
14530ISO 8859-3 (Latin-3) letters allowed in identifiers
14531
14532@item
14533
14534@emph{4}
14535
14536@tab
14537
14538ISO 8859-4 (Latin-4) letters allowed in identifiers
14539
14540@item
14541
14542@emph{5}
14543
14544@tab
14545
14546ISO 8859-5 (Cyrillic) letters allowed in identifiers
14547
14548@item
14549
14550@emph{9}
14551
14552@tab
14553
14554ISO 8859-15 (Latin-9) letters allowed in identifiers
14555
14556@item
14557
14558@emph{p}
14559
14560@tab
14561
14562IBM PC letters (code page 437) allowed in identifiers
14563
14564@item
14565
14566@emph{8}
14567
14568@tab
14569
14570IBM PC letters (code page 850) allowed in identifiers
14571
14572@item
14573
14574@emph{f}
14575
14576@tab
14577
14578Full upper-half codes allowed in identifiers
14579
14580@item
14581
14582@emph{n}
14583
14584@tab
14585
14586No upper-half codes allowed in identifiers
14587
14588@item
14589
14590@emph{w}
14591
14592@tab
14593
14594Wide-character codes (that is, codes greater than 255)
14595allowed in identifiers
14596
14597@end multitable
14598
14599
14600See @ref{3e,,Foreign Language Representation} for full details on the
14601implementation of these character sets.
14602@end table
14603
14604@geindex -gnatW (gcc)
14605
14606
14607@table @asis
14608
14609@item @code{-gnatW@emph{e}}
14610
14611Specify the method of encoding for wide characters.
14612@code{e} is one of the following:
14613
14614
14615@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14616@item
14617
14618@emph{h}
14619
14620@tab
14621
14622Hex encoding (brackets coding also recognized)
14623
14624@item
14625
14626@emph{u}
14627
14628@tab
14629
14630Upper half encoding (brackets encoding also recognized)
14631
14632@item
14633
14634@emph{s}
14635
14636@tab
14637
14638Shift/JIS encoding (brackets encoding also recognized)
14639
14640@item
14641
14642@emph{e}
14643
14644@tab
14645
14646EUC encoding (brackets encoding also recognized)
14647
14648@item
14649
14650@emph{8}
14651
14652@tab
14653
14654UTF-8 encoding (brackets encoding also recognized)
14655
14656@item
14657
14658@emph{b}
14659
14660@tab
14661
14662Brackets encoding only (default value)
14663
14664@end multitable
14665
14666
14667For full details on these encoding
14668methods see @ref{4e,,Wide_Character Encodings}.
14669Note that brackets coding is always accepted, even if one of the other
14670options is specified, so for example @code{-gnatW8} specifies that both
14671brackets and UTF-8 encodings will be recognized. The units that are
14672with'ed directly or indirectly will be scanned using the specified
14673representation scheme, and so if one of the non-brackets scheme is
14674used, it must be used consistently throughout the program. However,
14675since brackets encoding is always recognized, it may be conveniently
14676used in standard libraries, allowing these libraries to be used with
14677any of the available coding schemes.
14678
14679Note that brackets encoding only applies to program text. Within comments,
14680brackets are considered to be normal graphic characters, and bracket sequences
14681are never recognized as wide characters.
14682
14683If no @code{-gnatW?} parameter is present, then the default
14684representation is normally Brackets encoding only. However, if the
14685first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14686byte order mark or BOM for UTF-8), then these three characters are
14687skipped and the default representation for the file is set to UTF-8.
14688
14689Note that the wide character representation that is specified (explicitly
14690or by default) for the main program also acts as the default encoding used
14691for Wide_Text_IO files if not specifically overridden by a WCEM form
14692parameter.
14693@end table
14694
14695When no @code{-gnatW?} is specified, then characters (other than wide
14696characters represented using brackets notation) are treated as 8-bit
14697Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14698and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14699characters in the range 16#00#..16#1F# are not accepted in program text
14700or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14701in program text, but allowed and ignored in comments. Note in particular
14702that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14703as an end of line in this default mode. If your source program contains
14704instances of the NEL character used as a line terminator,
14705you must use UTF-8 encoding for the whole
14706source program. In default mode, all lines must be ended by a standard
14707end of line sequence (CR, CR/LF, or LF).
14708
14709Note that the convention of simply accepting all upper half characters in
14710comments means that programs that use standard ASCII for program text, but
14711UTF-8 encoding for comments are accepted in default mode, providing that the
14712comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14713This is a common mode for many programs with foreign language comments.
14714
14715@node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14716@anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{10b}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{10c}
14717@subsection File Naming Control
14718
14719
14720@geindex -gnatk (gcc)
14721
14722
14723@table @asis
14724
14725@item @code{-gnatk@emph{n}}
14726
14727Activates file name 'krunching'. @code{n}, a decimal integer in the range
147281-999, indicates the maximum allowable length of a file name (not
14729including the @code{.ads} or @code{.adb} extension). The default is not
14730to enable file name krunching.
14731
14732For the source file naming rules, @ref{52,,File Naming Rules}.
14733@end table
14734
14735@node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14736@anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{10d}@anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{10e}
14737@subsection Subprogram Inlining Control
14738
14739
14740@geindex -gnatn (gcc)
14741
14742
14743@table @asis
14744
14745@item @code{-gnatn[12]}
14746
14747The @code{n} here is intended to suggest the first syllable of the word 'inline'.
14748GNAT recognizes and processes @code{Inline} pragmas. However, for inlining to
14749actually occur, optimization must be enabled and, by default, inlining of
14750subprograms across units is not performed. If you want to additionally
14751enable inlining of subprograms specified by pragma @code{Inline} across units,
14752you must also specify this switch.
14753
14754In the absence of this switch, GNAT does not attempt inlining across units
14755and does not access the bodies of subprograms for which @code{pragma Inline} is
14756specified if they are not in the current unit.
14757
14758You can optionally specify the inlining level: 1 for moderate inlining across
14759units, which is a good compromise between compilation times and performances
14760at run time, or 2 for full inlining across units, which may bring about
14761longer compilation times. If no inlining level is specified, the compiler will
14762pick it based on the optimization level: 1 for @code{-O1}, @code{-O2} or
14763@code{-Os} and 2 for @code{-O3}.
14764
14765If you specify this switch the compiler will access these bodies,
14766creating an extra source dependency for the resulting object file, and
14767where possible, the call will be inlined.
14768For further details on when inlining is possible
14769see @ref{10f,,Inlining of Subprograms}.
14770@end table
14771
14772@geindex -gnatN (gcc)
14773
14774
14775@table @asis
14776
14777@item @code{-gnatN}
14778
14779This switch activates front-end inlining which also
14780generates additional dependencies.
14781
14782When using a gcc-based back end (in practice this means using any version
14783of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
14784@code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
14785Historically front end inlining was more extensive than the gcc back end
14786inlining, but that is no longer the case.
14787@end table
14788
14789@node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14790@anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{110}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{111}
14791@subsection Auxiliary Output Control
14792
14793
14794@geindex -gnatt (gcc)
14795
14796@geindex Writing internal trees
14797
14798@geindex Internal trees
14799@geindex writing to file
14800
14801
14802@table @asis
14803
14804@item @code{-gnatt}
14805
14806Causes GNAT to write the internal tree for a unit to a file (with the
14807extension @code{.adt}.
14808This not normally required, but is used by separate analysis tools.
14809Typically
14810these tools do the necessary compilations automatically, so you should
14811not have to specify this switch in normal operation.
14812Note that the combination of switches @code{-gnatct}
14813generates a tree in the form required by ASIS applications.
14814@end table
14815
14816@geindex -gnatu (gcc)
14817
14818
14819@table @asis
14820
14821@item @code{-gnatu}
14822
14823Print a list of units required by this compilation on @code{stdout}.
14824The listing includes all units on which the unit being compiled depends
14825either directly or indirectly.
14826@end table
14827
14828@geindex -pass-exit-codes (gcc)
14829
14830
14831@table @asis
14832
14833@item @code{-pass-exit-codes}
14834
14835If this switch is not used, the exit code returned by @code{gcc} when
14836compiling multiple files indicates whether all source files have
14837been successfully used to generate object files or not.
14838
14839When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
14840exit status and allows an integrated development environment to better
14841react to a compilation failure. Those exit status are:
14842
14843
14844@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14845@item
14846
14847@emph{5}
14848
14849@tab
14850
14851There was an error in at least one source file.
14852
14853@item
14854
14855@emph{3}
14856
14857@tab
14858
14859At least one source file did not generate an object file.
14860
14861@item
14862
14863@emph{2}
14864
14865@tab
14866
14867The compiler died unexpectedly (internal error for example).
14868
14869@item
14870
14871@emph{0}
14872
14873@tab
14874
14875An object file has been generated for every source file.
14876
14877@end multitable
14878
14879@end table
14880
14881@node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
14882@anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{112}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{113}
14883@subsection Debugging Control
14884
14885
14886@quotation
14887
14888@geindex Debugging options
14889@end quotation
14890
14891@geindex -gnatd (gcc)
14892
14893
14894@table @asis
14895
14896@item @code{-gnatd@emph{x}}
14897
14898Activate internal debugging switches. @code{x} is a letter or digit, or
14899string of letters or digits, which specifies the type of debugging
14900outputs desired. Normally these are used only for internal development
14901or system debugging purposes. You can find full documentation for these
14902switches in the body of the @code{Debug} unit in the compiler source
14903file @code{debug.adb}.
14904@end table
14905
14906@geindex -gnatG (gcc)
14907
14908
14909@table @asis
14910
14911@item @code{-gnatG[=@emph{nn}]}
14912
14913This switch causes the compiler to generate auxiliary output containing
14914a pseudo-source listing of the generated expanded code. Like most Ada
14915compilers, GNAT works by first transforming the high level Ada code into
14916lower level constructs. For example, tasking operations are transformed
14917into calls to the tasking run-time routines. A unique capability of GNAT
14918is to list this expanded code in a form very close to normal Ada source.
14919This is very useful in understanding the implications of various Ada
14920usage on the efficiency of the generated code. There are many cases in
14921Ada (e.g., the use of controlled types), where simple Ada statements can
14922generate a lot of run-time code. By using @code{-gnatG} you can identify
14923these cases, and consider whether it may be desirable to modify the coding
14924approach to improve efficiency.
14925
14926The optional parameter @code{nn} if present after -gnatG specifies an
14927alternative maximum line length that overrides the normal default of 72.
14928This value is in the range 40-999999, values less than 40 being silently
14929reset to 40. The equal sign is optional.
14930
14931The format of the output is very similar to standard Ada source, and is
14932easily understood by an Ada programmer. The following special syntactic
14933additions correspond to low level features used in the generated code that
14934do not have any exact analogies in pure Ada source form. The following
14935is a partial list of these special constructions. See the spec
14936of package @code{Sprint} in file @code{sprint.ads} for a full list.
14937
14938@geindex -gnatL (gcc)
14939
14940If the switch @code{-gnatL} is used in conjunction with
14941@code{-gnatG}, then the original source lines are interspersed
14942in the expanded source (as comment lines with the original line number).
14943
14944
14945@table @asis
14946
14947@item @code{new @emph{xxx} [storage_pool = @emph{yyy}]}
14948
14949Shows the storage pool being used for an allocator.
14950
14951@item @code{at end @emph{procedure-name};}
14952
14953Shows the finalization (cleanup) procedure for a scope.
14954
14955@item @code{(if @emph{expr} then @emph{expr} else @emph{expr})}
14956
14957Conditional expression equivalent to the @code{x?y:z} construction in C.
14958
14959@item @code{@emph{target}^(@emph{source})}
14960
14961A conversion with floating-point truncation instead of rounding.
14962
14963@item @code{@emph{target}?(@emph{source})}
14964
14965A conversion that bypasses normal Ada semantic checking. In particular
14966enumeration types and fixed-point types are treated simply as integers.
14967
14968@item @code{@emph{target}?^(@emph{source})}
14969
14970Combines the above two cases.
14971@end table
14972
14973@code{@emph{x} #/ @emph{y}}
14974
14975@code{@emph{x} #mod @emph{y}}
14976
14977@code{@emph{x} # @emph{y}}
14978
14979
14980@table @asis
14981
14982@item @code{@emph{x} #rem @emph{y}}
14983
14984A division or multiplication of fixed-point values which are treated as
14985integers without any kind of scaling.
14986
14987@item @code{free @emph{expr} [storage_pool = @emph{xxx}]}
14988
14989Shows the storage pool associated with a @code{free} statement.
14990
14991@item @code{[subtype or type declaration]}
14992
14993Used to list an equivalent declaration for an internally generated
14994type that is referenced elsewhere in the listing.
14995
14996@item @code{freeze @emph{type-name} [@emph{actions}]}
14997
14998Shows the point at which @code{type-name} is frozen, with possible
14999associated actions to be performed at the freeze point.
15000
15001@item @code{reference @emph{itype}}
15002
15003Reference (and hence definition) to internal type @code{itype}.
15004
15005@item @code{@emph{function-name}! (@emph{arg}, @emph{arg}, @emph{arg})}
15006
15007Intrinsic function call.
15008
15009@item @code{@emph{label-name} : label}
15010
15011Declaration of label @code{labelname}.
15012
15013@item @code{#$ @emph{subprogram-name}}
15014
15015An implicit call to a run-time support routine
15016(to meet the requirement of H.3.1(9) in a
15017convenient manner).
15018
15019@item @code{@emph{expr} && @emph{expr} && @emph{expr} ... && @emph{expr}}
15020
15021A multiple concatenation (same effect as @code{expr} & @code{expr} &
15022@code{expr}, but handled more efficiently).
15023
15024@item @code{[constraint_error]}
15025
15026Raise the @code{Constraint_Error} exception.
15027
15028@item @code{@emph{expression}'reference}
15029
15030A pointer to the result of evaluating @{expression@}.
15031
15032@item @code{@emph{target-type}!(@emph{source-expression})}
15033
15034An unchecked conversion of @code{source-expression} to @code{target-type}.
15035
15036@item @code{[@emph{numerator}/@emph{denominator}]}
15037
15038Used to represent internal real literals (that) have no exact
15039representation in base 2-16 (for example, the result of compile time
15040evaluation of the expression 1.0/27.0).
15041@end table
15042@end table
15043
15044@geindex -gnatD (gcc)
15045
15046
15047@table @asis
15048
15049@item @code{-gnatD[=nn]}
15050
15051When used in conjunction with @code{-gnatG}, this switch causes
15052the expanded source, as described above for
15053@code{-gnatG} to be written to files with names
15054@code{xxx.dg}, where @code{xxx} is the normal file name,
15055instead of to the standard output file. For
15056example, if the source file name is @code{hello.adb}, then a file
15057@code{hello.adb.dg} will be written.  The debugging
15058information generated by the @code{gcc} @code{-g} switch
15059will refer to the generated @code{xxx.dg} file. This allows
15060you to do source level debugging using the generated code which is
15061sometimes useful for complex code, for example to find out exactly
15062which part of a complex construction raised an exception. This switch
15063also suppresses generation of cross-reference information (see
15064@code{-gnatx}) since otherwise the cross-reference information
15065would refer to the @code{.dg} file, which would cause
15066confusion since this is not the original source file.
15067
15068Note that @code{-gnatD} actually implies @code{-gnatG}
15069automatically, so it is not necessary to give both options.
15070In other words @code{-gnatD} is equivalent to @code{-gnatDG}).
15071
15072@geindex -gnatL (gcc)
15073
15074If the switch @code{-gnatL} is used in conjunction with
15075@code{-gnatDG}, then the original source lines are interspersed
15076in the expanded source (as comment lines with the original line number).
15077
15078The optional parameter @code{nn} if present after -gnatD specifies an
15079alternative maximum line length that overrides the normal default of 72.
15080This value is in the range 40-999999, values less than 40 being silently
15081reset to 40. The equal sign is optional.
15082@end table
15083
15084@geindex -gnatr (gcc)
15085
15086@geindex pragma Restrictions
15087
15088
15089@table @asis
15090
15091@item @code{-gnatr}
15092
15093This switch causes pragma Restrictions to be treated as Restriction_Warnings
15094so that violation of restrictions causes warnings rather than illegalities.
15095This is useful during the development process when new restrictions are added
15096or investigated. The switch also causes pragma Profile to be treated as
15097Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
15098restriction warnings rather than restrictions.
15099@end table
15100
15101@geindex -gnatR (gcc)
15102
15103
15104@table @asis
15105
15106@item @code{-gnatR[0|1|2|3|4][e][j][m][s]}
15107
15108This switch controls output from the compiler of a listing showing
15109representation information for declared types, objects and subprograms.
15110For @code{-gnatR0}, no information is output (equivalent to omitting
15111the @code{-gnatR} switch). For @code{-gnatR1} (which is the default,
15112so @code{-gnatR} with no parameter has the same effect), size and
15113alignment information is listed for declared array and record types.
15114
15115For @code{-gnatR2}, size and alignment information is listed for all
15116declared types and objects. The @code{Linker_Section} is also listed for any
15117entity for which the @code{Linker_Section} is set explicitly or implicitly (the
15118latter case occurs for objects of a type for which a @code{Linker_Section}
15119is set).
15120
15121For @code{-gnatR3}, symbolic expressions for values that are computed
15122at run time for records are included. These symbolic expressions have
15123a mostly obvious format with #n being used to represent the value of the
15124n'th discriminant. See source files @code{repinfo.ads/adb} in the
15125GNAT sources for full details on the format of @code{-gnatR3} output.
15126
15127For @code{-gnatR4}, information for relevant compiler-generated types
15128is also listed, i.e. when they are structurally part of other declared
15129types and objects.
15130
15131If the switch is followed by an @code{e} (e.g. @code{-gnatR2e}), then
15132extended representation information for record sub-components of records
15133is included.
15134
15135If the switch is followed by an @code{m} (e.g. @code{-gnatRm}), then
15136subprogram conventions and parameter passing mechanisms for all the
15137subprograms are included.
15138
15139If the switch is followed by a @code{j} (e.g., @code{-gnatRj}), then
15140the output is in the JSON data interchange format specified by the
15141ECMA-404 standard. The semantic description of this JSON output is
15142available in the specification of the Repinfo unit present in the
15143compiler sources.
15144
15145If the switch is followed by an @code{s} (e.g., @code{-gnatR3s}), then
15146the output is to a file with the name @code{file.rep} where file is
15147the name of the corresponding source file, except if @cite{j`} is also
15148specified, in which case the file name is @code{file.json}.
15149
15150Note that it is possible for record components to have zero size. In
15151this case, the component clause uses an obvious extension of permitted
15152Ada syntax, for example @code{at 0 range 0 .. -1}.
15153@end table
15154
15155@geindex -gnatS (gcc)
15156
15157
15158@table @asis
15159
15160@item @code{-gnatS}
15161
15162The use of the switch @code{-gnatS} for an
15163Ada compilation will cause the compiler to output a
15164representation of package Standard in a form very
15165close to standard Ada. It is not quite possible to
15166do this entirely in standard Ada (since new
15167numeric base types cannot be created in standard
15168Ada), but the output is easily
15169readable to any Ada programmer, and is useful to
15170determine the characteristics of target dependent
15171types in package Standard.
15172@end table
15173
15174@geindex -gnatx (gcc)
15175
15176
15177@table @asis
15178
15179@item @code{-gnatx}
15180
15181Normally the compiler generates full cross-referencing information in
15182the @code{ALI} file. This information is used by a number of tools,
15183including @code{gnatfind} and @code{gnatxref}. The @code{-gnatx} switch
15184suppresses this information. This saves some space and may slightly
15185speed up compilation, but means that these tools cannot be used.
15186@end table
15187
15188@geindex -fgnat-encodings (gcc)
15189
15190
15191@table @asis
15192
15193@item @code{-fgnat-encodings=[all|gdb|minimal]}
15194
15195This switch controls the balance between GNAT encodings and standard DWARF
15196emitted in the debug information.
15197
15198Historically, old debug formats like stabs were not powerful enough to
15199express some Ada types (for instance, variant records or fixed-point types).
15200To work around this, GNAT introduced proprietary encodings that embed the
15201missing information ("GNAT encodings").
15202
15203Recent versions of the DWARF debug information format are now able to
15204correctly describe most of these Ada constructs ("standard DWARF"). As
15205third-party tools started to use this format, GNAT has been enhanced to
15206generate it. However, most tools (including GDB) are still relying on GNAT
15207encodings.
15208
15209To support all tools, GNAT needs to be versatile about the balance between
15210generation of GNAT encodings and standard DWARF. This is what
15211@code{-fgnat-encodings} is about.
15212
15213
15214@itemize *
15215
15216@item
15217@code{=all}: Emit all GNAT encodings, and then emit as much standard DWARF as
15218possible so it does not conflict with GNAT encodings.
15219
15220@item
15221@code{=gdb}: Emit as much standard DWARF as possible as long as the current
15222GDB handles it. Emit GNAT encodings for the rest.
15223
15224@item
15225@code{=minimal}: Emit as much standard DWARF as possible and emit GNAT
15226encodings for the rest.
15227@end itemize
15228@end table
15229
15230@node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
15231@anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{114}@anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{115}
15232@subsection Exception Handling Control
15233
15234
15235GNAT uses two methods for handling exceptions at run time. The
15236@code{setjmp/longjmp} method saves the context when entering
15237a frame with an exception handler. Then when an exception is
15238raised, the context can be restored immediately, without the
15239need for tracing stack frames. This method provides very fast
15240exception propagation, but introduces significant overhead for
15241the use of exception handlers, even if no exception is raised.
15242
15243The other approach is called 'zero cost' exception handling.
15244With this method, the compiler builds static tables to describe
15245the exception ranges. No dynamic code is required when entering
15246a frame containing an exception handler. When an exception is
15247raised, the tables are used to control a back trace of the
15248subprogram invocation stack to locate the required exception
15249handler. This method has considerably poorer performance for
15250the propagation of exceptions, but there is no overhead for
15251exception handlers if no exception is raised. Note that in this
15252mode and in the context of mixed Ada and C/C++ programming,
15253to propagate an exception through a C/C++ code, the C/C++ code
15254must be compiled with the @code{-funwind-tables} GCC's
15255option.
15256
15257The following switches may be used to control which of the
15258two exception handling methods is used.
15259
15260@geindex --RTS=sjlj (gnatmake)
15261
15262
15263@table @asis
15264
15265@item @code{--RTS=sjlj}
15266
15267This switch causes the setjmp/longjmp run-time (when available) to be used
15268for exception handling. If the default
15269mechanism for the target is zero cost exceptions, then
15270this switch can be used to modify this default, and must be
15271used for all units in the partition.
15272This option is rarely used. One case in which it may be
15273advantageous is if you have an application where exception
15274raising is common and the overall performance of the
15275application is improved by favoring exception propagation.
15276@end table
15277
15278@geindex --RTS=zcx (gnatmake)
15279
15280@geindex Zero Cost Exceptions
15281
15282
15283@table @asis
15284
15285@item @code{--RTS=zcx}
15286
15287This switch causes the zero cost approach to be used
15288for exception handling. If this is the default mechanism for the
15289target (see below), then this switch is unneeded. If the default
15290mechanism for the target is setjmp/longjmp exceptions, then
15291this switch can be used to modify this default, and must be
15292used for all units in the partition.
15293This option can only be used if the zero cost approach
15294is available for the target in use, otherwise it will generate an error.
15295@end table
15296
15297The same option @code{--RTS} must be used both for @code{gcc}
15298and @code{gnatbind}. Passing this option to @code{gnatmake}
15299(@ref{dc,,Switches for gnatmake}) will ensure the required consistency
15300through the compilation and binding steps.
15301
15302@node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
15303@anchor{gnat_ugn/building_executable_programs_with_gnat id29}@anchor{116}@anchor{gnat_ugn/building_executable_programs_with_gnat units-to-sources-mapping-files}@anchor{f7}
15304@subsection Units to Sources Mapping Files
15305
15306
15307@geindex -gnatem (gcc)
15308
15309
15310@table @asis
15311
15312@item @code{-gnatem=@emph{path}}
15313
15314A mapping file is a way to communicate to the compiler two mappings:
15315from unit names to file names (without any directory information) and from
15316file names to path names (with full directory information). These mappings
15317are used by the compiler to short-circuit the path search.
15318
15319The use of mapping files is not required for correct operation of the
15320compiler, but mapping files can improve efficiency, particularly when
15321sources are read over a slow network connection. In normal operation,
15322you need not be concerned with the format or use of mapping files,
15323and the @code{-gnatem} switch is not a switch that you would use
15324explicitly. It is intended primarily for use by automatic tools such as
15325@code{gnatmake} running under the project file facility. The
15326description here of the format of mapping files is provided
15327for completeness and for possible use by other tools.
15328
15329A mapping file is a sequence of sets of three lines. In each set, the
15330first line is the unit name, in lower case, with @code{%s} appended
15331for specs and @code{%b} appended for bodies; the second line is the
15332file name; and the third line is the path name.
15333
15334Example:
15335
15336@example
15337main%b
15338main.2.ada
15339/gnat/project1/sources/main.2.ada
15340@end example
15341
15342When the switch @code{-gnatem} is specified, the compiler will
15343create in memory the two mappings from the specified file. If there is
15344any problem (nonexistent file, truncated file or duplicate entries),
15345no mapping will be created.
15346
15347Several @code{-gnatem} switches may be specified; however, only the
15348last one on the command line will be taken into account.
15349
15350When using a project file, @code{gnatmake} creates a temporary
15351mapping file and communicates it to the compiler using this switch.
15352@end table
15353
15354@node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
15355@anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{117}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{118}
15356@subsection Code Generation Control
15357
15358
15359The GCC technology provides a wide range of target dependent
15360@code{-m} switches for controlling
15361details of code generation with respect to different versions of
15362architectures. This includes variations in instruction sets (e.g.,
15363different members of the power pc family), and different requirements
15364for optimal arrangement of instructions (e.g., different members of
15365the x86 family). The list of available @code{-m} switches may be
15366found in the GCC documentation.
15367
15368Use of these @code{-m} switches may in some cases result in improved
15369code performance.
15370
15371The GNAT technology is tested and qualified without any
15372@code{-m} switches,
15373so generally the most reliable approach is to avoid the use of these
15374switches. However, we generally expect most of these switches to work
15375successfully with GNAT, and many customers have reported successful
15376use of these options.
15377
15378Our general advice is to avoid the use of @code{-m} switches unless
15379special needs lead to requirements in this area. In particular,
15380there is no point in using @code{-m} switches to improve performance
15381unless you actually see a performance improvement.
15382
15383@node Linker Switches,Binding with gnatbind,Compiler Switches,Building Executable Programs with GNAT
15384@anchor{gnat_ugn/building_executable_programs_with_gnat linker-switches}@anchor{119}@anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{11a}
15385@section Linker Switches
15386
15387
15388Linker switches can be specified after @code{-largs} builder switch.
15389
15390@geindex -fuse-ld=name
15391
15392
15393@table @asis
15394
15395@item @code{-fuse-ld=@emph{name}}
15396
15397Linker to be used. The default is @code{bfd} for @code{ld.bfd},
15398the alternative being @code{gold} for @code{ld.gold}. The later is
15399a more recent and faster linker, but only available on GNU/Linux
15400platforms.
15401@end table
15402
15403@node Binding with gnatbind,Linking with gnatlink,Linker Switches,Building Executable Programs with GNAT
15404@anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{1d}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{11b}
15405@section Binding with @code{gnatbind}
15406
15407
15408@geindex gnatbind
15409
15410This chapter describes the GNAT binder, @code{gnatbind}, which is used
15411to bind compiled GNAT objects.
15412
15413The @code{gnatbind} program performs four separate functions:
15414
15415
15416@itemize *
15417
15418@item
15419Checks that a program is consistent, in accordance with the rules in
15420Chapter 10 of the Ada Reference Manual. In particular, error
15421messages are generated if a program uses inconsistent versions of a
15422given unit.
15423
15424@item
15425Checks that an acceptable order of elaboration exists for the program
15426and issues an error message if it cannot find an order of elaboration
15427that satisfies the rules in Chapter 10 of the Ada Language Manual.
15428
15429@item
15430Generates a main program incorporating the given elaboration order.
15431This program is a small Ada package (body and spec) that
15432must be subsequently compiled
15433using the GNAT compiler. The necessary compilation step is usually
15434performed automatically by @code{gnatlink}. The two most important
15435functions of this program
15436are to call the elaboration routines of units in an appropriate order
15437and to call the main program.
15438
15439@item
15440Determines the set of object files required by the given main program.
15441This information is output in the forms of comments in the generated program,
15442to be read by the @code{gnatlink} utility used to link the Ada application.
15443@end itemize
15444
15445@menu
15446* Running gnatbind::
15447* Switches for gnatbind::
15448* Command-Line Access::
15449* Search Paths for gnatbind::
15450* Examples of gnatbind Usage::
15451
15452@end menu
15453
15454@node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15455@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{11c}@anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{11d}
15456@subsection Running @code{gnatbind}
15457
15458
15459The form of the @code{gnatbind} command is
15460
15461@example
15462$ gnatbind [ switches ] mainprog[.ali] [ switches ]
15463@end example
15464
15465where @code{mainprog.adb} is the Ada file containing the main program
15466unit body. @code{gnatbind} constructs an Ada
15467package in two files whose names are
15468@code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15469For example, if given the
15470parameter @code{hello.ali}, for a main program contained in file
15471@code{hello.adb}, the binder output files would be @code{b~hello.ads}
15472and @code{b~hello.adb}.
15473
15474When doing consistency checking, the binder takes into consideration
15475any source files it can locate. For example, if the binder determines
15476that the given main program requires the package @code{Pack}, whose
15477@code{.ALI}
15478file is @code{pack.ali} and whose corresponding source spec file is
15479@code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15480(using the same search path conventions as previously described for the
15481@code{gcc} command). If it can locate this source file, it checks that
15482the time stamps
15483or source checksums of the source and its references to in @code{ALI} files
15484match. In other words, any @code{ALI} files that mentions this spec must have
15485resulted from compiling this version of the source file (or in the case
15486where the source checksums match, a version close enough that the
15487difference does not matter).
15488
15489@geindex Source files
15490@geindex use by binder
15491
15492The effect of this consistency checking, which includes source files, is
15493that the binder ensures that the program is consistent with the latest
15494version of the source files that can be located at bind time. Editing a
15495source file without compiling files that depend on the source file cause
15496error messages to be generated by the binder.
15497
15498For example, suppose you have a main program @code{hello.adb} and a
15499package @code{P}, from file @code{p.ads} and you perform the following
15500steps:
15501
15502
15503@itemize *
15504
15505@item
15506Enter @code{gcc -c hello.adb} to compile the main program.
15507
15508@item
15509Enter @code{gcc -c p.ads} to compile package @code{P}.
15510
15511@item
15512Edit file @code{p.ads}.
15513
15514@item
15515Enter @code{gnatbind hello}.
15516@end itemize
15517
15518At this point, the file @code{p.ali} contains an out-of-date time stamp
15519because the file @code{p.ads} has been edited. The attempt at binding
15520fails, and the binder generates the following error messages:
15521
15522@example
15523error: "hello.adb" must be recompiled ("p.ads" has been modified)
15524error: "p.ads" has been modified and must be recompiled
15525@end example
15526
15527Now both files must be recompiled as indicated, and then the bind can
15528succeed, generating a main program. You need not normally be concerned
15529with the contents of this file, but for reference purposes a sample
15530binder output file is given in @ref{e,,Example of Binder Output File}.
15531
15532In most normal usage, the default mode of @code{gnatbind} which is to
15533generate the main package in Ada, as described in the previous section.
15534In particular, this means that any Ada programmer can read and understand
15535the generated main program. It can also be debugged just like any other
15536Ada code provided the @code{-g} switch is used for
15537@code{gnatbind} and @code{gnatlink}.
15538
15539@node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15540@anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{11e}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{11f}
15541@subsection Switches for @code{gnatbind}
15542
15543
15544The following switches are available with @code{gnatbind}; details will
15545be presented in subsequent sections.
15546
15547@geindex --version (gnatbind)
15548
15549
15550@table @asis
15551
15552@item @code{--version}
15553
15554Display Copyright and version, then exit disregarding all other options.
15555@end table
15556
15557@geindex --help (gnatbind)
15558
15559
15560@table @asis
15561
15562@item @code{--help}
15563
15564If @code{--version} was not used, display usage, then exit disregarding
15565all other options.
15566@end table
15567
15568@geindex -a (gnatbind)
15569
15570
15571@table @asis
15572
15573@item @code{-a}
15574
15575Indicates that, if supported by the platform, the adainit procedure should
15576be treated as an initialisation routine by the linker (a constructor). This
15577is intended to be used by the Project Manager to automatically initialize
15578shared Stand-Alone Libraries.
15579@end table
15580
15581@geindex -aO (gnatbind)
15582
15583
15584@table @asis
15585
15586@item @code{-aO}
15587
15588Specify directory to be searched for ALI files.
15589@end table
15590
15591@geindex -aI (gnatbind)
15592
15593
15594@table @asis
15595
15596@item @code{-aI}
15597
15598Specify directory to be searched for source file.
15599@end table
15600
15601@geindex -A (gnatbind)
15602
15603
15604@table @asis
15605
15606@item @code{-A[=@emph{filename}]}
15607
15608Output ALI list (to standard output or to the named file).
15609@end table
15610
15611@geindex -b (gnatbind)
15612
15613
15614@table @asis
15615
15616@item @code{-b}
15617
15618Generate brief messages to @code{stderr} even if verbose mode set.
15619@end table
15620
15621@geindex -c (gnatbind)
15622
15623
15624@table @asis
15625
15626@item @code{-c}
15627
15628Check only, no generation of binder output file.
15629@end table
15630
15631@geindex -dnn[k|m] (gnatbind)
15632
15633
15634@table @asis
15635
15636@item @code{-d@emph{nn}[k|m]}
15637
15638This switch can be used to change the default task stack size value
15639to a specified size @code{nn}, which is expressed in bytes by default, or
15640in kilobytes when suffixed with @code{k} or in megabytes when suffixed
15641with @code{m}.
15642In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15643in effect, to completing all task specs with
15644
15645@example
15646pragma Storage_Size (nn);
15647@end example
15648
15649When they do not already have such a pragma.
15650@end table
15651
15652@geindex -D (gnatbind)
15653
15654
15655@table @asis
15656
15657@item @code{-D@emph{nn}[k|m]}
15658
15659Set the default secondary stack size to @code{nn}. The suffix indicates whether
15660the size is in bytes (no suffix), kilobytes (@code{k} suffix) or megabytes
15661(@code{m} suffix).
15662
15663The secondary stack holds objects of unconstrained types that are returned by
15664functions, for example unconstrained Strings. The size of the secondary stack
15665can be dynamic or fixed depending on the target.
15666
15667For most targets, the secondary stack grows on demand and is implemented as
15668a chain of blocks in the heap. In this case, the default secondary stack size
15669determines the initial size of the secondary stack for each task and the
15670smallest amount the secondary stack can grow by.
15671
15672For Ravenscar, ZFP, and Cert run-times the size of the secondary stack is
15673fixed. This switch can be used to change the default size of these stacks.
15674The default secondary stack size can be overridden on a per-task basis if
15675individual tasks have different secondary stack requirements. This is
15676achieved through the Secondary_Stack_Size aspect that takes the size of the
15677secondary stack in bytes.
15678@end table
15679
15680@geindex -e (gnatbind)
15681
15682
15683@table @asis
15684
15685@item @code{-e}
15686
15687Output complete list of elaboration-order dependencies.
15688@end table
15689
15690@geindex -Ea (gnatbind)
15691
15692
15693@table @asis
15694
15695@item @code{-Ea}
15696
15697Store tracebacks in exception occurrences when the target supports it.
15698The "a" is for "address"; tracebacks will contain hexadecimal addresses,
15699unless symbolic tracebacks are enabled.
15700
15701See also the packages @code{GNAT.Traceback} and
15702@code{GNAT.Traceback.Symbolic} for more information.
15703Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
15704@code{gcc} option.
15705@end table
15706
15707@geindex -Es (gnatbind)
15708
15709
15710@table @asis
15711
15712@item @code{-Es}
15713
15714Store tracebacks in exception occurrences when the target supports it.
15715The "s" is for "symbolic"; symbolic tracebacks are enabled.
15716@end table
15717
15718@geindex -E (gnatbind)
15719
15720
15721@table @asis
15722
15723@item @code{-E}
15724
15725Currently the same as @code{-Ea}.
15726@end table
15727
15728@geindex -f (gnatbind)
15729
15730
15731@table @asis
15732
15733@item @code{-f@emph{elab-order}}
15734
15735Force elaboration order.
15736@end table
15737
15738@geindex -F (gnatbind)
15739
15740
15741@table @asis
15742
15743@item @code{-F}
15744
15745Force the checks of elaboration flags. @code{gnatbind} does not normally
15746generate checks of elaboration flags for the main executable, except when
15747a Stand-Alone Library is used. However, there are cases when this cannot be
15748detected by gnatbind. An example is importing an interface of a Stand-Alone
15749Library through a pragma Import and only specifying through a linker switch
15750this Stand-Alone Library. This switch is used to guarantee that elaboration
15751flag checks are generated.
15752@end table
15753
15754@geindex -h (gnatbind)
15755
15756
15757@table @asis
15758
15759@item @code{-h}
15760
15761Output usage (help) information.
15762
15763@geindex -H32 (gnatbind)
15764
15765@item @code{-H32}
15766
15767Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
15768For further details see @ref{120,,Dynamic Allocation Control}.
15769
15770@geindex -H64 (gnatbind)
15771
15772@geindex __gnat_malloc
15773
15774@item @code{-H64}
15775
15776Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
15777For further details see @ref{120,,Dynamic Allocation Control}.
15778
15779@geindex -I (gnatbind)
15780
15781@item @code{-I}
15782
15783Specify directory to be searched for source and ALI files.
15784
15785@geindex -I- (gnatbind)
15786
15787@item @code{-I-}
15788
15789Do not look for sources in the current directory where @code{gnatbind} was
15790invoked, and do not look for ALI files in the directory containing the
15791ALI file named in the @code{gnatbind} command line.
15792
15793@geindex -l (gnatbind)
15794
15795@item @code{-l}
15796
15797Output chosen elaboration order.
15798
15799@geindex -L (gnatbind)
15800
15801@item @code{-L@emph{xxx}}
15802
15803Bind the units for library building. In this case the @code{adainit} and
15804@code{adafinal} procedures (@ref{b4,,Binding with Non-Ada Main Programs})
15805are renamed to @code{@emph{xxx}init} and
15806@code{@emph{xxx}final}.
15807Implies -n.
15808(@ref{15,,GNAT and Libraries}, for more details.)
15809
15810@geindex -M (gnatbind)
15811
15812@item @code{-M@emph{xyz}}
15813
15814Rename generated main program from main to xyz. This option is
15815supported on cross environments only.
15816
15817@geindex -m (gnatbind)
15818
15819@item @code{-m@emph{n}}
15820
15821Limit number of detected errors or warnings to @code{n}, where @code{n} is
15822in the range 1..999999. The default value if no switch is
15823given is 9999. If the number of warnings reaches this limit, then a
15824message is output and further warnings are suppressed, the bind
15825continues in this case. If the number of errors reaches this
15826limit, then a message is output and the bind is abandoned.
15827A value of zero means that no limit is enforced. The equal
15828sign is optional.
15829
15830@geindex -n (gnatbind)
15831
15832@item @code{-n}
15833
15834No main program.
15835
15836@geindex -nostdinc (gnatbind)
15837
15838@item @code{-nostdinc}
15839
15840Do not look for sources in the system default directory.
15841
15842@geindex -nostdlib (gnatbind)
15843
15844@item @code{-nostdlib}
15845
15846Do not look for library files in the system default directory.
15847
15848@geindex --RTS (gnatbind)
15849
15850@item @code{--RTS=@emph{rts-path}}
15851
15852Specifies the default location of the run-time library. Same meaning as the
15853equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
15854
15855@geindex -o (gnatbind)
15856
15857@item @code{-o @emph{file}}
15858
15859Name the output file @code{file} (default is @code{b~`xxx}.adb`).
15860Note that if this option is used, then linking must be done manually,
15861gnatlink cannot be used.
15862
15863@geindex -O (gnatbind)
15864
15865@item @code{-O[=@emph{filename}]}
15866
15867Output object list (to standard output or to the named file).
15868
15869@geindex -p (gnatbind)
15870
15871@item @code{-p}
15872
15873Pessimistic (worst-case) elaboration order.
15874
15875@geindex -P (gnatbind)
15876
15877@item @code{-P}
15878
15879Generate binder file suitable for CodePeer.
15880
15881@geindex -R (gnatbind)
15882
15883@item @code{-R}
15884
15885Output closure source list, which includes all non-run-time units that are
15886included in the bind.
15887
15888@geindex -Ra (gnatbind)
15889
15890@item @code{-Ra}
15891
15892Like @code{-R} but the list includes run-time units.
15893
15894@geindex -s (gnatbind)
15895
15896@item @code{-s}
15897
15898Require all source files to be present.
15899
15900@geindex -S (gnatbind)
15901
15902@item @code{-S@emph{xxx}}
15903
15904Specifies the value to be used when detecting uninitialized scalar
15905objects with pragma Initialize_Scalars.
15906The @code{xxx} string specified with the switch is one of:
15907
15908
15909@itemize *
15910
15911@item
15912@code{in} for an invalid value.
15913
15914If zero is invalid for the discrete type in question,
15915then the scalar value is set to all zero bits.
15916For signed discrete types, the largest possible negative value of
15917the underlying scalar is set (i.e. a one bit followed by all zero bits).
15918For unsigned discrete types, the underlying scalar value is set to all
15919one bits. For floating-point types, a NaN value is set
15920(see body of package System.Scalar_Values for exact values).
15921
15922@item
15923@code{lo} for low value.
15924
15925If zero is invalid for the discrete type in question,
15926then the scalar value is set to all zero bits.
15927For signed discrete types, the largest possible negative value of
15928the underlying scalar is set (i.e. a one bit followed by all zero bits).
15929For unsigned discrete types, the underlying scalar value is set to all
15930zero bits. For floating-point, a small value is set
15931(see body of package System.Scalar_Values for exact values).
15932
15933@item
15934@code{hi} for high value.
15935
15936If zero is invalid for the discrete type in question,
15937then the scalar value is set to all one bits.
15938For signed discrete types, the largest possible positive value of
15939the underlying scalar is set (i.e. a zero bit followed by all one bits).
15940For unsigned discrete types, the underlying scalar value is set to all
15941one bits. For floating-point, a large value is set
15942(see body of package System.Scalar_Values for exact values).
15943
15944@item
15945@code{xx} for hex value (two hex digits).
15946
15947The underlying scalar is set to a value consisting of repeated bytes, whose
15948value corresponds to the given value. For example if @code{BF} is given,
15949then a 32-bit scalar value will be set to the bit patterm @code{16#BFBFBFBF#}.
15950@end itemize
15951
15952@geindex GNAT_INIT_SCALARS
15953
15954In addition, you can specify @code{-Sev} to indicate that the value is
15955to be set at run time. In this case, the program will look for an environment
15956variable of the form @code{GNAT_INIT_SCALARS=@emph{yy}}, where @code{yy} is one
15957of @code{in/lo/hi/@emph{xx}} with the same meanings as above.
15958If no environment variable is found, or if it does not have a valid value,
15959then the default is @code{in} (invalid values).
15960@end table
15961
15962@geindex -static (gnatbind)
15963
15964
15965@table @asis
15966
15967@item @code{-static}
15968
15969Link against a static GNAT run-time.
15970
15971@geindex -shared (gnatbind)
15972
15973@item @code{-shared}
15974
15975Link against a shared GNAT run-time when available.
15976
15977@geindex -t (gnatbind)
15978
15979@item @code{-t}
15980
15981Tolerate time stamp and other consistency errors.
15982
15983@geindex -T (gnatbind)
15984
15985@item @code{-T@emph{n}}
15986
15987Set the time slice value to @code{n} milliseconds. If the system supports
15988the specification of a specific time slice value, then the indicated value
15989is used. If the system does not support specific time slice values, but
15990does support some general notion of round-robin scheduling, then any
15991nonzero value will activate round-robin scheduling.
15992
15993A value of zero is treated specially. It turns off time
15994slicing, and in addition, indicates to the tasking run-time that the
15995semantics should match as closely as possible the Annex D
15996requirements of the Ada RM, and in particular sets the default
15997scheduling policy to @code{FIFO_Within_Priorities}.
15998
15999@geindex -u (gnatbind)
16000
16001@item @code{-u@emph{n}}
16002
16003Enable dynamic stack usage, with @code{n} results stored and displayed
16004at program termination. A result is generated when a task
16005terminates. Results that can't be stored are displayed on the fly, at
16006task termination. This option is currently not supported on Itanium
16007platforms. (See @ref{121,,Dynamic Stack Usage Analysis} for details.)
16008
16009@geindex -v (gnatbind)
16010
16011@item @code{-v}
16012
16013Verbose mode. Write error messages, header, summary output to
16014@code{stdout}.
16015
16016@geindex -V (gnatbind)
16017
16018@item @code{-V@emph{key}=@emph{value}}
16019
16020Store the given association of @code{key} to @code{value} in the bind environment.
16021Values stored this way can be retrieved at run time using
16022@code{GNAT.Bind_Environment}.
16023
16024@geindex -w (gnatbind)
16025
16026@item @code{-w@emph{x}}
16027
16028Warning mode; @code{x} = s/e for suppress/treat as error.
16029
16030@geindex -Wx (gnatbind)
16031
16032@item @code{-Wx@emph{e}}
16033
16034Override default wide character encoding for standard Text_IO files.
16035
16036@geindex -x (gnatbind)
16037
16038@item @code{-x}
16039
16040Exclude source files (check object consistency only).
16041
16042@geindex -Xnnn (gnatbind)
16043
16044@item @code{-X@emph{nnn}}
16045
16046Set default exit status value, normally 0 for POSIX compliance.
16047
16048@geindex -y (gnatbind)
16049
16050@item @code{-y}
16051
16052Enable leap seconds support in @code{Ada.Calendar} and its children.
16053
16054@geindex -z (gnatbind)
16055
16056@item @code{-z}
16057
16058No main subprogram.
16059@end table
16060
16061You may obtain this listing of switches by running @code{gnatbind} with
16062no arguments.
16063
16064@menu
16065* Consistency-Checking Modes::
16066* Binder Error Message Control::
16067* Elaboration Control::
16068* Output Control::
16069* Dynamic Allocation Control::
16070* Binding with Non-Ada Main Programs::
16071* Binding Programs with No Main Subprogram::
16072
16073@end menu
16074
16075@node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
16076@anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{122}@anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{123}
16077@subsubsection Consistency-Checking Modes
16078
16079
16080As described earlier, by default @code{gnatbind} checks
16081that object files are consistent with one another and are consistent
16082with any source files it can locate. The following switches control binder
16083access to sources.
16084
16085@quotation
16086
16087@geindex -s (gnatbind)
16088@end quotation
16089
16090
16091@table @asis
16092
16093@item @code{-s}
16094
16095Require source files to be present. In this mode, the binder must be
16096able to locate all source files that are referenced, in order to check
16097their consistency. In normal mode, if a source file cannot be located it
16098is simply ignored. If you specify this switch, a missing source
16099file is an error.
16100
16101@geindex -Wx (gnatbind)
16102
16103@item @code{-Wx@emph{e}}
16104
16105Override default wide character encoding for standard Text_IO files.
16106Normally the default wide character encoding method used for standard
16107[Wide_[Wide_]]Text_IO files is taken from the encoding specified for
16108the main source input (see description of switch
16109@code{-gnatWx} for the compiler). The
16110use of this switch for the binder (which has the same set of
16111possible arguments) overrides this default as specified.
16112
16113@geindex -x (gnatbind)
16114
16115@item @code{-x}
16116
16117Exclude source files. In this mode, the binder only checks that ALI
16118files are consistent with one another. Source files are not accessed.
16119The binder runs faster in this mode, and there is still a guarantee that
16120the resulting program is self-consistent.
16121If a source file has been edited since it was last compiled, and you
16122specify this switch, the binder will not detect that the object
16123file is out of date with respect to the source file. Note that this is the
16124mode that is automatically used by @code{gnatmake} because in this
16125case the checking against sources has already been performed by
16126@code{gnatmake} in the course of compilation (i.e., before binding).
16127@end table
16128
16129@node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
16130@anchor{gnat_ugn/building_executable_programs_with_gnat id36}@anchor{124}@anchor{gnat_ugn/building_executable_programs_with_gnat binder-error-message-control}@anchor{125}
16131@subsubsection Binder Error Message Control
16132
16133
16134The following switches provide control over the generation of error
16135messages from the binder:
16136
16137@quotation
16138
16139@geindex -v (gnatbind)
16140@end quotation
16141
16142
16143@table @asis
16144
16145@item @code{-v}
16146
16147Verbose mode. In the normal mode, brief error messages are generated to
16148@code{stderr}. If this switch is present, a header is written
16149to @code{stdout} and any error messages are directed to @code{stdout}.
16150All that is written to @code{stderr} is a brief summary message.
16151
16152@geindex -b (gnatbind)
16153
16154@item @code{-b}
16155
16156Generate brief error messages to @code{stderr} even if verbose mode is
16157specified. This is relevant only when used with the
16158@code{-v} switch.
16159
16160@geindex -m (gnatbind)
16161
16162@item @code{-m@emph{n}}
16163
16164Limits the number of error messages to @code{n}, a decimal integer in the
16165range 1-999. The binder terminates immediately if this limit is reached.
16166
16167@geindex -M (gnatbind)
16168
16169@item @code{-M@emph{xxx}}
16170
16171Renames the generated main program from @code{main} to @code{xxx}.
16172This is useful in the case of some cross-building environments, where
16173the actual main program is separate from the one generated
16174by @code{gnatbind}.
16175
16176@geindex -ws (gnatbind)
16177
16178@geindex Warnings
16179
16180@item @code{-ws}
16181
16182Suppress all warning messages.
16183
16184@geindex -we (gnatbind)
16185
16186@item @code{-we}
16187
16188Treat any warning messages as fatal errors.
16189
16190@geindex -t (gnatbind)
16191
16192@geindex Time stamp checks
16193@geindex in binder
16194
16195@geindex Binder consistency checks
16196
16197@geindex Consistency checks
16198@geindex in binder
16199
16200@item @code{-t}
16201
16202The binder performs a number of consistency checks including:
16203
16204
16205@itemize *
16206
16207@item
16208Check that time stamps of a given source unit are consistent
16209
16210@item
16211Check that checksums of a given source unit are consistent
16212
16213@item
16214Check that consistent versions of @code{GNAT} were used for compilation
16215
16216@item
16217Check consistency of configuration pragmas as required
16218@end itemize
16219
16220Normally failure of such checks, in accordance with the consistency
16221requirements of the Ada Reference Manual, causes error messages to be
16222generated which abort the binder and prevent the output of a binder
16223file and subsequent link to obtain an executable.
16224
16225The @code{-t} switch converts these error messages
16226into warnings, so that
16227binding and linking can continue to completion even in the presence of such
16228errors. The result may be a failed link (due to missing symbols), or a
16229non-functional executable which has undefined semantics.
16230
16231@cartouche
16232@quotation Note
16233This means that @code{-t} should be used only in unusual situations,
16234with extreme care.
16235@end quotation
16236@end cartouche
16237@end table
16238
16239@node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
16240@anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{126}@anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{127}
16241@subsubsection Elaboration Control
16242
16243
16244The following switches provide additional control over the elaboration
16245order. For full details see @ref{f,,Elaboration Order Handling in GNAT}.
16246
16247@geindex -f (gnatbind)
16248
16249
16250@table @asis
16251
16252@item @code{-f@emph{elab-order}}
16253
16254Force elaboration order.
16255
16256@code{elab-order} should be the name of a "forced elaboration order file", that
16257is, a text file containing library item names, one per line. A name of the
16258form "some.unit%s" or "some.unit (spec)" denotes the spec of Some.Unit. A
16259name of the form "some.unit%b" or "some.unit (body)" denotes the body of
16260Some.Unit. Each pair of lines is taken to mean that there is an elaboration
16261dependence of the second line on the first. For example, if the file
16262contains:
16263
16264@example
16265this (spec)
16266this (body)
16267that (spec)
16268that (body)
16269@end example
16270
16271then the spec of This will be elaborated before the body of This, and the
16272body of This will be elaborated before the spec of That, and the spec of That
16273will be elaborated before the body of That. The first and last of these three
16274dependences are already required by Ada rules, so this file is really just
16275forcing the body of This to be elaborated before the spec of That.
16276
16277The given order must be consistent with Ada rules, or else @code{gnatbind} will
16278give elaboration cycle errors. For example, if you say x (body) should be
16279elaborated before x (spec), there will be a cycle, because Ada rules require
16280x (spec) to be elaborated before x (body); you can't have the spec and body
16281both elaborated before each other.
16282
16283If you later add "with That;" to the body of This, there will be a cycle, in
16284which case you should erase either "this (body)" or "that (spec)" from the
16285above forced elaboration order file.
16286
16287Blank lines and Ada-style comments are ignored. Unit names that do not exist
16288in the program are ignored. Units in the GNAT predefined library are also
16289ignored.
16290
16291@geindex -p (gnatbind)
16292
16293@item @code{-p}
16294
16295Normally the binder attempts to choose an elaboration order that is
16296likely to minimize the likelihood of an elaboration order error resulting
16297in raising a @code{Program_Error} exception. This switch reverses the
16298action of the binder, and requests that it deliberately choose an order
16299that is likely to maximize the likelihood of an elaboration error.
16300This is useful in ensuring portability and avoiding dependence on
16301accidental fortuitous elaboration ordering.
16302
16303Normally it only makes sense to use the @code{-p}
16304switch if dynamic
16305elaboration checking is used (@code{-gnatE} switch used for compilation).
16306This is because in the default static elaboration mode, all necessary
16307@code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
16308These implicit pragmas are still respected by the binder in
16309@code{-p} mode, so a
16310safe elaboration order is assured.
16311
16312Note that @code{-p} is not intended for
16313production use; it is more for debugging/experimental use.
16314@end table
16315
16316@node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
16317@anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{128}@anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{129}
16318@subsubsection Output Control
16319
16320
16321The following switches allow additional control over the output
16322generated by the binder.
16323
16324@quotation
16325
16326@geindex -c (gnatbind)
16327@end quotation
16328
16329
16330@table @asis
16331
16332@item @code{-c}
16333
16334Check only. Do not generate the binder output file. In this mode the
16335binder performs all error checks but does not generate an output file.
16336
16337@geindex -e (gnatbind)
16338
16339@item @code{-e}
16340
16341Output complete list of elaboration-order dependencies, showing the
16342reason for each dependency. This output can be rather extensive but may
16343be useful in diagnosing problems with elaboration order. The output is
16344written to @code{stdout}.
16345
16346@geindex -h (gnatbind)
16347
16348@item @code{-h}
16349
16350Output usage information. The output is written to @code{stdout}.
16351
16352@geindex -K (gnatbind)
16353
16354@item @code{-K}
16355
16356Output linker options to @code{stdout}. Includes library search paths,
16357contents of pragmas Ident and Linker_Options, and libraries added
16358by @code{gnatbind}.
16359
16360@geindex -l (gnatbind)
16361
16362@item @code{-l}
16363
16364Output chosen elaboration order. The output is written to @code{stdout}.
16365
16366@geindex -O (gnatbind)
16367
16368@item @code{-O}
16369
16370Output full names of all the object files that must be linked to provide
16371the Ada component of the program. The output is written to @code{stdout}.
16372This list includes the files explicitly supplied and referenced by the user
16373as well as implicitly referenced run-time unit files. The latter are
16374omitted if the corresponding units reside in shared libraries. The
16375directory names for the run-time units depend on the system configuration.
16376
16377@geindex -o (gnatbind)
16378
16379@item @code{-o @emph{file}}
16380
16381Set name of output file to @code{file} instead of the normal
16382@code{b~`mainprog}.adb` default. Note that @code{file} denote the Ada
16383binder generated body filename.
16384Note that if this option is used, then linking must be done manually.
16385It is not possible to use gnatlink in this case, since it cannot locate
16386the binder file.
16387
16388@geindex -r (gnatbind)
16389
16390@item @code{-r}
16391
16392Generate list of @code{pragma Restrictions} that could be applied to
16393the current unit. This is useful for code audit purposes, and also may
16394be used to improve code generation in some cases.
16395@end table
16396
16397@node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
16398@anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{120}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{12a}
16399@subsubsection Dynamic Allocation Control
16400
16401
16402The heap control switches -- @code{-H32} and @code{-H64} --
16403determine whether dynamic allocation uses 32-bit or 64-bit memory.
16404They only affect compiler-generated allocations via @code{__gnat_malloc};
16405explicit calls to @code{malloc} and related functions from the C
16406run-time library are unaffected.
16407
16408
16409@table @asis
16410
16411@item @code{-H32}
16412
16413Allocate memory on 32-bit heap
16414
16415@item @code{-H64}
16416
16417Allocate memory on 64-bit heap.  This is the default
16418unless explicitly overridden by a @code{'Size} clause on the access type.
16419@end table
16420
16421These switches are only effective on VMS platforms.
16422
16423@node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
16424@anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-non-ada-main-programs}@anchor{b4}@anchor{gnat_ugn/building_executable_programs_with_gnat id40}@anchor{12b}
16425@subsubsection Binding with Non-Ada Main Programs
16426
16427
16428The description so far has assumed that the main
16429program is in Ada, and that the task of the binder is to generate a
16430corresponding function @code{main} that invokes this Ada main
16431program. GNAT also supports the building of executable programs where
16432the main program is not in Ada, but some of the called routines are
16433written in Ada and compiled using GNAT (@ref{44,,Mixed Language Programming}).
16434The following switch is used in this situation:
16435
16436@quotation
16437
16438@geindex -n (gnatbind)
16439@end quotation
16440
16441
16442@table @asis
16443
16444@item @code{-n}
16445
16446No main program. The main program is not in Ada.
16447@end table
16448
16449In this case, most of the functions of the binder are still required,
16450but instead of generating a main program, the binder generates a file
16451containing the following callable routines:
16452
16453@quotation
16454
16455@geindex adainit
16456
16457
16458@table @asis
16459
16460@item @code{adainit}
16461
16462You must call this routine to initialize the Ada part of the program by
16463calling the necessary elaboration routines. A call to @code{adainit} is
16464required before the first call to an Ada subprogram.
16465
16466Note that it is assumed that the basic execution environment must be setup
16467to be appropriate for Ada execution at the point where the first Ada
16468subprogram is called. In particular, if the Ada code will do any
16469floating-point operations, then the FPU must be setup in an appropriate
16470manner. For the case of the x86, for example, full precision mode is
16471required. The procedure GNAT.Float_Control.Reset may be used to ensure
16472that the FPU is in the right state.
16473@end table
16474
16475@geindex adafinal
16476
16477
16478@table @asis
16479
16480@item @code{adafinal}
16481
16482You must call this routine to perform any library-level finalization
16483required by the Ada subprograms. A call to @code{adafinal} is required
16484after the last call to an Ada subprogram, and before the program
16485terminates.
16486@end table
16487@end quotation
16488
16489@geindex -n (gnatbind)
16490
16491@geindex Binder
16492@geindex multiple input files
16493
16494If the @code{-n} switch
16495is given, more than one ALI file may appear on
16496the command line for @code{gnatbind}. The normal @code{closure}
16497calculation is performed for each of the specified units. Calculating
16498the closure means finding out the set of units involved by tracing
16499@emph{with} references. The reason it is necessary to be able to
16500specify more than one ALI file is that a given program may invoke two or
16501more quite separate groups of Ada units.
16502
16503The binder takes the name of its output file from the last specified ALI
16504file, unless overridden by the use of the @code{-o file}.
16505
16506@geindex -o (gnatbind)
16507
16508The output is an Ada unit in source form that can be compiled with GNAT.
16509This compilation occurs automatically as part of the @code{gnatlink}
16510processing.
16511
16512Currently the GNAT run-time requires a FPU using 80 bits mode
16513precision. Under targets where this is not the default it is required to
16514call GNAT.Float_Control.Reset before using floating point numbers (this
16515include float computation, float input and output) in the Ada code. A
16516side effect is that this could be the wrong mode for the foreign code
16517where floating point computation could be broken after this call.
16518
16519@node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16520@anchor{gnat_ugn/building_executable_programs_with_gnat binding-programs-with-no-main-subprogram}@anchor{12c}@anchor{gnat_ugn/building_executable_programs_with_gnat id41}@anchor{12d}
16521@subsubsection Binding Programs with No Main Subprogram
16522
16523
16524It is possible to have an Ada program which does not have a main
16525subprogram. This program will call the elaboration routines of all the
16526packages, then the finalization routines.
16527
16528The following switch is used to bind programs organized in this manner:
16529
16530@quotation
16531
16532@geindex -z (gnatbind)
16533@end quotation
16534
16535
16536@table @asis
16537
16538@item @code{-z}
16539
16540Normally the binder checks that the unit name given on the command line
16541corresponds to a suitable main subprogram. When this switch is used,
16542a list of ALI files can be given, and the execution of the program
16543consists of elaboration of these units in an appropriate order. Note
16544that the default wide character encoding method for standard Text_IO
16545files is always set to Brackets if this switch is set (you can use
16546the binder switch
16547@code{-Wx} to override this default).
16548@end table
16549
16550@node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16551@anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{12e}@anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{12f}
16552@subsection Command-Line Access
16553
16554
16555The package @code{Ada.Command_Line} provides access to the command-line
16556arguments and program name. In order for this interface to operate
16557correctly, the two variables
16558
16559@example
16560int gnat_argc;
16561char **gnat_argv;
16562@end example
16563
16564@geindex gnat_argv
16565
16566@geindex gnat_argc
16567
16568are declared in one of the GNAT library routines. These variables must
16569be set from the actual @code{argc} and @code{argv} values passed to the
16570main program. With no @emph{n} present, @code{gnatbind}
16571generates the C main program to automatically set these variables.
16572If the @emph{n} switch is used, there is no automatic way to
16573set these variables. If they are not set, the procedures in
16574@code{Ada.Command_Line} will not be available, and any attempt to use
16575them will raise @code{Constraint_Error}. If command line access is
16576required, your main program must set @code{gnat_argc} and
16577@code{gnat_argv} from the @code{argc} and @code{argv} values passed to
16578it.
16579
16580@node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16581@anchor{gnat_ugn/building_executable_programs_with_gnat search-paths-for-gnatbind}@anchor{8c}@anchor{gnat_ugn/building_executable_programs_with_gnat id43}@anchor{130}
16582@subsection Search Paths for @code{gnatbind}
16583
16584
16585The binder takes the name of an ALI file as its argument and needs to
16586locate source files as well as other ALI files to verify object consistency.
16587
16588For source files, it follows exactly the same search rules as @code{gcc}
16589(see @ref{89,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16590directories searched are:
16591
16592
16593@itemize *
16594
16595@item
16596The directory containing the ALI file named in the command line, unless
16597the switch @code{-I-} is specified.
16598
16599@item
16600All directories specified by @code{-I}
16601switches on the @code{gnatbind}
16602command line, in the order given.
16603
16604@geindex ADA_PRJ_OBJECTS_FILE
16605
16606@item
16607Each of the directories listed in the text file whose name is given
16608by the
16609@geindex ADA_PRJ_OBJECTS_FILE
16610@geindex environment variable; ADA_PRJ_OBJECTS_FILE
16611@code{ADA_PRJ_OBJECTS_FILE} environment variable.
16612
16613@geindex ADA_PRJ_OBJECTS_FILE
16614@geindex environment variable; ADA_PRJ_OBJECTS_FILE
16615@code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16616driver when project files are used. It should not normally be set
16617by other means.
16618
16619@geindex ADA_OBJECTS_PATH
16620
16621@item
16622Each of the directories listed in the value of the
16623@geindex ADA_OBJECTS_PATH
16624@geindex environment variable; ADA_OBJECTS_PATH
16625@code{ADA_OBJECTS_PATH} environment variable.
16626Construct this value
16627exactly as the
16628@geindex PATH
16629@geindex environment variable; PATH
16630@code{PATH} environment variable: a list of directory
16631names separated by colons (semicolons when working with the NT version
16632of GNAT).
16633
16634@item
16635The content of the @code{ada_object_path} file which is part of the GNAT
16636installation tree and is used to store standard libraries such as the
16637GNAT Run-Time Library (RTL) unless the switch @code{-nostdlib} is
16638specified. See @ref{87,,Installing a library}
16639@end itemize
16640
16641@geindex -I (gnatbind)
16642
16643@geindex -aI (gnatbind)
16644
16645@geindex -aO (gnatbind)
16646
16647In the binder the switch @code{-I}
16648is used to specify both source and
16649library file paths. Use @code{-aI}
16650instead if you want to specify
16651source paths only, and @code{-aO}
16652if you want to specify library paths
16653only. This means that for the binder
16654@code{-I@emph{dir}} is equivalent to
16655@code{-aI@emph{dir}}
16656@code{-aO`@emph{dir}}.
16657The binder generates the bind file (a C language source file) in the
16658current working directory.
16659
16660@geindex Ada
16661
16662@geindex System
16663
16664@geindex Interfaces
16665
16666@geindex GNAT
16667
16668The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
16669children make up the GNAT Run-Time Library, together with the package
16670GNAT and its children, which contain a set of useful additional
16671library functions provided by GNAT. The sources for these units are
16672needed by the compiler and are kept together in one directory. The ALI
16673files and object files generated by compiling the RTL are needed by the
16674binder and the linker and are kept together in one directory, typically
16675different from the directory containing the sources. In a normal
16676installation, you need not specify these directory names when compiling
16677or binding. Either the environment variables or the built-in defaults
16678cause these files to be found.
16679
16680Besides simplifying access to the RTL, a major use of search paths is
16681in compiling sources from multiple directories. This can make
16682development environments much more flexible.
16683
16684@node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16685@anchor{gnat_ugn/building_executable_programs_with_gnat id44}@anchor{131}@anchor{gnat_ugn/building_executable_programs_with_gnat examples-of-gnatbind-usage}@anchor{132}
16686@subsection Examples of @code{gnatbind} Usage
16687
16688
16689Here are some examples of @code{gnatbind} invovations:
16690
16691@quotation
16692
16693@example
16694gnatbind hello
16695@end example
16696
16697The main program @code{Hello} (source program in @code{hello.adb}) is
16698bound using the standard switch settings. The generated main program is
16699@code{b~hello.adb}. This is the normal, default use of the binder.
16700
16701@example
16702gnatbind hello -o mainprog.adb
16703@end example
16704
16705The main program @code{Hello} (source program in @code{hello.adb}) is
16706bound using the standard switch settings. The generated main program is
16707@code{mainprog.adb} with the associated spec in
16708@code{mainprog.ads}. Note that you must specify the body here not the
16709spec. Note that if this option is used, then linking must be done manually,
16710since gnatlink will not be able to find the generated file.
16711@end quotation
16712
16713@node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16714@anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{133}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{1e}
16715@section Linking with @code{gnatlink}
16716
16717
16718@geindex gnatlink
16719
16720This chapter discusses @code{gnatlink}, a tool that links
16721an Ada program and builds an executable file. This utility
16722invokes the system linker (via the @code{gcc} command)
16723with a correct list of object files and library references.
16724@code{gnatlink} automatically determines the list of files and
16725references for the Ada part of a program. It uses the binder file
16726generated by the @code{gnatbind} to determine this list.
16727
16728@menu
16729* Running gnatlink::
16730* Switches for gnatlink::
16731
16732@end menu
16733
16734@node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16735@anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{134}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{135}
16736@subsection Running @code{gnatlink}
16737
16738
16739The form of the @code{gnatlink} command is
16740
16741@example
16742$ gnatlink [ switches ] mainprog [.ali]
16743           [ non-Ada objects ] [ linker options ]
16744@end example
16745
16746The arguments of @code{gnatlink} (switches, main @code{ALI} file,
16747non-Ada objects
16748or linker options) may be in any order, provided that no non-Ada object may
16749be mistaken for a main @code{ALI} file.
16750Any file name @code{F} without the @code{.ali}
16751extension will be taken as the main @code{ALI} file if a file exists
16752whose name is the concatenation of @code{F} and @code{.ali}.
16753
16754@code{mainprog.ali} references the ALI file of the main program.
16755The @code{.ali} extension of this file can be omitted. From this
16756reference, @code{gnatlink} locates the corresponding binder file
16757@code{b~mainprog.adb} and, using the information in this file along
16758with the list of non-Ada objects and linker options, constructs a
16759linker command file to create the executable.
16760
16761The arguments other than the @code{gnatlink} switches and the main
16762@code{ALI} file are passed to the linker uninterpreted.
16763They typically include the names of
16764object files for units written in other languages than Ada and any library
16765references required to resolve references in any of these foreign language
16766units, or in @code{Import} pragmas in any Ada units.
16767
16768@code{linker options} is an optional list of linker specific
16769switches.
16770The default linker called by gnatlink is @code{gcc} which in
16771turn calls the appropriate system linker.
16772
16773One useful option for the linker is @code{-s}: it reduces the size of the
16774executable by removing all symbol table and relocation information from the
16775executable.
16776
16777Standard options for the linker such as @code{-lmy_lib} or
16778@code{-Ldir} can be added as is.
16779For options that are not recognized by
16780@code{gcc} as linker options, use the @code{gcc} switches
16781@code{-Xlinker} or @code{-Wl,}.
16782
16783Refer to the GCC documentation for
16784details.
16785
16786Here is an example showing how to generate a linker map:
16787
16788@example
16789$ gnatlink my_prog -Wl,-Map,MAPFILE
16790@end example
16791
16792Using @code{linker options} it is possible to set the program stack and
16793heap size.
16794See @ref{136,,Setting Stack Size from gnatlink} and
16795@ref{137,,Setting Heap Size from gnatlink}.
16796
16797@code{gnatlink} determines the list of objects required by the Ada
16798program and prepends them to the list of objects passed to the linker.
16799@code{gnatlink} also gathers any arguments set by the use of
16800@code{pragma Linker_Options} and adds them to the list of arguments
16801presented to the linker.
16802
16803@node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
16804@anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{138}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{139}
16805@subsection Switches for @code{gnatlink}
16806
16807
16808The following switches are available with the @code{gnatlink} utility:
16809
16810@geindex --version (gnatlink)
16811
16812
16813@table @asis
16814
16815@item @code{--version}
16816
16817Display Copyright and version, then exit disregarding all other options.
16818@end table
16819
16820@geindex --help (gnatlink)
16821
16822
16823@table @asis
16824
16825@item @code{--help}
16826
16827If @code{--version} was not used, display usage, then exit disregarding
16828all other options.
16829@end table
16830
16831@geindex Command line length
16832
16833@geindex -f (gnatlink)
16834
16835
16836@table @asis
16837
16838@item @code{-f}
16839
16840On some targets, the command line length is limited, and @code{gnatlink}
16841will generate a separate file for the linker if the list of object files
16842is too long.
16843The @code{-f} switch forces this file
16844to be generated even if
16845the limit is not exceeded. This is useful in some cases to deal with
16846special situations where the command line length is exceeded.
16847@end table
16848
16849@geindex Debugging information
16850@geindex including
16851
16852@geindex -g (gnatlink)
16853
16854
16855@table @asis
16856
16857@item @code{-g}
16858
16859The option to include debugging information causes the Ada bind file (in
16860other words, @code{b~mainprog.adb}) to be compiled with @code{-g}.
16861In addition, the binder does not delete the @code{b~mainprog.adb},
16862@code{b~mainprog.o} and @code{b~mainprog.ali} files.
16863Without @code{-g}, the binder removes these files by default.
16864@end table
16865
16866@geindex -n (gnatlink)
16867
16868
16869@table @asis
16870
16871@item @code{-n}
16872
16873Do not compile the file generated by the binder. This may be used when
16874a link is rerun with different options, but there is no need to recompile
16875the binder file.
16876@end table
16877
16878@geindex -v (gnatlink)
16879
16880
16881@table @asis
16882
16883@item @code{-v}
16884
16885Verbose mode. Causes additional information to be output, including a full
16886list of the included object files.
16887This switch option is most useful when you want
16888to see what set of object files are being used in the link step.
16889@end table
16890
16891@geindex -v -v (gnatlink)
16892
16893
16894@table @asis
16895
16896@item @code{-v -v}
16897
16898Very verbose mode. Requests that the compiler operate in verbose mode when
16899it compiles the binder file, and that the system linker run in verbose mode.
16900@end table
16901
16902@geindex -o (gnatlink)
16903
16904
16905@table @asis
16906
16907@item @code{-o @emph{exec-name}}
16908
16909@code{exec-name} specifies an alternate name for the generated
16910executable program. If this switch is omitted, the executable has the same
16911name as the main unit. For example, @code{gnatlink try.ali} creates
16912an executable called @code{try}.
16913@end table
16914
16915@geindex -B (gnatlink)
16916
16917
16918@table @asis
16919
16920@item @code{-B@emph{dir}}
16921
16922Load compiler executables (for example, @code{gnat1}, the Ada compiler)
16923from @code{dir} instead of the default location. Only use this switch
16924when multiple versions of the GNAT compiler are available.
16925See the @code{Directory Options} section in @cite{The_GNU_Compiler_Collection}
16926for further details. You would normally use the @code{-b} or
16927@code{-V} switch instead.
16928@end table
16929
16930@geindex -M (gnatlink)
16931
16932
16933@table @asis
16934
16935@item @code{-M}
16936
16937When linking an executable, create a map file. The name of the map file
16938has the same name as the executable with extension ".map".
16939@end table
16940
16941@geindex -M= (gnatlink)
16942
16943
16944@table @asis
16945
16946@item @code{-M=@emph{mapfile}}
16947
16948When linking an executable, create a map file. The name of the map file is
16949@code{mapfile}.
16950@end table
16951
16952@geindex --GCC=compiler_name (gnatlink)
16953
16954
16955@table @asis
16956
16957@item @code{--GCC=@emph{compiler_name}}
16958
16959Program used for compiling the binder file. The default is
16960@code{gcc}. You need to use quotes around @code{compiler_name} if
16961@code{compiler_name} contains spaces or other separator characters.
16962As an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to
16963use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
16964inserted after your command name. Thus in the above example the compiler
16965command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
16966A limitation of this syntax is that the name and path name of the executable
16967itself must not include any embedded spaces. If the compiler executable is
16968different from the default one (gcc or <prefix>-gcc), then the back-end
16969switches in the ALI file are not used to compile the binder generated source.
16970For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
16971switches will be used for @code{--GCC="gcc -gnatv"}. If several
16972@code{--GCC=compiler_name} are used, only the last @code{compiler_name}
16973is taken into account. However, all the additional switches are also taken
16974into account. Thus,
16975@code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
16976@code{--GCC="bar -x -y -z -t"}.
16977@end table
16978
16979@geindex --LINK= (gnatlink)
16980
16981
16982@table @asis
16983
16984@item @code{--LINK=@emph{name}}
16985
16986@code{name} is the name of the linker to be invoked. This is especially
16987useful in mixed language programs since languages such as C++ require
16988their own linker to be used. When this switch is omitted, the default
16989name for the linker is @code{gcc}. When this switch is used, the
16990specified linker is called instead of @code{gcc} with exactly the same
16991parameters that would have been passed to @code{gcc} so if the desired
16992linker requires different parameters it is necessary to use a wrapper
16993script that massages the parameters before invoking the real linker. It
16994may be useful to control the exact invocation by using the verbose
16995switch.
16996@end table
16997
16998@node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
16999@anchor{gnat_ugn/building_executable_programs_with_gnat using-the-gnu-make-utility}@anchor{1f}@anchor{gnat_ugn/building_executable_programs_with_gnat id48}@anchor{13a}
17000@section Using the GNU @code{make} Utility
17001
17002
17003@geindex make (GNU)
17004@geindex GNU make
17005
17006This chapter offers some examples of makefiles that solve specific
17007problems. It does not explain how to write a makefile, nor does it try to replace the
17008@code{gnatmake} utility (@ref{1b,,Building with gnatmake}).
17009
17010All the examples in this section are specific to the GNU version of
17011make. Although @code{make} is a standard utility, and the basic language
17012is the same, these examples use some advanced features found only in
17013@code{GNU make}.
17014
17015@menu
17016* Using gnatmake in a Makefile::
17017* Automatically Creating a List of Directories::
17018* Generating the Command Line Switches::
17019* Overcoming Command Line Length Limits::
17020
17021@end menu
17022
17023@node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
17024@anchor{gnat_ugn/building_executable_programs_with_gnat using-gnatmake-in-a-makefile}@anchor{13b}@anchor{gnat_ugn/building_executable_programs_with_gnat id49}@anchor{13c}
17025@subsection Using gnatmake in a Makefile
17026
17027
17028@c index makefile (GNU make)
17029
17030Complex project organizations can be handled in a very powerful way by
17031using GNU make combined with gnatmake. For instance, here is a Makefile
17032which allows you to build each subsystem of a big project into a separate
17033shared library. Such a makefile allows you to significantly reduce the link
17034time of very big applications while maintaining full coherence at
17035each step of the build process.
17036
17037The list of dependencies are handled automatically by
17038@code{gnatmake}. The Makefile is simply used to call gnatmake in each of
17039the appropriate directories.
17040
17041Note that you should also read the example on how to automatically
17042create the list of directories
17043(@ref{13d,,Automatically Creating a List of Directories})
17044which might help you in case your project has a lot of subdirectories.
17045
17046@example
17047## This Makefile is intended to be used with the following directory
17048## configuration:
17049##  - The sources are split into a series of csc (computer software components)
17050##    Each of these csc is put in its own directory.
17051##    Their name are referenced by the directory names.
17052##    They will be compiled into shared library (although this would also work
17053##    with static libraries
17054##  - The main program (and possibly other packages that do not belong to any
17055##    csc is put in the top level directory (where the Makefile is).
17056##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
17057##                    \\_ second_csc (sources) __ lib (will contain the library)
17058##                    \\_ ...
17059## Although this Makefile is build for shared library, it is easy to modify
17060## to build partial link objects instead (modify the lines with -shared and
17061## gnatlink below)
17062##
17063## With this makefile, you can change any file in the system or add any new
17064## file, and everything will be recompiled correctly (only the relevant shared
17065## objects will be recompiled, and the main program will be re-linked).
17066
17067# The list of computer software component for your project. This might be
17068# generated automatically.
17069CSC_LIST=aa bb cc
17070
17071# Name of the main program (no extension)
17072MAIN=main
17073
17074# If we need to build objects with -fPIC, uncomment the following line
17075#NEED_FPIC=-fPIC
17076
17077# The following variable should give the directory containing libgnat.so
17078# You can get this directory through 'gnatls -v'. This is usually the last
17079# directory in the Object_Path.
17080GLIB=...
17081
17082# The directories for the libraries
17083# (This macro expands the list of CSC to the list of shared libraries, you
17084# could simply use the expanded form:
17085# LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17086LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17087
17088$@{MAIN@}: objects $@{LIB_DIR@}
17089    gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17090    gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17091
17092objects::
17093    # recompile the sources
17094    gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17095
17096# Note: In a future version of GNAT, the following commands will be simplified
17097# by a new tool, gnatmlib
17098$@{LIB_DIR@}:
17099    mkdir -p $@{dir $@@ @}
17100    cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17101    cd $@{dir $@@ @} && cp -f ../*.ali .
17102
17103# The dependencies for the modules
17104# Note that we have to force the expansion of *.o, since in some cases
17105# make won't be able to do it itself.
17106aa/lib/libaa.so: $@{wildcard aa/*.o@}
17107bb/lib/libbb.so: $@{wildcard bb/*.o@}
17108cc/lib/libcc.so: $@{wildcard cc/*.o@}
17109
17110# Make sure all of the shared libraries are in the path before starting the
17111# program
17112run::
17113    LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17114
17115clean::
17116    $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17117    $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17118    $@{RM@} $@{CSC_LIST:%=%/*.o@}
17119    $@{RM@} *.o *.ali $@{MAIN@}
17120@end example
17121
17122@node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
17123@anchor{gnat_ugn/building_executable_programs_with_gnat id50}@anchor{13e}@anchor{gnat_ugn/building_executable_programs_with_gnat automatically-creating-a-list-of-directories}@anchor{13d}
17124@subsection Automatically Creating a List of Directories
17125
17126
17127In most makefiles, you will have to specify a list of directories, and
17128store it in a variable. For small projects, it is often easier to
17129specify each of them by hand, since you then have full control over what
17130is the proper order for these directories, which ones should be
17131included.
17132
17133However, in larger projects, which might involve hundreds of
17134subdirectories, it might be more convenient to generate this list
17135automatically.
17136
17137The example below presents two methods. The first one, although less
17138general, gives you more control over the list. It involves wildcard
17139characters, that are automatically expanded by @code{make}. Its
17140shortcoming is that you need to explicitly specify some of the
17141organization of your project, such as for instance the directory tree
17142depth, whether some directories are found in a separate tree, etc.
17143
17144The second method is the most general one. It requires an external
17145program, called @code{find}, which is standard on all Unix systems. All
17146the directories found under a given root directory will be added to the
17147list.
17148
17149@example
17150# The examples below are based on the following directory hierarchy:
17151# All the directories can contain any number of files
17152# ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17153#                       ->  ab
17154#                       ->  ac
17155#                ->  b  ->  ba  ->  baa
17156#                       ->  bb
17157#                       ->  bc
17158# This Makefile creates a variable called DIRS, that can be reused any time
17159# you need this list (see the other examples in this section)
17160
17161# The root of your project's directory hierarchy
17162ROOT_DIRECTORY=.
17163
17164####
17165# First method: specify explicitly the list of directories
17166# This allows you to specify any subset of all the directories you need.
17167####
17168
17169DIRS := a/aa/ a/ab/ b/ba/
17170
17171####
17172# Second method: use wildcards
17173# Note that the argument(s) to wildcard below should end with a '/'.
17174# Since wildcards also return file names, we have to filter them out
17175# to avoid duplicate directory names.
17176# We thus use make's `@w{`}dir`@w{`} and `@w{`}sort`@w{`} functions.
17177# It sets DIRs to the following value (note that the directories aaa and baa
17178# are not given, unless you change the arguments to wildcard).
17179# DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17180####
17181
17182DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17183                    $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17184
17185####
17186# Third method: use an external program
17187# This command is much faster if run on local disks, avoiding NFS slowdowns.
17188# This is the most complete command: it sets DIRs to the following value:
17189# DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17190####
17191
17192DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17193@end example
17194
17195@node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
17196@anchor{gnat_ugn/building_executable_programs_with_gnat id51}@anchor{13f}@anchor{gnat_ugn/building_executable_programs_with_gnat generating-the-command-line-switches}@anchor{140}
17197@subsection Generating the Command Line Switches
17198
17199
17200Once you have created the list of directories as explained in the
17201previous section (@ref{13d,,Automatically Creating a List of Directories}),
17202you can easily generate the command line arguments to pass to gnatmake.
17203
17204For the sake of completeness, this example assumes that the source path
17205is not the same as the object path, and that you have two separate lists
17206of directories.
17207
17208@example
17209# see "Automatically creating a list of directories" to create
17210# these variables
17211SOURCE_DIRS=
17212OBJECT_DIRS=
17213
17214GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17215GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17216
17217all:
17218        gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17219@end example
17220
17221@node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
17222@anchor{gnat_ugn/building_executable_programs_with_gnat overcoming-command-line-length-limits}@anchor{141}@anchor{gnat_ugn/building_executable_programs_with_gnat id52}@anchor{142}
17223@subsection Overcoming Command Line Length Limits
17224
17225
17226One problem that might be encountered on big projects is that many
17227operating systems limit the length of the command line. It is thus hard to give
17228gnatmake the list of source and object directories.
17229
17230This example shows how you can set up environment variables, which will
17231make @code{gnatmake} behave exactly as if the directories had been
17232specified on the command line, but have a much higher length limit (or
17233even none on most systems).
17234
17235It assumes that you have created a list of directories in your Makefile,
17236using one of the methods presented in
17237@ref{13d,,Automatically Creating a List of Directories}.
17238For the sake of completeness, we assume that the object
17239path (where the ALI files are found) is different from the sources patch.
17240
17241Note a small trick in the Makefile below: for efficiency reasons, we
17242create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17243expanded immediately by @code{make}. This way we overcome the standard
17244make behavior which is to expand the variables only when they are
17245actually used.
17246
17247On Windows, if you are using the standard Windows command shell, you must
17248replace colons with semicolons in the assignments to these variables.
17249
17250@example
17251# In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17252# This is the same thing as putting the -I arguments on the command line.
17253# (the equivalent of using -aI on the command line would be to define
17254#  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17255# You can of course have different values for these variables.
17256#
17257# Note also that we need to keep the previous values of these variables, since
17258# they might have been set before running 'make' to specify where the GNAT
17259# library is installed.
17260
17261# see "Automatically creating a list of directories" to create these
17262# variables
17263SOURCE_DIRS=
17264OBJECT_DIRS=
17265
17266empty:=
17267space:=$@{empty@} $@{empty@}
17268SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17269OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17270ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17271ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17272export ADA_INCLUDE_PATH
17273export ADA_OBJECTS_PATH
17274
17275all:
17276        gnatmake main_unit
17277@end example
17278
17279@node GNAT Utility Programs,GNAT and Program Execution,Building Executable Programs with GNAT,Top
17280@anchor{gnat_ugn/gnat_utility_programs doc}@anchor{143}@anchor{gnat_ugn/gnat_utility_programs gnat-utility-programs}@anchor{b}@anchor{gnat_ugn/gnat_utility_programs id1}@anchor{144}
17281@chapter GNAT Utility Programs
17282
17283
17284This chapter describes a number of utility programs:
17285
17286
17287
17288@itemize *
17289
17290@item
17291@ref{20,,The File Cleanup Utility gnatclean}
17292
17293@item
17294@ref{21,,The GNAT Library Browser gnatls}
17295
17296@item
17297@ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
17298
17299@item
17300@ref{23,,The Ada to HTML Converter gnathtml}
17301@end itemize
17302
17303Other GNAT utilities are described elsewhere in this manual:
17304
17305
17306@itemize *
17307
17308@item
17309@ref{59,,Handling Arbitrary File Naming Conventions with gnatname}
17310
17311@item
17312@ref{63,,File Name Krunching with gnatkr}
17313
17314@item
17315@ref{36,,Renaming Files with gnatchop}
17316
17317@item
17318@ref{17,,Preprocessing with gnatprep}
17319@end itemize
17320
17321@menu
17322* The File Cleanup Utility gnatclean::
17323* The GNAT Library Browser gnatls::
17324* The Cross-Referencing Tools gnatxref and gnatfind::
17325* The Ada to HTML Converter gnathtml::
17326
17327@end menu
17328
17329@node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
17330@anchor{gnat_ugn/gnat_utility_programs id2}@anchor{145}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{20}
17331@section The File Cleanup Utility @code{gnatclean}
17332
17333
17334@geindex File cleanup tool
17335
17336@geindex gnatclean
17337
17338@code{gnatclean} is a tool that allows the deletion of files produced by the
17339compiler, binder and linker, including ALI files, object files, tree files,
17340expanded source files, library files, interface copy source files, binder
17341generated files and executable files.
17342
17343@menu
17344* Running gnatclean::
17345* Switches for gnatclean::
17346
17347@end menu
17348
17349@node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
17350@anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{146}@anchor{gnat_ugn/gnat_utility_programs id3}@anchor{147}
17351@subsection Running @code{gnatclean}
17352
17353
17354The @code{gnatclean} command has the form:
17355
17356@quotation
17357
17358@example
17359$ gnatclean switches names
17360@end example
17361@end quotation
17362
17363where @code{names} is a list of source file names. Suffixes @code{.ads} and
17364@code{adb} may be omitted. If a project file is specified using switch
17365@code{-P}, then @code{names} may be completely omitted.
17366
17367In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17368if switch @code{-c} is not specified, by the binder and
17369the linker. In informative-only mode, specified by switch
17370@code{-n}, the list of files that would have been deleted in
17371normal mode is listed, but no file is actually deleted.
17372
17373@node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
17374@anchor{gnat_ugn/gnat_utility_programs id4}@anchor{148}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{149}
17375@subsection Switches for @code{gnatclean}
17376
17377
17378@code{gnatclean} recognizes the following switches:
17379
17380@geindex --version (gnatclean)
17381
17382
17383@table @asis
17384
17385@item @code{--version}
17386
17387Display copyright and version, then exit disregarding all other options.
17388@end table
17389
17390@geindex --help (gnatclean)
17391
17392
17393@table @asis
17394
17395@item @code{--help}
17396
17397If @code{--version} was not used, display usage, then exit disregarding
17398all other options.
17399
17400@item @code{--subdirs=@emph{subdir}}
17401
17402Actual object directory of each project file is the subdirectory subdir of the
17403object directory specified or defaulted in the project file.
17404
17405@item @code{--unchecked-shared-lib-imports}
17406
17407By default, shared library projects are not allowed to import static library
17408projects. When this switch is used on the command line, this restriction is
17409relaxed.
17410@end table
17411
17412@geindex -c (gnatclean)
17413
17414
17415@table @asis
17416
17417@item @code{-c}
17418
17419Only attempt to delete the files produced by the compiler, not those produced
17420by the binder or the linker. The files that are not to be deleted are library
17421files, interface copy files, binder generated files and executable files.
17422@end table
17423
17424@geindex -D (gnatclean)
17425
17426
17427@table @asis
17428
17429@item @code{-D @emph{dir}}
17430
17431Indicate that ALI and object files should normally be found in directory @code{dir}.
17432@end table
17433
17434@geindex -F (gnatclean)
17435
17436
17437@table @asis
17438
17439@item @code{-F}
17440
17441When using project files, if some errors or warnings are detected during
17442parsing and verbose mode is not in effect (no use of switch
17443-v), then error lines start with the full path name of the project
17444file, rather than its simple file name.
17445@end table
17446
17447@geindex -h (gnatclean)
17448
17449
17450@table @asis
17451
17452@item @code{-h}
17453
17454Output a message explaining the usage of @code{gnatclean}.
17455@end table
17456
17457@geindex -n (gnatclean)
17458
17459
17460@table @asis
17461
17462@item @code{-n}
17463
17464Informative-only mode. Do not delete any files. Output the list of the files
17465that would have been deleted if this switch was not specified.
17466@end table
17467
17468@geindex -P (gnatclean)
17469
17470
17471@table @asis
17472
17473@item @code{-P@emph{project}}
17474
17475Use project file @code{project}. Only one such switch can be used.
17476When cleaning a project file, the files produced by the compilation of the
17477immediate sources or inherited sources of the project files are to be
17478deleted. This is not depending on the presence or not of executable names
17479on the command line.
17480@end table
17481
17482@geindex -q (gnatclean)
17483
17484
17485@table @asis
17486
17487@item @code{-q}
17488
17489Quiet output. If there are no errors, do not output anything, except in
17490verbose mode (switch -v) or in informative-only mode
17491(switch -n).
17492@end table
17493
17494@geindex -r (gnatclean)
17495
17496
17497@table @asis
17498
17499@item @code{-r}
17500
17501When a project file is specified (using switch -P),
17502clean all imported and extended project files, recursively. If this switch
17503is not specified, only the files related to the main project file are to be
17504deleted. This switch has no effect if no project file is specified.
17505@end table
17506
17507@geindex -v (gnatclean)
17508
17509
17510@table @asis
17511
17512@item @code{-v}
17513
17514Verbose mode.
17515@end table
17516
17517@geindex -vP (gnatclean)
17518
17519
17520@table @asis
17521
17522@item @code{-vP@emph{x}}
17523
17524Indicates the verbosity of the parsing of GNAT project files.
17525@ref{de,,Switches Related to Project Files}.
17526@end table
17527
17528@geindex -X (gnatclean)
17529
17530
17531@table @asis
17532
17533@item @code{-X@emph{name}=@emph{value}}
17534
17535Indicates that external variable @code{name} has the value @code{value}.
17536The Project Manager will use this value for occurrences of
17537@code{external(name)} when parsing the project file.
17538See @ref{de,,Switches Related to Project Files}.
17539@end table
17540
17541@geindex -aO (gnatclean)
17542
17543
17544@table @asis
17545
17546@item @code{-aO@emph{dir}}
17547
17548When searching for ALI and object files, look in directory @code{dir}.
17549@end table
17550
17551@geindex -I (gnatclean)
17552
17553
17554@table @asis
17555
17556@item @code{-I@emph{dir}}
17557
17558Equivalent to @code{-aO@emph{dir}}.
17559@end table
17560
17561@geindex -I- (gnatclean)
17562
17563@geindex Source files
17564@geindex suppressing search
17565
17566
17567@table @asis
17568
17569@item @code{-I-}
17570
17571Do not look for ALI or object files in the directory
17572where @code{gnatclean} was invoked.
17573@end table
17574
17575@node The GNAT Library Browser gnatls,The Cross-Referencing Tools gnatxref and gnatfind,The File Cleanup Utility gnatclean,GNAT Utility Programs
17576@anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{21}@anchor{gnat_ugn/gnat_utility_programs id5}@anchor{14a}
17577@section The GNAT Library Browser @code{gnatls}
17578
17579
17580@geindex Library browser
17581
17582@geindex gnatls
17583
17584@code{gnatls} is a tool that outputs information about compiled
17585units. It gives the relationship between objects, unit names and source
17586files. It can also be used to check the source dependencies of a unit
17587as well as various characteristics.
17588
17589@menu
17590* Running gnatls::
17591* Switches for gnatls::
17592* Example of gnatls Usage::
17593
17594@end menu
17595
17596@node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
17597@anchor{gnat_ugn/gnat_utility_programs id6}@anchor{14b}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{14c}
17598@subsection Running @code{gnatls}
17599
17600
17601The @code{gnatls} command has the form
17602
17603@quotation
17604
17605@example
17606$ gnatls switches object_or_ali_file
17607@end example
17608@end quotation
17609
17610The main argument is the list of object or @code{ali} files
17611(see @ref{42,,The Ada Library Information Files})
17612for which information is requested.
17613
17614In normal mode, without additional option, @code{gnatls} produces a
17615four-column listing. Each line represents information for a specific
17616object. The first column gives the full path of the object, the second
17617column gives the name of the principal unit in this object, the third
17618column gives the status of the source and the fourth column gives the
17619full path of the source representing this unit.
17620Here is a simple example of use:
17621
17622@quotation
17623
17624@example
17625$ gnatls *.o
17626./demo1.o            demo1            DIF demo1.adb
17627./demo2.o            demo2             OK demo2.adb
17628./hello.o            h1                OK hello.adb
17629./instr-child.o      instr.child      MOK instr-child.adb
17630./instr.o            instr             OK instr.adb
17631./tef.o              tef              DIF tef.adb
17632./text_io_example.o  text_io_example   OK text_io_example.adb
17633./tgef.o             tgef             DIF tgef.adb
17634@end example
17635@end quotation
17636
17637The first line can be interpreted as follows: the main unit which is
17638contained in
17639object file @code{demo1.o} is demo1, whose main source is in
17640@code{demo1.adb}. Furthermore, the version of the source used for the
17641compilation of demo1 has been modified (DIF). Each source file has a status
17642qualifier which can be:
17643
17644
17645@table @asis
17646
17647@item @emph{OK (unchanged)}
17648
17649The version of the source file used for the compilation of the
17650specified unit corresponds exactly to the actual source file.
17651
17652@item @emph{MOK (slightly modified)}
17653
17654The version of the source file used for the compilation of the
17655specified unit differs from the actual source file but not enough to
17656require recompilation. If you use gnatmake with the option
17657@code{-m} (minimal recompilation), a file marked
17658MOK will not be recompiled.
17659
17660@item @emph{DIF (modified)}
17661
17662No version of the source found on the path corresponds to the source
17663used to build this object.
17664
17665@item @emph{??? (file not found)}
17666
17667No source file was found for this unit.
17668
17669@item @emph{HID (hidden,  unchanged version not first on PATH)}
17670
17671The version of the source that corresponds exactly to the source used
17672for compilation has been found on the path but it is hidden by another
17673version of the same source that has been modified.
17674@end table
17675
17676@node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
17677@anchor{gnat_ugn/gnat_utility_programs id7}@anchor{14d}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{14e}
17678@subsection Switches for @code{gnatls}
17679
17680
17681@code{gnatls} recognizes the following switches:
17682
17683@geindex --version (gnatls)
17684
17685
17686@table @asis
17687
17688@item @code{--version}
17689
17690Display copyright and version, then exit disregarding all other options.
17691@end table
17692
17693@geindex --help (gnatls)
17694
17695
17696@table @asis
17697
17698@item @code{--help}
17699
17700If @code{--version} was not used, display usage, then exit disregarding
17701all other options.
17702@end table
17703
17704@geindex -a (gnatls)
17705
17706
17707@table @asis
17708
17709@item @code{-a}
17710
17711Consider all units, including those of the predefined Ada library.
17712Especially useful with @code{-d}.
17713@end table
17714
17715@geindex -d (gnatls)
17716
17717
17718@table @asis
17719
17720@item @code{-d}
17721
17722List sources from which specified units depend on.
17723@end table
17724
17725@geindex -h (gnatls)
17726
17727
17728@table @asis
17729
17730@item @code{-h}
17731
17732Output the list of options.
17733@end table
17734
17735@geindex -o (gnatls)
17736
17737
17738@table @asis
17739
17740@item @code{-o}
17741
17742Only output information about object files.
17743@end table
17744
17745@geindex -s (gnatls)
17746
17747
17748@table @asis
17749
17750@item @code{-s}
17751
17752Only output information about source files.
17753@end table
17754
17755@geindex -u (gnatls)
17756
17757
17758@table @asis
17759
17760@item @code{-u}
17761
17762Only output information about compilation units.
17763@end table
17764
17765@geindex -files (gnatls)
17766
17767
17768@table @asis
17769
17770@item @code{-files=@emph{file}}
17771
17772Take as arguments the files listed in text file @code{file}.
17773Text file @code{file} may contain empty lines that are ignored.
17774Each nonempty line should contain the name of an existing file.
17775Several such switches may be specified simultaneously.
17776@end table
17777
17778@geindex -aO (gnatls)
17779
17780@geindex -aI (gnatls)
17781
17782@geindex -I (gnatls)
17783
17784@geindex -I- (gnatls)
17785
17786
17787@table @asis
17788
17789@item @code{-aO@emph{dir}}, @code{-aI@emph{dir}}, @code{-I@emph{dir}}, @code{-I-}, @code{-nostdinc}
17790
17791Source path manipulation. Same meaning as the equivalent @code{gnatmake}
17792flags (@ref{dc,,Switches for gnatmake}).
17793@end table
17794
17795@geindex -aP (gnatls)
17796
17797
17798@table @asis
17799
17800@item @code{-aP@emph{dir}}
17801
17802Add @code{dir} at the beginning of the project search dir.
17803@end table
17804
17805@geindex --RTS (gnatls)
17806
17807
17808@table @asis
17809
17810@item @code{--RTS=@emph{rts-path}}
17811
17812Specifies the default location of the runtime library. Same meaning as the
17813equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17814@end table
17815
17816@geindex -v (gnatls)
17817
17818
17819@table @asis
17820
17821@item @code{-v}
17822
17823Verbose mode. Output the complete source, object and project paths. Do not use
17824the default column layout but instead use long format giving as much as
17825information possible on each requested units, including special
17826characteristics such as:
17827
17828
17829@itemize *
17830
17831@item
17832@emph{Preelaborable}: The unit is preelaborable in the Ada sense.
17833
17834@item
17835@emph{No_Elab_Code}:  No elaboration code has been produced by the compiler for this unit.
17836
17837@item
17838@emph{Pure}: The unit is pure in the Ada sense.
17839
17840@item
17841@emph{Elaborate_Body}: The unit contains a pragma Elaborate_Body.
17842
17843@item
17844@emph{Remote_Types}: The unit contains a pragma Remote_Types.
17845
17846@item
17847@emph{Shared_Passive}: The unit contains a pragma Shared_Passive.
17848
17849@item
17850@emph{Predefined}: This unit is part of the predefined environment and cannot be modified
17851by the user.
17852
17853@item
17854@emph{Remote_Call_Interface}: The unit contains a pragma Remote_Call_Interface.
17855@end itemize
17856@end table
17857
17858@node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
17859@anchor{gnat_ugn/gnat_utility_programs id8}@anchor{14f}@anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{150}
17860@subsection Example of @code{gnatls} Usage
17861
17862
17863Example of using the verbose switch. Note how the source and
17864object paths are affected by the -I switch.
17865
17866@quotation
17867
17868@example
17869$ gnatls -v -I.. demo1.o
17870
17871GNATLS 5.03w (20041123-34)
17872Copyright 1997-2004 Free Software Foundation, Inc.
17873
17874Source Search Path:
17875   <Current_Directory>
17876   ../
17877   /home/comar/local/adainclude/
17878
17879Object Search Path:
17880   <Current_Directory>
17881   ../
17882   /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17883
17884Project Search Path:
17885   <Current_Directory>
17886   /home/comar/local/lib/gnat/
17887
17888./demo1.o
17889   Unit =>
17890     Name   => demo1
17891     Kind   => subprogram body
17892     Flags  => No_Elab_Code
17893     Source => demo1.adb    modified
17894@end example
17895@end quotation
17896
17897The following is an example of use of the dependency list.
17898Note the use of the -s switch
17899which gives a straight list of source files. This can be useful for
17900building specialized scripts.
17901
17902@quotation
17903
17904@example
17905$ gnatls -d demo2.o
17906./demo2.o   demo2        OK demo2.adb
17907                         OK gen_list.ads
17908                         OK gen_list.adb
17909                         OK instr.ads
17910                         OK instr-child.ads
17911
17912$ gnatls -d -s -a demo1.o
17913demo1.adb
17914/home/comar/local/adainclude/ada.ads
17915/home/comar/local/adainclude/a-finali.ads
17916/home/comar/local/adainclude/a-filico.ads
17917/home/comar/local/adainclude/a-stream.ads
17918/home/comar/local/adainclude/a-tags.ads
17919gen_list.ads
17920gen_list.adb
17921/home/comar/local/adainclude/gnat.ads
17922/home/comar/local/adainclude/g-io.ads
17923instr.ads
17924/home/comar/local/adainclude/system.ads
17925/home/comar/local/adainclude/s-exctab.ads
17926/home/comar/local/adainclude/s-finimp.ads
17927/home/comar/local/adainclude/s-finroo.ads
17928/home/comar/local/adainclude/s-secsta.ads
17929/home/comar/local/adainclude/s-stalib.ads
17930/home/comar/local/adainclude/s-stoele.ads
17931/home/comar/local/adainclude/s-stratt.ads
17932/home/comar/local/adainclude/s-tasoli.ads
17933/home/comar/local/adainclude/s-unstyp.ads
17934/home/comar/local/adainclude/unchconv.ads
17935@end example
17936@end quotation
17937
17938@node The Cross-Referencing Tools gnatxref and gnatfind,The Ada to HTML Converter gnathtml,The GNAT Library Browser gnatls,GNAT Utility Programs
17939@anchor{gnat_ugn/gnat_utility_programs the-cross-referencing-tools-gnatxref-and-gnatfind}@anchor{22}@anchor{gnat_ugn/gnat_utility_programs id9}@anchor{151}
17940@section The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
17941
17942
17943@geindex gnatxref
17944
17945@geindex gnatfind
17946
17947The compiler generates cross-referencing information (unless
17948you set the @code{-gnatx} switch), which are saved in the @code{.ali} files.
17949This information indicates where in the source each entity is declared and
17950referenced. Note that entities in package Standard are not included, but
17951entities in all other predefined units are included in the output.
17952
17953Before using any of these two tools, you need to compile successfully your
17954application, so that GNAT gets a chance to generate the cross-referencing
17955information.
17956
17957The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
17958information to provide the user with the capability to easily locate the
17959declaration and references to an entity. These tools are quite similar,
17960the difference being that @code{gnatfind} is intended for locating
17961definitions and/or references to a specified entity or entities, whereas
17962@code{gnatxref} is oriented to generating a full report of all
17963cross-references.
17964
17965To use these tools, you must not compile your application using the
17966@code{-gnatx} switch on the @code{gnatmake} command line
17967(see @ref{1b,,Building with gnatmake}). Otherwise, cross-referencing
17968information will not be generated.
17969
17970@menu
17971* gnatxref Switches::
17972* gnatfind Switches::
17973* Configuration Files for gnatxref and gnatfind::
17974* Regular Expressions in gnatfind and gnatxref::
17975* Examples of gnatxref Usage::
17976* Examples of gnatfind Usage::
17977
17978@end menu
17979
17980@node gnatxref Switches,gnatfind Switches,,The Cross-Referencing Tools gnatxref and gnatfind
17981@anchor{gnat_ugn/gnat_utility_programs id10}@anchor{152}@anchor{gnat_ugn/gnat_utility_programs gnatxref-switches}@anchor{153}
17982@subsection @code{gnatxref} Switches
17983
17984
17985The command invocation for @code{gnatxref} is:
17986
17987@quotation
17988
17989@example
17990$ gnatxref [ switches ] sourcefile1 [ sourcefile2 ... ]
17991@end example
17992@end quotation
17993
17994where
17995
17996
17997@table @asis
17998
17999@item @code{sourcefile1} [, @code{sourcefile2} ...]
18000
18001identify the source files for which a report is to be generated. The
18002@code{with}ed units will be processed too. You must provide at least one file.
18003
18004These file names are considered to be regular expressions, so for instance
18005specifying @code{source*.adb} is the same as giving every file in the current
18006directory whose name starts with @code{source} and whose extension is
18007@code{adb}.
18008
18009You shouldn't specify any directory name, just base names. @code{gnatxref}
18010and @code{gnatfind} will be able to locate these files by themselves using
18011the source path. If you specify directories, no result is produced.
18012@end table
18013
18014The following switches are available for @code{gnatxref}:
18015
18016@geindex --version (gnatxref)
18017
18018
18019@table @asis
18020
18021@item @code{--version}
18022
18023Display copyright and version, then exit disregarding all other options.
18024@end table
18025
18026@geindex --help (gnatxref)
18027
18028
18029@table @asis
18030
18031@item @code{--help}
18032
18033If @code{--version} was not used, display usage, then exit disregarding
18034all other options.
18035@end table
18036
18037@geindex -a (gnatxref)
18038
18039
18040@table @asis
18041
18042@item @code{-a}
18043
18044If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
18045the read-only files found in the library search path. Otherwise, these files
18046will be ignored. This option can be used to protect Gnat sources or your own
18047libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
18048much faster, and their output much smaller. Read-only here refers to access
18049or permissions status in the file system for the current user.
18050@end table
18051
18052@geindex -aIDIR (gnatxref)
18053
18054
18055@table @asis
18056
18057@item @code{-aI@emph{DIR}}
18058
18059When looking for source files also look in directory DIR. The order in which
18060source file search is undertaken is the same as for @code{gnatmake}.
18061@end table
18062
18063@geindex -aODIR (gnatxref)
18064
18065
18066@table @asis
18067
18068@item @code{aO@emph{DIR}}
18069
18070When -searching for library and object files, look in directory
18071DIR. The order in which library files are searched is the same as for
18072@code{gnatmake}.
18073@end table
18074
18075@geindex -nostdinc (gnatxref)
18076
18077
18078@table @asis
18079
18080@item @code{-nostdinc}
18081
18082Do not look for sources in the system default directory.
18083@end table
18084
18085@geindex -nostdlib (gnatxref)
18086
18087
18088@table @asis
18089
18090@item @code{-nostdlib}
18091
18092Do not look for library files in the system default directory.
18093@end table
18094
18095@geindex --ext (gnatxref)
18096
18097
18098@table @asis
18099
18100@item @code{--ext=@emph{extension}}
18101
18102Specify an alternate ali file extension. The default is @code{ali} and other
18103extensions (e.g. @code{gli} for C/C++ sources) may be specified via this switch.
18104Note that if this switch overrides the default, only the new extension will
18105be considered.
18106@end table
18107
18108@geindex --RTS (gnatxref)
18109
18110
18111@table @asis
18112
18113@item @code{--RTS=@emph{rts-path}}
18114
18115Specifies the default location of the runtime library. Same meaning as the
18116equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
18117@end table
18118
18119@geindex -d (gnatxref)
18120
18121
18122@table @asis
18123
18124@item @code{-d}
18125
18126If this switch is set @code{gnatxref} will output the parent type
18127reference for each matching derived types.
18128@end table
18129
18130@geindex -f (gnatxref)
18131
18132
18133@table @asis
18134
18135@item @code{-f}
18136
18137If this switch is set, the output file names will be preceded by their
18138directory (if the file was found in the search path). If this switch is
18139not set, the directory will not be printed.
18140@end table
18141
18142@geindex -g (gnatxref)
18143
18144
18145@table @asis
18146
18147@item @code{-g}
18148
18149If this switch is set, information is output only for library-level
18150entities, ignoring local entities. The use of this switch may accelerate
18151@code{gnatfind} and @code{gnatxref}.
18152@end table
18153
18154@geindex -IDIR (gnatxref)
18155
18156
18157@table @asis
18158
18159@item @code{-I@emph{DIR}}
18160
18161Equivalent to @code{-aODIR -aIDIR}.
18162@end table
18163
18164@geindex -pFILE (gnatxref)
18165
18166
18167@table @asis
18168
18169@item @code{-p@emph{FILE}}
18170
18171Specify a configuration file to use to list the source and object directories.
18172
18173If a file is specified, then the content of the source directory and object
18174directory lines are added as if they had been specified respectively
18175by @code{-aI} and @code{-aO}.
18176
18177See @ref{154,,Configuration Files for gnatxref and gnatfind} for the syntax
18178of this configuration file.
18179
18180@item @code{-u}
18181
18182Output only unused symbols. This may be really useful if you give your
18183main compilation unit on the command line, as @code{gnatxref} will then
18184display every unused entity and 'with'ed package.
18185
18186@item @code{-v}
18187
18188Instead of producing the default output, @code{gnatxref} will generate a
18189@code{tags} file that can be used by vi. For examples how to use this
18190feature, see @ref{155,,Examples of gnatxref Usage}. The tags file is output
18191to the standard output, thus you will have to redirect it to a file.
18192@end table
18193
18194All these switches may be in any order on the command line, and may even
18195appear after the file names. They need not be separated by spaces, thus
18196you can say @code{gnatxref -ag} instead of @code{gnatxref -a -g}.
18197
18198@node gnatfind Switches,Configuration Files for gnatxref and gnatfind,gnatxref Switches,The Cross-Referencing Tools gnatxref and gnatfind
18199@anchor{gnat_ugn/gnat_utility_programs id11}@anchor{156}@anchor{gnat_ugn/gnat_utility_programs gnatfind-switches}@anchor{157}
18200@subsection @code{gnatfind} Switches
18201
18202
18203The command invocation for @code{gnatfind} is:
18204
18205@quotation
18206
18207@example
18208$ gnatfind [ switches ]  pattern[:sourcefile[:line[:column]]]
18209      [file1 file2 ...]
18210@end example
18211@end quotation
18212
18213with the following iterpretation of the command arguments:
18214
18215
18216@table @asis
18217
18218@item @emph{pattern}
18219
18220An entity will be output only if it matches the regular expression found
18221in @emph{pattern}, see @ref{158,,Regular Expressions in gnatfind and gnatxref}.
18222
18223Omitting the pattern is equivalent to specifying @code{*}, which
18224will match any entity. Note that if you do not provide a pattern, you
18225have to provide both a sourcefile and a line.
18226
18227Entity names are given in Latin-1, with uppercase/lowercase equivalence
18228for matching purposes. At the current time there is no support for
182298-bit codes other than Latin-1, or for wide characters in identifiers.
18230
18231@item @emph{sourcefile}
18232
18233@code{gnatfind} will look for references, bodies or declarations
18234of symbols referenced in @code{sourcefile}, at line @code{line}
18235and column @code{column}. See @ref{159,,Examples of gnatfind Usage}
18236for syntax examples.
18237
18238@item @emph{line}
18239
18240A decimal integer identifying the line number containing
18241the reference to the entity (or entities) to be located.
18242
18243@item @emph{column}
18244
18245A decimal integer identifying the exact location on the
18246line of the first character of the identifier for the
18247entity reference. Columns are numbered from 1.
18248
18249@item @emph{file1 file2 ...}
18250
18251The search will be restricted to these source files. If none are given, then
18252the search will be conducted for every library file in the search path.
18253These files must appear only after the pattern or sourcefile.
18254
18255These file names are considered to be regular expressions, so for instance
18256specifying @code{source*.adb} is the same as giving every file in the current
18257directory whose name starts with @code{source} and whose extension is
18258@code{adb}.
18259
18260The location of the spec of the entity will always be displayed, even if it
18261isn't in one of @code{file1}, @code{file2}, ... The
18262occurrences of the entity in the separate units of the ones given on the
18263command line will also be displayed.
18264
18265Note that if you specify at least one file in this part, @code{gnatfind} may
18266sometimes not be able to find the body of the subprograms.
18267@end table
18268
18269At least one of 'sourcefile' or 'pattern' has to be present on
18270the command line.
18271
18272The following switches are available:
18273
18274@geindex --version (gnatfind)
18275
18276
18277@table @asis
18278
18279@item @code{--version}
18280
18281Display copyright and version, then exit disregarding all other options.
18282@end table
18283
18284@geindex --help (gnatfind)
18285
18286
18287@table @asis
18288
18289@item @code{--help}
18290
18291If @code{--version} was not used, display usage, then exit disregarding
18292all other options.
18293@end table
18294
18295@geindex -a (gnatfind)
18296
18297
18298@table @asis
18299
18300@item @code{-a}
18301
18302If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
18303the read-only files found in the library search path. Otherwise, these files
18304will be ignored. This option can be used to protect Gnat sources or your own
18305libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
18306much faster, and their output much smaller. Read-only here refers to access
18307or permission status in the file system for the current user.
18308@end table
18309
18310@geindex -aIDIR (gnatfind)
18311
18312
18313@table @asis
18314
18315@item @code{-aI@emph{DIR}}
18316
18317When looking for source files also look in directory DIR. The order in which
18318source file search is undertaken is the same as for @code{gnatmake}.
18319@end table
18320
18321@geindex -aODIR (gnatfind)
18322
18323
18324@table @asis
18325
18326@item @code{-aO@emph{DIR}}
18327
18328When searching for library and object files, look in directory
18329DIR. The order in which library files are searched is the same as for
18330@code{gnatmake}.
18331@end table
18332
18333@geindex -nostdinc (gnatfind)
18334
18335
18336@table @asis
18337
18338@item @code{-nostdinc}
18339
18340Do not look for sources in the system default directory.
18341@end table
18342
18343@geindex -nostdlib (gnatfind)
18344
18345
18346@table @asis
18347
18348@item @code{-nostdlib}
18349
18350Do not look for library files in the system default directory.
18351@end table
18352
18353@geindex --ext (gnatfind)
18354
18355
18356@table @asis
18357
18358@item @code{--ext=@emph{extension}}
18359
18360Specify an alternate ali file extension. The default is @code{ali} and other
18361extensions may be specified via this switch. Note that if this switch
18362overrides the default, only the new extension will be considered.
18363@end table
18364
18365@geindex --RTS (gnatfind)
18366
18367
18368@table @asis
18369
18370@item @code{--RTS=@emph{rts-path}}
18371
18372Specifies the default location of the runtime library. Same meaning as the
18373equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
18374@end table
18375
18376@geindex -d (gnatfind)
18377
18378
18379@table @asis
18380
18381@item @code{-d}
18382
18383If this switch is set, then @code{gnatfind} will output the parent type
18384reference for each matching derived types.
18385@end table
18386
18387@geindex -e (gnatfind)
18388
18389
18390@table @asis
18391
18392@item @code{-e}
18393
18394By default, @code{gnatfind} accept the simple regular expression set for
18395@code{pattern}. If this switch is set, then the pattern will be
18396considered as full Unix-style regular expression.
18397@end table
18398
18399@geindex -f (gnatfind)
18400
18401
18402@table @asis
18403
18404@item @code{-f}
18405
18406If this switch is set, the output file names will be preceded by their
18407directory (if the file was found in the search path). If this switch is
18408not set, the directory will not be printed.
18409@end table
18410
18411@geindex -g (gnatfind)
18412
18413
18414@table @asis
18415
18416@item @code{-g}
18417
18418If this switch is set, information is output only for library-level
18419entities, ignoring local entities. The use of this switch may accelerate
18420@code{gnatfind} and @code{gnatxref}.
18421@end table
18422
18423@geindex -IDIR (gnatfind)
18424
18425
18426@table @asis
18427
18428@item @code{-I@emph{DIR}}
18429
18430Equivalent to @code{-aODIR -aIDIR}.
18431@end table
18432
18433@geindex -pFILE (gnatfind)
18434
18435
18436@table @asis
18437
18438@item @code{-p@emph{FILE}}
18439
18440Specify a configuration file to use to list the source and object directories.
18441
18442If a file is specified, then the content of the source directory and object
18443directory lines are added as if they had been specified respectively
18444by @code{-aI} and @code{-aO}.
18445
18446See @ref{154,,Configuration Files for gnatxref and gnatfind} for the syntax
18447of this configuration file.
18448@end table
18449
18450@geindex -r (gnatfind)
18451
18452
18453@table @asis
18454
18455@item @code{-r}
18456
18457By default, @code{gnatfind} will output only the information about the
18458declaration, body or type completion of the entities. If this switch is
18459set, the @code{gnatfind} will locate every reference to the entities in
18460the files specified on the command line (or in every file in the search
18461path if no file is given on the command line).
18462@end table
18463
18464@geindex -s (gnatfind)
18465
18466
18467@table @asis
18468
18469@item @code{-s}
18470
18471If this switch is set, then @code{gnatfind} will output the content
18472of the Ada source file lines were the entity was found.
18473@end table
18474
18475@geindex -t (gnatfind)
18476
18477
18478@table @asis
18479
18480@item @code{-t}
18481
18482If this switch is set, then @code{gnatfind} will output the type hierarchy for
18483the specified type. It act like -d option but recursively from parent
18484type to parent type. When this switch is set it is not possible to
18485specify more than one file.
18486@end table
18487
18488All these switches may be in any order on the command line, and may even
18489appear after the file names. They need not be separated by spaces, thus
18490you can say @code{gnatxref -ag} instead of
18491@code{gnatxref -a -g}.
18492
18493As stated previously, @code{gnatfind} will search in every directory in the
18494search path. You can force it to look only in the current directory if
18495you specify @code{*} at the end of the command line.
18496
18497@node Configuration Files for gnatxref and gnatfind,Regular Expressions in gnatfind and gnatxref,gnatfind Switches,The Cross-Referencing Tools gnatxref and gnatfind
18498@anchor{gnat_ugn/gnat_utility_programs configuration-files-for-gnatxref-and-gnatfind}@anchor{154}@anchor{gnat_ugn/gnat_utility_programs id12}@anchor{15a}
18499@subsection Configuration Files for @code{gnatxref} and @code{gnatfind}
18500
18501
18502Configuration files are used by @code{gnatxref} and @code{gnatfind} to specify
18503the list of source and object directories to consider. They can be
18504specified via the @code{-p} switch.
18505
18506The following lines can be included, in any order in the file:
18507
18508
18509@itemize *
18510
18511@item
18512
18513@table @asis
18514
18515@item @emph{src_dir=DIR}
18516
18517[default: @code{"./"}].
18518Specifies a directory where to look for source files. Multiple @code{src_dir}
18519lines can be specified and they will be searched in the order they
18520are specified.
18521@end table
18522
18523@item
18524
18525@table @asis
18526
18527@item @emph{obj_dir=DIR}
18528
18529[default: @code{"./"}].
18530Specifies a directory where to look for object and library files. Multiple
18531@code{obj_dir} lines can be specified, and they will be searched in the order
18532they are specified
18533@end table
18534@end itemize
18535
18536Any other line will be silently ignored.
18537
18538@node Regular Expressions in gnatfind and gnatxref,Examples of gnatxref Usage,Configuration Files for gnatxref and gnatfind,The Cross-Referencing Tools gnatxref and gnatfind
18539@anchor{gnat_ugn/gnat_utility_programs id13}@anchor{15b}@anchor{gnat_ugn/gnat_utility_programs regular-expressions-in-gnatfind-and-gnatxref}@anchor{158}
18540@subsection Regular Expressions in @code{gnatfind} and @code{gnatxref}
18541
18542
18543As specified in the section about @code{gnatfind}, the pattern can be a
18544regular expression. Two kinds of regular expressions
18545are recognized:
18546
18547
18548@itemize *
18549
18550@item
18551
18552@table @asis
18553
18554@item @emph{Globbing pattern}
18555
18556These are the most common regular expression. They are the same as are
18557generally used in a Unix shell command line, or in a DOS session.
18558
18559Here is a more formal grammar:
18560
18561@example
18562regexp ::= term
18563term   ::= elmt            -- matches elmt
18564term   ::= elmt elmt       -- concatenation (elmt then elmt)
18565term   ::= *               -- any string of 0 or more characters
18566term   ::= ?               -- matches any character
18567term   ::= [char @{char@}]   -- matches any character listed
18568term   ::= [char - char]   -- matches any character in range
18569@end example
18570@end table
18571
18572@item
18573
18574@table @asis
18575
18576@item @emph{Full regular expression}
18577
18578The second set of regular expressions is much more powerful. This is the
18579type of regular expressions recognized by utilities such as @code{grep}.
18580
18581The following is the form of a regular expression, expressed in same BNF
18582style as is found in the Ada Reference Manual:
18583
18584@example
18585regexp ::= term @{| term@}   -- alternation (term or term ...)
18586
18587term ::= item @{item@}       -- concatenation (item then item)
18588
18589item ::= elmt              -- match elmt
18590item ::= elmt *            -- zero or more elmt's
18591item ::= elmt +            -- one or more elmt's
18592item ::= elmt ?            -- matches elmt or nothing
18593
18594elmt ::= nschar            -- matches given character
18595elmt ::= [nschar @{nschar@}]   -- matches any character listed
18596elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
18597elmt ::= [char - char]     -- matches chars in given range
18598elmt ::= \\ char            -- matches given character
18599elmt ::= .                 -- matches any single character
18600elmt ::= ( regexp )        -- parens used for grouping
18601
18602char ::= any character, including special characters
18603nschar ::= any character except ()[].*+?^
18604@end example
18605
18606Here are a few examples:
18607
18608@quotation
18609
18610
18611@table @asis
18612
18613@item @code{abcde|fghi}
18614
18615will match any of the two strings @code{abcde} and @code{fghi},
18616
18617@item @code{abc*d}
18618
18619will match any string like @code{abd}, @code{abcd}, @code{abccd},
18620@code{abcccd}, and so on,
18621
18622@item @code{[a-z]+}
18623
18624will match any string which has only lowercase characters in it (and at
18625least one character.
18626@end table
18627@end quotation
18628@end table
18629@end itemize
18630
18631@node Examples of gnatxref Usage,Examples of gnatfind Usage,Regular Expressions in gnatfind and gnatxref,The Cross-Referencing Tools gnatxref and gnatfind
18632@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatxref-usage}@anchor{155}@anchor{gnat_ugn/gnat_utility_programs id14}@anchor{15c}
18633@subsection Examples of @code{gnatxref} Usage
18634
18635
18636@menu
18637* General Usage::
18638* Using gnatxref with vi::
18639
18640@end menu
18641
18642@node General Usage,Using gnatxref with vi,,Examples of gnatxref Usage
18643@anchor{gnat_ugn/gnat_utility_programs general-usage}@anchor{15d}
18644@subsubsection General Usage
18645
18646
18647For the following examples, we will consider the following units:
18648
18649@quotation
18650
18651@example
18652main.ads:
186531: with Bar;
186542: package Main is
186553:     procedure Foo (B : in Integer);
186564:     C : Integer;
186575: private
186586:     D : Integer;
186597: end Main;
18660
18661main.adb:
186621: package body Main is
186632:     procedure Foo (B : in Integer) is
186643:     begin
186654:        C := B;
186665:        D := B;
186676:        Bar.Print (B);
186687:        Bar.Print (C);
186698:     end Foo;
186709: end Main;
18671
18672bar.ads:
186731: package Bar is
186742:     procedure Print (B : Integer);
186753: end bar;
18676@end example
18677@end quotation
18678
18679The first thing to do is to recompile your application (for instance, in
18680that case just by doing a @code{gnatmake main}, so that GNAT generates
18681the cross-referencing information.
18682You can then issue any of the following commands:
18683
18684@quotation
18685
18686
18687@itemize *
18688
18689@item
18690@code{gnatxref main.adb}
18691@code{gnatxref} generates cross-reference information for main.adb
18692and every unit 'with'ed by main.adb.
18693
18694The output would be:
18695
18696@quotation
18697
18698@example
18699B                                                      Type: Integer
18700  Decl: bar.ads           2:22
18701B                                                      Type: Integer
18702  Decl: main.ads          3:20
18703  Body: main.adb          2:20
18704  Ref:  main.adb          4:13     5:13     6:19
18705Bar                                                    Type: Unit
18706  Decl: bar.ads           1:9
18707  Ref:  main.adb          6:8      7:8
18708       main.ads           1:6
18709C                                                      Type: Integer
18710  Decl: main.ads          4:5
18711  Modi: main.adb          4:8
18712  Ref:  main.adb          7:19
18713D                                                      Type: Integer
18714  Decl: main.ads          6:5
18715  Modi: main.adb          5:8
18716Foo                                                    Type: Unit
18717  Decl: main.ads          3:15
18718  Body: main.adb          2:15
18719Main                                                    Type: Unit
18720  Decl: main.ads          2:9
18721  Body: main.adb          1:14
18722Print                                                   Type: Unit
18723  Decl: bar.ads           2:15
18724  Ref:  main.adb          6:12     7:12
18725@end example
18726@end quotation
18727
18728This shows that the entity @code{Main} is declared in main.ads, line 2, column 9,
18729its body is in main.adb, line 1, column 14 and is not referenced any where.
18730
18731The entity @code{Print} is declared in @code{bar.ads}, line 2, column 15 and it
18732is referenced in @code{main.adb}, line 6 column 12 and line 7 column 12.
18733
18734@item
18735@code{gnatxref package1.adb package2.ads}
18736@code{gnatxref} will generates cross-reference information for
18737@code{package1.adb}, @code{package2.ads} and any other package @code{with}ed by any
18738of these.
18739@end itemize
18740@end quotation
18741
18742@node Using gnatxref with vi,,General Usage,Examples of gnatxref Usage
18743@anchor{gnat_ugn/gnat_utility_programs using-gnatxref-with-vi}@anchor{15e}
18744@subsubsection Using @code{gnatxref} with @code{vi}
18745
18746
18747@code{gnatxref} can generate a tags file output, which can be used
18748directly from @code{vi}. Note that the standard version of @code{vi}
18749will not work properly with overloaded symbols. Consider using another
18750free implementation of @code{vi}, such as @code{vim}.
18751
18752@quotation
18753
18754@example
18755$ gnatxref -v gnatfind.adb > tags
18756@end example
18757@end quotation
18758
18759The following command will generate the tags file for @code{gnatfind} itself
18760(if the sources are in the search path!):
18761
18762@quotation
18763
18764@example
18765$ gnatxref -v gnatfind.adb > tags
18766@end example
18767@end quotation
18768
18769From @code{vi}, you can then use the command @code{:tag @emph{entity}}
18770(replacing @code{entity} by whatever you are looking for), and vi will
18771display a new file with the corresponding declaration of entity.
18772
18773@node Examples of gnatfind Usage,,Examples of gnatxref Usage,The Cross-Referencing Tools gnatxref and gnatfind
18774@anchor{gnat_ugn/gnat_utility_programs id15}@anchor{15f}@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatfind-usage}@anchor{159}
18775@subsection Examples of @code{gnatfind} Usage
18776
18777
18778
18779@itemize *
18780
18781@item
18782@code{gnatfind -f xyz:main.adb}
18783Find declarations for all entities xyz referenced at least once in
18784main.adb. The references are search in every library file in the search
18785path.
18786
18787The directories will be printed as well (as the @code{-f}
18788switch is set)
18789
18790The output will look like:
18791
18792@quotation
18793
18794@example
18795directory/main.ads:106:14: xyz <= declaration
18796directory/main.adb:24:10: xyz <= body
18797directory/foo.ads:45:23: xyz <= declaration
18798@end example
18799@end quotation
18800
18801I.e., one of the entities xyz found in main.adb is declared at
18802line 12 of main.ads (and its body is in main.adb), and another one is
18803declared at line 45 of foo.ads
18804
18805@item
18806@code{gnatfind -fs xyz:main.adb}
18807This is the same command as the previous one, but @code{gnatfind} will
18808display the content of the Ada source file lines.
18809
18810The output will look like:
18811
18812@example
18813directory/main.ads:106:14: xyz <= declaration
18814   procedure xyz;
18815directory/main.adb:24:10: xyz <= body
18816   procedure xyz is
18817directory/foo.ads:45:23: xyz <= declaration
18818   xyz : Integer;
18819@end example
18820
18821This can make it easier to find exactly the location your are looking
18822for.
18823
18824@item
18825@code{gnatfind -r "*x*":main.ads:123 foo.adb}
18826Find references to all entities containing an x that are
18827referenced on line 123 of main.ads.
18828The references will be searched only in main.ads and foo.adb.
18829
18830@item
18831@code{gnatfind main.ads:123}
18832Find declarations and bodies for all entities that are referenced on
18833line 123 of main.ads.
18834
18835This is the same as @code{gnatfind "*":main.adb:123`}
18836
18837@item
18838@code{gnatfind mydir/main.adb:123:45}
18839Find the declaration for the entity referenced at column 45 in
18840line 123 of file main.adb in directory mydir. Note that it
18841is usual to omit the identifier name when the column is given,
18842since the column position identifies a unique reference.
18843
18844The column has to be the beginning of the identifier, and should not
18845point to any character in the middle of the identifier.
18846@end itemize
18847
18848@node The Ada to HTML Converter gnathtml,,The Cross-Referencing Tools gnatxref and gnatfind,GNAT Utility Programs
18849@anchor{gnat_ugn/gnat_utility_programs the-ada-to-html-converter-gnathtml}@anchor{23}@anchor{gnat_ugn/gnat_utility_programs id16}@anchor{160}
18850@section The Ada to HTML Converter @code{gnathtml}
18851
18852
18853@geindex gnathtml
18854
18855@code{gnathtml} is a Perl script that allows Ada source files to be browsed using
18856standard Web browsers. For installation information, see @ref{161,,Installing gnathtml}.
18857
18858Ada reserved keywords are highlighted in a bold font and Ada comments in
18859a blue font. Unless your program was compiled with the gcc @code{-gnatx}
18860switch to suppress the generation of cross-referencing information, user
18861defined variables and types will appear in a different color; you will
18862be able to click on any identifier and go to its declaration.
18863
18864@menu
18865* Invoking gnathtml::
18866* Installing gnathtml::
18867
18868@end menu
18869
18870@node Invoking gnathtml,Installing gnathtml,,The Ada to HTML Converter gnathtml
18871@anchor{gnat_ugn/gnat_utility_programs invoking-gnathtml}@anchor{162}@anchor{gnat_ugn/gnat_utility_programs id17}@anchor{163}
18872@subsection Invoking @code{gnathtml}
18873
18874
18875The command line is as follows:
18876
18877@quotation
18878
18879@example
18880$ perl gnathtml.pl [ switches ] ada-files
18881@end example
18882@end quotation
18883
18884You can specify as many Ada files as you want. @code{gnathtml} will generate
18885an html file for every ada file, and a global file called @code{index.htm}.
18886This file is an index of every identifier defined in the files.
18887
18888The following switches are available:
18889
18890@geindex -83 (gnathtml)
18891
18892
18893@table @asis
18894
18895@item @code{83}
18896
18897Only the Ada 83 subset of keywords will be highlighted.
18898@end table
18899
18900@geindex -cc (gnathtml)
18901
18902
18903@table @asis
18904
18905@item @code{cc @emph{color}}
18906
18907This option allows you to change the color used for comments. The default
18908value is green. The color argument can be any name accepted by html.
18909@end table
18910
18911@geindex -d (gnathtml)
18912
18913
18914@table @asis
18915
18916@item @code{d}
18917
18918If the Ada files depend on some other files (for instance through
18919@code{with} clauses, the latter files will also be converted to html.
18920Only the files in the user project will be converted to html, not the files
18921in the run-time library itself.
18922@end table
18923
18924@geindex -D (gnathtml)
18925
18926
18927@table @asis
18928
18929@item @code{D}
18930
18931This command is the same as @code{-d} above, but @code{gnathtml} will
18932also look for files in the run-time library, and generate html files for them.
18933@end table
18934
18935@geindex -ext (gnathtml)
18936
18937
18938@table @asis
18939
18940@item @code{ext @emph{extension}}
18941
18942This option allows you to change the extension of the generated HTML files.
18943If you do not specify an extension, it will default to @code{htm}.
18944@end table
18945
18946@geindex -f (gnathtml)
18947
18948
18949@table @asis
18950
18951@item @code{f}
18952
18953By default, gnathtml will generate html links only for global entities
18954('with'ed units, global variables and types,...).  If you specify
18955@code{-f} on the command line, then links will be generated for local
18956entities too.
18957@end table
18958
18959@geindex -l (gnathtml)
18960
18961
18962@table @asis
18963
18964@item @code{l @emph{number}}
18965
18966If this switch is provided and @code{number} is not 0, then
18967@code{gnathtml} will number the html files every @code{number} line.
18968@end table
18969
18970@geindex -I (gnathtml)
18971
18972
18973@table @asis
18974
18975@item @code{I @emph{dir}}
18976
18977Specify a directory to search for library files (@code{.ALI} files) and
18978source files. You can provide several -I switches on the command line,
18979and the directories will be parsed in the order of the command line.
18980@end table
18981
18982@geindex -o (gnathtml)
18983
18984
18985@table @asis
18986
18987@item @code{o @emph{dir}}
18988
18989Specify the output directory for html files. By default, gnathtml will
18990saved the generated html files in a subdirectory named @code{html/}.
18991@end table
18992
18993@geindex -p (gnathtml)
18994
18995
18996@table @asis
18997
18998@item @code{p @emph{file}}
18999
19000If you are using Emacs and the most recent Emacs Ada mode, which provides
19001a full Integrated Development Environment for compiling, checking,
19002running and debugging applications, you may use @code{.gpr} files
19003to give the directories where Emacs can find sources and object files.
19004
19005Using this switch, you can tell gnathtml to use these files.
19006This allows you to get an html version of your application, even if it
19007is spread over multiple directories.
19008@end table
19009
19010@geindex -sc (gnathtml)
19011
19012
19013@table @asis
19014
19015@item @code{sc @emph{color}}
19016
19017This switch allows you to change the color used for symbol
19018definitions.
19019The default value is red. The color argument can be any name accepted by html.
19020@end table
19021
19022@geindex -t (gnathtml)
19023
19024
19025@table @asis
19026
19027@item @code{t @emph{file}}
19028
19029This switch provides the name of a file. This file contains a list of
19030file names to be converted, and the effect is exactly as though they had
19031appeared explicitly on the command line. This
19032is the recommended way to work around the command line length limit on some
19033systems.
19034@end table
19035
19036@node Installing gnathtml,,Invoking gnathtml,The Ada to HTML Converter gnathtml
19037@anchor{gnat_ugn/gnat_utility_programs installing-gnathtml}@anchor{161}@anchor{gnat_ugn/gnat_utility_programs id18}@anchor{164}
19038@subsection Installing @code{gnathtml}
19039
19040
19041@code{Perl} needs to be installed on your machine to run this script.
19042@code{Perl} is freely available for almost every architecture and
19043operating system via the Internet.
19044
19045On Unix systems, you  may want to modify  the  first line of  the script
19046@code{gnathtml},  to explicitly  specify  where Perl
19047is located. The syntax of this line is:
19048
19049@quotation
19050
19051@example
19052#!full_path_name_to_perl
19053@end example
19054@end quotation
19055
19056Alternatively, you may run the script using the following command line:
19057
19058@quotation
19059
19060@example
19061$ perl gnathtml.pl [ switches ] files
19062@end example
19063@end quotation
19064
19065@c -- +---------------------------------------------------------------------+
19066
19067@c -- | The following sections are present only in the PRO and GPL editions |
19068
19069@c -- +---------------------------------------------------------------------+
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
19080
19081@node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
19082@anchor{gnat_ugn/gnat_and_program_execution gnat-and-program-execution}@anchor{c}@anchor{gnat_ugn/gnat_and_program_execution doc}@anchor{165}@anchor{gnat_ugn/gnat_and_program_execution id1}@anchor{166}
19083@chapter GNAT and Program Execution
19084
19085
19086This chapter covers several topics:
19087
19088
19089@itemize *
19090
19091@item
19092@ref{167,,Running and Debugging Ada Programs}
19093
19094@item
19095@ref{25,,Profiling}
19096
19097@item
19098@ref{168,,Improving Performance}
19099
19100@item
19101@ref{169,,Overflow Check Handling in GNAT}
19102
19103@item
19104@ref{16a,,Performing Dimensionality Analysis in GNAT}
19105
19106@item
19107@ref{16b,,Stack Related Facilities}
19108
19109@item
19110@ref{16c,,Memory Management Issues}
19111@end itemize
19112
19113@menu
19114* Running and Debugging Ada Programs::
19115* Profiling::
19116* Improving Performance::
19117* Overflow Check Handling in GNAT::
19118* Performing Dimensionality Analysis in GNAT::
19119* Stack Related Facilities::
19120* Memory Management Issues::
19121
19122@end menu
19123
19124@node Running and Debugging Ada Programs,Profiling,,GNAT and Program Execution
19125@anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{167}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{24}
19126@section Running and Debugging Ada Programs
19127
19128
19129@geindex Debugging
19130
19131This section discusses how to debug Ada programs.
19132
19133An incorrect Ada program may be handled in three ways by the GNAT compiler:
19134
19135
19136@itemize *
19137
19138@item
19139The illegality may be a violation of the static semantics of Ada. In
19140that case GNAT diagnoses the constructs in the program that are illegal.
19141It is then a straightforward matter for the user to modify those parts of
19142the program.
19143
19144@item
19145The illegality may be a violation of the dynamic semantics of Ada. In
19146that case the program compiles and executes, but may generate incorrect
19147results, or may terminate abnormally with some exception.
19148
19149@item
19150When presented with a program that contains convoluted errors, GNAT
19151itself may terminate abnormally without providing full diagnostics on
19152the incorrect user program.
19153@end itemize
19154
19155@geindex Debugger
19156
19157@geindex gdb
19158
19159@menu
19160* The GNAT Debugger GDB::
19161* Running GDB::
19162* Introduction to GDB Commands::
19163* Using Ada Expressions::
19164* Calling User-Defined Subprograms::
19165* Using the next Command in a Function::
19166* Stopping When Ada Exceptions Are Raised::
19167* Ada Tasks::
19168* Debugging Generic Units::
19169* Remote Debugging with gdbserver::
19170* GNAT Abnormal Termination or Failure to Terminate::
19171* Naming Conventions for GNAT Source Files::
19172* Getting Internal Debugging Information::
19173* Stack Traceback::
19174* Pretty-Printers for the GNAT runtime::
19175
19176@end menu
19177
19178@node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
19179@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{16d}@anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{16e}
19180@subsection The GNAT Debugger GDB
19181
19182
19183@code{GDB} is a general purpose, platform-independent debugger that
19184can be used to debug mixed-language programs compiled with @code{gcc},
19185and in particular is capable of debugging Ada programs compiled with
19186GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19187complex Ada data structures.
19188
19189See @cite{Debugging with GDB},
19190for full details on the usage of @code{GDB}, including a section on
19191its usage on programs. This manual should be consulted for full
19192details. The section that follows is a brief introduction to the
19193philosophy and use of @code{GDB}.
19194
19195When GNAT programs are compiled, the compiler optionally writes debugging
19196information into the generated object file, including information on
19197line numbers, and on declared types and variables. This information is
19198separate from the generated code. It makes the object files considerably
19199larger, but it does not add to the size of the actual executable that
19200will be loaded into memory, and has no impact on run-time performance. The
19201generation of debug information is triggered by the use of the
19202@code{-g} switch in the @code{gcc} or @code{gnatmake} command
19203used to carry out the compilations. It is important to emphasize that
19204the use of these options does not change the generated code.
19205
19206The debugging information is written in standard system formats that
19207are used by many tools, including debuggers and profilers. The format
19208of the information is typically designed to describe C types and
19209semantics, but GNAT implements a translation scheme which allows full
19210details about Ada types and variables to be encoded into these
19211standard C formats. Details of this encoding scheme may be found in
19212the file exp_dbug.ads in the GNAT source distribution. However, the
19213details of this encoding are, in general, of no interest to a user,
19214since @code{GDB} automatically performs the necessary decoding.
19215
19216When a program is bound and linked, the debugging information is
19217collected from the object files, and stored in the executable image of
19218the program. Again, this process significantly increases the size of
19219the generated executable file, but it does not increase the size of
19220the executable program itself. Furthermore, if this program is run in
19221the normal manner, it runs exactly as if the debug information were
19222not present, and takes no more actual memory.
19223
19224However, if the program is run under control of @code{GDB}, the
19225debugger is activated.  The image of the program is loaded, at which
19226point it is ready to run.  If a run command is given, then the program
19227will run exactly as it would have if @code{GDB} were not present. This
19228is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19229entirely non-intrusive until a breakpoint is encountered.  If no
19230breakpoint is ever hit, the program will run exactly as it would if no
19231debugger were present. When a breakpoint is hit, @code{GDB} accesses
19232the debugging information and can respond to user commands to inspect
19233variables, and more generally to report on the state of execution.
19234
19235@node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
19236@anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{16f}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{170}
19237@subsection Running GDB
19238
19239
19240This section describes how to initiate the debugger.
19241
19242The debugger can be launched from a @code{GPS} menu or
19243directly from the command line. The description below covers the latter use.
19244All the commands shown can be used in the @code{GPS} debug console window,
19245but there are usually more GUI-based ways to achieve the same effect.
19246
19247The command to run @code{GDB} is
19248
19249@quotation
19250
19251@example
19252$ gdb program
19253@end example
19254@end quotation
19255
19256where @code{program} is the name of the executable file. This
19257activates the debugger and results in a prompt for debugger commands.
19258The simplest command is simply @code{run}, which causes the program to run
19259exactly as if the debugger were not present. The following section
19260describes some of the additional commands that can be given to @code{GDB}.
19261
19262@node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
19263@anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{171}@anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{172}
19264@subsection Introduction to GDB Commands
19265
19266
19267@code{GDB} contains a large repertoire of commands.
19268See @cite{Debugging with GDB} for extensive documentation on the use
19269of these commands, together with examples of their use. Furthermore,
19270the command @emph{help} invoked from within GDB activates a simple help
19271facility which summarizes the available commands and their options.
19272In this section we summarize a few of the most commonly
19273used commands to give an idea of what @code{GDB} is about. You should create
19274a simple program with debugging information and experiment with the use of
19275these @code{GDB} commands on the program as you read through the
19276following section.
19277
19278
19279@itemize *
19280
19281@item
19282
19283@table @asis
19284
19285@item @code{set args @emph{arguments}}
19286
19287The @emph{arguments} list above is a list of arguments to be passed to
19288the program on a subsequent run command, just as though the arguments
19289had been entered on a normal invocation of the program. The @code{set args}
19290command is not needed if the program does not require arguments.
19291@end table
19292
19293@item
19294
19295@table @asis
19296
19297@item @code{run}
19298
19299The @code{run} command causes execution of the program to start from
19300the beginning. If the program is already running, that is to say if
19301you are currently positioned at a breakpoint, then a prompt will ask
19302for confirmation that you want to abandon the current execution and
19303restart.
19304@end table
19305
19306@item
19307
19308@table @asis
19309
19310@item @code{breakpoint @emph{location}}
19311
19312The breakpoint command sets a breakpoint, that is to say a point at which
19313execution will halt and @code{GDB} will await further
19314commands. @emph{location} is
19315either a line number within a file, given in the format @code{file:linenumber},
19316or it is the name of a subprogram. If you request that a breakpoint be set on
19317a subprogram that is overloaded, a prompt will ask you to specify on which of
19318those subprograms you want to breakpoint. You can also
19319specify that all of them should be breakpointed. If the program is run
19320and execution encounters the breakpoint, then the program
19321stops and @code{GDB} signals that the breakpoint was encountered by
19322printing the line of code before which the program is halted.
19323@end table
19324
19325@item
19326
19327@table @asis
19328
19329@item @code{catch exception @emph{name}}
19330
19331This command causes the program execution to stop whenever exception
19332@code{name} is raised.  If @code{name} is omitted, then the execution is
19333suspended when any exception is raised.
19334@end table
19335
19336@item
19337
19338@table @asis
19339
19340@item @code{print @emph{expression}}
19341
19342This will print the value of the given expression. Most simple
19343Ada expression formats are properly handled by @code{GDB}, so the expression
19344can contain function calls, variables, operators, and attribute references.
19345@end table
19346
19347@item
19348
19349@table @asis
19350
19351@item @code{continue}
19352
19353Continues execution following a breakpoint, until the next breakpoint or the
19354termination of the program.
19355@end table
19356
19357@item
19358
19359@table @asis
19360
19361@item @code{step}
19362
19363Executes a single line after a breakpoint. If the next statement
19364is a subprogram call, execution continues into (the first statement of)
19365the called subprogram.
19366@end table
19367
19368@item
19369
19370@table @asis
19371
19372@item @code{next}
19373
19374Executes a single line. If this line is a subprogram call, executes and
19375returns from the call.
19376@end table
19377
19378@item
19379
19380@table @asis
19381
19382@item @code{list}
19383
19384Lists a few lines around the current source location. In practice, it
19385is usually more convenient to have a separate edit window open with the
19386relevant source file displayed. Successive applications of this command
19387print subsequent lines. The command can be given an argument which is a
19388line number, in which case it displays a few lines around the specified one.
19389@end table
19390
19391@item
19392
19393@table @asis
19394
19395@item @code{backtrace}
19396
19397Displays a backtrace of the call chain. This command is typically
19398used after a breakpoint has occurred, to examine the sequence of calls that
19399leads to the current breakpoint. The display includes one line for each
19400activation record (frame) corresponding to an active subprogram.
19401@end table
19402
19403@item
19404
19405@table @asis
19406
19407@item @code{up}
19408
19409At a breakpoint, @code{GDB} can display the values of variables local
19410to the current frame. The command @code{up} can be used to
19411examine the contents of other active frames, by moving the focus up
19412the stack, that is to say from callee to caller, one frame at a time.
19413@end table
19414
19415@item
19416
19417@table @asis
19418
19419@item @code{down}
19420
19421Moves the focus of @code{GDB} down from the frame currently being
19422examined to the frame of its callee (the reverse of the previous command),
19423@end table
19424
19425@item
19426
19427@table @asis
19428
19429@item @code{frame @emph{n}}
19430
19431Inspect the frame with the given number. The value 0 denotes the frame
19432of the current breakpoint, that is to say the top of the call stack.
19433@end table
19434
19435@item
19436
19437@table @asis
19438
19439@item @code{kill}
19440
19441Kills the child process in which the program is running under GDB.
19442This may be useful for several purposes:
19443
19444
19445@itemize *
19446
19447@item
19448It allows you to recompile and relink your program, since on many systems
19449you cannot regenerate an executable file while it is running in a process.
19450
19451@item
19452You can run your program outside the debugger, on systems that do not
19453permit executing a program outside GDB while breakpoints are set
19454within GDB.
19455
19456@item
19457It allows you to debug a core dump rather than a running process.
19458@end itemize
19459@end table
19460@end itemize
19461
19462The above list is a very short introduction to the commands that
19463@code{GDB} provides. Important additional capabilities, including conditional
19464breakpoints, the ability to execute command sequences on a breakpoint,
19465the ability to debug at the machine instruction level and many other
19466features are described in detail in @cite{Debugging with GDB}.
19467Note that most commands can be abbreviated
19468(for example, c for continue, bt for backtrace).
19469
19470@node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
19471@anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{173}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{174}
19472@subsection Using Ada Expressions
19473
19474
19475@geindex Ada expressions (in gdb)
19476
19477@code{GDB} supports a fairly large subset of Ada expression syntax, with some
19478extensions. The philosophy behind the design of this subset is
19479
19480@quotation
19481
19482
19483@itemize *
19484
19485@item
19486That @code{GDB} should provide basic literals and access to operations for
19487arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19488leaving more sophisticated computations to subprograms written into the
19489program (which therefore may be called from @code{GDB}).
19490
19491@item
19492That type safety and strict adherence to Ada language restrictions
19493are not particularly relevant in a debugging context.
19494
19495@item
19496That brevity is important to the @code{GDB} user.
19497@end itemize
19498@end quotation
19499
19500Thus, for brevity, the debugger acts as if there were
19501implicit @code{with} and @code{use} clauses in effect for all user-written
19502packages, thus making it unnecessary to fully qualify most names with
19503their packages, regardless of context. Where this causes ambiguity,
19504@code{GDB} asks the user's intent.
19505
19506For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19507
19508@node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
19509@anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{175}@anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{176}
19510@subsection Calling User-Defined Subprograms
19511
19512
19513An important capability of @code{GDB} is the ability to call user-defined
19514subprograms while debugging. This is achieved simply by entering
19515a subprogram call statement in the form:
19516
19517@quotation
19518
19519@example
19520call subprogram-name (parameters)
19521@end example
19522@end quotation
19523
19524The keyword @code{call} can be omitted in the normal case where the
19525@code{subprogram-name} does not coincide with any of the predefined
19526@code{GDB} commands.
19527
19528The effect is to invoke the given subprogram, passing it the
19529list of parameters that is supplied. The parameters can be expressions and
19530can include variables from the program being debugged. The
19531subprogram must be defined
19532at the library level within your program, and @code{GDB} will call the
19533subprogram within the environment of your program execution (which
19534means that the subprogram is free to access or even modify variables
19535within your program).
19536
19537The most important use of this facility is in allowing the inclusion of
19538debugging routines that are tailored to particular data structures
19539in your program. Such debugging routines can be written to provide a suitably
19540high-level description of an abstract type, rather than a low-level dump
19541of its physical layout. After all, the standard
19542@code{GDB print} command only knows the physical layout of your
19543types, not their abstract meaning. Debugging routines can provide information
19544at the desired semantic level and are thus enormously useful.
19545
19546For example, when debugging GNAT itself, it is crucial to have access to
19547the contents of the tree nodes used to represent the program internally.
19548But tree nodes are represented simply by an integer value (which in turn
19549is an index into a table of nodes).
19550Using the @code{print} command on a tree node would simply print this integer
19551value, which is not very useful. But the PN routine (defined in file
19552treepr.adb in the GNAT sources) takes a tree node as input, and displays
19553a useful high level representation of the tree node, which includes the
19554syntactic category of the node, its position in the source, the integers
19555that denote descendant nodes and parent node, as well as varied
19556semantic information. To study this example in more detail, you might want to
19557look at the body of the PN procedure in the stated file.
19558
19559Another useful application of this capability is to deal with situations of
19560complex data which are not handled suitably by GDB. For example, if you specify
19561Convention Fortran for a multi-dimensional array, GDB does not know that
19562the ordering of array elements has been switched and will not properly
19563address the array elements. In such a case, instead of trying to print the
19564elements directly from GDB, you can write a callable procedure that prints
19565the elements in the desired format.
19566
19567@node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
19568@anchor{gnat_ugn/gnat_and_program_execution using-the-next-command-in-a-function}@anchor{177}@anchor{gnat_ugn/gnat_and_program_execution id8}@anchor{178}
19569@subsection Using the @emph{next} Command in a Function
19570
19571
19572When you use the @code{next} command in a function, the current source
19573location will advance to the next statement as usual. A special case
19574arises in the case of a @code{return} statement.
19575
19576Part of the code for a return statement is the 'epilogue' of the function.
19577This is the code that returns to the caller. There is only one copy of
19578this epilogue code, and it is typically associated with the last return
19579statement in the function if there is more than one return. In some
19580implementations, this epilogue is associated with the first statement
19581of the function.
19582
19583The result is that if you use the @code{next} command from a return
19584statement that is not the last return statement of the function you
19585may see a strange apparent jump to the last return statement or to
19586the start of the function. You should simply ignore this odd jump.
19587The value returned is always that from the first return statement
19588that was stepped through.
19589
19590@node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
19591@anchor{gnat_ugn/gnat_and_program_execution stopping-when-ada-exceptions-are-raised}@anchor{179}@anchor{gnat_ugn/gnat_and_program_execution id9}@anchor{17a}
19592@subsection Stopping When Ada Exceptions Are Raised
19593
19594
19595@geindex Exceptions (in gdb)
19596
19597You can set catchpoints that stop the program execution when your program
19598raises selected exceptions.
19599
19600
19601@itemize *
19602
19603@item
19604
19605@table @asis
19606
19607@item @code{catch exception}
19608
19609Set a catchpoint that stops execution whenever (any task in the) program
19610raises any exception.
19611@end table
19612
19613@item
19614
19615@table @asis
19616
19617@item @code{catch exception @emph{name}}
19618
19619Set a catchpoint that stops execution whenever (any task in the) program
19620raises the exception @emph{name}.
19621@end table
19622
19623@item
19624
19625@table @asis
19626
19627@item @code{catch exception unhandled}
19628
19629Set a catchpoint that stops executing whenever (any task in the) program
19630raises an exception for which there is no handler.
19631@end table
19632
19633@item
19634
19635@table @asis
19636
19637@item @code{info exceptions}, @code{info exceptions @emph{regexp}}
19638
19639The @code{info exceptions} command permits the user to examine all defined
19640exceptions within Ada programs. With a regular expression, @emph{regexp}, as
19641argument, prints out only those exceptions whose name matches @emph{regexp}.
19642@end table
19643@end itemize
19644
19645@geindex Tasks (in gdb)
19646
19647@node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
19648@anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{17b}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{17c}
19649@subsection Ada Tasks
19650
19651
19652@code{GDB} allows the following task-related commands:
19653
19654
19655@itemize *
19656
19657@item
19658
19659@table @asis
19660
19661@item @code{info tasks}
19662
19663This command shows a list of current Ada tasks, as in the following example:
19664
19665@example
19666(gdb) info tasks
19667  ID       TID P-ID   Thread Pri State                 Name
19668   1   8088000   0   807e000  15 Child Activation Wait main_task
19669   2   80a4000   1   80ae000  15 Accept/Select Wait    b
19670   3   809a800   1   80a4800  15 Child Activation Wait a
19671*  4   80ae800   3   80b8000  15 Running               c
19672@end example
19673
19674In this listing, the asterisk before the first task indicates it to be the
19675currently running task. The first column lists the task ID that is used
19676to refer to tasks in the following commands.
19677@end table
19678@end itemize
19679
19680@geindex Breakpoints and tasks
19681
19682
19683@itemize *
19684
19685@item
19686@code{break`@w{`}*linespec* `@w{`}task} @emph{taskid}, @code{break} @emph{linespec} @code{task} @emph{taskid} @code{if} ...
19687
19688@quotation
19689
19690These commands are like the @code{break ... thread ...}.
19691@emph{linespec} specifies source lines.
19692
19693Use the qualifier @code{task @emph{taskid}} with a breakpoint command
19694to specify that you only want @code{GDB} to stop the program when a
19695particular Ada task reaches this breakpoint. @emph{taskid} is one of the
19696numeric task identifiers assigned by @code{GDB}, shown in the first
19697column of the @code{info tasks} display.
19698
19699If you do not specify @code{task @emph{taskid}} when you set a
19700breakpoint, the breakpoint applies to @emph{all} tasks of your
19701program.
19702
19703You can use the @code{task} qualifier on conditional breakpoints as
19704well; in this case, place @code{task @emph{taskid}} before the
19705breakpoint condition (before the @code{if}).
19706@end quotation
19707@end itemize
19708
19709@geindex Task switching (in gdb)
19710
19711
19712@itemize *
19713
19714@item
19715@code{task @emph{taskno}}
19716
19717@quotation
19718
19719This command allows switching to the task referred by @emph{taskno}. In
19720particular, this allows browsing of the backtrace of the specified
19721task. It is advisable to switch back to the original task before
19722continuing execution otherwise the scheduling of the program may be
19723perturbed.
19724@end quotation
19725@end itemize
19726
19727For more detailed information on the tasking support,
19728see @cite{Debugging with GDB}.
19729
19730@geindex Debugging Generic Units
19731
19732@geindex Generics
19733
19734@node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
19735@anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{17d}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{17e}
19736@subsection Debugging Generic Units
19737
19738
19739GNAT always uses code expansion for generic instantiation. This means that
19740each time an instantiation occurs, a complete copy of the original code is
19741made, with appropriate substitutions of formals by actuals.
19742
19743It is not possible to refer to the original generic entities in
19744@code{GDB}, but it is always possible to debug a particular instance of
19745a generic, by using the appropriate expanded names. For example, if we have
19746
19747@quotation
19748
19749@example
19750procedure g is
19751
19752   generic package k is
19753      procedure kp (v1 : in out integer);
19754   end k;
19755
19756   package body k is
19757      procedure kp (v1 : in out integer) is
19758      begin
19759         v1 := v1 + 1;
19760      end kp;
19761   end k;
19762
19763   package k1 is new k;
19764   package k2 is new k;
19765
19766   var : integer := 1;
19767
19768begin
19769   k1.kp (var);
19770   k2.kp (var);
19771   k1.kp (var);
19772   k2.kp (var);
19773end;
19774@end example
19775@end quotation
19776
19777Then to break on a call to procedure kp in the k2 instance, simply
19778use the command:
19779
19780@quotation
19781
19782@example
19783(gdb) break g.k2.kp
19784@end example
19785@end quotation
19786
19787When the breakpoint occurs, you can step through the code of the
19788instance in the normal manner and examine the values of local variables, as for
19789other units.
19790
19791@geindex Remote Debugging with gdbserver
19792
19793@node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
19794@anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{17f}@anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{180}
19795@subsection Remote Debugging with gdbserver
19796
19797
19798On platforms where gdbserver is supported, it is possible to use this tool
19799to debug your application remotely.  This can be useful in situations
19800where the program needs to be run on a target host that is different
19801from the host used for development, particularly when the target has
19802a limited amount of resources (either CPU and/or memory).
19803
19804To do so, start your program using gdbserver on the target machine.
19805gdbserver then automatically suspends the execution of your program
19806at its entry point, waiting for a debugger to connect to it.  The
19807following commands starts an application and tells gdbserver to
19808wait for a connection with the debugger on localhost port 4444.
19809
19810@quotation
19811
19812@example
19813$ gdbserver localhost:4444 program
19814Process program created; pid = 5685
19815Listening on port 4444
19816@end example
19817@end quotation
19818
19819Once gdbserver has started listening, we can tell the debugger to establish
19820a connection with this gdbserver, and then start the same debugging session
19821as if the program was being debugged on the same host, directly under
19822the control of GDB.
19823
19824@quotation
19825
19826@example
19827$ gdb program
19828(gdb) target remote targethost:4444
19829Remote debugging using targethost:4444
198300x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19831(gdb) b foo.adb:3
19832Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19833(gdb) continue
19834Continuing.
19835
19836Breakpoint 1, foo () at foo.adb:4
198374       end foo;
19838@end example
19839@end quotation
19840
19841It is also possible to use gdbserver to attach to an already running
19842program, in which case the execution of that program is simply suspended
19843until the connection between the debugger and gdbserver is established.
19844
19845For more information on how to use gdbserver, see the @emph{Using the gdbserver Program}
19846section in @cite{Debugging with GDB}.
19847GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
19848
19849@geindex Abnormal Termination or Failure to Terminate
19850
19851@node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
19852@anchor{gnat_ugn/gnat_and_program_execution gnat-abnormal-termination-or-failure-to-terminate}@anchor{181}@anchor{gnat_ugn/gnat_and_program_execution id13}@anchor{182}
19853@subsection GNAT Abnormal Termination or Failure to Terminate
19854
19855
19856When presented with programs that contain serious errors in syntax
19857or semantics,
19858GNAT may on rare occasions  experience problems in operation, such
19859as aborting with a
19860segmentation fault or illegal memory access, raising an internal
19861exception, terminating abnormally, or failing to terminate at all.
19862In such cases, you can activate
19863various features of GNAT that can help you pinpoint the construct in your
19864program that is the likely source of the problem.
19865
19866The following strategies are presented in increasing order of
19867difficulty, corresponding to your experience in using GNAT and your
19868familiarity with compiler internals.
19869
19870
19871@itemize *
19872
19873@item
19874Run @code{gcc} with the @code{-gnatf}. This first
19875switch causes all errors on a given line to be reported. In its absence,
19876only the first error on a line is displayed.
19877
19878The @code{-gnatdO} switch causes errors to be displayed as soon as they
19879are encountered, rather than after compilation is terminated. If GNAT
19880terminates prematurely or goes into an infinite loop, the last error
19881message displayed may help to pinpoint the culprit.
19882
19883@item
19884Run @code{gcc} with the @code{-v} (verbose) switch. In this
19885mode, @code{gcc} produces ongoing information about the progress of the
19886compilation and provides the name of each procedure as code is
19887generated. This switch allows you to find which Ada procedure was being
19888compiled when it encountered a code generation problem.
19889@end itemize
19890
19891@geindex -gnatdc switch
19892
19893
19894@itemize *
19895
19896@item
19897Run @code{gcc} with the @code{-gnatdc} switch. This is a GNAT specific
19898switch that does for the front-end what @code{-v} does
19899for the back end. The system prints the name of each unit,
19900either a compilation unit or nested unit, as it is being analyzed.
19901
19902@item
19903Finally, you can start
19904@code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19905front-end of GNAT, and can be run independently (normally it is just
19906called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
19907would on a C program (but @ref{16d,,The GNAT Debugger GDB} for caveats). The
19908@code{where} command is the first line of attack; the variable
19909@code{lineno} (seen by @code{print lineno}), used by the second phase of
19910@code{gnat1} and by the @code{gcc} backend, indicates the source line at
19911which the execution stopped, and @code{input_file name} indicates the name of
19912the source file.
19913@end itemize
19914
19915@node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
19916@anchor{gnat_ugn/gnat_and_program_execution naming-conventions-for-gnat-source-files}@anchor{183}@anchor{gnat_ugn/gnat_and_program_execution id14}@anchor{184}
19917@subsection Naming Conventions for GNAT Source Files
19918
19919
19920In order to examine the workings of the GNAT system, the following
19921brief description of its organization may be helpful:
19922
19923
19924@itemize *
19925
19926@item
19927Files with prefix @code{sc} contain the lexical scanner.
19928
19929@item
19930All files prefixed with @code{par} are components of the parser. The
19931numbers correspond to chapters of the Ada Reference Manual. For example,
19932parsing of select statements can be found in @code{par-ch9.adb}.
19933
19934@item
19935All files prefixed with @code{sem} perform semantic analysis. The
19936numbers correspond to chapters of the Ada standard. For example, all
19937issues involving context clauses can be found in @code{sem_ch10.adb}. In
19938addition, some features of the language require sufficient special processing
19939to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19940dynamic dispatching, etc.
19941
19942@item
19943All files prefixed with @code{exp} perform normalization and
19944expansion of the intermediate representation (abstract syntax tree, or AST).
19945these files use the same numbering scheme as the parser and semantics files.
19946For example, the construction of record initialization procedures is done in
19947@code{exp_ch3.adb}.
19948
19949@item
19950The files prefixed with @code{bind} implement the binder, which
19951verifies the consistency of the compilation, determines an order of
19952elaboration, and generates the bind file.
19953
19954@item
19955The files @code{atree.ads} and @code{atree.adb} detail the low-level
19956data structures used by the front-end.
19957
19958@item
19959The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
19960the abstract syntax tree as produced by the parser.
19961
19962@item
19963The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
19964all entities, computed during semantic analysis.
19965
19966@item
19967Library management issues are dealt with in files with prefix
19968@code{lib}.
19969
19970@geindex Annex A (in Ada Reference Manual)
19971
19972@item
19973Ada files with the prefix @code{a-} are children of @code{Ada}, as
19974defined in Annex A.
19975
19976@geindex Annex B (in Ada reference Manual)
19977
19978@item
19979Files with prefix @code{i-} are children of @code{Interfaces}, as
19980defined in Annex B.
19981
19982@geindex System (package in Ada Reference Manual)
19983
19984@item
19985Files with prefix @code{s-} are children of @code{System}. This includes
19986both language-defined children and GNAT run-time routines.
19987
19988@geindex GNAT (package)
19989
19990@item
19991Files with prefix @code{g-} are children of @code{GNAT}. These are useful
19992general-purpose packages, fully documented in their specs. All
19993the other @code{.c} files are modifications of common @code{gcc} files.
19994@end itemize
19995
19996@node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
19997@anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{185}@anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{186}
19998@subsection Getting Internal Debugging Information
19999
20000
20001Most compilers have internal debugging switches and modes. GNAT
20002does also, except GNAT internal debugging switches and modes are not
20003secret. A summary and full description of all the compiler and binder
20004debug flags are in the file @code{debug.adb}. You must obtain the
20005sources of the compiler to see the full detailed effects of these flags.
20006
20007The switches that print the source of the program (reconstructed from
20008the internal tree) are of general interest for user programs, as are the
20009options to print
20010the full internal tree, and the entity table (the symbol table
20011information). The reconstructed source provides a readable version of the
20012program after the front-end has completed analysis and  expansion,
20013and is useful when studying the performance of specific constructs.
20014For example, constraint checks are indicated, complex aggregates
20015are replaced with loops and assignments, and tasking primitives
20016are replaced with run-time calls.
20017
20018@geindex traceback
20019
20020@geindex stack traceback
20021
20022@geindex stack unwinding
20023
20024@node Stack Traceback,Pretty-Printers for the GNAT runtime,Getting Internal Debugging Information,Running and Debugging Ada Programs
20025@anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{187}@anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{188}
20026@subsection Stack Traceback
20027
20028
20029Traceback is a mechanism to display the sequence of subprogram calls that
20030leads to a specified execution point in a program. Often (but not always)
20031the execution point is an instruction at which an exception has been raised.
20032This mechanism is also known as @emph{stack unwinding} because it obtains
20033its information by scanning the run-time stack and recovering the activation
20034records of all active subprograms. Stack unwinding is one of the most
20035important tools for program debugging.
20036
20037The first entry stored in traceback corresponds to the deepest calling level,
20038that is to say the subprogram currently executing the instruction
20039from which we want to obtain the traceback.
20040
20041Note that there is no runtime performance penalty when stack traceback
20042is enabled, and no exception is raised during program execution.
20043
20044@geindex traceback
20045@geindex non-symbolic
20046
20047@menu
20048* Non-Symbolic Traceback::
20049* Symbolic Traceback::
20050
20051@end menu
20052
20053@node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
20054@anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{189}@anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{18a}
20055@subsubsection Non-Symbolic Traceback
20056
20057
20058Note: this feature is not supported on all platforms. See
20059@code{GNAT.Traceback} spec in @code{g-traceb.ads}
20060for a complete list of supported platforms.
20061
20062@subsubheading Tracebacks From an Unhandled Exception
20063
20064
20065A runtime non-symbolic traceback is a list of addresses of call instructions.
20066To enable this feature you must use the @code{-E}
20067@code{gnatbind} option. With this option a stack traceback is stored as part
20068of exception information. You can retrieve this information using the
20069@code{addr2line} tool.
20070
20071Here is a simple example:
20072
20073@quotation
20074
20075@example
20076procedure STB is
20077
20078   procedure P1 is
20079   begin
20080      raise Constraint_Error;
20081   end P1;
20082
20083   procedure P2 is
20084   begin
20085      P1;
20086   end P2;
20087
20088begin
20089   P2;
20090end STB;
20091@end example
20092
20093@example
20094$ gnatmake stb -bargs -E
20095$ stb
20096
20097Execution terminated by unhandled exception
20098Exception name: CONSTRAINT_ERROR
20099Message: stb.adb:5
20100Call stack traceback locations:
201010x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20102@end example
20103@end quotation
20104
20105As we see the traceback lists a sequence of addresses for the unhandled
20106exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
20107guess that this exception come from procedure P1. To translate these
20108addresses into the source lines where the calls appear, the
20109@code{addr2line} tool, described below, is invaluable. The use of this tool
20110requires the program to be compiled with debug information.
20111
20112@quotation
20113
20114@example
20115$ gnatmake -g stb -bargs -E
20116$ stb
20117
20118Execution terminated by unhandled exception
20119Exception name: CONSTRAINT_ERROR
20120Message: stb.adb:5
20121Call stack traceback locations:
201220x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
20123
20124$ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
20125   0x4011f1 0x77e892a4
20126
2012700401373 at d:/stb/stb.adb:5
201280040138B at d:/stb/stb.adb:10
201290040139C at d:/stb/stb.adb:14
2013000401335 at d:/stb/b~stb.adb:104
20131004011C4 at /build/.../crt1.c:200
20132004011F1 at /build/.../crt1.c:222
2013377E892A4 in ?? at ??:0
20134@end example
20135@end quotation
20136
20137The @code{addr2line} tool has several other useful options:
20138
20139@quotation
20140
20141
20142@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
20143@item
20144
20145@code{--functions}
20146
20147@tab
20148
20149to get the function name corresponding to any location
20150
20151@item
20152
20153@code{--demangle=gnat}
20154
20155@tab
20156
20157to use the gnat decoding mode for the function names.
20158Note that for binutils version 2.9.x the option is
20159simply @code{--demangle}.
20160
20161@end multitable
20162
20163
20164@example
20165$ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20166   0x40139c 0x401335 0x4011c4 0x4011f1
20167
2016800401373 in stb.p1 at d:/stb/stb.adb:5
201690040138B in stb.p2 at d:/stb/stb.adb:10
201700040139C in stb at d:/stb/stb.adb:14
2017100401335 in main at d:/stb/b~stb.adb:104
20172004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
20173004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
20174@end example
20175@end quotation
20176
20177From this traceback we can see that the exception was raised in
20178@code{stb.adb} at line 5, which was reached from a procedure call in
20179@code{stb.adb} at line 10, and so on. The @code{b~std.adb} is the binder file,
20180which contains the call to the main program.
20181@ref{11c,,Running gnatbind}. The remaining entries are assorted runtime routines,
20182and the output will vary from platform to platform.
20183
20184It is also possible to use @code{GDB} with these traceback addresses to debug
20185the program. For example, we can break at a given code location, as reported
20186in the stack traceback:
20187
20188@quotation
20189
20190@example
20191$ gdb -nw stb
20192@end example
20193@end quotation
20194
20195Furthermore, this feature is not implemented inside Windows DLL. Only
20196the non-symbolic traceback is reported in this case.
20197
20198@quotation
20199
20200@example
20201(gdb) break *0x401373
20202Breakpoint 1 at 0x401373: file stb.adb, line 5.
20203@end example
20204@end quotation
20205
20206It is important to note that the stack traceback addresses
20207do not change when debug information is included. This is particularly useful
20208because it makes it possible to release software without debug information (to
20209minimize object size), get a field report that includes a stack traceback
20210whenever an internal bug occurs, and then be able to retrieve the sequence
20211of calls with the same program compiled with debug information.
20212
20213@subsubheading Tracebacks From Exception Occurrences
20214
20215
20216Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
20217The stack traceback is attached to the exception information string, and can
20218be retrieved in an exception handler within the Ada program, by means of the
20219Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20220
20221@quotation
20222
20223@example
20224with Ada.Text_IO;
20225with Ada.Exceptions;
20226
20227procedure STB is
20228
20229   use Ada;
20230   use Ada.Exceptions;
20231
20232   procedure P1 is
20233      K : Positive := 1;
20234   begin
20235      K := K - 1;
20236   exception
20237      when E : others =>
20238         Text_IO.Put_Line (Exception_Information (E));
20239   end P1;
20240
20241   procedure P2 is
20242   begin
20243      P1;
20244   end P2;
20245
20246begin
20247   P2;
20248end STB;
20249@end example
20250@end quotation
20251
20252This program will output:
20253
20254@quotation
20255
20256@example
20257$ stb
20258
20259Exception name: CONSTRAINT_ERROR
20260Message: stb.adb:12
20261Call stack traceback locations:
202620x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20263@end example
20264@end quotation
20265
20266@subsubheading Tracebacks From Anywhere in a Program
20267
20268
20269It is also possible to retrieve a stack traceback from anywhere in a
20270program. For this you need to
20271use the @code{GNAT.Traceback} API. This package includes a procedure called
20272@code{Call_Chain} that computes a complete stack traceback, as well as useful
20273display procedures described below. It is not necessary to use the
20274@code{-E} @code{gnatbind} option in this case, because the stack traceback mechanism
20275is invoked explicitly.
20276
20277In the following example we compute a traceback at a specific location in
20278the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20279convert addresses to strings:
20280
20281@quotation
20282
20283@example
20284with Ada.Text_IO;
20285with GNAT.Traceback;
20286with GNAT.Debug_Utilities;
20287
20288procedure STB is
20289
20290   use Ada;
20291   use GNAT;
20292   use GNAT.Traceback;
20293
20294   procedure P1 is
20295      TB  : Tracebacks_Array (1 .. 10);
20296      --  We are asking for a maximum of 10 stack frames.
20297      Len : Natural;
20298      --  Len will receive the actual number of stack frames returned.
20299   begin
20300      Call_Chain (TB, Len);
20301
20302      Text_IO.Put ("In STB.P1 : ");
20303
20304      for K in 1 .. Len loop
20305         Text_IO.Put (Debug_Utilities.Image (TB (K)));
20306         Text_IO.Put (' ');
20307      end loop;
20308
20309      Text_IO.New_Line;
20310   end P1;
20311
20312   procedure P2 is
20313   begin
20314      P1;
20315   end P2;
20316
20317begin
20318   P2;
20319end STB;
20320@end example
20321
20322@example
20323$ gnatmake -g stb
20324$ stb
20325
20326In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
2032716#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20328@end example
20329@end quotation
20330
20331You can then get further information by invoking the @code{addr2line}
20332tool as described earlier (note that the hexadecimal addresses
20333need to be specified in C format, with a leading '0x').
20334
20335@geindex traceback
20336@geindex symbolic
20337
20338@node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
20339@anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{18b}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{18c}
20340@subsubsection Symbolic Traceback
20341
20342
20343A symbolic traceback is a stack traceback in which procedure names are
20344associated with each code location.
20345
20346Note that this feature is not supported on all platforms. See
20347@code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
20348list of currently supported platforms.
20349
20350Note that the symbolic traceback requires that the program be compiled
20351with debug information. If it is not compiled with debug information
20352only the non-symbolic information will be valid.
20353
20354@subsubheading Tracebacks From Exception Occurrences
20355
20356
20357Here is an example:
20358
20359@quotation
20360
20361@example
20362with Ada.Text_IO;
20363with GNAT.Traceback.Symbolic;
20364
20365procedure STB is
20366
20367   procedure P1 is
20368   begin
20369      raise Constraint_Error;
20370   end P1;
20371
20372   procedure P2 is
20373   begin
20374      P1;
20375   end P2;
20376
20377   procedure P3 is
20378   begin
20379      P2;
20380   end P3;
20381
20382begin
20383   P3;
20384exception
20385   when E : others =>
20386      Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20387end STB;
20388@end example
20389
20390@example
20391$ gnatmake -g .\stb -bargs -E
20392$ stb
20393
203940040149F in stb.p1 at stb.adb:8
20395004014B7 in stb.p2 at stb.adb:13
20396004014CF in stb.p3 at stb.adb:18
20397004015DD in ada.stb at stb.adb:22
2039800401461 in main at b~stb.adb:168
20399004011C4 in __mingw_CRTStartup at crt1.c:200
20400004011F1 in mainCRTStartup at crt1.c:222
2040177E892A4 in ?? at ??:0
20402@end example
20403@end quotation
20404
20405In the above example the @code{.\} syntax in the @code{gnatmake} command
20406is currently required by @code{addr2line} for files that are in
20407the current working directory.
20408Moreover, the exact sequence of linker options may vary from platform
20409to platform.
20410The above @code{-largs} section is for Windows platforms. By contrast,
20411under Unix there is no need for the @code{-largs} section.
20412Differences across platforms are due to details of linker implementation.
20413
20414@subsubheading Tracebacks From Anywhere in a Program
20415
20416
20417It is possible to get a symbolic stack traceback
20418from anywhere in a program, just as for non-symbolic tracebacks.
20419The first step is to obtain a non-symbolic
20420traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20421information. Here is an example:
20422
20423@quotation
20424
20425@example
20426with Ada.Text_IO;
20427with GNAT.Traceback;
20428with GNAT.Traceback.Symbolic;
20429
20430procedure STB is
20431
20432   use Ada;
20433   use GNAT.Traceback;
20434   use GNAT.Traceback.Symbolic;
20435
20436   procedure P1 is
20437      TB  : Tracebacks_Array (1 .. 10);
20438      --  We are asking for a maximum of 10 stack frames.
20439      Len : Natural;
20440      --  Len will receive the actual number of stack frames returned.
20441   begin
20442      Call_Chain (TB, Len);
20443      Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20444   end P1;
20445
20446   procedure P2 is
20447   begin
20448      P1;
20449   end P2;
20450
20451begin
20452   P2;
20453end STB;
20454@end example
20455@end quotation
20456
20457@subsubheading Automatic Symbolic Tracebacks
20458
20459
20460Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
20461in @code{gprbuild -g ... -bargs -Es}).
20462This will cause the Exception_Information to contain a symbolic traceback,
20463which will also be printed if an unhandled exception terminates the
20464program.
20465
20466@node Pretty-Printers for the GNAT runtime,,Stack Traceback,Running and Debugging Ada Programs
20467@anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{18d}@anchor{gnat_ugn/gnat_and_program_execution pretty-printers-for-the-gnat-runtime}@anchor{18e}
20468@subsection Pretty-Printers for the GNAT runtime
20469
20470
20471As discussed in @cite{Calling User-Defined Subprograms}, GDB's
20472@code{print} command only knows about the physical layout of program data
20473structures and therefore normally displays only low-level dumps, which
20474are often hard to understand.
20475
20476An example of this is when trying to display the contents of an Ada
20477standard container, such as @code{Ada.Containers.Ordered_Maps.Map}:
20478
20479@quotation
20480
20481@example
20482with Ada.Containers.Ordered_Maps;
20483
20484procedure PP is
20485   package Int_To_Nat is
20486      new Ada.Containers.Ordered_Maps (Integer, Natural);
20487
20488   Map : Int_To_Nat.Map;
20489begin
20490   Map.Insert (1, 10);
20491   Map.Insert (2, 20);
20492   Map.Insert (3, 30);
20493
20494   Map.Clear; --  BREAK HERE
20495end PP;
20496@end example
20497@end quotation
20498
20499When this program is built with debugging information and run under
20500GDB up to the @code{Map.Clear} statement, trying to print @code{Map} will
20501yield information that is only relevant to the developers of our standard
20502containers:
20503
20504@quotation
20505
20506@example
20507(gdb) print map
20508$1 = (
20509  tree => (
20510    first => 0x64e010,
20511    last => 0x64e070,
20512    root => 0x64e040,
20513    length => 3,
20514    tc => (
20515      busy => 0,
20516      lock => 0
20517    )
20518  )
20519)
20520@end example
20521@end quotation
20522
20523Fortunately, GDB has a feature called pretty-printers@footnote{http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Introduction},
20524which allows customizing how GDB displays data structures. The GDB
20525shipped with GNAT embeds such pretty-printers for the most common
20526containers in the standard library.  To enable them, either run the
20527following command manually under GDB or add it to your @code{.gdbinit} file:
20528
20529@quotation
20530
20531@example
20532python import gnatdbg; gnatdbg.setup()
20533@end example
20534@end quotation
20535
20536Once this is done, GDB's @code{print} command will automatically use
20537these pretty-printers when appropriate. Using the previous example:
20538
20539@quotation
20540
20541@example
20542(gdb) print map
20543$1 = pp.int_to_nat.map of length 3 = @{
20544  [1] = 10,
20545  [2] = 20,
20546  [3] = 30
20547@}
20548@end example
20549@end quotation
20550
20551Pretty-printers are invoked each time GDB tries to display a value,
20552including when displaying the arguments of a called subprogram (in
20553GDB's @code{backtrace} command) or when printing the value returned by a
20554function (in GDB's @code{finish} command).
20555
20556To display a value without involving pretty-printers, @code{print} can be
20557invoked with its @code{/r} option:
20558
20559@quotation
20560
20561@example
20562(gdb) print/r map
20563$1 = (
20564  tree => (...
20565@end example
20566@end quotation
20567
20568Finer control of pretty-printers is also possible: see GDB's online documentation@footnote{http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Commands}
20569for more information.
20570
20571@geindex Profiling
20572
20573@node Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
20574@anchor{gnat_ugn/gnat_and_program_execution profiling}@anchor{25}@anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{18f}
20575@section Profiling
20576
20577
20578This section describes how to use the the @code{gprof} profiler tool on Ada
20579programs.
20580
20581@geindex gprof
20582
20583@geindex Profiling
20584
20585@menu
20586* Profiling an Ada Program with gprof::
20587
20588@end menu
20589
20590@node Profiling an Ada Program with gprof,,,Profiling
20591@anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{190}@anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{191}
20592@subsection Profiling an Ada Program with gprof
20593
20594
20595This section is not meant to be an exhaustive documentation of @code{gprof}.
20596Full documentation for it can be found in the @cite{GNU Profiler User's Guide}
20597documentation that is part of this GNAT distribution.
20598
20599Profiling a program helps determine the parts of a program that are executed
20600most often, and are therefore the most time-consuming.
20601
20602@code{gprof} is the standard GNU profiling tool; it has been enhanced to
20603better handle Ada programs and multitasking.
20604It is currently supported on the following platforms
20605
20606
20607@itemize *
20608
20609@item
20610linux x86/x86_64
20611
20612@item
20613windows x86
20614@end itemize
20615
20616In order to profile a program using @code{gprof}, several steps are needed:
20617
20618
20619@enumerate
20620
20621@item
20622Instrument the code, which requires a full recompilation of the project with the
20623proper switches.
20624
20625@item
20626Execute the program under the analysis conditions, i.e. with the desired
20627input.
20628
20629@item
20630Analyze the results using the @code{gprof} tool.
20631@end enumerate
20632
20633The following sections detail the different steps, and indicate how
20634to interpret the results.
20635
20636@menu
20637* Compilation for profiling::
20638* Program execution::
20639* Running gprof::
20640* Interpretation of profiling results::
20641
20642@end menu
20643
20644@node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
20645@anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{192}@anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{193}
20646@subsubsection Compilation for profiling
20647
20648
20649@geindex -pg (gcc)
20650@geindex for profiling
20651
20652@geindex -pg (gnatlink)
20653@geindex for profiling
20654
20655In order to profile a program the first step is to tell the compiler
20656to generate the necessary profiling information. The compiler switch to be used
20657is @code{-pg}, which must be added to other compilation switches. This
20658switch needs to be specified both during compilation and link stages, and can
20659be specified once when using gnatmake:
20660
20661@quotation
20662
20663@example
20664$ gnatmake -f -pg -P my_project
20665@end example
20666@end quotation
20667
20668Note that only the objects that were compiled with the @code{-pg} switch will
20669be profiled; if you need to profile your whole project, use the @code{-f}
20670gnatmake switch to force full recompilation.
20671
20672@node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
20673@anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{194}@anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{195}
20674@subsubsection Program execution
20675
20676
20677Once the program has been compiled for profiling, you can run it as usual.
20678
20679The only constraint imposed by profiling is that the program must terminate
20680normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20681properly analyzed.
20682
20683Once the program completes execution, a data file called @code{gmon.out} is
20684generated in the directory where the program was launched from. If this file
20685already exists, it will be overwritten.
20686
20687@node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
20688@anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{196}@anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{197}
20689@subsubsection Running gprof
20690
20691
20692The @code{gprof} tool is called as follow:
20693
20694@quotation
20695
20696@example
20697$ gprof my_prog gmon.out
20698@end example
20699@end quotation
20700
20701or simply:
20702
20703@quotation
20704
20705@example
20706$  gprof my_prog
20707@end example
20708@end quotation
20709
20710The complete form of the gprof command line is the following:
20711
20712@quotation
20713
20714@example
20715$ gprof [switches] [executable [data-file]]
20716@end example
20717@end quotation
20718
20719@code{gprof} supports numerous switches. The order of these
20720switch does not matter. The full list of options can be found in
20721the GNU Profiler User's Guide documentation that comes with this documentation.
20722
20723The following is the subset of those switches that is most relevant:
20724
20725@geindex --demangle (gprof)
20726
20727
20728@table @asis
20729
20730@item @code{--demangle[=@emph{style}]}, @code{--no-demangle}
20731
20732These options control whether symbol names should be demangled when
20733printing output.  The default is to demangle C++ symbols.  The
20734@code{--no-demangle} option may be used to turn off demangling. Different
20735compilers have different mangling styles.  The optional demangling style
20736argument can be used to choose an appropriate demangling style for your
20737compiler, in particular Ada symbols generated by GNAT can be demangled using
20738@code{--demangle=gnat}.
20739@end table
20740
20741@geindex -e (gprof)
20742
20743
20744@table @asis
20745
20746@item @code{-e @emph{function_name}}
20747
20748The @code{-e @emph{function}} option tells @code{gprof} not to print
20749information about the function @code{function_name} (and its
20750children...) in the call graph.  The function will still be listed
20751as a child of any functions that call it, but its index number will be
20752shown as @code{[not printed]}.  More than one @code{-e} option may be
20753given; only one @code{function_name} may be indicated with each @code{-e}
20754option.
20755@end table
20756
20757@geindex -E (gprof)
20758
20759
20760@table @asis
20761
20762@item @code{-E @emph{function_name}}
20763
20764The @code{-E @emph{function}} option works like the @code{-e} option, but
20765execution time spent in the function (and children who were not called from
20766anywhere else), will not be used to compute the percentages-of-time for
20767the call graph.  More than one @code{-E} option may be given; only one
20768@code{function_name} may be indicated with each @code{-E`} option.
20769@end table
20770
20771@geindex -f (gprof)
20772
20773
20774@table @asis
20775
20776@item @code{-f @emph{function_name}}
20777
20778The @code{-f @emph{function}} option causes @code{gprof} to limit the
20779call graph to the function @code{function_name} and its children (and
20780their children...).  More than one @code{-f} option may be given;
20781only one @code{function_name} may be indicated with each @code{-f}
20782option.
20783@end table
20784
20785@geindex -F (gprof)
20786
20787
20788@table @asis
20789
20790@item @code{-F @emph{function_name}}
20791
20792The @code{-F @emph{function}} option works like the @code{-f} option, but
20793only time spent in the function and its children (and their
20794children...) will be used to determine total-time and
20795percentages-of-time for the call graph.  More than one @code{-F} option
20796may be given; only one @code{function_name} may be indicated with each
20797@code{-F} option.  The @code{-F} option overrides the @code{-E} option.
20798@end table
20799
20800@node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
20801@anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{198}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{199}
20802@subsubsection Interpretation of profiling results
20803
20804
20805The results of the profiling analysis are represented by two arrays: the
20806'flat profile' and the 'call graph'. Full documentation of those outputs
20807can be found in the GNU Profiler User's Guide.
20808
20809The flat profile shows the time spent in each function of the program, and how
20810many time it has been called. This allows you to locate easily the most
20811time-consuming functions.
20812
20813The call graph shows, for each subprogram, the subprograms that call it,
20814and the subprograms that it calls. It also provides an estimate of the time
20815spent in each of those callers/called subprograms.
20816
20817@node Improving Performance,Overflow Check Handling in GNAT,Profiling,GNAT and Program Execution
20818@anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{26}@anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{168}
20819@section Improving Performance
20820
20821
20822@geindex Improving performance
20823
20824This section presents several topics related to program performance.
20825It first describes some of the tradeoffs that need to be considered
20826and some of the techniques for making your program run faster.
20827
20828
20829It then documents the unused subprogram/data elimination feature,
20830which can reduce the size of program executables.
20831
20832@menu
20833* Performance Considerations::
20834* Text_IO Suggestions::
20835* Reducing Size of Executables with Unused Subprogram/Data Elimination::
20836
20837@end menu
20838
20839@node Performance Considerations,Text_IO Suggestions,,Improving Performance
20840@anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{19a}@anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{19b}
20841@subsection Performance Considerations
20842
20843
20844The GNAT system provides a number of options that allow a trade-off
20845between
20846
20847
20848@itemize *
20849
20850@item
20851performance of the generated code
20852
20853@item
20854speed of compilation
20855
20856@item
20857minimization of dependences and recompilation
20858
20859@item
20860the degree of run-time checking.
20861@end itemize
20862
20863The defaults (if no options are selected) aim at improving the speed
20864of compilation and minimizing dependences, at the expense of performance
20865of the generated code:
20866
20867
20868@itemize *
20869
20870@item
20871no optimization
20872
20873@item
20874no inlining of subprogram calls
20875
20876@item
20877all run-time checks enabled except overflow and elaboration checks
20878@end itemize
20879
20880These options are suitable for most program development purposes. This
20881section describes how you can modify these choices, and also provides
20882some guidelines on debugging optimized code.
20883
20884@menu
20885* Controlling Run-Time Checks::
20886* Use of Restrictions::
20887* Optimization Levels::
20888* Debugging Optimized Code::
20889* Inlining of Subprograms::
20890* Floating_Point_Operations::
20891* Vectorization of loops::
20892* Other Optimization Switches::
20893* Optimization and Strict Aliasing::
20894* Aliased Variables and Optimization::
20895* Atomic Variables and Optimization::
20896* Passive Task Optimization::
20897
20898@end menu
20899
20900@node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
20901@anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{19c}@anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{19d}
20902@subsubsection Controlling Run-Time Checks
20903
20904
20905By default, GNAT generates all run-time checks, except stack overflow
20906checks, and checks for access before elaboration on subprogram
20907calls. The latter are not required in default mode, because all
20908necessary checking is done at compile time.
20909
20910@geindex -gnatp (gcc)
20911
20912@geindex -gnato (gcc)
20913
20914The gnat switch, @code{-gnatp} allows this default to be modified. See
20915@ref{f9,,Run-Time Checks}.
20916
20917Our experience is that the default is suitable for most development
20918purposes.
20919
20920Elaboration checks are off by default, and also not needed by default, since
20921GNAT uses a static elaboration analysis approach that avoids the need for
20922run-time checking. This manual contains a full chapter discussing the issue
20923of elaboration checks, and if the default is not satisfactory for your use,
20924you should read this chapter.
20925
20926For validity checks, the minimal checks required by the Ada Reference
20927Manual (for case statements and assignments to array elements) are on
20928by default. These can be suppressed by use of the @code{-gnatVn} switch.
20929Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20930is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20931it may be reasonable to routinely use @code{-gnatVn}. Validity checks
20932are also suppressed entirely if @code{-gnatp} is used.
20933
20934@geindex Overflow checks
20935
20936@geindex Checks
20937@geindex overflow
20938
20939@geindex Suppress
20940
20941@geindex Unsuppress
20942
20943@geindex pragma Suppress
20944
20945@geindex pragma Unsuppress
20946
20947Note that the setting of the switches controls the default setting of
20948the checks. They may be modified using either @code{pragma Suppress} (to
20949remove checks) or @code{pragma Unsuppress} (to add back suppressed
20950checks) in the program source.
20951
20952@node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
20953@anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{19e}@anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{19f}
20954@subsubsection Use of Restrictions
20955
20956
20957The use of pragma Restrictions allows you to control which features are
20958permitted in your program. Apart from the obvious point that if you avoid
20959relatively expensive features like finalization (enforceable by the use
20960of pragma Restrictions (No_Finalization), the use of this pragma does not
20961affect the generated code in most cases.
20962
20963One notable exception to this rule is that the possibility of task abort
20964results in some distributed overhead, particularly if finalization or
20965exception handlers are used. The reason is that certain sections of code
20966have to be marked as non-abortable.
20967
20968If you use neither the @code{abort} statement, nor asynchronous transfer
20969of control (@code{select ... then abort}), then this distributed overhead
20970is removed, which may have a general positive effect in improving
20971overall performance.  Especially code involving frequent use of tasking
20972constructs and controlled types will show much improved performance.
20973The relevant restrictions pragmas are
20974
20975@quotation
20976
20977@example
20978pragma Restrictions (No_Abort_Statements);
20979pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
20980@end example
20981@end quotation
20982
20983It is recommended that these restriction pragmas be used if possible. Note
20984that this also means that you can write code without worrying about the
20985possibility of an immediate abort at any point.
20986
20987@node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
20988@anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{1a0}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{fc}
20989@subsubsection Optimization Levels
20990
20991
20992@geindex -O (gcc)
20993
20994Without any optimization option,
20995the compiler's goal is to reduce the cost of
20996compilation and to make debugging produce the expected results.
20997Statements are independent: if you stop the program with a breakpoint between
20998statements, you can then assign a new value to any variable or change
20999the program counter to any other statement in the subprogram and get exactly
21000the results you would expect from the source code.
21001
21002Turning on optimization makes the compiler attempt to improve the
21003performance and/or code size at the expense of compilation time and
21004possibly the ability to debug the program.
21005
21006If you use multiple
21007-O options, with or without level numbers,
21008the last such option is the one that is effective.
21009
21010The default is optimization off. This results in the fastest compile
21011times, but GNAT makes absolutely no attempt to optimize, and the
21012generated programs are considerably larger and slower than when
21013optimization is enabled. You can use the
21014@code{-O} switch (the permitted forms are @code{-O0}, @code{-O1}
21015@code{-O2}, @code{-O3}, and @code{-Os})
21016to @code{gcc} to control the optimization level:
21017
21018
21019@itemize *
21020
21021@item
21022
21023@table @asis
21024
21025@item @code{-O0}
21026
21027No optimization (the default);
21028generates unoptimized code but has
21029the fastest compilation time.
21030
21031Note that many other compilers do substantial optimization even
21032if 'no optimization' is specified. With gcc, it is very unusual
21033to use @code{-O0} for production if execution time is of any concern,
21034since @code{-O0} means (almost) no optimization. This difference
21035between gcc and other compilers should be kept in mind when
21036doing performance comparisons.
21037@end table
21038
21039@item
21040
21041@table @asis
21042
21043@item @code{-O1}
21044
21045Moderate optimization;
21046optimizes reasonably well but does not
21047degrade compilation time significantly.
21048@end table
21049
21050@item
21051
21052@table @asis
21053
21054@item @code{-O2}
21055
21056Full optimization;
21057generates highly optimized code and has
21058the slowest compilation time.
21059@end table
21060
21061@item
21062
21063@table @asis
21064
21065@item @code{-O3}
21066
21067Full optimization as in @code{-O2};
21068also uses more aggressive automatic inlining of subprograms within a unit
21069(@ref{10f,,Inlining of Subprograms}) and attempts to vectorize loops.
21070@end table
21071
21072@item
21073
21074@table @asis
21075
21076@item @code{-Os}
21077
21078Optimize space usage (code and data) of resulting program.
21079@end table
21080@end itemize
21081
21082Higher optimization levels perform more global transformations on the
21083program and apply more expensive analysis algorithms in order to generate
21084faster and more compact code. The price in compilation time, and the
21085resulting improvement in execution time,
21086both depend on the particular application and the hardware environment.
21087You should experiment to find the best level for your application.
21088
21089Since the precise set of optimizations done at each level will vary from
21090release to release (and sometime from target to target), it is best to think
21091of the optimization settings in general terms.
21092See the @emph{Options That Control Optimization} section in
21093@cite{Using the GNU Compiler Collection (GCC)}
21094for details about
21095the @code{-O} settings and a number of @code{-f} options that
21096individually enable or disable specific optimizations.
21097
21098Unlike some other compilation systems, @code{gcc} has
21099been tested extensively at all optimization levels. There are some bugs
21100which appear only with optimization turned on, but there have also been
21101bugs which show up only in @emph{unoptimized} code. Selecting a lower
21102level of optimization does not improve the reliability of the code
21103generator, which in practice is highly reliable at all optimization
21104levels.
21105
21106Note regarding the use of @code{-O3}: The use of this optimization level
21107ought not to be automatically preferred over that of level @code{-O2},
21108since it often results in larger executables which may run more slowly.
21109See further discussion of this point in @ref{10f,,Inlining of Subprograms}.
21110
21111@node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
21112@anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{1a1}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{1a2}
21113@subsubsection Debugging Optimized Code
21114
21115
21116@geindex Debugging optimized code
21117
21118@geindex Optimization and debugging
21119
21120Although it is possible to do a reasonable amount of debugging at
21121nonzero optimization levels,
21122the higher the level the more likely that
21123source-level constructs will have been eliminated by optimization.
21124For example, if a loop is strength-reduced, the loop
21125control variable may be completely eliminated and thus cannot be
21126displayed in the debugger.
21127This can only happen at @code{-O2} or @code{-O3}.
21128Explicit temporary variables that you code might be eliminated at
21129level @code{-O1} or higher.
21130
21131@geindex -g (gcc)
21132
21133The use of the @code{-g} switch,
21134which is needed for source-level debugging,
21135affects the size of the program executable on disk,
21136and indeed the debugging information can be quite large.
21137However, it has no effect on the generated code (and thus does not
21138degrade performance)
21139
21140Since the compiler generates debugging tables for a compilation unit before
21141it performs optimizations, the optimizing transformations may invalidate some
21142of the debugging data.  You therefore need to anticipate certain
21143anomalous situations that may arise while debugging optimized code.
21144These are the most common cases:
21145
21146
21147@itemize *
21148
21149@item
21150@emph{The 'hopping Program Counter':}  Repeated @code{step} or @code{next}
21151commands show
21152the PC bouncing back and forth in the code.  This may result from any of
21153the following optimizations:
21154
21155
21156@itemize -
21157
21158@item
21159@emph{Common subexpression elimination:} using a single instance of code for a
21160quantity that the source computes several times.  As a result you
21161may not be able to stop on what looks like a statement.
21162
21163@item
21164@emph{Invariant code motion:} moving an expression that does not change within a
21165loop, to the beginning of the loop.
21166
21167@item
21168@emph{Instruction scheduling:} moving instructions so as to
21169overlap loads and stores (typically) with other code, or in
21170general to move computations of values closer to their uses. Often
21171this causes you to pass an assignment statement without the assignment
21172happening and then later bounce back to the statement when the
21173value is actually needed.  Placing a breakpoint on a line of code
21174and then stepping over it may, therefore, not always cause all the
21175expected side-effects.
21176@end itemize
21177
21178@item
21179@emph{The 'big leap':} More commonly known as @emph{cross-jumping}, in which
21180two identical pieces of code are merged and the program counter suddenly
21181jumps to a statement that is not supposed to be executed, simply because
21182it (and the code following) translates to the same thing as the code
21183that @emph{was} supposed to be executed.  This effect is typically seen in
21184sequences that end in a jump, such as a @code{goto}, a @code{return}, or
21185a @code{break} in a C @code{switch} statement.
21186
21187@item
21188@emph{The 'roving variable':} The symptom is an unexpected value in a variable.
21189There are various reasons for this effect:
21190
21191
21192@itemize -
21193
21194@item
21195In a subprogram prologue, a parameter may not yet have been moved to its
21196'home'.
21197
21198@item
21199A variable may be dead, and its register re-used.  This is
21200probably the most common cause.
21201
21202@item
21203As mentioned above, the assignment of a value to a variable may
21204have been moved.
21205
21206@item
21207A variable may be eliminated entirely by value propagation or
21208other means.  In this case, GCC may incorrectly generate debugging
21209information for the variable
21210@end itemize
21211
21212In general, when an unexpected value appears for a local variable or parameter
21213you should first ascertain if that value was actually computed by
21214your program, as opposed to being incorrectly reported by the debugger.
21215Record fields or
21216array elements in an object designated by an access value
21217are generally less of a problem, once you have ascertained that the access
21218value is sensible.
21219Typically, this means checking variables in the preceding code and in the
21220calling subprogram to verify that the value observed is explainable from other
21221values (one must apply the procedure recursively to those
21222other values); or re-running the code and stopping a little earlier
21223(perhaps before the call) and stepping to better see how the variable obtained
21224the value in question; or continuing to step @emph{from} the point of the
21225strange value to see if code motion had simply moved the variable's
21226assignments later.
21227@end itemize
21228
21229In light of such anomalies, a recommended technique is to use @code{-O0}
21230early in the software development cycle, when extensive debugging capabilities
21231are most needed, and then move to @code{-O1} and later @code{-O2} as
21232the debugger becomes less critical.
21233Whether to use the @code{-g} switch in the release version is
21234a release management issue.
21235Note that if you use @code{-g} you can then use the @code{strip} program
21236on the resulting executable,
21237which removes both debugging information and global symbols.
21238
21239@node Inlining of Subprograms,Floating_Point_Operations,Debugging Optimized Code,Performance Considerations
21240@anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{1a3}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{10f}
21241@subsubsection Inlining of Subprograms
21242
21243
21244A call to a subprogram in the current unit is inlined if all the
21245following conditions are met:
21246
21247
21248@itemize *
21249
21250@item
21251The optimization level is at least @code{-O1}.
21252
21253@item
21254The called subprogram is suitable for inlining: It must be small enough
21255and not contain something that @code{gcc} cannot support in inlined
21256subprograms.
21257
21258@geindex pragma Inline
21259
21260@geindex Inline
21261
21262@item
21263Any one of the following applies: @code{pragma Inline} is applied to the
21264subprogram; the subprogram is local to the unit and called once from
21265within it; the subprogram is small and optimization level @code{-O2} is
21266specified; optimization level @code{-O3} is specified.
21267@end itemize
21268
21269Calls to subprograms in @emph{with}ed units are normally not inlined.
21270To achieve actual inlining (that is, replacement of the call by the code
21271in the body of the subprogram), the following conditions must all be true:
21272
21273
21274@itemize *
21275
21276@item
21277The optimization level is at least @code{-O1}.
21278
21279@item
21280The called subprogram is suitable for inlining: It must be small enough
21281and not contain something that @code{gcc} cannot support in inlined
21282subprograms.
21283
21284@item
21285There is a @code{pragma Inline} for the subprogram.
21286
21287@item
21288The @code{-gnatn} switch is used on the command line.
21289@end itemize
21290
21291Even if all these conditions are met, it may not be possible for
21292the compiler to inline the call, due to the length of the body,
21293or features in the body that make it impossible for the compiler
21294to do the inlining.
21295
21296Note that specifying the @code{-gnatn} switch causes additional
21297compilation dependencies. Consider the following:
21298
21299@quotation
21300
21301@example
21302package R is
21303   procedure Q;
21304   pragma Inline (Q);
21305end R;
21306package body R is
21307   ...
21308end R;
21309
21310with R;
21311procedure Main is
21312begin
21313   ...
21314   R.Q;
21315end Main;
21316@end example
21317@end quotation
21318
21319With the default behavior (no @code{-gnatn} switch specified), the
21320compilation of the @code{Main} procedure depends only on its own source,
21321@code{main.adb}, and the spec of the package in file @code{r.ads}. This
21322means that editing the body of @code{R} does not require recompiling
21323@code{Main}.
21324
21325On the other hand, the call @code{R.Q} is not inlined under these
21326circumstances. If the @code{-gnatn} switch is present when @code{Main}
21327is compiled, the call will be inlined if the body of @code{Q} is small
21328enough, but now @code{Main} depends on the body of @code{R} in
21329@code{r.adb} as well as on the spec. This means that if this body is edited,
21330the main program must be recompiled. Note that this extra dependency
21331occurs whether or not the call is in fact inlined by @code{gcc}.
21332
21333The use of front end inlining with @code{-gnatN} generates similar
21334additional dependencies.
21335
21336@geindex -fno-inline (gcc)
21337
21338Note: The @code{-fno-inline} switch overrides all other conditions and ensures that
21339no inlining occurs, unless requested with pragma Inline_Always for @code{gcc}
21340back-ends. The extra dependences resulting from @code{-gnatn} will still be active,
21341even if this switch is used to suppress the resulting inlining actions.
21342
21343@geindex -fno-inline-functions (gcc)
21344
21345Note: The @code{-fno-inline-functions} switch can be used to prevent
21346automatic inlining of subprograms if @code{-O3} is used.
21347
21348@geindex -fno-inline-small-functions (gcc)
21349
21350Note: The @code{-fno-inline-small-functions} switch can be used to prevent
21351automatic inlining of small subprograms if @code{-O2} is used.
21352
21353@geindex -fno-inline-functions-called-once (gcc)
21354
21355Note: The @code{-fno-inline-functions-called-once} switch
21356can be used to prevent inlining of subprograms local to the unit
21357and called once from within it if @code{-O1} is used.
21358
21359Note regarding the use of @code{-O3}: @code{-gnatn} is made up of two
21360sub-switches @code{-gnatn1} and @code{-gnatn2} that can be directly
21361specified in lieu of it, @code{-gnatn} being translated into one of them
21362based on the optimization level. With @code{-O2} or below, @code{-gnatn}
21363is equivalent to @code{-gnatn1} which activates pragma @code{Inline} with
21364moderate inlining across modules. With @code{-O3}, @code{-gnatn} is
21365equivalent to @code{-gnatn2} which activates pragma @code{Inline} with
21366full inlining across modules. If you have used pragma @code{Inline} in
21367appropriate cases, then it is usually much better to use @code{-O2}
21368and @code{-gnatn} and avoid the use of @code{-O3} which has the additional
21369effect of inlining subprograms you did not think should be inlined. We have
21370found that the use of @code{-O3} may slow down the compilation and increase
21371the code size by performing excessive inlining, leading to increased
21372instruction cache pressure from the increased code size and thus minor
21373performance improvements. So the bottom line here is that you should not
21374automatically assume that @code{-O3} is better than @code{-O2}, and
21375indeed you should use @code{-O3} only if tests show that it actually
21376improves performance for your program.
21377
21378@node Floating_Point_Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
21379@anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{1a4}@anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{1a5}
21380@subsubsection Floating_Point_Operations
21381
21382
21383@geindex Floating-Point Operations
21384
21385On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
2138664-bit standard IEEE floating-point representations, and operations will
21387use standard IEEE arithmetic as provided by the processor. On most, but
21388not all, architectures, the attribute Machine_Overflows is False for these
21389types, meaning that the semantics of overflow is implementation-defined.
21390In the case of GNAT, these semantics correspond to the normal IEEE
21391treatment of infinities and NaN (not a number) values. For example,
213921.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
21393avoiding explicit overflow checks, the performance is greatly improved
21394on many targets. However, if required, floating-point overflow can be
21395enabled by the use of the pragma Check_Float_Overflow.
21396
21397Another consideration that applies specifically to x86 32-bit
21398architectures is which form of floating-point arithmetic is used.
21399By default the operations use the old style x86 floating-point,
21400which implements an 80-bit extended precision form (on these
21401architectures the type Long_Long_Float corresponds to that form).
21402In addition, generation of efficient code in this mode means that
21403the extended precision form will be used for intermediate results.
21404This may be helpful in improving the final precision of a complex
21405expression. However it means that the results obtained on the x86
21406will be different from those on other architectures, and for some
21407algorithms, the extra intermediate precision can be detrimental.
21408
21409In addition to this old-style floating-point, all modern x86 chips
21410implement an alternative floating-point operation model referred
21411to as SSE2. In this model there is no extended form, and furthermore
21412execution performance is significantly enhanced. To force GNAT to use
21413this more modern form, use both of the switches:
21414
21415@quotation
21416
21417-msse2 -mfpmath=sse
21418@end quotation
21419
21420A unit compiled with these switches will automatically use the more
21421efficient SSE2 instruction set for Float and Long_Float operations.
21422Note that the ABI has the same form for both floating-point models,
21423so it is permissible to mix units compiled with and without these
21424switches.
21425
21426@node Vectorization of loops,Other Optimization Switches,Floating_Point_Operations,Performance Considerations
21427@anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{1a6}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{1a7}
21428@subsubsection Vectorization of loops
21429
21430
21431@geindex Optimization Switches
21432
21433You can take advantage of the auto-vectorizer present in the @code{gcc}
21434back end to vectorize loops with GNAT.  The corresponding command line switch
21435is @code{-ftree-vectorize} but, as it is enabled by default at @code{-O3}
21436and other aggressive optimizations helpful for vectorization also are enabled
21437by default at this level, using @code{-O3} directly is recommended.
21438
21439You also need to make sure that the target architecture features a supported
21440SIMD instruction set.  For example, for the x86 architecture, you should at
21441least specify @code{-msse2} to get significant vectorization (but you don't
21442need to specify it for x86-64 as it is part of the base 64-bit architecture).
21443Similarly, for the PowerPC architecture, you should specify @code{-maltivec}.
21444
21445The preferred loop form for vectorization is the @code{for} iteration scheme.
21446Loops with a @code{while} iteration scheme can also be vectorized if they are
21447very simple, but the vectorizer will quickly give up otherwise.  With either
21448iteration scheme, the flow of control must be straight, in particular no
21449@code{exit} statement may appear in the loop body.  The loop may however
21450contain a single nested loop, if it can be vectorized when considered alone:
21451
21452@quotation
21453
21454@example
21455A : array (1..4, 1..4) of Long_Float;
21456S : array (1..4) of Long_Float;
21457
21458procedure Sum is
21459begin
21460   for I in A'Range(1) loop
21461      for J in A'Range(2) loop
21462         S (I) := S (I) + A (I, J);
21463      end loop;
21464   end loop;
21465end Sum;
21466@end example
21467@end quotation
21468
21469The vectorizable operations depend on the targeted SIMD instruction set, but
21470the adding and some of the multiplying operators are generally supported, as
21471well as the logical operators for modular types. Note that compiling
21472with @code{-gnatp} might well reveal cases where some checks do thwart
21473vectorization.
21474
21475Type conversions may also prevent vectorization if they involve semantics that
21476are not directly supported by the code generator or the SIMD instruction set.
21477A typical example is direct conversion from floating-point to integer types.
21478The solution in this case is to use the following idiom:
21479
21480@quotation
21481
21482@example
21483Integer (S'Truncation (F))
21484@end example
21485@end quotation
21486
21487if @code{S} is the subtype of floating-point object @code{F}.
21488
21489In most cases, the vectorizable loops are loops that iterate over arrays.
21490All kinds of array types are supported, i.e. constrained array types with
21491static bounds:
21492
21493@quotation
21494
21495@example
21496type Array_Type is array (1 .. 4) of Long_Float;
21497@end example
21498@end quotation
21499
21500constrained array types with dynamic bounds:
21501
21502@quotation
21503
21504@example
21505type Array_Type is array (1 .. Q.N) of Long_Float;
21506
21507type Array_Type is array (Q.K .. 4) of Long_Float;
21508
21509type Array_Type is array (Q.K .. Q.N) of Long_Float;
21510@end example
21511@end quotation
21512
21513or unconstrained array types:
21514
21515@quotation
21516
21517@example
21518type Array_Type is array (Positive range <>) of Long_Float;
21519@end example
21520@end quotation
21521
21522The quality of the generated code decreases when the dynamic aspect of the
21523array type increases, the worst code being generated for unconstrained array
21524types.  This is so because, the less information the compiler has about the
21525bounds of the array, the more fallback code it needs to generate in order to
21526fix things up at run time.
21527
21528It is possible to specify that a given loop should be subject to vectorization
21529preferably to other optimizations by means of pragma @code{Loop_Optimize}:
21530
21531@quotation
21532
21533@example
21534pragma Loop_Optimize (Vector);
21535@end example
21536@end quotation
21537
21538placed immediately within the loop will convey the appropriate hint to the
21539compiler for this loop.
21540
21541It is also possible to help the compiler generate better vectorized code
21542for a given loop by asserting that there are no loop-carried dependencies
21543in the loop.  Consider for example the procedure:
21544
21545@quotation
21546
21547@example
21548type Arr is array (1 .. 4) of Long_Float;
21549
21550procedure Add (X, Y : not null access Arr; R : not null access Arr) is
21551begin
21552  for I in Arr'Range loop
21553    R(I) := X(I) + Y(I);
21554  end loop;
21555end;
21556@end example
21557@end quotation
21558
21559By default, the compiler cannot unconditionally vectorize the loop because
21560assigning to a component of the array designated by R in one iteration could
21561change the value read from the components of the array designated by X or Y
21562in a later iteration.  As a result, the compiler will generate two versions
21563of the loop in the object code, one vectorized and the other not vectorized,
21564as well as a test to select the appropriate version at run time.  This can
21565be overcome by another hint:
21566
21567@quotation
21568
21569@example
21570pragma Loop_Optimize (Ivdep);
21571@end example
21572@end quotation
21573
21574placed immediately within the loop will tell the compiler that it can safely
21575omit the non-vectorized version of the loop as well as the run-time test.
21576
21577@node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
21578@anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{1a8}@anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{1a9}
21579@subsubsection Other Optimization Switches
21580
21581
21582@geindex Optimization Switches
21583
21584Since GNAT uses the @code{gcc} back end, all the specialized
21585@code{gcc} optimization switches are potentially usable. These switches
21586have not been extensively tested with GNAT but can generally be expected
21587to work. Examples of switches in this category are @code{-funroll-loops}
21588and the various target-specific @code{-m} options (in particular, it has
21589been observed that @code{-march=xxx} can significantly improve performance
21590on appropriate machines). For full details of these switches, see
21591the @emph{Submodel Options} section in the @emph{Hardware Models and Configurations}
21592chapter of @cite{Using the GNU Compiler Collection (GCC)}.
21593
21594@node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
21595@anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{f3}@anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{1aa}
21596@subsubsection Optimization and Strict Aliasing
21597
21598
21599@geindex Aliasing
21600
21601@geindex Strict Aliasing
21602
21603@geindex No_Strict_Aliasing
21604
21605The strong typing capabilities of Ada allow an optimizer to generate
21606efficient code in situations where other languages would be forced to
21607make worst case assumptions preventing such optimizations. Consider
21608the following example:
21609
21610@quotation
21611
21612@example
21613procedure R is
21614   type Int1 is new Integer;
21615   type Int2 is new Integer;
21616   type Int1A is access Int1;
21617   type Int2A is access Int2;
21618   Int1V : Int1A;
21619   Int2V : Int2A;
21620   ...
21621
21622begin
21623   ...
21624   for J in Data'Range loop
21625      if Data (J) = Int1V.all then
21626         Int2V.all := Int2V.all + 1;
21627      end if;
21628   end loop;
21629   ...
21630end R;
21631@end example
21632@end quotation
21633
21634In this example, since the variable @code{Int1V} can only access objects
21635of type @code{Int1}, and @code{Int2V} can only access objects of type
21636@code{Int2}, there is no possibility that the assignment to
21637@code{Int2V.all} affects the value of @code{Int1V.all}. This means that
21638the compiler optimizer can "know" that the value @code{Int1V.all} is constant
21639for all iterations of the loop and avoid the extra memory reference
21640required to dereference it each time through the loop.
21641
21642This kind of optimization, called strict aliasing analysis, is
21643triggered by specifying an optimization level of @code{-O2} or
21644higher or @code{-Os} and allows GNAT to generate more efficient code
21645when access values are involved.
21646
21647However, although this optimization is always correct in terms of
21648the formal semantics of the Ada Reference Manual, difficulties can
21649arise if features like @code{Unchecked_Conversion} are used to break
21650the typing system. Consider the following complete program example:
21651
21652@quotation
21653
21654@example
21655package p1 is
21656   type int1 is new integer;
21657   type int2 is new integer;
21658   type a1 is access int1;
21659   type a2 is access int2;
21660end p1;
21661
21662with p1; use p1;
21663package p2 is
21664   function to_a2 (Input : a1) return a2;
21665end p2;
21666
21667with Unchecked_Conversion;
21668package body p2 is
21669   function to_a2 (Input : a1) return a2 is
21670      function to_a2u is
21671        new Unchecked_Conversion (a1, a2);
21672   begin
21673      return to_a2u (Input);
21674   end to_a2;
21675end p2;
21676
21677with p2; use p2;
21678with p1; use p1;
21679with Text_IO; use Text_IO;
21680procedure m is
21681   v1 : a1 := new int1;
21682   v2 : a2 := to_a2 (v1);
21683begin
21684   v1.all := 1;
21685   v2.all := 0;
21686   put_line (int1'image (v1.all));
21687end;
21688@end example
21689@end quotation
21690
21691This program prints out 0 in @code{-O0} or @code{-O1}
21692mode, but it prints out 1 in @code{-O2} mode. That's
21693because in strict aliasing mode, the compiler can and
21694does assume that the assignment to @code{v2.all} could not
21695affect the value of @code{v1.all}, since different types
21696are involved.
21697
21698This behavior is not a case of non-conformance with the standard, since
21699the Ada RM specifies that an unchecked conversion where the resulting
21700bit pattern is not a correct value of the target type can result in an
21701abnormal value and attempting to reference an abnormal value makes the
21702execution of a program erroneous.  That's the case here since the result
21703does not point to an object of type @code{int2}.  This means that the
21704effect is entirely unpredictable.
21705
21706However, although that explanation may satisfy a language
21707lawyer, in practice an applications programmer expects an
21708unchecked conversion involving pointers to create true
21709aliases and the behavior of printing 1 seems plain wrong.
21710In this case, the strict aliasing optimization is unwelcome.
21711
21712Indeed the compiler recognizes this possibility, and the
21713unchecked conversion generates a warning:
21714
21715@quotation
21716
21717@example
21718p2.adb:5:07: warning: possible aliasing problem with type "a2"
21719p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
21720p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
21721@end example
21722@end quotation
21723
21724Unfortunately the problem is recognized when compiling the body of
21725package @code{p2}, but the actual "bad" code is generated while
21726compiling the body of @code{m} and this latter compilation does not see
21727the suspicious @code{Unchecked_Conversion}.
21728
21729As implied by the warning message, there are approaches you can use to
21730avoid the unwanted strict aliasing optimization in a case like this.
21731
21732One possibility is to simply avoid the use of @code{-O2}, but
21733that is a bit drastic, since it throws away a number of useful
21734optimizations that do not involve strict aliasing assumptions.
21735
21736A less drastic approach is to compile the program using the
21737option @code{-fno-strict-aliasing}. Actually it is only the
21738unit containing the dereferencing of the suspicious pointer
21739that needs to be compiled. So in this case, if we compile
21740unit @code{m} with this switch, then we get the expected
21741value of zero printed. Analyzing which units might need
21742the switch can be painful, so a more reasonable approach
21743is to compile the entire program with options @code{-O2}
21744and @code{-fno-strict-aliasing}. If the performance is
21745satisfactory with this combination of options, then the
21746advantage is that the entire issue of possible "wrong"
21747optimization due to strict aliasing is avoided.
21748
21749To avoid the use of compiler switches, the configuration
21750pragma @code{No_Strict_Aliasing} with no parameters may be
21751used to specify that for all access types, the strict
21752aliasing optimization should be suppressed.
21753
21754However, these approaches are still overkill, in that they causes
21755all manipulations of all access values to be deoptimized. A more
21756refined approach is to concentrate attention on the specific
21757access type identified as problematic.
21758
21759First, if a careful analysis of uses of the pointer shows
21760that there are no possible problematic references, then
21761the warning can be suppressed by bracketing the
21762instantiation of @code{Unchecked_Conversion} to turn
21763the warning off:
21764
21765@quotation
21766
21767@example
21768pragma Warnings (Off);
21769function to_a2u is
21770  new Unchecked_Conversion (a1, a2);
21771pragma Warnings (On);
21772@end example
21773@end quotation
21774
21775Of course that approach is not appropriate for this particular
21776example, since indeed there is a problematic reference. In this
21777case we can take one of two other approaches.
21778
21779The first possibility is to move the instantiation of unchecked
21780conversion to the unit in which the type is declared. In
21781this example, we would move the instantiation of
21782@code{Unchecked_Conversion} from the body of package
21783@code{p2} to the spec of package @code{p1}. Now the
21784warning disappears. That's because any use of the
21785access type knows there is a suspicious unchecked
21786conversion, and the strict aliasing optimization
21787is automatically suppressed for the type.
21788
21789If it is not practical to move the unchecked conversion to the same unit
21790in which the destination access type is declared (perhaps because the
21791source type is not visible in that unit), you may use pragma
21792@code{No_Strict_Aliasing} for the type. This pragma must occur in the
21793same declarative sequence as the declaration of the access type:
21794
21795@quotation
21796
21797@example
21798type a2 is access int2;
21799pragma No_Strict_Aliasing (a2);
21800@end example
21801@end quotation
21802
21803Here again, the compiler now knows that the strict aliasing optimization
21804should be suppressed for any reference to type @code{a2} and the
21805expected behavior is obtained.
21806
21807Finally, note that although the compiler can generate warnings for
21808simple cases of unchecked conversions, there are tricker and more
21809indirect ways of creating type incorrect aliases which the compiler
21810cannot detect. Examples are the use of address overlays and unchecked
21811conversions involving composite types containing access types as
21812components. In such cases, no warnings are generated, but there can
21813still be aliasing problems. One safe coding practice is to forbid the
21814use of address clauses for type overlaying, and to allow unchecked
21815conversion only for primitive types. This is not really a significant
21816restriction since any possible desired effect can be achieved by
21817unchecked conversion of access values.
21818
21819The aliasing analysis done in strict aliasing mode can certainly
21820have significant benefits. We have seen cases of large scale
21821application code where the time is increased by up to 5% by turning
21822this optimization off. If you have code that includes significant
21823usage of unchecked conversion, you might want to just stick with
21824@code{-O1} and avoid the entire issue. If you get adequate
21825performance at this level of optimization level, that's probably
21826the safest approach. If tests show that you really need higher
21827levels of optimization, then you can experiment with @code{-O2}
21828and @code{-O2 -fno-strict-aliasing} to see how much effect this
21829has on size and speed of the code. If you really need to use
21830@code{-O2} with strict aliasing in effect, then you should
21831review any uses of unchecked conversion of access types,
21832particularly if you are getting the warnings described above.
21833
21834@node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
21835@anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{1ab}@anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{1ac}
21836@subsubsection Aliased Variables and Optimization
21837
21838
21839@geindex Aliasing
21840
21841There are scenarios in which programs may
21842use low level techniques to modify variables
21843that otherwise might be considered to be unassigned. For example,
21844a variable can be passed to a procedure by reference, which takes
21845the address of the parameter and uses the address to modify the
21846variable's value, even though it is passed as an IN parameter.
21847Consider the following example:
21848
21849@quotation
21850
21851@example
21852procedure P is
21853   Max_Length : constant Natural := 16;
21854   type Char_Ptr is access all Character;
21855
21856   procedure Get_String(Buffer: Char_Ptr; Size : Integer);
21857   pragma Import (C, Get_String, "get_string");
21858
21859   Name : aliased String (1 .. Max_Length) := (others => ' ');
21860   Temp : Char_Ptr;
21861
21862   function Addr (S : String) return Char_Ptr is
21863      function To_Char_Ptr is
21864        new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
21865   begin
21866      return To_Char_Ptr (S (S'First)'Address);
21867   end;
21868
21869begin
21870   Temp := Addr (Name);
21871   Get_String (Temp, Max_Length);
21872end;
21873@end example
21874@end quotation
21875
21876where Get_String is a C function that uses the address in Temp to
21877modify the variable @code{Name}. This code is dubious, and arguably
21878erroneous, and the compiler would be entitled to assume that
21879@code{Name} is never modified, and generate code accordingly.
21880
21881However, in practice, this would cause some existing code that
21882seems to work with no optimization to start failing at high
21883levels of optimzization.
21884
21885What the compiler does for such cases is to assume that marking
21886a variable as aliased indicates that some "funny business" may
21887be going on. The optimizer recognizes the aliased keyword and
21888inhibits optimizations that assume the value cannot be assigned.
21889This means that the above example will in fact "work" reliably,
21890that is, it will produce the expected results.
21891
21892@node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
21893@anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{1ad}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{1ae}
21894@subsubsection Atomic Variables and Optimization
21895
21896
21897@geindex Atomic
21898
21899There are two considerations with regard to performance when
21900atomic variables are used.
21901
21902First, the RM only guarantees that access to atomic variables
21903be atomic, it has nothing to say about how this is achieved,
21904though there is a strong implication that this should not be
21905achieved by explicit locking code. Indeed GNAT will never
21906generate any locking code for atomic variable access (it will
21907simply reject any attempt to make a variable or type atomic
21908if the atomic access cannot be achieved without such locking code).
21909
21910That being said, it is important to understand that you cannot
21911assume that the entire variable will always be accessed. Consider
21912this example:
21913
21914@quotation
21915
21916@example
21917type R is record
21918   A,B,C,D : Character;
21919end record;
21920for R'Size use 32;
21921for R'Alignment use 4;
21922
21923RV : R;
21924pragma Atomic (RV);
21925X : Character;
21926...
21927X := RV.B;
21928@end example
21929@end quotation
21930
21931You cannot assume that the reference to @code{RV.B}
21932will read the entire 32-bit
21933variable with a single load instruction. It is perfectly legitimate if
21934the hardware allows it to do a byte read of just the B field. This read
21935is still atomic, which is all the RM requires. GNAT can and does take
21936advantage of this, depending on the architecture and optimization level.
21937Any assumption to the contrary is non-portable and risky. Even if you
21938examine the assembly language and see a full 32-bit load, this might
21939change in a future version of the compiler.
21940
21941If your application requires that all accesses to @code{RV} in this
21942example be full 32-bit loads, you need to make a copy for the access
21943as in:
21944
21945@quotation
21946
21947@example
21948declare
21949   RV_Copy : constant R := RV;
21950begin
21951   X := RV_Copy.B;
21952end;
21953@end example
21954@end quotation
21955
21956Now the reference to RV must read the whole variable.
21957Actually one can imagine some compiler which figures
21958out that the whole copy is not required (because only
21959the B field is actually accessed), but GNAT
21960certainly won't do that, and we don't know of any
21961compiler that would not handle this right, and the
21962above code will in practice work portably across
21963all architectures (that permit the Atomic declaration).
21964
21965The second issue with atomic variables has to do with
21966the possible requirement of generating synchronization
21967code. For more details on this, consult the sections on
21968the pragmas Enable/Disable_Atomic_Synchronization in the
21969GNAT Reference Manual. If performance is critical, and
21970such synchronization code is not required, it may be
21971useful to disable it.
21972
21973@node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
21974@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{1af}@anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{1b0}
21975@subsubsection Passive Task Optimization
21976
21977
21978@geindex Passive Task
21979
21980A passive task is one which is sufficiently simple that
21981in theory a compiler could recognize it an implement it
21982efficiently without creating a new thread. The original design
21983of Ada 83 had in mind this kind of passive task optimization, but
21984only a few Ada 83 compilers attempted it. The problem was that
21985it was difficult to determine the exact conditions under which
21986the optimization was possible. The result is a very fragile
21987optimization where a very minor change in the program can
21988suddenly silently make a task non-optimizable.
21989
21990With the revisiting of this issue in Ada 95, there was general
21991agreement that this approach was fundamentally flawed, and the
21992notion of protected types was introduced. When using protected
21993types, the restrictions are well defined, and you KNOW that the
21994operations will be optimized, and furthermore this optimized
21995performance is fully portable.
21996
21997Although it would theoretically be possible for GNAT to attempt to
21998do this optimization, but it really doesn't make sense in the
21999context of Ada 95, and none of the Ada 95 compilers implement
22000this optimization as far as we know. In particular GNAT never
22001attempts to perform this optimization.
22002
22003In any new Ada 95 code that is written, you should always
22004use protected types in place of tasks that might be able to
22005be optimized in this manner.
22006Of course this does not help if you have legacy Ada 83 code
22007that depends on this optimization, but it is unusual to encounter
22008a case where the performance gains from this optimization
22009are significant.
22010
22011Your program should work correctly without this optimization. If
22012you have performance problems, then the most practical
22013approach is to figure out exactly where these performance problems
22014arise, and update those particular tasks to be protected types. Note
22015that typically clients of the tasks who call entries, will not have
22016to be modified, only the task definition itself.
22017
22018@node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
22019@anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{1b1}@anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{1b2}
22020@subsection @code{Text_IO} Suggestions
22021
22022
22023@geindex Text_IO and performance
22024
22025The @code{Ada.Text_IO} package has fairly high overheads due in part to
22026the requirement of maintaining page and line counts. If performance
22027is critical, a recommendation is to use @code{Stream_IO} instead of
22028@code{Text_IO} for volume output, since this package has less overhead.
22029
22030If @code{Text_IO} must be used, note that by default output to the standard
22031output and standard error files is unbuffered (this provides better
22032behavior when output statements are used for debugging, or if the
22033progress of a program is observed by tracking the output, e.g. by
22034using the Unix @emph{tail -f} command to watch redirected output.
22035
22036If you are generating large volumes of output with @code{Text_IO} and
22037performance is an important factor, use a designated file instead
22038of the standard output file, or change the standard output file to
22039be buffered using @code{Interfaces.C_Streams.setvbuf}.
22040
22041@node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
22042@anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{1b3}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{1b4}
22043@subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
22044
22045
22046@geindex Uunused subprogram/data elimination
22047
22048This section describes how you can eliminate unused subprograms and data from
22049your executable just by setting options at compilation time.
22050
22051@menu
22052* About unused subprogram/data elimination::
22053* Compilation options::
22054* Example of unused subprogram/data elimination::
22055
22056@end menu
22057
22058@node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
22059@anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{1b5}@anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{1b6}
22060@subsubsection About unused subprogram/data elimination
22061
22062
22063By default, an executable contains all code and data of its composing objects
22064(directly linked or coming from statically linked libraries), even data or code
22065never used by this executable.
22066
22067This feature will allow you to eliminate such unused code from your
22068executable, making it smaller (in disk and in memory).
22069
22070This functionality is available on all Linux platforms except for the IA-64
22071architecture and on all cross platforms using the ELF binary file format.
22072In both cases GNU binutils version 2.16 or later are required to enable it.
22073
22074@node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
22075@anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{1b7}@anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{1b8}
22076@subsubsection Compilation options
22077
22078
22079The operation of eliminating the unused code and data from the final executable
22080is directly performed by the linker.
22081
22082@geindex -ffunction-sections (gcc)
22083
22084@geindex -fdata-sections (gcc)
22085
22086In order to do this, it has to work with objects compiled with the
22087following options:
22088@code{-ffunction-sections} @code{-fdata-sections}.
22089
22090These options are usable with C and Ada files.
22091They will place respectively each
22092function or data in a separate section in the resulting object file.
22093
22094Once the objects and static libraries are created with these options, the
22095linker can perform the dead code elimination. You can do this by setting
22096the @code{-Wl,--gc-sections} option to gcc command or in the
22097@code{-largs} section of @code{gnatmake}. This will perform a
22098garbage collection of code and data never referenced.
22099
22100If the linker performs a partial link (@code{-r} linker option), then you
22101will need to provide the entry point using the @code{-e} / @code{--entry}
22102linker option.
22103
22104Note that objects compiled without the @code{-ffunction-sections} and
22105@code{-fdata-sections} options can still be linked with the executable.
22106However, no dead code elimination will be performed on those objects (they will
22107be linked as is).
22108
22109The GNAT static library is now compiled with -ffunction-sections and
22110-fdata-sections on some platforms. This allows you to eliminate the unused code
22111and data of the GNAT library from your executable.
22112
22113@node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
22114@anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{1b9}@anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{1ba}
22115@subsubsection Example of unused subprogram/data elimination
22116
22117
22118Here is a simple example:
22119
22120@quotation
22121
22122@example
22123with Aux;
22124
22125procedure Test is
22126begin
22127   Aux.Used (10);
22128end Test;
22129
22130package Aux is
22131   Used_Data   : Integer;
22132   Unused_Data : Integer;
22133
22134   procedure Used   (Data : Integer);
22135   procedure Unused (Data : Integer);
22136end Aux;
22137
22138package body Aux is
22139   procedure Used (Data : Integer) is
22140   begin
22141      Used_Data := Data;
22142   end Used;
22143
22144   procedure Unused (Data : Integer) is
22145   begin
22146      Unused_Data := Data;
22147   end Unused;
22148end Aux;
22149@end example
22150@end quotation
22151
22152@code{Unused} and @code{Unused_Data} are never referenced in this code
22153excerpt, and hence they may be safely removed from the final executable.
22154
22155@quotation
22156
22157@example
22158$ gnatmake test
22159
22160$ nm test | grep used
22161020015f0 T aux__unused
2216202005d88 B aux__unused_data
22163020015cc T aux__used
2216402005d84 B aux__used_data
22165
22166$ gnatmake test -cargs -fdata-sections -ffunction-sections \\
22167     -largs -Wl,--gc-sections
22168
22169$ nm test | grep used
2217002005350 T aux__used
221710201ffe0 B aux__used_data
22172@end example
22173@end quotation
22174
22175It can be observed that the procedure @code{Unused} and the object
22176@code{Unused_Data} are removed by the linker when using the
22177appropriate options.
22178
22179@geindex Overflow checks
22180
22181@geindex Checks (overflow)
22182
22183
22184@node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
22185@anchor{gnat_ugn/gnat_and_program_execution id50}@anchor{169}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{27}
22186@section Overflow Check Handling in GNAT
22187
22188
22189This section explains how to control the handling of overflow checks.
22190
22191@menu
22192* Background::
22193* Management of Overflows in GNAT::
22194* Specifying the Desired Mode::
22195* Default Settings::
22196* Implementation Notes::
22197
22198@end menu
22199
22200@node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
22201@anchor{gnat_ugn/gnat_and_program_execution id51}@anchor{1bb}@anchor{gnat_ugn/gnat_and_program_execution background}@anchor{1bc}
22202@subsection Background
22203
22204
22205Overflow checks are checks that the compiler may make to ensure
22206that intermediate results are not out of range. For example:
22207
22208@quotation
22209
22210@example
22211A : Integer;
22212...
22213A := A + 1;
22214@end example
22215@end quotation
22216
22217If @code{A} has the value @code{Integer'Last}, then the addition may cause
22218overflow since the result is out of range of the type @code{Integer}.
22219In this case @code{Constraint_Error} will be raised if checks are
22220enabled.
22221
22222A trickier situation arises in examples like the following:
22223
22224@quotation
22225
22226@example
22227A, C : Integer;
22228...
22229A := (A + 1) + C;
22230@end example
22231@end quotation
22232
22233where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
22234Now the final result of the expression on the right hand side is
22235@code{Integer'Last} which is in range, but the question arises whether the
22236intermediate addition of @code{(A + 1)} raises an overflow error.
22237
22238The (perhaps surprising) answer is that the Ada language
22239definition does not answer this question. Instead it leaves
22240it up to the implementation to do one of two things if overflow
22241checks are enabled.
22242
22243
22244@itemize *
22245
22246@item
22247raise an exception (@code{Constraint_Error}), or
22248
22249@item
22250yield the correct mathematical result which is then used in
22251subsequent operations.
22252@end itemize
22253
22254If the compiler chooses the first approach, then the assignment of this
22255example will indeed raise @code{Constraint_Error} if overflow checking is
22256enabled, or result in erroneous execution if overflow checks are suppressed.
22257
22258But if the compiler
22259chooses the second approach, then it can perform both additions yielding
22260the correct mathematical result, which is in range, so no exception
22261will be raised, and the right result is obtained, regardless of whether
22262overflow checks are suppressed.
22263
22264Note that in the first example an
22265exception will be raised in either case, since if the compiler
22266gives the correct mathematical result for the addition, it will
22267be out of range of the target type of the assignment, and thus
22268fails the range check.
22269
22270This lack of specified behavior in the handling of overflow for
22271intermediate results is a source of non-portability, and can thus
22272be problematic when programs are ported. Most typically this arises
22273in a situation where the original compiler did not raise an exception,
22274and then the application is moved to a compiler where the check is
22275performed on the intermediate result and an unexpected exception is
22276raised.
22277
22278Furthermore, when using Ada 2012's preconditions and other
22279assertion forms, another issue arises. Consider:
22280
22281@quotation
22282
22283@example
22284procedure P (A, B : Integer) with
22285  Pre => A + B <= Integer'Last;
22286@end example
22287@end quotation
22288
22289One often wants to regard arithmetic in a context like this from
22290a mathematical point of view. So for example, if the two actual parameters
22291for a call to @code{P} are both @code{Integer'Last}, then
22292the precondition should be regarded as False. If we are executing
22293in a mode with run-time checks enabled for preconditions, then we would
22294like this precondition to fail, rather than raising an exception
22295because of the intermediate overflow.
22296
22297However, the language definition leaves the specification of
22298whether the above condition fails (raising @code{Assert_Error}) or
22299causes an intermediate overflow (raising @code{Constraint_Error})
22300up to the implementation.
22301
22302The situation is worse in a case such as the following:
22303
22304@quotation
22305
22306@example
22307procedure Q (A, B, C : Integer) with
22308  Pre => A + B + C <= Integer'Last;
22309@end example
22310@end quotation
22311
22312Consider the call
22313
22314@quotation
22315
22316@example
22317Q (A => Integer'Last, B => 1, C => -1);
22318@end example
22319@end quotation
22320
22321From a mathematical point of view the precondition
22322is True, but at run time we may (but are not guaranteed to) get an
22323exception raised because of the intermediate overflow (and we really
22324would prefer this precondition to be considered True at run time).
22325
22326@node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
22327@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{1bd}@anchor{gnat_ugn/gnat_and_program_execution id52}@anchor{1be}
22328@subsection Management of Overflows in GNAT
22329
22330
22331To deal with the portability issue, and with the problem of
22332mathematical versus run-time interpretation of the expressions in
22333assertions, GNAT provides comprehensive control over the handling
22334of intermediate overflow. GNAT can operate in three modes, and
22335furthemore, permits separate selection of operating modes for
22336the expressions within assertions (here the term 'assertions'
22337is used in the technical sense, which includes preconditions and so forth)
22338and for expressions appearing outside assertions.
22339
22340The three modes are:
22341
22342
22343@itemize *
22344
22345@item
22346@emph{Use base type for intermediate operations} (@code{STRICT})
22347
22348In this mode, all intermediate results for predefined arithmetic
22349operators are computed using the base type, and the result must
22350be in range of the base type. If this is not the
22351case then either an exception is raised (if overflow checks are
22352enabled) or the execution is erroneous (if overflow checks are suppressed).
22353This is the normal default mode.
22354
22355@item
22356@emph{Most intermediate overflows avoided} (@code{MINIMIZED})
22357
22358In this mode, the compiler attempts to avoid intermediate overflows by
22359using a larger integer type, typically @code{Long_Long_Integer},
22360as the type in which arithmetic is
22361performed for predefined arithmetic operators. This may be slightly more
22362expensive at
22363run time (compared to suppressing intermediate overflow checks), though
22364the cost is negligible on modern 64-bit machines. For the examples given
22365earlier, no intermediate overflows would have resulted in exceptions,
22366since the intermediate results are all in the range of
22367@code{Long_Long_Integer} (typically 64-bits on nearly all implementations
22368of GNAT). In addition, if checks are enabled, this reduces the number of
22369checks that must be made, so this choice may actually result in an
22370improvement in space and time behavior.
22371
22372However, there are cases where @code{Long_Long_Integer} is not large
22373enough, consider the following example:
22374
22375@quotation
22376
22377@example
22378procedure R (A, B, C, D : Integer) with
22379  Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
22380@end example
22381@end quotation
22382
22383where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
22384Now the intermediate results are
22385out of the range of @code{Long_Long_Integer} even though the final result
22386is in range and the precondition is True (from a mathematical point
22387of view). In such a case, operating in this mode, an overflow occurs
22388for the intermediate computation (which is why this mode
22389says @emph{most} intermediate overflows are avoided). In this case,
22390an exception is raised if overflow checks are enabled, and the
22391execution is erroneous if overflow checks are suppressed.
22392
22393@item
22394@emph{All intermediate overflows avoided} (@code{ELIMINATED})
22395
22396In this mode, the compiler  avoids all intermediate overflows
22397by using arbitrary precision arithmetic as required. In this
22398mode, the above example with @code{A**2 * B**2} would
22399not cause intermediate overflow, because the intermediate result
22400would be evaluated using sufficient precision, and the result
22401of evaluating the precondition would be True.
22402
22403This mode has the advantage of avoiding any intermediate
22404overflows, but at the expense of significant run-time overhead,
22405including the use of a library (included automatically in this
22406mode) for multiple-precision arithmetic.
22407
22408This mode provides cleaner semantics for assertions, since now
22409the run-time behavior emulates true arithmetic behavior for the
22410predefined arithmetic operators, meaning that there is never a
22411conflict between the mathematical view of the assertion, and its
22412run-time behavior.
22413
22414Note that in this mode, the behavior is unaffected by whether or
22415not overflow checks are suppressed, since overflow does not occur.
22416It is possible for gigantic intermediate expressions to raise
22417@code{Storage_Error} as a result of attempting to compute the
22418results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
22419but overflow is impossible.
22420@end itemize
22421
22422Note that these modes apply only to the evaluation of predefined
22423arithmetic, membership, and comparison operators for signed integer
22424arithmetic.
22425
22426For fixed-point arithmetic, checks can be suppressed. But if checks
22427are enabled
22428then fixed-point values are always checked for overflow against the
22429base type for intermediate expressions (that is such checks always
22430operate in the equivalent of @code{STRICT} mode).
22431
22432For floating-point, on nearly all architectures, @code{Machine_Overflows}
22433is False, and IEEE infinities are generated, so overflow exceptions
22434are never raised. If you want to avoid infinities, and check that
22435final results of expressions are in range, then you can declare a
22436constrained floating-point type, and range checks will be carried
22437out in the normal manner (with infinite values always failing all
22438range checks).
22439
22440@node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
22441@anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{f8}@anchor{gnat_ugn/gnat_and_program_execution id53}@anchor{1bf}
22442@subsection Specifying the Desired Mode
22443
22444
22445@geindex pragma Overflow_Mode
22446
22447The desired mode of for handling intermediate overflow can be specified using
22448either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
22449The pragma has the form
22450
22451@quotation
22452
22453@example
22454pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
22455@end example
22456@end quotation
22457
22458where @code{MODE} is one of
22459
22460
22461@itemize *
22462
22463@item
22464@code{STRICT}:  intermediate overflows checked (using base type)
22465
22466@item
22467@code{MINIMIZED}: minimize intermediate overflows
22468
22469@item
22470@code{ELIMINATED}: eliminate intermediate overflows
22471@end itemize
22472
22473The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
22474@code{minimized} all have the same effect.
22475
22476If only the @code{General} parameter is present, then the given @code{MODE} applies
22477to expressions both within and outside assertions. If both arguments
22478are present, then @code{General} applies to expressions outside assertions,
22479and @code{Assertions} applies to expressions within assertions. For example:
22480
22481@quotation
22482
22483@example
22484pragma Overflow_Mode
22485  (General => Minimized, Assertions => Eliminated);
22486@end example
22487@end quotation
22488
22489specifies that general expressions outside assertions be evaluated
22490in 'minimize intermediate overflows' mode, and expressions within
22491assertions be evaluated in 'eliminate intermediate overflows' mode.
22492This is often a reasonable choice, avoiding excessive overhead
22493outside assertions, but assuring a high degree of portability
22494when importing code from another compiler, while incurring
22495the extra overhead for assertion expressions to ensure that
22496the behavior at run time matches the expected mathematical
22497behavior.
22498
22499The @code{Overflow_Mode} pragma has the same scoping and placement
22500rules as pragma @code{Suppress}, so it can occur either as a
22501configuration pragma, specifying a default for the whole
22502program, or in a declarative scope, where it applies to the
22503remaining declarations and statements in that scope.
22504
22505Note that pragma @code{Overflow_Mode} does not affect whether
22506overflow checks are enabled or suppressed. It only controls the
22507method used to compute intermediate values. To control whether
22508overflow checking is enabled or suppressed, use pragma @code{Suppress}
22509or @code{Unsuppress} in the usual manner.
22510
22511@geindex -gnato? (gcc)
22512
22513@geindex -gnato?? (gcc)
22514
22515Additionally, a compiler switch @code{-gnato?} or @code{-gnato??}
22516can be used to control the checking mode default (which can be subsequently
22517overridden using pragmas).
22518
22519Here @code{?} is one of the digits @code{1} through @code{3}:
22520
22521@quotation
22522
22523
22524@multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
22525@item
22526
22527@code{1}
22528
22529@tab
22530
22531use base type for intermediate operations (@code{STRICT})
22532
22533@item
22534
22535@code{2}
22536
22537@tab
22538
22539minimize intermediate overflows (@code{MINIMIZED})
22540
22541@item
22542
22543@code{3}
22544
22545@tab
22546
22547eliminate intermediate overflows (@code{ELIMINATED})
22548
22549@end multitable
22550
22551@end quotation
22552
22553As with the pragma, if only one digit appears then it applies to all
22554cases; if two digits are given, then the first applies outside
22555assertions, and the second within assertions. Thus the equivalent
22556of the example pragma above would be
22557@code{-gnato23}.
22558
22559If no digits follow the @code{-gnato}, then it is equivalent to
22560@code{-gnato11},
22561causing all intermediate operations to be computed using the base
22562type (@code{STRICT} mode).
22563
22564@node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
22565@anchor{gnat_ugn/gnat_and_program_execution id54}@anchor{1c0}@anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{1c1}
22566@subsection Default Settings
22567
22568
22569The default mode for overflow checks is
22570
22571@quotation
22572
22573@example
22574General => Strict
22575@end example
22576@end quotation
22577
22578which causes all computations both inside and outside assertions to use
22579the base type.
22580
22581This retains compatibility with previous versions of
22582GNAT which suppressed overflow checks by default and always
22583used the base type for computation of intermediate results.
22584
22585@c Sphinx allows no emphasis within :index: role. As a workaround we
22586@c point the index to "switch" and use emphasis for "-gnato".
22587
22588The
22589@geindex -gnato (gcc)
22590switch @code{-gnato} (with no digits following)
22591is equivalent to
22592
22593@quotation
22594
22595@example
22596General => Strict
22597@end example
22598@end quotation
22599
22600which causes overflow checking of all intermediate overflows
22601both inside and outside assertions against the base type.
22602
22603The pragma @code{Suppress (Overflow_Check)} disables overflow
22604checking, but it has no effect on the method used for computing
22605intermediate results.
22606
22607The pragma @code{Unsuppress (Overflow_Check)} enables overflow
22608checking, but it has no effect on the method used for computing
22609intermediate results.
22610
22611@node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
22612@anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{1c2}@anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{1c3}
22613@subsection Implementation Notes
22614
22615
22616In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
22617reasonably efficient, and can be generally used. It also helps
22618to ensure compatibility with code imported from some other
22619compiler to GNAT.
22620
22621Setting all intermediate overflows checking (@code{CHECKED} mode)
22622makes sense if you want to
22623make sure that your code is compatible with any other possible
22624Ada implementation. This may be useful in ensuring portability
22625for code that is to be exported to some other compiler than GNAT.
22626
22627The Ada standard allows the reassociation of expressions at
22628the same precedence level if no parentheses are present. For
22629example, @code{A+B+C} parses as though it were @code{(A+B)+C}, but
22630the compiler can reintepret this as @code{A+(B+C)}, possibly
22631introducing or eliminating an overflow exception. The GNAT
22632compiler never takes advantage of this freedom, and the
22633expression @code{A+B+C} will be evaluated as @code{(A+B)+C}.
22634If you need the other order, you can write the parentheses
22635explicitly @code{A+(B+C)} and GNAT will respect this order.
22636
22637The use of @code{ELIMINATED} mode will cause the compiler to
22638automatically include an appropriate arbitrary precision
22639integer arithmetic package. The compiler will make calls
22640to this package, though only in cases where it cannot be
22641sure that @code{Long_Long_Integer} is sufficient to guard against
22642intermediate overflows. This package does not use dynamic
22643alllocation, but it does use the secondary stack, so an
22644appropriate secondary stack package must be present (this
22645is always true for standard full Ada, but may require
22646specific steps for restricted run times such as ZFP).
22647
22648Although @code{ELIMINATED} mode causes expressions to use arbitrary
22649precision arithmetic, avoiding overflow, the final result
22650must be in an appropriate range. This is true even if the
22651final result is of type @code{[Long_[Long_]]Integer'Base}, which
22652still has the same bounds as its associated constrained
22653type at run-time.
22654
22655Currently, the @code{ELIMINATED} mode is only available on target
22656platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
22657platforms).
22658
22659@node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
22660@anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{16a}@anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{28}
22661@section Performing Dimensionality Analysis in GNAT
22662
22663
22664@geindex Dimensionality analysis
22665
22666The GNAT compiler supports dimensionality checking. The user can
22667specify physical units for objects, and the compiler will verify that uses
22668of these objects are compatible with their dimensions, in a fashion that is
22669familiar to engineering practice. The dimensions of algebraic expressions
22670(including powers with static exponents) are computed from their constituents.
22671
22672@geindex Dimension_System aspect
22673
22674@geindex Dimension aspect
22675
22676This feature depends on Ada 2012 aspect specifications, and is available from
22677version 7.0.1 of GNAT onwards.
22678The GNAT-specific aspect @code{Dimension_System}
22679allows you to define a system of units; the aspect @code{Dimension}
22680then allows the user to declare dimensioned quantities within a given system.
22681(These aspects are described in the @emph{Implementation Defined Aspects}
22682chapter of the @emph{GNAT Reference Manual}).
22683
22684The major advantage of this model is that it does not require the declaration of
22685multiple operators for all possible combinations of types: it is only necessary
22686to use the proper subtypes in object declarations.
22687
22688@geindex System.Dim.Mks package (GNAT library)
22689
22690@geindex MKS_Type type
22691
22692The simplest way to impose dimensionality checking on a computation is to make
22693use of one of the instantiations of the package @code{System.Dim.Generic_Mks}, which
22694are part of the GNAT library. This generic package defines a floating-point
22695type @code{MKS_Type}, for which a sequence of dimension names are specified,
22696together with their conventional abbreviations.  The following should be read
22697together with the full specification of the package, in file
22698@code{s-digemk.ads}.
22699
22700@quotation
22701
22702@geindex s-digemk.ads file
22703
22704@example
22705type Mks_Type is new Float_Type
22706  with
22707   Dimension_System => (
22708     (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
22709     (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
22710     (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
22711     (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
22712     (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
22713     (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
22714     (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
22715@end example
22716@end quotation
22717
22718The package then defines a series of subtypes that correspond to these
22719conventional units. For example:
22720
22721@quotation
22722
22723@example
22724subtype Length is Mks_Type
22725  with
22726   Dimension => (Symbol => 'm', Meter  => 1, others => 0);
22727@end example
22728@end quotation
22729
22730and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
22731@code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
22732@code{Luminous_Intensity} (the standard set of units of the SI system).
22733
22734The package also defines conventional names for values of each unit, for
22735example:
22736
22737@quotation
22738
22739@example
22740m   : constant Length           := 1.0;
22741kg  : constant Mass             := 1.0;
22742s   : constant Time             := 1.0;
22743A   : constant Electric_Current := 1.0;
22744@end example
22745@end quotation
22746
22747as well as useful multiples of these units:
22748
22749@quotation
22750
22751@example
22752 cm  : constant Length := 1.0E-02;
22753 g   : constant Mass   := 1.0E-03;
22754 min : constant Time   := 60.0;
22755 day : constant Time   := 60.0 * 24.0 * min;
22756...
22757@end example
22758@end quotation
22759
22760There are three instantiations of @code{System.Dim.Generic_Mks} defined in the
22761GNAT library:
22762
22763
22764@itemize *
22765
22766@item
22767@code{System.Dim.Float_Mks} based on @code{Float} defined in @code{s-diflmk.ads}.
22768
22769@item
22770@code{System.Dim.Long_Mks} based on @code{Long_Float} defined in @code{s-dilomk.ads}.
22771
22772@item
22773@code{System.Dim.Mks} based on @code{Long_Long_Float} defined in @code{s-dimmks.ads}.
22774@end itemize
22775
22776Using one of these packages, you can then define a derived unit by providing
22777the aspect that specifies its dimensions within the MKS system, as well as the
22778string to be used for output of a value of that unit:
22779
22780@quotation
22781
22782@example
22783subtype Acceleration is Mks_Type
22784  with Dimension => ("m/sec^2",
22785                     Meter => 1,
22786                     Second => -2,
22787                     others => 0);
22788@end example
22789@end quotation
22790
22791Here is a complete example of use:
22792
22793@quotation
22794
22795@example
22796with System.Dim.MKS; use System.Dim.Mks;
22797with System.Dim.Mks_IO; use System.Dim.Mks_IO;
22798with Text_IO; use Text_IO;
22799procedure Free_Fall is
22800  subtype Acceleration is Mks_Type
22801    with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
22802  G : constant acceleration := 9.81 * m / (s ** 2);
22803  T : Time := 10.0*s;
22804  Distance : Length;
22805
22806begin
22807  Put ("Gravitational constant: ");
22808  Put (G, Aft => 2, Exp => 0); Put_Line ("");
22809  Distance := 0.5 * G * T ** 2;
22810  Put ("distance travelled in 10 seconds of free fall ");
22811  Put (Distance, Aft => 2, Exp => 0);
22812  Put_Line ("");
22813end Free_Fall;
22814@end example
22815@end quotation
22816
22817Execution of this program yields:
22818
22819@quotation
22820
22821@example
22822Gravitational constant:  9.81 m/sec^2
22823distance travelled in 10 seconds of free fall 490.50 m
22824@end example
22825@end quotation
22826
22827However, incorrect assignments such as:
22828
22829@quotation
22830
22831@example
22832Distance := 5.0;
22833Distance := 5.0 * kg;
22834@end example
22835@end quotation
22836
22837are rejected with the following diagnoses:
22838
22839@quotation
22840
22841@example
22842Distance := 5.0;
22843   >>> dimensions mismatch in assignment
22844   >>> left-hand side has dimension [L]
22845   >>> right-hand side is dimensionless
22846
22847Distance := 5.0 * kg:
22848   >>> dimensions mismatch in assignment
22849   >>> left-hand side has dimension [L]
22850   >>> right-hand side has dimension [M]
22851@end example
22852@end quotation
22853
22854The dimensions of an expression are properly displayed, even if there is
22855no explicit subtype for it. If we add to the program:
22856
22857@quotation
22858
22859@example
22860Put ("Final velocity: ");
22861Put (G * T, Aft =>2, Exp =>0);
22862Put_Line ("");
22863@end example
22864@end quotation
22865
22866then the output includes:
22867
22868@quotation
22869
22870@example
22871Final velocity: 98.10 m.s**(-1)
22872@end example
22873
22874@geindex Dimensionable type
22875
22876@geindex Dimensioned subtype
22877@end quotation
22878
22879The type @code{Mks_Type} is said to be a @emph{dimensionable type} since it has a
22880@code{Dimension_System} aspect, and the subtypes @code{Length}, @code{Mass}, etc.,
22881are said to be @emph{dimensioned subtypes} since each one has a @code{Dimension}
22882aspect.
22883
22884@quotation
22885
22886@geindex Dimension Vector (for a dimensioned subtype)
22887
22888@geindex Dimension aspect
22889
22890@geindex Dimension_System aspect
22891@end quotation
22892
22893The @code{Dimension} aspect of a dimensioned subtype @code{S} defines a mapping
22894from the base type's Unit_Names to integer (or, more generally, rational)
22895values. This mapping is the @emph{dimension vector} (also referred to as the
22896@emph{dimensionality}) for that subtype, denoted by @code{DV(S)}, and thus for each
22897object of that subtype. Intuitively, the value specified for each
22898@code{Unit_Name} is the exponent associated with that unit; a zero value
22899means that the unit is not used. For example:
22900
22901@quotation
22902
22903@example
22904declare
22905   Acc : Acceleration;
22906   ...
22907begin
22908   ...
22909end;
22910@end example
22911@end quotation
22912
22913Here @code{DV(Acc)} = @code{DV(Acceleration)} =
22914@code{(Meter=>1, Kilogram=>0, Second=>-2, Ampere=>0, Kelvin=>0, Mole=>0, Candela=>0)}.
22915Symbolically, we can express this as @code{Meter / Second**2}.
22916
22917The dimension vector of an arithmetic expression is synthesized from the
22918dimension vectors of its components, with compile-time dimensionality checks
22919that help prevent mismatches such as using an @code{Acceleration} where a
22920@code{Length} is required.
22921
22922The dimension vector of the result of an arithmetic expression @emph{expr}, or
22923@code{DV(@emph{expr})}, is defined as follows, assuming conventional
22924mathematical definitions for the vector operations that are used:
22925
22926
22927@itemize *
22928
22929@item
22930If @emph{expr} is of the type @emph{universal_real}, or is not of a dimensioned subtype,
22931then @emph{expr} is dimensionless; @code{DV(@emph{expr})} is the empty vector.
22932
22933@item
22934@code{DV(@emph{op expr})}, where @emph{op} is a unary operator, is @code{DV(@emph{expr})}
22935
22936@item
22937@code{DV(@emph{expr1 op expr2})} where @emph{op} is "+" or "-" is @code{DV(@emph{expr1})}
22938provided that @code{DV(@emph{expr1})} = @code{DV(@emph{expr2})}.
22939If this condition is not met then the construct is illegal.
22940
22941@item
22942@code{DV(@emph{expr1} * @emph{expr2})} is @code{DV(@emph{expr1})} + @code{DV(@emph{expr2})},
22943and @code{DV(@emph{expr1} / @emph{expr2})} = @code{DV(@emph{expr1})} - @code{DV(@emph{expr2})}.
22944In this context if one of the @emph{expr}s is dimensionless then its empty
22945dimension vector is treated as @code{(others => 0)}.
22946
22947@item
22948@code{DV(@emph{expr} ** @emph{power})} is @emph{power} * @code{DV(@emph{expr})},
22949provided that @emph{power} is a static rational value. If this condition is not
22950met then the construct is illegal.
22951@end itemize
22952
22953Note that, by the above rules, it is illegal to use binary "+" or "-" to
22954combine a dimensioned and dimensionless value.  Thus an expression such as
22955@code{acc-10.0} is illegal, where @code{acc} is an object of subtype
22956@code{Acceleration}.
22957
22958The dimensionality checks for relationals use the same rules as
22959for "+" and "-", except when comparing to a literal; thus
22960
22961@quotation
22962
22963@example
22964acc > len
22965@end example
22966@end quotation
22967
22968is equivalent to
22969
22970@quotation
22971
22972@example
22973acc-len > 0.0
22974@end example
22975@end quotation
22976
22977and is thus illegal, but
22978
22979@quotation
22980
22981@example
22982acc > 10.0
22983@end example
22984@end quotation
22985
22986is accepted with a warning. Analogously a conditional expression requires the
22987same dimension vector for each branch (with no exception for literals).
22988
22989The dimension vector of a type conversion @code{T(@emph{expr})} is defined
22990as follows, based on the nature of @code{T}:
22991
22992
22993@itemize *
22994
22995@item
22996If @code{T} is a dimensioned subtype then @code{DV(T(@emph{expr}))} is @code{DV(T)}
22997provided that either @emph{expr} is dimensionless or
22998@code{DV(T)} = @code{DV(@emph{expr})}. The conversion is illegal
22999if @emph{expr} is dimensioned and @code{DV(@emph{expr})} /= @code{DV(T)}.
23000Note that vector equality does not require that the corresponding
23001Unit_Names be the same.
23002
23003As a consequence of the above rule, it is possible to convert between
23004different dimension systems that follow the same international system
23005of units, with the seven physical components given in the standard order
23006(length, mass, time, etc.). Thus a length in meters can be converted to
23007a length in inches (with a suitable conversion factor) but cannot be
23008converted, for example, to a mass in pounds.
23009
23010@item
23011If @code{T} is the base type for @emph{expr} (and the dimensionless root type of
23012the dimension system), then @code{DV(T(@emph{expr}))} is @code{DV(expr)}.
23013Thus, if @emph{expr} is of a dimensioned subtype of @code{T}, the conversion may
23014be regarded as a "view conversion" that preserves dimensionality.
23015
23016This rule makes it possible to write generic code that can be instantiated
23017with compatible dimensioned subtypes.  The generic unit will contain
23018conversions that will consequently be present in instantiations, but
23019conversions to the base type will preserve dimensionality and make it
23020possible to write generic code that is correct with respect to
23021dimensionality.
23022
23023@item
23024Otherwise (i.e., @code{T} is neither a dimensioned subtype nor a dimensionable
23025base type), @code{DV(T(@emph{expr}))} is the empty vector. Thus a dimensioned
23026value can be explicitly converted to a non-dimensioned subtype, which
23027of course then escapes dimensionality analysis.
23028@end itemize
23029
23030The dimension vector for a type qualification @code{T'(@emph{expr})} is the same
23031as for the type conversion @code{T(@emph{expr})}.
23032
23033An assignment statement
23034
23035@quotation
23036
23037@example
23038Source := Target;
23039@end example
23040@end quotation
23041
23042requires @code{DV(Source)} = @code{DV(Target)}, and analogously for parameter
23043passing (the dimension vector for the actual parameter must be equal to the
23044dimension vector for the formal parameter).
23045
23046@node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
23047@anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{16b}@anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{29}
23048@section Stack Related Facilities
23049
23050
23051This section describes some useful tools associated with stack
23052checking and analysis. In
23053particular, it deals with dynamic and static stack usage measurements.
23054
23055@menu
23056* Stack Overflow Checking::
23057* Static Stack Usage Analysis::
23058* Dynamic Stack Usage Analysis::
23059
23060@end menu
23061
23062@node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
23063@anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{1c4}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{f4}
23064@subsection Stack Overflow Checking
23065
23066
23067@geindex Stack Overflow Checking
23068
23069@geindex -fstack-check (gcc)
23070
23071For most operating systems, @code{gcc} does not perform stack overflow
23072checking by default. This means that if the main environment task or
23073some other task exceeds the available stack space, then unpredictable
23074behavior will occur. Most native systems offer some level of protection by
23075adding a guard page at the end of each task stack. This mechanism is usually
23076not enough for dealing properly with stack overflow situations because
23077a large local variable could "jump" above the guard page.
23078Furthermore, when the
23079guard page is hit, there may not be any space left on the stack for executing
23080the exception propagation code. Enabling stack checking avoids
23081such situations.
23082
23083To activate stack checking, compile all units with the @code{gcc} option
23084@code{-fstack-check}. For example:
23085
23086@quotation
23087
23088@example
23089$ gcc -c -fstack-check package1.adb
23090@end example
23091@end quotation
23092
23093Units compiled with this option will generate extra instructions to check
23094that any use of the stack (for procedure calls or for declaring local
23095variables in declare blocks) does not exceed the available stack space.
23096If the space is exceeded, then a @code{Storage_Error} exception is raised.
23097
23098For declared tasks, the default stack size is defined by the GNAT runtime,
23099whose size may be modified at bind time through the @code{-d} bind switch
23100(@ref{11f,,Switches for gnatbind}). Task specific stack sizes may be set using the
23101@code{Storage_Size} pragma.
23102
23103For the environment task, the stack size is determined by the operating system.
23104Consequently, to modify the size of the environment task please refer to your
23105operating system documentation.
23106
23107@node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
23108@anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{f5}@anchor{gnat_ugn/gnat_and_program_execution id59}@anchor{1c5}
23109@subsection Static Stack Usage Analysis
23110
23111
23112@geindex Static Stack Usage Analysis
23113
23114@geindex -fstack-usage
23115
23116A unit compiled with @code{-fstack-usage} will generate an extra file
23117that specifies
23118the maximum amount of stack used, on a per-function basis.
23119The file has the same
23120basename as the target object file with a @code{.su} extension.
23121Each line of this file is made up of three fields:
23122
23123
23124@itemize *
23125
23126@item
23127The name of the function.
23128
23129@item
23130A number of bytes.
23131
23132@item
23133One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
23134@end itemize
23135
23136The second field corresponds to the size of the known part of the function
23137frame.
23138
23139The qualifier @code{static} means that the function frame size
23140is purely static.
23141It usually means that all local variables have a static size.
23142In this case, the second field is a reliable measure of the function stack
23143utilization.
23144
23145The qualifier @code{dynamic} means that the function frame size is not static.
23146It happens mainly when some local variables have a dynamic size. When this
23147qualifier appears alone, the second field is not a reliable measure
23148of the function stack analysis. When it is qualified with  @code{bounded}, it
23149means that the second field is a reliable maximum of the function stack
23150utilization.
23151
23152A unit compiled with @code{-Wstack-usage} will issue a warning for each
23153subprogram whose stack usage might be larger than the specified amount of
23154bytes.  The wording is in keeping with the qualifier documented above.
23155
23156@node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
23157@anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{121}@anchor{gnat_ugn/gnat_and_program_execution id60}@anchor{1c6}
23158@subsection Dynamic Stack Usage Analysis
23159
23160
23161It is possible to measure the maximum amount of stack used by a task, by
23162adding a switch to @code{gnatbind}, as:
23163
23164@quotation
23165
23166@example
23167$ gnatbind -u0 file
23168@end example
23169@end quotation
23170
23171With this option, at each task termination, its stack usage is  output on
23172@code{stderr}.
23173It is not always convenient to output the stack usage when the program
23174is still running. Hence, it is possible to delay this output until program
23175termination. for a given number of tasks specified as the argument of the
23176@code{-u} option. For instance:
23177
23178@quotation
23179
23180@example
23181$ gnatbind -u100 file
23182@end example
23183@end quotation
23184
23185will buffer the stack usage information of the first 100 tasks to terminate and
23186output this info at program termination. Results are displayed in four
23187columns:
23188
23189@quotation
23190
23191@example
23192Index | Task Name | Stack Size | Stack Usage
23193@end example
23194@end quotation
23195
23196where:
23197
23198
23199@itemize *
23200
23201@item
23202@emph{Index} is a number associated with each task.
23203
23204@item
23205@emph{Task Name} is the name of the task analyzed.
23206
23207@item
23208@emph{Stack Size} is the maximum size for the stack.
23209
23210@item
23211@emph{Stack Usage} is the measure done by the stack analyzer.
23212In order to prevent overflow, the stack
23213is not entirely analyzed, and it's not possible to know exactly how
23214much has actually been used.
23215@end itemize
23216
23217By default the environment task stack, the stack that contains the main unit,
23218is not processed. To enable processing of the environment task stack, the
23219environment variable GNAT_STACK_LIMIT needs to be set to the maximum size of
23220the environment task stack. This amount is given in kilobytes. For example:
23221
23222@quotation
23223
23224@example
23225$ set GNAT_STACK_LIMIT 1600
23226@end example
23227@end quotation
23228
23229would specify to the analyzer that the environment task stack has a limit
23230of 1.6 megabytes. Any stack usage beyond this will be ignored by the analysis.
23231
23232The package @code{GNAT.Task_Stack_Usage} provides facilities to get
23233stack-usage reports at run time. See its body for the details.
23234
23235@node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
23236@anchor{gnat_ugn/gnat_and_program_execution id61}@anchor{16c}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{2a}
23237@section Memory Management Issues
23238
23239
23240This section describes some useful memory pools provided in the GNAT library
23241and in particular the GNAT Debug Pool facility, which can be used to detect
23242incorrect uses of access values (including 'dangling references').
23243
23244
23245@menu
23246* Some Useful Memory Pools::
23247* The GNAT Debug Pool Facility::
23248
23249@end menu
23250
23251@node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
23252@anchor{gnat_ugn/gnat_and_program_execution id62}@anchor{1c7}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{1c8}
23253@subsection Some Useful Memory Pools
23254
23255
23256@geindex Memory Pool
23257
23258@geindex storage
23259@geindex pool
23260
23261The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
23262storage pool. Allocations use the standard system call @code{malloc} while
23263deallocations use the standard system call @code{free}. No reclamation is
23264performed when the pool goes out of scope. For performance reasons, the
23265standard default Ada allocators/deallocators do not use any explicit storage
23266pools but if they did, they could use this storage pool without any change in
23267behavior. That is why this storage pool is used  when the user
23268manages to make the default implicit allocator explicit as in this example:
23269
23270@quotation
23271
23272@example
23273type T1 is access Something;
23274 -- no Storage pool is defined for T2
23275
23276type T2 is access Something_Else;
23277for T2'Storage_Pool use T1'Storage_Pool;
23278-- the above is equivalent to
23279for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
23280@end example
23281@end quotation
23282
23283The @code{System.Pool_Local} package offers the @code{Unbounded_Reclaim_Pool} storage
23284pool. The allocation strategy is similar to @code{Pool_Local}
23285except that the all
23286storage allocated with this pool is reclaimed when the pool object goes out of
23287scope. This pool provides a explicit mechanism similar to the implicit one
23288provided by several Ada 83 compilers for allocations performed through a local
23289access type and whose purpose was to reclaim memory when exiting the
23290scope of a given local access. As an example, the following program does not
23291leak memory even though it does not perform explicit deallocation:
23292
23293@quotation
23294
23295@example
23296with System.Pool_Local;
23297procedure Pooloc1 is
23298   procedure Internal is
23299      type A is access Integer;
23300      X : System.Pool_Local.Unbounded_Reclaim_Pool;
23301      for A'Storage_Pool use X;
23302      v : A;
23303   begin
23304      for I in  1 .. 50 loop
23305         v := new Integer;
23306      end loop;
23307   end Internal;
23308begin
23309   for I in  1 .. 100 loop
23310      Internal;
23311   end loop;
23312end Pooloc1;
23313@end example
23314@end quotation
23315
23316The @code{System.Pool_Size} package implements the @code{Stack_Bounded_Pool} used when
23317@code{Storage_Size} is specified for an access type.
23318The whole storage for the pool is
23319allocated at once, usually on the stack at the point where the access type is
23320elaborated. It is automatically reclaimed when exiting the scope where the
23321access type is defined. This package is not intended to be used directly by the
23322user and it is implicitly used for each such declaration:
23323
23324@quotation
23325
23326@example
23327type T1 is access Something;
23328for T1'Storage_Size use 10_000;
23329@end example
23330@end quotation
23331
23332@node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
23333@anchor{gnat_ugn/gnat_and_program_execution id63}@anchor{1c9}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{1ca}
23334@subsection The GNAT Debug Pool Facility
23335
23336
23337@geindex Debug Pool
23338
23339@geindex storage
23340@geindex pool
23341@geindex memory corruption
23342
23343The use of unchecked deallocation and unchecked conversion can easily
23344lead to incorrect memory references. The problems generated by such
23345references are usually difficult to tackle because the symptoms can be
23346very remote from the origin of the problem. In such cases, it is
23347very helpful to detect the problem as early as possible. This is the
23348purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
23349
23350In order to use the GNAT specific debugging pool, the user must
23351associate a debug pool object with each of the access types that may be
23352related to suspected memory problems. See Ada Reference Manual 13.11.
23353
23354@quotation
23355
23356@example
23357type Ptr is access Some_Type;
23358Pool : GNAT.Debug_Pools.Debug_Pool;
23359for Ptr'Storage_Pool use Pool;
23360@end example
23361@end quotation
23362
23363@code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
23364pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
23365allow the user to redefine allocation and deallocation strategies. They
23366also provide a checkpoint for each dereference, through the use of
23367the primitive operation @code{Dereference} which is implicitly called at
23368each dereference of an access value.
23369
23370Once an access type has been associated with a debug pool, operations on
23371values of the type may raise four distinct exceptions,
23372which correspond to four potential kinds of memory corruption:
23373
23374
23375@itemize *
23376
23377@item
23378@code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
23379
23380@item
23381@code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
23382
23383@item
23384@code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
23385
23386@item
23387@code{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
23388@end itemize
23389
23390For types associated with a Debug_Pool, dynamic allocation is performed using
23391the standard GNAT allocation routine. References to all allocated chunks of
23392memory are kept in an internal dictionary. Several deallocation strategies are
23393provided, whereupon the user can choose to release the memory to the system,
23394keep it allocated for further invalid access checks, or fill it with an easily
23395recognizable pattern for debug sessions. The memory pattern is the old IBM
23396hexadecimal convention: @code{16#DEADBEEF#}.
23397
23398See the documentation in the file g-debpoo.ads for more information on the
23399various strategies.
23400
23401Upon each dereference, a check is made that the access value denotes a
23402properly allocated memory location. Here is a complete example of use of
23403@code{Debug_Pools}, that includes typical instances of  memory corruption:
23404
23405@quotation
23406
23407@example
23408with Gnat.Io; use Gnat.Io;
23409with Unchecked_Deallocation;
23410with Unchecked_Conversion;
23411with GNAT.Debug_Pools;
23412with System.Storage_Elements;
23413with Ada.Exceptions; use Ada.Exceptions;
23414procedure Debug_Pool_Test is
23415
23416   type T is access Integer;
23417   type U is access all T;
23418
23419   P : GNAT.Debug_Pools.Debug_Pool;
23420   for T'Storage_Pool use P;
23421
23422   procedure Free is new Unchecked_Deallocation (Integer, T);
23423   function UC is new Unchecked_Conversion (U, T);
23424   A, B : aliased T;
23425
23426   procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
23427
23428begin
23429   Info (P);
23430   A := new Integer;
23431   B := new Integer;
23432   B := A;
23433   Info (P);
23434   Free (A);
23435   begin
23436      Put_Line (Integer'Image(B.all));
23437   exception
23438      when E : others => Put_Line ("raised: " & Exception_Name (E));
23439   end;
23440   begin
23441      Free (B);
23442   exception
23443      when E : others => Put_Line ("raised: " & Exception_Name (E));
23444   end;
23445   B := UC(A'Access);
23446   begin
23447      Put_Line (Integer'Image(B.all));
23448   exception
23449      when E : others => Put_Line ("raised: " & Exception_Name (E));
23450   end;
23451   begin
23452      Free (B);
23453   exception
23454      when E : others => Put_Line ("raised: " & Exception_Name (E));
23455   end;
23456   Info (P);
23457end Debug_Pool_Test;
23458@end example
23459@end quotation
23460
23461The debug pool mechanism provides the following precise diagnostics on the
23462execution of this erroneous program:
23463
23464@quotation
23465
23466@example
23467Debug Pool info:
23468  Total allocated bytes :  0
23469  Total deallocated bytes :  0
23470  Current Water Mark:  0
23471  High Water Mark:  0
23472
23473Debug Pool info:
23474  Total allocated bytes :  8
23475  Total deallocated bytes :  0
23476  Current Water Mark:  8
23477  High Water Mark:  8
23478
23479raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
23480raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
23481raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
23482raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
23483Debug Pool info:
23484  Total allocated bytes :  8
23485  Total deallocated bytes :  4
23486  Current Water Mark:  4
23487  High Water Mark:  8
23488@end example
23489@end quotation
23490
23491
23492@c -- Non-breaking space in running text
23493@c -- E.g. Ada |nbsp| 95
23494
23495@node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
23496@anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{d}@anchor{gnat_ugn/platform_specific_information doc}@anchor{1cb}@anchor{gnat_ugn/platform_specific_information id1}@anchor{1cc}
23497@chapter Platform-Specific Information
23498
23499
23500This appendix contains information relating to the implementation
23501of run-time libraries on various platforms and also covers
23502topics related to the GNAT implementation on Windows and Mac OS.
23503
23504@menu
23505* Run-Time Libraries::
23506* Specifying a Run-Time Library::
23507* GNU/Linux Topics::
23508* Microsoft Windows Topics::
23509* Mac OS Topics::
23510
23511@end menu
23512
23513@node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
23514@anchor{gnat_ugn/platform_specific_information id2}@anchor{1cd}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{2b}
23515@section Run-Time Libraries
23516
23517
23518@geindex Tasking and threads libraries
23519
23520@geindex Threads libraries and tasking
23521
23522@geindex Run-time libraries (platform-specific information)
23523
23524The GNAT run-time implementation may vary with respect to both the
23525underlying threads library and the exception-handling scheme.
23526For threads support, the default run-time will bind to the thread
23527package of the underlying operating system.
23528
23529For exception handling, either or both of two models are supplied:
23530
23531@quotation
23532
23533@geindex Zero-Cost Exceptions
23534
23535@geindex ZCX (Zero-Cost Exceptions)
23536@end quotation
23537
23538
23539@itemize *
23540
23541@item
23542@strong{Zero-Cost Exceptions} ("ZCX"),
23543which uses binder-generated tables that
23544are interrogated at run time to locate a handler.
23545
23546@geindex setjmp/longjmp Exception Model
23547
23548@geindex SJLJ (setjmp/longjmp Exception Model)
23549
23550@item
23551@strong{setjmp / longjmp} ('SJLJ'),
23552which uses dynamically-set data to establish
23553the set of handlers
23554@end itemize
23555
23556Most programs should experience a substantial speed improvement by
23557being compiled with a ZCX run-time.
23558This is especially true for
23559tasking applications or applications with many exception handlers.@}
23560
23561This section summarizes which combinations of threads and exception support
23562are supplied on various GNAT platforms.
23563It then shows how to select a particular library either
23564permanently or temporarily,
23565explains the properties of (and tradeoffs among) the various threads
23566libraries, and provides some additional
23567information about several specific platforms.
23568
23569@menu
23570* Summary of Run-Time Configurations::
23571
23572@end menu
23573
23574@node Summary of Run-Time Configurations,,,Run-Time Libraries
23575@anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{1ce}@anchor{gnat_ugn/platform_specific_information id3}@anchor{1cf}
23576@subsection Summary of Run-Time Configurations
23577
23578
23579
23580@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx}
23581@headitem
23582
23583Platform
23584
23585@tab
23586
23587Run-Time
23588
23589@tab
23590
23591Tasking
23592
23593@tab
23594
23595Exceptions
23596
23597@item
23598
23599GNU/Linux
23600
23601@tab
23602
23603rts-native
23604(default)
23605
23606@tab
23607
23608pthread library
23609
23610@tab
23611
23612ZCX
23613
23614@item
23615
23616rts-sjlj
23617
23618@tab
23619
23620pthread library
23621
23622@tab
23623
23624SJLJ
23625
23626@item
23627
23628Windows
23629
23630@tab
23631
23632rts-native
23633(default)
23634
23635@tab
23636
23637native Win32 threads
23638
23639@tab
23640
23641ZCX
23642
23643@item
23644
23645rts-sjlj
23646
23647@tab
23648
23649native Win32 threads
23650
23651@tab
23652
23653SJLJ
23654
23655@item
23656
23657Mac OS
23658
23659@tab
23660
23661rts-native
23662
23663@tab
23664
23665pthread library
23666
23667@tab
23668
23669ZCX
23670
23671@end multitable
23672
23673
23674@node Specifying a Run-Time Library,GNU/Linux Topics,Run-Time Libraries,Platform-Specific Information
23675@anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{1d0}@anchor{gnat_ugn/platform_specific_information id4}@anchor{1d1}
23676@section Specifying a Run-Time Library
23677
23678
23679The @code{adainclude} subdirectory containing the sources of the GNAT
23680run-time library, and the @code{adalib} subdirectory containing the
23681@code{ALI} files and the static and/or shared GNAT library, are located
23682in the gcc target-dependent area:
23683
23684@quotation
23685
23686@example
23687target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
23688@end example
23689@end quotation
23690
23691As indicated above, on some platforms several run-time libraries are supplied.
23692These libraries are installed in the target dependent area and
23693contain a complete source and binary subdirectory. The detailed description
23694below explains the differences between the different libraries in terms of
23695their thread support.
23696
23697The default run-time library (when GNAT is installed) is @emph{rts-native}.
23698This default run-time is selected by the means of soft links.
23699For example on x86-linux:
23700
23701@c --
23702@c --  $(target-dir)
23703@c --      |
23704@c --      +--- adainclude----------+
23705@c --      |                        |
23706@c --      +--- adalib-----------+  |
23707@c --      |                     |  |
23708@c --      +--- rts-native       |  |
23709@c --      |    |                |  |
23710@c --      |    +--- adainclude <---+
23711@c --      |    |                |
23712@c --      |    +--- adalib <----+
23713@c --      |
23714@c --      +--- rts-sjlj
23715@c --           |
23716@c --           +--- adainclude
23717@c --           |
23718@c --           +--- adalib
23719
23720
23721@example
23722               $(target-dir)
23723              __/ /      \ \___
23724      _______/   /        \    \_________________
23725     /          /          \                     \
23726    /          /            \                     \
23727ADAINCLUDE  ADALIB      rts-native             rts-sjlj
23728   :          :            /    \                 /   \
23729   :          :           /      \               /     \
23730   :          :          /        \             /       \
23731   :          :         /          \           /         \
23732   +-------------> adainclude     adalib   adainclude   adalib
23733              :                     ^
23734              :                     :
23735              +---------------------+
23736
23737              Run-Time Library Directory Structure
23738   (Upper-case names and dotted/dashed arrows represent soft links)
23739@end example
23740
23741If the @emph{rts-sjlj} library is to be selected on a permanent basis,
23742these soft links can be modified with the following commands:
23743
23744@quotation
23745
23746@example
23747$ cd $target
23748$ rm -f adainclude adalib
23749$ ln -s rts-sjlj/adainclude adainclude
23750$ ln -s rts-sjlj/adalib adalib
23751@end example
23752@end quotation
23753
23754Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
23755@code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
23756@code{$target/ada_object_path}.
23757
23758@geindex --RTS option
23759
23760Selecting another run-time library temporarily can be
23761achieved by using the @code{--RTS} switch, e.g., @code{--RTS=sjlj}
23762@anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{1d2}
23763@geindex SCHED_FIFO scheduling policy
23764
23765@geindex SCHED_RR scheduling policy
23766
23767@geindex SCHED_OTHER scheduling policy
23768
23769@menu
23770* Choosing the Scheduling Policy::
23771
23772@end menu
23773
23774@node Choosing the Scheduling Policy,,,Specifying a Run-Time Library
23775@anchor{gnat_ugn/platform_specific_information id5}@anchor{1d3}
23776@subsection Choosing the Scheduling Policy
23777
23778
23779When using a POSIX threads implementation, you have a choice of several
23780scheduling policies: @code{SCHED_FIFO}, @code{SCHED_RR} and @code{SCHED_OTHER}.
23781
23782Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
23783or @code{SCHED_RR} requires special (e.g., root) privileges.
23784
23785@geindex pragma Time_Slice
23786
23787@geindex -T0 option
23788
23789@geindex pragma Task_Dispatching_Policy
23790
23791By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
23792@code{SCHED_FIFO},
23793you can use one of the following:
23794
23795
23796@itemize *
23797
23798@item
23799@code{pragma Time_Slice (0.0)}
23800
23801@item
23802the corresponding binder option @code{-T0}
23803
23804@item
23805@code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23806@end itemize
23807
23808To specify @code{SCHED_RR},
23809you should use @code{pragma Time_Slice} with a
23810value greater than 0.0, or else use the corresponding @code{-T}
23811binder option.
23812
23813To make sure a program is running as root, you can put something like
23814this in a library package body in your application:
23815
23816@quotation
23817
23818@example
23819function geteuid return Integer;
23820pragma Import (C, geteuid, "geteuid");
23821Ignore : constant Boolean :=
23822  (if geteuid = 0 then True else raise Program_Error with "must be root");
23823@end example
23824@end quotation
23825
23826It gets the effective user id, and if it's not 0 (i.e. root), it raises
23827Program_Error.
23828
23829@geindex Linux
23830
23831@geindex GNU/Linux
23832
23833@node GNU/Linux Topics,Microsoft Windows Topics,Specifying a Run-Time Library,Platform-Specific Information
23834@anchor{gnat_ugn/platform_specific_information id6}@anchor{1d4}@anchor{gnat_ugn/platform_specific_information gnu-linux-topics}@anchor{1d5}
23835@section GNU/Linux Topics
23836
23837
23838This section describes topics that are specific to GNU/Linux platforms.
23839
23840@menu
23841* Required Packages on GNU/Linux::
23842
23843@end menu
23844
23845@node Required Packages on GNU/Linux,,,GNU/Linux Topics
23846@anchor{gnat_ugn/platform_specific_information id7}@anchor{1d6}@anchor{gnat_ugn/platform_specific_information required-packages-on-gnu-linux}@anchor{1d7}
23847@subsection Required Packages on GNU/Linux
23848
23849
23850GNAT requires the C library developer's package to be installed.
23851The name of of that package depends on your GNU/Linux distribution:
23852
23853
23854@itemize *
23855
23856@item
23857RedHat, SUSE: @code{glibc-devel};
23858
23859@item
23860Debian, Ubuntu: @code{libc6-dev} (normally installed by default).
23861@end itemize
23862
23863If using the 32-bit version of GNAT on a 64-bit version of GNU/Linux,
23864you'll need the 32-bit version of the following packages:
23865
23866
23867@itemize *
23868
23869@item
23870RedHat, SUSE: @code{glibc.i686}, @code{glibc-devel.i686}, @code{ncurses-libs.i686}
23871
23872@item
23873Debian, Ubuntu: @code{libc6:i386}, @code{libc6-dev:i386}, @code{lib32ncursesw5}
23874@end itemize
23875
23876Other GNU/Linux distributions might be choosing a different name
23877for those packages.
23878
23879@geindex Windows
23880
23881@node Microsoft Windows Topics,Mac OS Topics,GNU/Linux Topics,Platform-Specific Information
23882@anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{2c}@anchor{gnat_ugn/platform_specific_information id8}@anchor{1d8}
23883@section Microsoft Windows Topics
23884
23885
23886This section describes topics that are specific to the Microsoft Windows
23887platforms.
23888
23889
23890
23891
23892
23893@menu
23894* Using GNAT on Windows::
23895* Using a network installation of GNAT::
23896* CONSOLE and WINDOWS subsystems::
23897* Temporary Files::
23898* Disabling Command Line Argument Expansion::
23899* Mixed-Language Programming on Windows::
23900* Windows Specific Add-Ons::
23901
23902@end menu
23903
23904@node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
23905@anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{1d9}@anchor{gnat_ugn/platform_specific_information id9}@anchor{1da}
23906@subsection Using GNAT on Windows
23907
23908
23909One of the strengths of the GNAT technology is that its tool set
23910(@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
23911@code{gdb} debugger, etc.) is used in the same way regardless of the
23912platform.
23913
23914On Windows this tool set is complemented by a number of Microsoft-specific
23915tools that have been provided to facilitate interoperability with Windows
23916when this is required. With these tools:
23917
23918
23919@itemize *
23920
23921@item
23922You can build applications using the @code{CONSOLE} or @code{WINDOWS}
23923subsystems.
23924
23925@item
23926You can use any Dynamically Linked Library (DLL) in your Ada code (both
23927relocatable and non-relocatable DLLs are supported).
23928
23929@item
23930You can build Ada DLLs for use in other applications. These applications
23931can be written in a language other than Ada (e.g., C, C++, etc). Again both
23932relocatable and non-relocatable Ada DLLs are supported.
23933
23934@item
23935You can include Windows resources in your Ada application.
23936
23937@item
23938You can use or create COM/DCOM objects.
23939@end itemize
23940
23941Immediately below are listed all known general GNAT-for-Windows restrictions.
23942Other restrictions about specific features like Windows Resources and DLLs
23943are listed in separate sections below.
23944
23945
23946@itemize *
23947
23948@item
23949It is not possible to use @code{GetLastError} and @code{SetLastError}
23950when tasking, protected records, or exceptions are used. In these
23951cases, in order to implement Ada semantics, the GNAT run-time system
23952calls certain Win32 routines that set the last error variable to 0 upon
23953success. It should be possible to use @code{GetLastError} and
23954@code{SetLastError} when tasking, protected record, and exception
23955features are not used, but it is not guaranteed to work.
23956
23957@item
23958It is not possible to link against Microsoft C++ libraries except for
23959import libraries. Interfacing must be done by the mean of DLLs.
23960
23961@item
23962It is possible to link against Microsoft C libraries. Yet the preferred
23963solution is to use C/C++ compiler that comes with GNAT, since it
23964doesn't require having two different development environments and makes the
23965inter-language debugging experience smoother.
23966
23967@item
23968When the compilation environment is located on FAT32 drives, users may
23969experience recompilations of the source files that have not changed if
23970Daylight Saving Time (DST) state has changed since the last time files
23971were compiled. NTFS drives do not have this problem.
23972
23973@item
23974No components of the GNAT toolset use any entries in the Windows
23975registry. The only entries that can be created are file associations and
23976PATH settings, provided the user has chosen to create them at installation
23977time, as well as some minimal book-keeping information needed to correctly
23978uninstall or integrate different GNAT products.
23979@end itemize
23980
23981@node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
23982@anchor{gnat_ugn/platform_specific_information id10}@anchor{1db}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{1dc}
23983@subsection Using a network installation of GNAT
23984
23985
23986Make sure the system on which GNAT is installed is accessible from the
23987current machine, i.e., the install location is shared over the network.
23988Shared resources are accessed on Windows by means of UNC paths, which
23989have the format @code{\\\\server\\sharename\\path}
23990
23991In order to use such a network installation, simply add the UNC path of the
23992@code{bin} directory of your GNAT installation in front of your PATH. For
23993example, if GNAT is installed in @code{\GNAT} directory of a share location
23994called @code{c-drive} on a machine @code{LOKI}, the following command will
23995make it available:
23996
23997@quotation
23998
23999@example
24000$ path \\loki\c-drive\gnat\bin;%path%`
24001@end example
24002@end quotation
24003
24004Be aware that every compilation using the network installation results in the
24005transfer of large amounts of data across the network and will likely cause
24006serious performance penalty.
24007
24008@node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
24009@anchor{gnat_ugn/platform_specific_information id11}@anchor{1dd}@anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{1de}
24010@subsection CONSOLE and WINDOWS subsystems
24011
24012
24013@geindex CONSOLE Subsystem
24014
24015@geindex WINDOWS Subsystem
24016
24017@geindex -mwindows
24018
24019There are two main subsystems under Windows. The @code{CONSOLE} subsystem
24020(which is the default subsystem) will always create a console when
24021launching the application. This is not something desirable when the
24022application has a Windows GUI. To get rid of this console the
24023application must be using the @code{WINDOWS} subsystem. To do so
24024the @code{-mwindows} linker option must be specified.
24025
24026@quotation
24027
24028@example
24029$ gnatmake winprog -largs -mwindows
24030@end example
24031@end quotation
24032
24033@node Temporary Files,Disabling Command Line Argument Expansion,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
24034@anchor{gnat_ugn/platform_specific_information id12}@anchor{1df}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{1e0}
24035@subsection Temporary Files
24036
24037
24038@geindex Temporary files
24039
24040It is possible to control where temporary files gets created by setting
24041the
24042@geindex TMP
24043@geindex environment variable; TMP
24044@code{TMP} environment variable. The file will be created:
24045
24046
24047@itemize *
24048
24049@item
24050Under the directory pointed to by the
24051@geindex TMP
24052@geindex environment variable; TMP
24053@code{TMP} environment variable if
24054this directory exists.
24055
24056@item
24057Under @code{c:\temp}, if the
24058@geindex TMP
24059@geindex environment variable; TMP
24060@code{TMP} environment variable is not
24061set (or not pointing to a directory) and if this directory exists.
24062
24063@item
24064Under the current working directory otherwise.
24065@end itemize
24066
24067This allows you to determine exactly where the temporary
24068file will be created. This is particularly useful in networked
24069environments where you may not have write access to some
24070directories.
24071
24072@node Disabling Command Line Argument Expansion,Mixed-Language Programming on Windows,Temporary Files,Microsoft Windows Topics
24073@anchor{gnat_ugn/platform_specific_information disabling-command-line-argument-expansion}@anchor{1e1}
24074@subsection Disabling Command Line Argument Expansion
24075
24076
24077@geindex Command Line Argument Expansion
24078
24079By default, an executable compiled for the Windows platform will do
24080the following postprocessing on the arguments passed on the command
24081line:
24082
24083
24084@itemize *
24085
24086@item
24087If the argument contains the characters @code{*} and/or @code{?}, then
24088file expansion will be attempted. For example, if the current directory
24089contains @code{a.txt} and @code{b.txt}, then when calling:
24090
24091@example
24092$ my_ada_program *.txt
24093@end example
24094
24095The following arguments will effectively be passed to the main program
24096(for example when using @code{Ada.Command_Line.Argument}):
24097
24098@example
24099Ada.Command_Line.Argument (1) -> "a.txt"
24100Ada.Command_Line.Argument (2) -> "b.txt"
24101@end example
24102
24103@item
24104Filename expansion can be disabled for a given argument by using single
24105quotes. Thus, calling:
24106
24107@example
24108$ my_ada_program '*.txt'
24109@end example
24110
24111will result in:
24112
24113@example
24114Ada.Command_Line.Argument (1) -> "*.txt"
24115@end example
24116@end itemize
24117
24118Note that if the program is launched from a shell such as Cygwin Bash
24119then quote removal might be performed by the shell.
24120
24121In some contexts it might be useful to disable this feature (for example if
24122the program performs its own argument expansion). In order to do this, a C
24123symbol needs to be defined and set to @code{0}. You can do this by
24124adding the following code fragment in one of your Ada units:
24125
24126@example
24127Do_Argv_Expansion : Integer := 0;
24128pragma Export (C, Do_Argv_Expansion, "__gnat_do_argv_expansion");
24129@end example
24130
24131The results of previous examples will be respectively:
24132
24133@example
24134Ada.Command_Line.Argument (1) -> "*.txt"
24135@end example
24136
24137and:
24138
24139@example
24140Ada.Command_Line.Argument (1) -> "'*.txt'"
24141@end example
24142
24143@node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Disabling Command Line Argument Expansion,Microsoft Windows Topics
24144@anchor{gnat_ugn/platform_specific_information id13}@anchor{1e2}@anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{1e3}
24145@subsection Mixed-Language Programming on Windows
24146
24147
24148Developing pure Ada applications on Windows is no different than on
24149other GNAT-supported platforms. However, when developing or porting an
24150application that contains a mix of Ada and C/C++, the choice of your
24151Windows C/C++ development environment conditions your overall
24152interoperability strategy.
24153
24154If you use @code{gcc} or Microsoft C to compile the non-Ada part of
24155your application, there are no Windows-specific restrictions that
24156affect the overall interoperability with your Ada code. If you do want
24157to use the Microsoft tools for your C++ code, you have two choices:
24158
24159
24160@itemize *
24161
24162@item
24163Encapsulate your C++ code in a DLL to be linked with your Ada
24164application. In this case, use the Microsoft or whatever environment to
24165build the DLL and use GNAT to build your executable
24166(@ref{1e4,,Using DLLs with GNAT}).
24167
24168@item
24169Or you can encapsulate your Ada code in a DLL to be linked with the
24170other part of your application. In this case, use GNAT to build the DLL
24171(@ref{1e5,,Building DLLs with GNAT Project files}) and use the Microsoft
24172or whatever environment to build your executable.
24173@end itemize
24174
24175In addition to the description about C main in
24176@ref{44,,Mixed Language Programming} section, if the C main uses a
24177stand-alone library it is required on x86-windows to
24178setup the SEH context. For this the C main must looks like this:
24179
24180@quotation
24181
24182@example
24183/* main.c */
24184extern void adainit (void);
24185extern void adafinal (void);
24186extern void __gnat_initialize(void*);
24187extern void call_to_ada (void);
24188
24189int main (int argc, char *argv[])
24190@{
24191  int SEH [2];
24192
24193  /* Initialize the SEH context */
24194  __gnat_initialize (&SEH);
24195
24196  adainit();
24197
24198  /* Then call Ada services in the stand-alone library */
24199
24200  call_to_ada();
24201
24202  adafinal();
24203@}
24204@end example
24205@end quotation
24206
24207Note that this is not needed on x86_64-windows where the Windows
24208native SEH support is used.
24209
24210@menu
24211* Windows Calling Conventions::
24212* Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs.
24213* Using DLLs with GNAT::
24214* Building DLLs with GNAT Project files::
24215* Building DLLs with GNAT::
24216* Building DLLs with gnatdll::
24217* Ada DLLs and Finalization::
24218* Creating a Spec for Ada DLLs::
24219* GNAT and Windows Resources::
24220* Using GNAT DLLs from Microsoft Visual Studio Applications::
24221* Debugging a DLL::
24222* Setting Stack Size from gnatlink::
24223* Setting Heap Size from gnatlink::
24224
24225@end menu
24226
24227@node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
24228@anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{1e6}@anchor{gnat_ugn/platform_specific_information id14}@anchor{1e7}
24229@subsubsection Windows Calling Conventions
24230
24231
24232@geindex Stdcall
24233
24234@geindex APIENTRY
24235
24236This section pertain only to Win32. On Win64 there is a single native
24237calling convention. All convention specifiers are ignored on this
24238platform.
24239
24240When a subprogram @code{F} (caller) calls a subprogram @code{G}
24241(callee), there are several ways to push @code{G}'s parameters on the
24242stack and there are several possible scenarios to clean up the stack
24243upon @code{G}'s return. A calling convention is an agreed upon software
24244protocol whereby the responsibilities between the caller (@code{F}) and
24245the callee (@code{G}) are clearly defined. Several calling conventions
24246are available for Windows:
24247
24248
24249@itemize *
24250
24251@item
24252@code{C} (Microsoft defined)
24253
24254@item
24255@code{Stdcall} (Microsoft defined)
24256
24257@item
24258@code{Win32} (GNAT specific)
24259
24260@item
24261@code{DLL} (GNAT specific)
24262@end itemize
24263
24264@menu
24265* C Calling Convention::
24266* Stdcall Calling Convention::
24267* Win32 Calling Convention::
24268* DLL Calling Convention::
24269
24270@end menu
24271
24272@node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
24273@anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{1e8}@anchor{gnat_ugn/platform_specific_information id15}@anchor{1e9}
24274@subsubsection @code{C} Calling Convention
24275
24276
24277This is the default calling convention used when interfacing to C/C++
24278routines compiled with either @code{gcc} or Microsoft Visual C++.
24279
24280In the @code{C} calling convention subprogram parameters are pushed on the
24281stack by the caller from right to left. The caller itself is in charge of
24282cleaning up the stack after the call. In addition, the name of a routine
24283with @code{C} calling convention is mangled by adding a leading underscore.
24284
24285The name to use on the Ada side when importing (or exporting) a routine
24286with @code{C} calling convention is the name of the routine. For
24287instance the C function:
24288
24289@quotation
24290
24291@example
24292int get_val (long);
24293@end example
24294@end quotation
24295
24296should be imported from Ada as follows:
24297
24298@quotation
24299
24300@example
24301function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24302pragma Import (C, Get_Val, External_Name => "get_val");
24303@end example
24304@end quotation
24305
24306Note that in this particular case the @code{External_Name} parameter could
24307have been omitted since, when missing, this parameter is taken to be the
24308name of the Ada entity in lower case. When the @code{Link_Name} parameter
24309is missing, as in the above example, this parameter is set to be the
24310@code{External_Name} with a leading underscore.
24311
24312When importing a variable defined in C, you should always use the @code{C}
24313calling convention unless the object containing the variable is part of a
24314DLL (in which case you should use the @code{Stdcall} calling
24315convention, @ref{1ea,,Stdcall Calling Convention}).
24316
24317@node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
24318@anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{1ea}@anchor{gnat_ugn/platform_specific_information id16}@anchor{1eb}
24319@subsubsection @code{Stdcall} Calling Convention
24320
24321
24322This convention, which was the calling convention used for Pascal
24323programs, is used by Microsoft for all the routines in the Win32 API for
24324efficiency reasons. It must be used to import any routine for which this
24325convention was specified.
24326
24327In the @code{Stdcall} calling convention subprogram parameters are pushed
24328on the stack by the caller from right to left. The callee (and not the
24329caller) is in charge of cleaning the stack on routine exit. In addition,
24330the name of a routine with @code{Stdcall} calling convention is mangled by
24331adding a leading underscore (as for the @code{C} calling convention) and a
24332trailing @code{@@@emph{nn}}, where @code{nn} is the overall size (in
24333bytes) of the parameters passed to the routine.
24334
24335The name to use on the Ada side when importing a C routine with a
24336@code{Stdcall} calling convention is the name of the C routine. The leading
24337underscore and trailing @code{@@@emph{nn}} are added automatically by
24338the compiler. For instance the Win32 function:
24339
24340@quotation
24341
24342@example
24343APIENTRY int get_val (long);
24344@end example
24345@end quotation
24346
24347should be imported from Ada as follows:
24348
24349@quotation
24350
24351@example
24352function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24353pragma Import (Stdcall, Get_Val);
24354--  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
24355@end example
24356@end quotation
24357
24358As for the @code{C} calling convention, when the @code{External_Name}
24359parameter is missing, it is taken to be the name of the Ada entity in lower
24360case. If instead of writing the above import pragma you write:
24361
24362@quotation
24363
24364@example
24365function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24366pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
24367@end example
24368@end quotation
24369
24370then the imported routine is @code{_retrieve_val@@4}. However, if instead
24371of specifying the @code{External_Name} parameter you specify the
24372@code{Link_Name} as in the following example:
24373
24374@quotation
24375
24376@example
24377function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24378pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
24379@end example
24380@end quotation
24381
24382then the imported routine is @code{retrieve_val}, that is, there is no
24383decoration at all. No leading underscore and no Stdcall suffix
24384@code{@@@emph{nn}}.
24385
24386This is especially important as in some special cases a DLL's entry
24387point name lacks a trailing @code{@@@emph{nn}} while the exported
24388name generated for a call has it.
24389
24390It is also possible to import variables defined in a DLL by using an
24391import pragma for a variable. As an example, if a DLL contains a
24392variable defined as:
24393
24394@quotation
24395
24396@example
24397int my_var;
24398@end example
24399@end quotation
24400
24401then, to access this variable from Ada you should write:
24402
24403@quotation
24404
24405@example
24406My_Var : Interfaces.C.int;
24407pragma Import (Stdcall, My_Var);
24408@end example
24409@end quotation
24410
24411Note that to ease building cross-platform bindings this convention
24412will be handled as a @code{C} calling convention on non-Windows platforms.
24413
24414@node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
24415@anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{1ec}@anchor{gnat_ugn/platform_specific_information id17}@anchor{1ed}
24416@subsubsection @code{Win32} Calling Convention
24417
24418
24419This convention, which is GNAT-specific is fully equivalent to the
24420@code{Stdcall} calling convention described above.
24421
24422@node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
24423@anchor{gnat_ugn/platform_specific_information id18}@anchor{1ee}@anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{1ef}
24424@subsubsection @code{DLL} Calling Convention
24425
24426
24427This convention, which is GNAT-specific is fully equivalent to the
24428@code{Stdcall} calling convention described above.
24429
24430@node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
24431@anchor{gnat_ugn/platform_specific_information id19}@anchor{1f0}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{1f1}
24432@subsubsection Introduction to Dynamic Link Libraries (DLLs)
24433
24434
24435@geindex DLL
24436
24437A Dynamically Linked Library (DLL) is a library that can be shared by
24438several applications running under Windows. A DLL can contain any number of
24439routines and variables.
24440
24441One advantage of DLLs is that you can change and enhance them without
24442forcing all the applications that depend on them to be relinked or
24443recompiled. However, you should be aware than all calls to DLL routines are
24444slower since, as you will understand below, such calls are indirect.
24445
24446To illustrate the remainder of this section, suppose that an application
24447wants to use the services of a DLL @code{API.dll}. To use the services
24448provided by @code{API.dll} you must statically link against the DLL or
24449an import library which contains a jump table with an entry for each
24450routine and variable exported by the DLL. In the Microsoft world this
24451import library is called @code{API.lib}. When using GNAT this import
24452library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
24453@code{libAPI.a} or @code{libapi.a} (names are case insensitive).
24454
24455After you have linked your application with the DLL or the import library
24456and you run your application, here is what happens:
24457
24458
24459@itemize *
24460
24461@item
24462Your application is loaded into memory.
24463
24464@item
24465The DLL @code{API.dll} is mapped into the address space of your
24466application. This means that:
24467
24468
24469@itemize -
24470
24471@item
24472The DLL will use the stack of the calling thread.
24473
24474@item
24475The DLL will use the virtual address space of the calling process.
24476
24477@item
24478The DLL will allocate memory from the virtual address space of the calling
24479process.
24480
24481@item
24482Handles (pointers) can be safely exchanged between routines in the DLL
24483routines and routines in the application using the DLL.
24484@end itemize
24485
24486@item
24487The entries in the jump table (from the import library @code{libAPI.dll.a}
24488or @code{API.lib} or automatically created when linking against a DLL)
24489which is part of your application are initialized with the addresses
24490of the routines and variables in @code{API.dll}.
24491
24492@item
24493If present in @code{API.dll}, routines @code{DllMain} or
24494@code{DllMainCRTStartup} are invoked. These routines typically contain
24495the initialization code needed for the well-being of the routines and
24496variables exported by the DLL.
24497@end itemize
24498
24499There is an additional point which is worth mentioning. In the Windows
24500world there are two kind of DLLs: relocatable and non-relocatable
24501DLLs. Non-relocatable DLLs can only be loaded at a very specific address
24502in the target application address space. If the addresses of two
24503non-relocatable DLLs overlap and these happen to be used by the same
24504application, a conflict will occur and the application will run
24505incorrectly. Hence, when possible, it is always preferable to use and
24506build relocatable DLLs. Both relocatable and non-relocatable DLLs are
24507supported by GNAT. Note that the @code{-s} linker option (see GNU Linker
24508User's Guide) removes the debugging symbols from the DLL but the DLL can
24509still be relocated.
24510
24511As a side note, an interesting difference between Microsoft DLLs and
24512Unix shared libraries, is the fact that on most Unix systems all public
24513routines are exported by default in a Unix shared library, while under
24514Windows it is possible (but not required) to list exported routines in
24515a definition file (see @ref{1f2,,The Definition File}).
24516
24517@node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
24518@anchor{gnat_ugn/platform_specific_information id20}@anchor{1f3}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{1e4}
24519@subsubsection Using DLLs with GNAT
24520
24521
24522To use the services of a DLL, say @code{API.dll}, in your Ada application
24523you must have:
24524
24525
24526@itemize *
24527
24528@item
24529The Ada spec for the routines and/or variables you want to access in
24530@code{API.dll}. If not available this Ada spec must be built from the C/C++
24531header files provided with the DLL.
24532
24533@item
24534The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
24535mentioned an import library is a statically linked library containing the
24536import table which will be filled at load time to point to the actual
24537@code{API.dll} routines. Sometimes you don't have an import library for the
24538DLL you want to use. The following sections will explain how to build
24539one. Note that this is optional.
24540
24541@item
24542The actual DLL, @code{API.dll}.
24543@end itemize
24544
24545Once you have all the above, to compile an Ada application that uses the
24546services of @code{API.dll} and whose main subprogram is @code{My_Ada_App},
24547you simply issue the command
24548
24549@quotation
24550
24551@example
24552$ gnatmake my_ada_app -largs -lAPI
24553@end example
24554@end quotation
24555
24556The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
24557tells the GNAT linker to look for an import library. The linker will
24558look for a library name in this specific order:
24559
24560
24561@itemize *
24562
24563@item
24564@code{libAPI.dll.a}
24565
24566@item
24567@code{API.dll.a}
24568
24569@item
24570@code{libAPI.a}
24571
24572@item
24573@code{API.lib}
24574
24575@item
24576@code{libAPI.dll}
24577
24578@item
24579@code{API.dll}
24580@end itemize
24581
24582The first three are the GNU style import libraries. The third is the
24583Microsoft style import libraries. The last two are the actual DLL names.
24584
24585Note that if the Ada package spec for @code{API.dll} contains the
24586following pragma
24587
24588@quotation
24589
24590@example
24591pragma Linker_Options ("-lAPI");
24592@end example
24593@end quotation
24594
24595you do not have to add @code{-largs -lAPI} at the end of the
24596@code{gnatmake} command.
24597
24598If any one of the items above is missing you will have to create it
24599yourself. The following sections explain how to do so using as an
24600example a fictitious DLL called @code{API.dll}.
24601
24602@menu
24603* Creating an Ada Spec for the DLL Services::
24604* Creating an Import Library::
24605
24606@end menu
24607
24608@node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
24609@anchor{gnat_ugn/platform_specific_information id21}@anchor{1f4}@anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{1f5}
24610@subsubsection Creating an Ada Spec for the DLL Services
24611
24612
24613A DLL typically comes with a C/C++ header file which provides the
24614definitions of the routines and variables exported by the DLL. The Ada
24615equivalent of this header file is a package spec that contains definitions
24616for the imported entities. If the DLL you intend to use does not come with
24617an Ada spec you have to generate one such spec yourself. For example if
24618the header file of @code{API.dll} is a file @code{api.h} containing the
24619following two definitions:
24620
24621@quotation
24622
24623@example
24624int some_var;
24625int get (char *);
24626@end example
24627@end quotation
24628
24629then the equivalent Ada spec could be:
24630
24631@quotation
24632
24633@example
24634with Interfaces.C.Strings;
24635package API is
24636   use Interfaces;
24637
24638   Some_Var : C.int;
24639   function Get (Str : C.Strings.Chars_Ptr) return C.int;
24640
24641private
24642   pragma Import (C, Get);
24643   pragma Import (DLL, Some_Var);
24644end API;
24645@end example
24646@end quotation
24647
24648@node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
24649@anchor{gnat_ugn/platform_specific_information id22}@anchor{1f6}@anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{1f7}
24650@subsubsection Creating an Import Library
24651
24652
24653@geindex Import library
24654
24655If a Microsoft-style import library @code{API.lib} or a GNAT-style
24656import library @code{libAPI.dll.a} or @code{libAPI.a} is available
24657with @code{API.dll} you can skip this section. You can also skip this
24658section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
24659as in this case it is possible to link directly against the
24660DLL. Otherwise read on.
24661
24662@geindex Definition file
24663@anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{1f2}
24664@subsubheading The Definition File
24665
24666
24667As previously mentioned, and unlike Unix systems, the list of symbols
24668that are exported from a DLL must be provided explicitly in Windows.
24669The main goal of a definition file is precisely that: list the symbols
24670exported by a DLL. A definition file (usually a file with a @code{.def}
24671suffix) has the following structure:
24672
24673@quotation
24674
24675@example
24676[LIBRARY `@w{`}name`@w{`}]
24677[DESCRIPTION `@w{`}string`@w{`}]
24678EXPORTS
24679   `@w{`}symbol1`@w{`}
24680   `@w{`}symbol2`@w{`}
24681   ...
24682@end example
24683@end quotation
24684
24685
24686@table @asis
24687
24688@item @emph{LIBRARY name}
24689
24690This section, which is optional, gives the name of the DLL.
24691
24692@item @emph{DESCRIPTION string}
24693
24694This section, which is optional, gives a description string that will be
24695embedded in the import library.
24696
24697@item @emph{EXPORTS}
24698
24699This section gives the list of exported symbols (procedures, functions or
24700variables). For instance in the case of @code{API.dll} the @code{EXPORTS}
24701section of @code{API.def} looks like:
24702
24703@example
24704EXPORTS
24705   some_var
24706   get
24707@end example
24708@end table
24709
24710Note that you must specify the correct suffix (@code{@@@emph{nn}})
24711(see @ref{1e6,,Windows Calling Conventions}) for a Stdcall
24712calling convention function in the exported symbols list.
24713
24714There can actually be other sections in a definition file, but these
24715sections are not relevant to the discussion at hand.
24716@anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{1f8}
24717@subsubheading Creating a Definition File Automatically
24718
24719
24720You can automatically create the definition file @code{API.def}
24721(see @ref{1f2,,The Definition File}) from a DLL.
24722For that use the @code{dlltool} program as follows:
24723
24724@quotation
24725
24726@example
24727$ dlltool API.dll -z API.def --export-all-symbols
24728@end example
24729
24730Note that if some routines in the DLL have the @code{Stdcall} convention
24731(@ref{1e6,,Windows Calling Conventions}) with stripped @code{@@@emph{nn}}
24732suffix then you'll have to edit @code{api.def} to add it, and specify
24733@code{-k} to @code{gnatdll} when creating the import library.
24734
24735Here are some hints to find the right @code{@@@emph{nn}} suffix.
24736
24737
24738@itemize -
24739
24740@item
24741If you have the Microsoft import library (.lib), it is possible to get
24742the right symbols by using Microsoft @code{dumpbin} tool (see the
24743corresponding Microsoft documentation for further details).
24744
24745@example
24746$ dumpbin /exports api.lib
24747@end example
24748
24749@item
24750If you have a message about a missing symbol at link time the compiler
24751tells you what symbol is expected. You just have to go back to the
24752definition file and add the right suffix.
24753@end itemize
24754@end quotation
24755@anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{1f9}
24756@subsubheading GNAT-Style Import Library
24757
24758
24759To create a static import library from @code{API.dll} with the GNAT tools
24760you should create the .def file, then use @code{gnatdll} tool
24761(see @ref{1fa,,Using gnatdll}) as follows:
24762
24763@quotation
24764
24765@example
24766$ gnatdll -e API.def -d API.dll
24767@end example
24768
24769@code{gnatdll} takes as input a definition file @code{API.def} and the
24770name of the DLL containing the services listed in the definition file
24771@code{API.dll}. The name of the static import library generated is
24772computed from the name of the definition file as follows: if the
24773definition file name is @code{xyz.def}, the import library name will
24774be @code{libxyz.a}. Note that in the previous example option
24775@code{-e} could have been removed because the name of the definition
24776file (before the @code{.def} suffix) is the same as the name of the
24777DLL (@ref{1fa,,Using gnatdll} for more information about @code{gnatdll}).
24778@end quotation
24779@anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{1fb}
24780@subsubheading Microsoft-Style Import Library
24781
24782
24783A Microsoft import library is needed only if you plan to make an
24784Ada DLL available to applications developed with Microsoft
24785tools (@ref{1e3,,Mixed-Language Programming on Windows}).
24786
24787To create a Microsoft-style import library for @code{API.dll} you
24788should create the .def file, then build the actual import library using
24789Microsoft's @code{lib} utility:
24790
24791@quotation
24792
24793@example
24794$ lib -machine:IX86 -def:API.def -out:API.lib
24795@end example
24796
24797If you use the above command the definition file @code{API.def} must
24798contain a line giving the name of the DLL:
24799
24800@example
24801LIBRARY      "API"
24802@end example
24803
24804See the Microsoft documentation for further details about the usage of
24805@code{lib}.
24806@end quotation
24807
24808@node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
24809@anchor{gnat_ugn/platform_specific_information id23}@anchor{1fc}@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{1e5}
24810@subsubsection Building DLLs with GNAT Project files
24811
24812
24813@geindex DLLs
24814@geindex building
24815
24816There is nothing specific to Windows in the build process.
24817See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24818chapter of the @emph{GPRbuild User's Guide}.
24819
24820Due to a system limitation, it is not possible under Windows to create threads
24821when inside the @code{DllMain} routine which is used for auto-initialization
24822of shared libraries, so it is not possible to have library level tasks in SALs.
24823
24824@node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
24825@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{1fd}@anchor{gnat_ugn/platform_specific_information id24}@anchor{1fe}
24826@subsubsection Building DLLs with GNAT
24827
24828
24829@geindex DLLs
24830@geindex building
24831
24832This section explain how to build DLLs using the GNAT built-in DLL
24833support. With the following procedure it is straight forward to build
24834and use DLLs with GNAT.
24835
24836
24837@itemize *
24838
24839@item
24840Building object files.
24841The first step is to build all objects files that are to be included
24842into the DLL. This is done by using the standard @code{gnatmake} tool.
24843
24844@item
24845Building the DLL.
24846To build the DLL you must use the @code{gcc} @code{-shared} and
24847@code{-shared-libgcc} options. It is quite simple to use this method:
24848
24849@example
24850$ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
24851@end example
24852
24853It is important to note that in this case all symbols found in the
24854object files are automatically exported. It is possible to restrict
24855the set of symbols to export by passing to @code{gcc} a definition
24856file (see @ref{1f2,,The Definition File}).
24857For example:
24858
24859@example
24860$ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
24861@end example
24862
24863If you use a definition file you must export the elaboration procedures
24864for every package that required one. Elaboration procedures are named
24865using the package name followed by "_E".
24866
24867@item
24868Preparing DLL to be used.
24869For the DLL to be used by client programs the bodies must be hidden
24870from it and the .ali set with read-only attribute. This is very important
24871otherwise GNAT will recompile all packages and will not actually use
24872the code in the DLL. For example:
24873
24874@example
24875$ mkdir apilib
24876$ copy *.ads *.ali api.dll apilib
24877$ attrib +R apilib\\*.ali
24878@end example
24879@end itemize
24880
24881At this point it is possible to use the DLL by directly linking
24882against it. Note that you must use the GNAT shared runtime when using
24883GNAT shared libraries. This is achieved by using the @code{-shared} binder
24884option.
24885
24886@quotation
24887
24888@example
24889$ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
24890@end example
24891@end quotation
24892
24893@node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
24894@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{1ff}@anchor{gnat_ugn/platform_specific_information id25}@anchor{200}
24895@subsubsection Building DLLs with gnatdll
24896
24897
24898@geindex DLLs
24899@geindex building
24900
24901Note that it is preferred to use GNAT Project files
24902(@ref{1e5,,Building DLLs with GNAT Project files}) or the built-in GNAT
24903DLL support (@ref{1fd,,Building DLLs with GNAT}) or to build DLLs.
24904
24905This section explains how to build DLLs containing Ada code using
24906@code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
24907remainder of this section.
24908
24909The steps required to build an Ada DLL that is to be used by Ada as well as
24910non-Ada applications are as follows:
24911
24912
24913@itemize *
24914
24915@item
24916You need to mark each Ada entity exported by the DLL with a @code{C} or
24917@code{Stdcall} calling convention to avoid any Ada name mangling for the
24918entities exported by the DLL
24919(see @ref{201,,Exporting Ada Entities}). You can
24920skip this step if you plan to use the Ada DLL only from Ada applications.
24921
24922@item
24923Your Ada code must export an initialization routine which calls the routine
24924@code{adainit} generated by @code{gnatbind} to perform the elaboration of
24925the Ada code in the DLL (@ref{202,,Ada DLLs and Elaboration}). The initialization
24926routine exported by the Ada DLL must be invoked by the clients of the DLL
24927to initialize the DLL.
24928
24929@item
24930When useful, the DLL should also export a finalization routine which calls
24931routine @code{adafinal} generated by @code{gnatbind} to perform the
24932finalization of the Ada code in the DLL (@ref{203,,Ada DLLs and Finalization}).
24933The finalization routine exported by the Ada DLL must be invoked by the
24934clients of the DLL when the DLL services are no further needed.
24935
24936@item
24937You must provide a spec for the services exported by the Ada DLL in each
24938of the programming languages to which you plan to make the DLL available.
24939
24940@item
24941You must provide a definition file listing the exported entities
24942(@ref{1f2,,The Definition File}).
24943
24944@item
24945Finally you must use @code{gnatdll} to produce the DLL and the import
24946library (@ref{1fa,,Using gnatdll}).
24947@end itemize
24948
24949Note that a relocatable DLL stripped using the @code{strip}
24950binutils tool will not be relocatable anymore. To build a DLL without
24951debug information pass @code{-largs -s} to @code{gnatdll}. This
24952restriction does not apply to a DLL built using a Library Project.
24953See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24954chapter of the @emph{GPRbuild User's Guide}.
24955
24956@c Limitations_When_Using_Ada_DLLs_from Ada:
24957
24958@menu
24959* Limitations When Using Ada DLLs from Ada::
24960* Exporting Ada Entities::
24961* Ada DLLs and Elaboration::
24962
24963@end menu
24964
24965@node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
24966@anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{204}
24967@subsubsection Limitations When Using Ada DLLs from Ada
24968
24969
24970When using Ada DLLs from Ada applications there is a limitation users
24971should be aware of. Because on Windows the GNAT run-time is not in a DLL of
24972its own, each Ada DLL includes a part of the GNAT run-time. Specifically,
24973each Ada DLL includes the services of the GNAT run-time that are necessary
24974to the Ada code inside the DLL. As a result, when an Ada program uses an
24975Ada DLL there are two independent GNAT run-times: one in the Ada DLL and
24976one in the main program.
24977
24978It is therefore not possible to exchange GNAT run-time objects between the
24979Ada DLL and the main Ada program. Example of GNAT run-time objects are file
24980handles (e.g., @code{Text_IO.File_Type}), tasks types, protected objects
24981types, etc.
24982
24983It is completely safe to exchange plain elementary, array or record types,
24984Windows object handles, etc.
24985
24986@node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
24987@anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{201}@anchor{gnat_ugn/platform_specific_information id26}@anchor{205}
24988@subsubsection Exporting Ada Entities
24989
24990
24991@geindex Export table
24992
24993Building a DLL is a way to encapsulate a set of services usable from any
24994application. As a result, the Ada entities exported by a DLL should be
24995exported with the @code{C} or @code{Stdcall} calling conventions to avoid
24996any Ada name mangling. As an example here is an Ada package
24997@code{API}, spec and body, exporting two procedures, a function, and a
24998variable:
24999
25000@quotation
25001
25002@example
25003with Interfaces.C; use Interfaces;
25004package API is
25005   Count : C.int := 0;
25006   function Factorial (Val : C.int) return C.int;
25007
25008   procedure Initialize_API;
25009   procedure Finalize_API;
25010   --  Initialization & Finalization routines. More in the next section.
25011private
25012   pragma Export (C, Initialize_API);
25013   pragma Export (C, Finalize_API);
25014   pragma Export (C, Count);
25015   pragma Export (C, Factorial);
25016end API;
25017@end example
25018
25019@example
25020package body API is
25021   function Factorial (Val : C.int) return C.int is
25022      Fact : C.int := 1;
25023   begin
25024      Count := Count + 1;
25025      for K in 1 .. Val loop
25026         Fact := Fact * K;
25027      end loop;
25028      return Fact;
25029   end Factorial;
25030
25031   procedure Initialize_API is
25032      procedure Adainit;
25033      pragma Import (C, Adainit);
25034   begin
25035      Adainit;
25036   end Initialize_API;
25037
25038   procedure Finalize_API is
25039      procedure Adafinal;
25040      pragma Import (C, Adafinal);
25041   begin
25042      Adafinal;
25043   end Finalize_API;
25044end API;
25045@end example
25046@end quotation
25047
25048If the Ada DLL you are building will only be used by Ada applications
25049you do not have to export Ada entities with a @code{C} or @code{Stdcall}
25050convention. As an example, the previous package could be written as
25051follows:
25052
25053@quotation
25054
25055@example
25056package API is
25057   Count : Integer := 0;
25058   function Factorial (Val : Integer) return Integer;
25059
25060   procedure Initialize_API;
25061   procedure Finalize_API;
25062   --  Initialization and Finalization routines.
25063end API;
25064@end example
25065
25066@example
25067package body API is
25068   function Factorial (Val : Integer) return Integer is
25069      Fact : Integer := 1;
25070   begin
25071      Count := Count + 1;
25072      for K in 1 .. Val loop
25073         Fact := Fact * K;
25074      end loop;
25075      return Fact;
25076   end Factorial;
25077
25078   ...
25079   --  The remainder of this package body is unchanged.
25080end API;
25081@end example
25082@end quotation
25083
25084Note that if you do not export the Ada entities with a @code{C} or
25085@code{Stdcall} convention you will have to provide the mangled Ada names
25086in the definition file of the Ada DLL
25087(@ref{206,,Creating the Definition File}).
25088
25089@node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
25090@anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{202}@anchor{gnat_ugn/platform_specific_information id27}@anchor{207}
25091@subsubsection Ada DLLs and Elaboration
25092
25093
25094@geindex DLLs and elaboration
25095
25096The DLL that you are building contains your Ada code as well as all the
25097routines in the Ada library that are needed by it. The first thing a
25098user of your DLL must do is elaborate the Ada code
25099(@ref{f,,Elaboration Order Handling in GNAT}).
25100
25101To achieve this you must export an initialization routine
25102(@code{Initialize_API} in the previous example), which must be invoked
25103before using any of the DLL services. This elaboration routine must call
25104the Ada elaboration routine @code{adainit} generated by the GNAT binder
25105(@ref{b4,,Binding with Non-Ada Main Programs}). See the body of
25106@code{Initialize_Api} for an example. Note that the GNAT binder is
25107automatically invoked during the DLL build process by the @code{gnatdll}
25108tool (@ref{1fa,,Using gnatdll}).
25109
25110When a DLL is loaded, Windows systematically invokes a routine called
25111@code{DllMain}. It would therefore be possible to call @code{adainit}
25112directly from @code{DllMain} without having to provide an explicit
25113initialization routine. Unfortunately, it is not possible to call
25114@code{adainit} from the @code{DllMain} if your program has library level
25115tasks because access to the @code{DllMain} entry point is serialized by
25116the system (that is, only a single thread can execute 'through' it at a
25117time), which means that the GNAT run-time will deadlock waiting for the
25118newly created task to complete its initialization.
25119
25120@node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
25121@anchor{gnat_ugn/platform_specific_information id28}@anchor{208}@anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{203}
25122@subsubsection Ada DLLs and Finalization
25123
25124
25125@geindex DLLs and finalization
25126
25127When the services of an Ada DLL are no longer needed, the client code should
25128invoke the DLL finalization routine, if available. The DLL finalization
25129routine is in charge of releasing all resources acquired by the DLL. In the
25130case of the Ada code contained in the DLL, this is achieved by calling
25131routine @code{adafinal} generated by the GNAT binder
25132(@ref{b4,,Binding with Non-Ada Main Programs}).
25133See the body of @code{Finalize_Api} for an
25134example. As already pointed out the GNAT binder is automatically invoked
25135during the DLL build process by the @code{gnatdll} tool
25136(@ref{1fa,,Using gnatdll}).
25137
25138@node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
25139@anchor{gnat_ugn/platform_specific_information id29}@anchor{209}@anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{20a}
25140@subsubsection Creating a Spec for Ada DLLs
25141
25142
25143To use the services exported by the Ada DLL from another programming
25144language (e.g., C), you have to translate the specs of the exported Ada
25145entities in that language. For instance in the case of @code{API.dll},
25146the corresponding C header file could look like:
25147
25148@quotation
25149
25150@example
25151extern int *_imp__count;
25152#define count (*_imp__count)
25153int factorial (int);
25154@end example
25155@end quotation
25156
25157It is important to understand that when building an Ada DLL to be used by
25158other Ada applications, you need two different specs for the packages
25159contained in the DLL: one for building the DLL and the other for using
25160the DLL. This is because the @code{DLL} calling convention is needed to
25161use a variable defined in a DLL, but when building the DLL, the variable
25162must have either the @code{Ada} or @code{C} calling convention. As an
25163example consider a DLL comprising the following package @code{API}:
25164
25165@quotation
25166
25167@example
25168package API is
25169   Count : Integer := 0;
25170   ...
25171   --  Remainder of the package omitted.
25172end API;
25173@end example
25174@end quotation
25175
25176After producing a DLL containing package @code{API}, the spec that
25177must be used to import @code{API.Count} from Ada code outside of the
25178DLL is:
25179
25180@quotation
25181
25182@example
25183package API is
25184   Count : Integer;
25185   pragma Import (DLL, Count);
25186end API;
25187@end example
25188@end quotation
25189
25190@menu
25191* Creating the Definition File::
25192* Using gnatdll::
25193
25194@end menu
25195
25196@node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
25197@anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{206}@anchor{gnat_ugn/platform_specific_information id30}@anchor{20b}
25198@subsubsection Creating the Definition File
25199
25200
25201The definition file is the last file needed to build the DLL. It lists
25202the exported symbols. As an example, the definition file for a DLL
25203containing only package @code{API} (where all the entities are exported
25204with a @code{C} calling convention) is:
25205
25206@quotation
25207
25208@example
25209EXPORTS
25210    count
25211    factorial
25212    finalize_api
25213    initialize_api
25214@end example
25215@end quotation
25216
25217If the @code{C} calling convention is missing from package @code{API},
25218then the definition file contains the mangled Ada names of the above
25219entities, which in this case are:
25220
25221@quotation
25222
25223@example
25224EXPORTS
25225    api__count
25226    api__factorial
25227    api__finalize_api
25228    api__initialize_api
25229@end example
25230@end quotation
25231
25232@node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
25233@anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{1fa}@anchor{gnat_ugn/platform_specific_information id31}@anchor{20c}
25234@subsubsection Using @code{gnatdll}
25235
25236
25237@geindex gnatdll
25238
25239@code{gnatdll} is a tool to automate the DLL build process once all the Ada
25240and non-Ada sources that make up your DLL have been compiled.
25241@code{gnatdll} is actually in charge of two distinct tasks: build the
25242static import library for the DLL and the actual DLL. The form of the
25243@code{gnatdll} command is
25244
25245@quotation
25246
25247@example
25248$ gnatdll [ switches ] list-of-files [ -largs opts ]
25249@end example
25250@end quotation
25251
25252where @code{list-of-files} is a list of ALI and object files. The object
25253file list must be the exact list of objects corresponding to the non-Ada
25254sources whose services are to be included in the DLL. The ALI file list
25255must be the exact list of ALI files for the corresponding Ada sources
25256whose services are to be included in the DLL. If @code{list-of-files} is
25257missing, only the static import library is generated.
25258
25259You may specify any of the following switches to @code{gnatdll}:
25260
25261@quotation
25262
25263@geindex -a (gnatdll)
25264@end quotation
25265
25266
25267@table @asis
25268
25269@item @code{-a[@emph{address}]}
25270
25271Build a non-relocatable DLL at @code{address}. If @code{address} is not
25272specified the default address @code{0x11000000} will be used. By default,
25273when this switch is missing, @code{gnatdll} builds relocatable DLL. We
25274advise the reader to build relocatable DLL.
25275
25276@geindex -b (gnatdll)
25277
25278@item @code{-b @emph{address}}
25279
25280Set the relocatable DLL base address. By default the address is
25281@code{0x11000000}.
25282
25283@geindex -bargs (gnatdll)
25284
25285@item @code{-bargs @emph{opts}}
25286
25287Binder options. Pass @code{opts} to the binder.
25288
25289@geindex -d (gnatdll)
25290
25291@item @code{-d @emph{dllfile}}
25292
25293@code{dllfile} is the name of the DLL. This switch must be present for
25294@code{gnatdll} to do anything. The name of the generated import library is
25295obtained algorithmically from @code{dllfile} as shown in the following
25296example: if @code{dllfile} is @code{xyz.dll}, the import library name is
25297@code{libxyz.dll.a}. The name of the definition file to use (if not specified
25298by option @code{-e}) is obtained algorithmically from @code{dllfile}
25299as shown in the following example:
25300if @code{dllfile} is @code{xyz.dll}, the definition
25301file used is @code{xyz.def}.
25302
25303@geindex -e (gnatdll)
25304
25305@item @code{-e @emph{deffile}}
25306
25307@code{deffile} is the name of the definition file.
25308
25309@geindex -g (gnatdll)
25310
25311@item @code{-g}
25312
25313Generate debugging information. This information is stored in the object
25314file and copied from there to the final DLL file by the linker,
25315where it can be read by the debugger. You must use the
25316@code{-g} switch if you plan on using the debugger or the symbolic
25317stack traceback.
25318
25319@geindex -h (gnatdll)
25320
25321@item @code{-h}
25322
25323Help mode. Displays @code{gnatdll} switch usage information.
25324
25325@geindex -I (gnatdll)
25326
25327@item @code{-I@emph{dir}}
25328
25329Direct @code{gnatdll} to search the @code{dir} directory for source and
25330object files needed to build the DLL.
25331(@ref{89,,Search Paths and the Run-Time Library (RTL)}).
25332
25333@geindex -k (gnatdll)
25334
25335@item @code{-k}
25336
25337Removes the @code{@@@emph{nn}} suffix from the import library's exported
25338names, but keeps them for the link names. You must specify this
25339option if you want to use a @code{Stdcall} function in a DLL for which
25340the @code{@@@emph{nn}} suffix has been removed. This is the case for most
25341of the Windows NT DLL for example. This option has no effect when
25342@code{-n} option is specified.
25343
25344@geindex -l (gnatdll)
25345
25346@item @code{-l @emph{file}}
25347
25348The list of ALI and object files used to build the DLL are listed in
25349@code{file}, instead of being given in the command line. Each line in
25350@code{file} contains the name of an ALI or object file.
25351
25352@geindex -n (gnatdll)
25353
25354@item @code{-n}
25355
25356No Import. Do not create the import library.
25357
25358@geindex -q (gnatdll)
25359
25360@item @code{-q}
25361
25362Quiet mode. Do not display unnecessary messages.
25363
25364@geindex -v (gnatdll)
25365
25366@item @code{-v}
25367
25368Verbose mode. Display extra information.
25369
25370@geindex -largs (gnatdll)
25371
25372@item @code{-largs @emph{opts}}
25373
25374Linker options. Pass @code{opts} to the linker.
25375@end table
25376
25377@subsubheading @code{gnatdll} Example
25378
25379
25380As an example the command to build a relocatable DLL from @code{api.adb}
25381once @code{api.adb} has been compiled and @code{api.def} created is
25382
25383@quotation
25384
25385@example
25386$ gnatdll -d api.dll api.ali
25387@end example
25388@end quotation
25389
25390The above command creates two files: @code{libapi.dll.a} (the import
25391library) and @code{api.dll} (the actual DLL). If you want to create
25392only the DLL, just type:
25393
25394@quotation
25395
25396@example
25397$ gnatdll -d api.dll -n api.ali
25398@end example
25399@end quotation
25400
25401Alternatively if you want to create just the import library, type:
25402
25403@quotation
25404
25405@example
25406$ gnatdll -d api.dll
25407@end example
25408@end quotation
25409
25410@subsubheading @code{gnatdll} behind the Scenes
25411
25412
25413This section details the steps involved in creating a DLL. @code{gnatdll}
25414does these steps for you. Unless you are interested in understanding what
25415goes on behind the scenes, you should skip this section.
25416
25417We use the previous example of a DLL containing the Ada package @code{API},
25418to illustrate the steps necessary to build a DLL. The starting point is a
25419set of objects that will make up the DLL and the corresponding ALI
25420files. In the case of this example this means that @code{api.o} and
25421@code{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
25422the following:
25423
25424
25425@itemize *
25426
25427@item
25428@code{gnatdll} builds the base file (@code{api.base}). A base file gives
25429the information necessary to generate relocation information for the
25430DLL.
25431
25432@example
25433$ gnatbind -n api
25434$ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
25435@end example
25436
25437In addition to the base file, the @code{gnatlink} command generates an
25438output file @code{api.jnk} which can be discarded. The @code{-mdll} switch
25439asks @code{gnatlink} to generate the routines @code{DllMain} and
25440@code{DllMainCRTStartup} that are called by the Windows loader when the DLL
25441is loaded into memory.
25442
25443@item
25444@code{gnatdll} uses @code{dlltool} (see @ref{20d,,Using dlltool}) to build the
25445export table (@code{api.exp}). The export table contains the relocation
25446information in a form which can be used during the final link to ensure
25447that the Windows loader is able to place the DLL anywhere in memory.
25448
25449@example
25450$ dlltool --dllname api.dll --def api.def --base-file api.base \\
25451          --output-exp api.exp
25452@end example
25453
25454@item
25455@code{gnatdll} builds the base file using the new export table. Note that
25456@code{gnatbind} must be called once again since the binder generated file
25457has been deleted during the previous call to @code{gnatlink}.
25458
25459@example
25460$ gnatbind -n api
25461$ gnatlink api -o api.jnk api.exp -mdll
25462      -Wl,--base-file,api.base
25463@end example
25464
25465@item
25466@code{gnatdll} builds the new export table using the new base file and
25467generates the DLL import library @code{libAPI.dll.a}.
25468
25469@example
25470$ dlltool --dllname api.dll --def api.def --base-file api.base \\
25471          --output-exp api.exp --output-lib libAPI.a
25472@end example
25473
25474@item
25475Finally @code{gnatdll} builds the relocatable DLL using the final export
25476table.
25477
25478@example
25479$ gnatbind -n api
25480$ gnatlink api api.exp -o api.dll -mdll
25481@end example
25482@end itemize
25483@anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{20d}
25484@subsubheading Using @code{dlltool}
25485
25486
25487@code{dlltool} is the low-level tool used by @code{gnatdll} to build
25488DLLs and static import libraries. This section summarizes the most
25489common @code{dlltool} switches. The form of the @code{dlltool} command
25490is
25491
25492@quotation
25493
25494@example
25495$ dlltool [`switches`]
25496@end example
25497@end quotation
25498
25499@code{dlltool} switches include:
25500
25501@geindex --base-file (dlltool)
25502
25503
25504@table @asis
25505
25506@item @code{--base-file @emph{basefile}}
25507
25508Read the base file @code{basefile} generated by the linker. This switch
25509is used to create a relocatable DLL.
25510@end table
25511
25512@geindex --def (dlltool)
25513
25514
25515@table @asis
25516
25517@item @code{--def @emph{deffile}}
25518
25519Read the definition file.
25520@end table
25521
25522@geindex --dllname (dlltool)
25523
25524
25525@table @asis
25526
25527@item @code{--dllname @emph{name}}
25528
25529Gives the name of the DLL. This switch is used to embed the name of the
25530DLL in the static import library generated by @code{dlltool} with switch
25531@code{--output-lib}.
25532@end table
25533
25534@geindex -k (dlltool)
25535
25536
25537@table @asis
25538
25539@item @code{-k}
25540
25541Kill @code{@@@emph{nn}} from exported names
25542(@ref{1e6,,Windows Calling Conventions}
25543for a discussion about @code{Stdcall}-style symbols.
25544@end table
25545
25546@geindex --help (dlltool)
25547
25548
25549@table @asis
25550
25551@item @code{--help}
25552
25553Prints the @code{dlltool} switches with a concise description.
25554@end table
25555
25556@geindex --output-exp (dlltool)
25557
25558
25559@table @asis
25560
25561@item @code{--output-exp @emph{exportfile}}
25562
25563Generate an export file @code{exportfile}. The export file contains the
25564export table (list of symbols in the DLL) and is used to create the DLL.
25565@end table
25566
25567@geindex --output-lib (dlltool)
25568
25569
25570@table @asis
25571
25572@item @code{--output-lib @emph{libfile}}
25573
25574Generate a static import library @code{libfile}.
25575@end table
25576
25577@geindex -v (dlltool)
25578
25579
25580@table @asis
25581
25582@item @code{-v}
25583
25584Verbose mode.
25585@end table
25586
25587@geindex --as (dlltool)
25588
25589
25590@table @asis
25591
25592@item @code{--as @emph{assembler-name}}
25593
25594Use @code{assembler-name} as the assembler. The default is @code{as}.
25595@end table
25596
25597@node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
25598@anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{20e}@anchor{gnat_ugn/platform_specific_information id32}@anchor{20f}
25599@subsubsection GNAT and Windows Resources
25600
25601
25602@geindex Resources
25603@geindex windows
25604
25605Resources are an easy way to add Windows specific objects to your
25606application. The objects that can be added as resources include:
25607
25608
25609@itemize *
25610
25611@item
25612menus
25613
25614@item
25615accelerators
25616
25617@item
25618dialog boxes
25619
25620@item
25621string tables
25622
25623@item
25624bitmaps
25625
25626@item
25627cursors
25628
25629@item
25630icons
25631
25632@item
25633fonts
25634
25635@item
25636version information
25637@end itemize
25638
25639For example, a version information resource can be defined as follow and
25640embedded into an executable or DLL:
25641
25642A version information resource can be used to embed information into an
25643executable or a DLL. These information can be viewed using the file properties
25644from the Windows Explorer. Here is an example of a version information
25645resource:
25646
25647@quotation
25648
25649@example
256501 VERSIONINFO
25651FILEVERSION     1,0,0,0
25652PRODUCTVERSION  1,0,0,0
25653BEGIN
25654  BLOCK "StringFileInfo"
25655  BEGIN
25656    BLOCK "080904E4"
25657    BEGIN
25658      VALUE "CompanyName", "My Company Name"
25659      VALUE "FileDescription", "My application"
25660      VALUE "FileVersion", "1.0"
25661      VALUE "InternalName", "my_app"
25662      VALUE "LegalCopyright", "My Name"
25663      VALUE "OriginalFilename", "my_app.exe"
25664      VALUE "ProductName", "My App"
25665      VALUE "ProductVersion", "1.0"
25666    END
25667  END
25668
25669  BLOCK "VarFileInfo"
25670  BEGIN
25671    VALUE "Translation", 0x809, 1252
25672  END
25673END
25674@end example
25675@end quotation
25676
25677The value @code{0809} (langID) is for the U.K English language and
25678@code{04E4} (charsetID), which is equal to @code{1252} decimal, for
25679multilingual.
25680
25681This section explains how to build, compile and use resources. Note that this
25682section does not cover all resource objects, for a complete description see
25683the corresponding Microsoft documentation.
25684
25685@menu
25686* Building Resources::
25687* Compiling Resources::
25688* Using Resources::
25689
25690@end menu
25691
25692@node Building Resources,Compiling Resources,,GNAT and Windows Resources
25693@anchor{gnat_ugn/platform_specific_information building-resources}@anchor{210}@anchor{gnat_ugn/platform_specific_information id33}@anchor{211}
25694@subsubsection Building Resources
25695
25696
25697@geindex Resources
25698@geindex building
25699
25700A resource file is an ASCII file. By convention resource files have an
25701@code{.rc} extension.
25702The easiest way to build a resource file is to use Microsoft tools
25703such as @code{imagedit.exe} to build bitmaps, icons and cursors and
25704@code{dlgedit.exe} to build dialogs.
25705It is always possible to build an @code{.rc} file yourself by writing a
25706resource script.
25707
25708It is not our objective to explain how to write a resource file. A
25709complete description of the resource script language can be found in the
25710Microsoft documentation.
25711
25712@node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
25713@anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{212}@anchor{gnat_ugn/platform_specific_information id34}@anchor{213}
25714@subsubsection Compiling Resources
25715
25716
25717@geindex rc
25718
25719@geindex windres
25720
25721@geindex Resources
25722@geindex compiling
25723
25724This section describes how to build a GNAT-compatible (COFF) object file
25725containing the resources. This is done using the Resource Compiler
25726@code{windres} as follows:
25727
25728@quotation
25729
25730@example
25731$ windres -i myres.rc -o myres.o
25732@end example
25733@end quotation
25734
25735By default @code{windres} will run @code{gcc} to preprocess the @code{.rc}
25736file. You can specify an alternate preprocessor (usually named
25737@code{cpp.exe}) using the @code{windres} @code{--preprocessor}
25738parameter. A list of all possible options may be obtained by entering
25739the command @code{windres} @code{--help}.
25740
25741It is also possible to use the Microsoft resource compiler @code{rc.exe}
25742to produce a @code{.res} file (binary resource file). See the
25743corresponding Microsoft documentation for further details. In this case
25744you need to use @code{windres} to translate the @code{.res} file to a
25745GNAT-compatible object file as follows:
25746
25747@quotation
25748
25749@example
25750$ windres -i myres.res -o myres.o
25751@end example
25752@end quotation
25753
25754@node Using Resources,,Compiling Resources,GNAT and Windows Resources
25755@anchor{gnat_ugn/platform_specific_information using-resources}@anchor{214}@anchor{gnat_ugn/platform_specific_information id35}@anchor{215}
25756@subsubsection Using Resources
25757
25758
25759@geindex Resources
25760@geindex using
25761
25762To include the resource file in your program just add the
25763GNAT-compatible object file for the resource(s) to the linker
25764arguments. With @code{gnatmake} this is done by using the @code{-largs}
25765option:
25766
25767@quotation
25768
25769@example
25770$ gnatmake myprog -largs myres.o
25771@end example
25772@end quotation
25773
25774@node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
25775@anchor{gnat_ugn/platform_specific_information using-gnat-dll-from-msvs}@anchor{216}@anchor{gnat_ugn/platform_specific_information using-gnat-dlls-from-microsoft-visual-studio-applications}@anchor{217}
25776@subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
25777
25778
25779@geindex Microsoft Visual Studio
25780@geindex use with GNAT DLLs
25781
25782This section describes a common case of mixed GNAT/Microsoft Visual Studio
25783application development, where the main program is developed using MSVS, and
25784is linked with a DLL developed using GNAT. Such a mixed application should
25785be developed following the general guidelines outlined above; below is the
25786cookbook-style sequence of steps to follow:
25787
25788
25789@enumerate
25790
25791@item
25792First develop and build the GNAT shared library using a library project
25793(let's assume the project is @code{mylib.gpr}, producing the library @code{libmylib.dll}):
25794@end enumerate
25795
25796@quotation
25797
25798@example
25799$ gprbuild -p mylib.gpr
25800@end example
25801@end quotation
25802
25803
25804@enumerate 2
25805
25806@item
25807Produce a .def file for the symbols you need to interface with, either by
25808hand or automatically with possibly some manual adjustments
25809(see @ref{1f8,,Creating Definition File Automatically}):
25810@end enumerate
25811
25812@quotation
25813
25814@example
25815$ dlltool libmylib.dll -z libmylib.def --export-all-symbols
25816@end example
25817@end quotation
25818
25819
25820@enumerate 3
25821
25822@item
25823Make sure that MSVS command-line tools are accessible on the path.
25824
25825@item
25826Create the Microsoft-style import library (see @ref{1fb,,MSVS-Style Import Library}):
25827@end enumerate
25828
25829@quotation
25830
25831@example
25832$ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
25833@end example
25834@end quotation
25835
25836If you are using a 64-bit toolchain, the above becomes...
25837
25838@quotation
25839
25840@example
25841$ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
25842@end example
25843@end quotation
25844
25845
25846@enumerate 5
25847
25848@item
25849Build the C main
25850@end enumerate
25851
25852@quotation
25853
25854@example
25855$ cl /O2 /MD main.c libmylib.lib
25856@end example
25857@end quotation
25858
25859
25860@enumerate 6
25861
25862@item
25863Before running the executable, make sure you have set the PATH to the DLL,
25864or copy the DLL into into the directory containing the .exe.
25865@end enumerate
25866
25867@node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
25868@anchor{gnat_ugn/platform_specific_information id36}@anchor{218}@anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{219}
25869@subsubsection Debugging a DLL
25870
25871
25872@geindex DLL debugging
25873
25874Debugging a DLL is similar to debugging a standard program. But
25875we have to deal with two different executable parts: the DLL and the
25876program that uses it. We have the following four possibilities:
25877
25878
25879@itemize *
25880
25881@item
25882The program and the DLL are built with GCC/GNAT.
25883
25884@item
25885The program is built with foreign tools and the DLL is built with
25886GCC/GNAT.
25887
25888@item
25889The program is built with GCC/GNAT and the DLL is built with
25890foreign tools.
25891@end itemize
25892
25893In this section we address only cases one and two above.
25894There is no point in trying to debug
25895a DLL with GNU/GDB, if there is no GDB-compatible debugging
25896information in it. To do so you must use a debugger compatible with the
25897tools suite used to build the DLL.
25898
25899@menu
25900* Program and DLL Both Built with GCC/GNAT::
25901* Program Built with Foreign Tools and DLL Built with GCC/GNAT::
25902
25903@end menu
25904
25905@node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
25906@anchor{gnat_ugn/platform_specific_information id37}@anchor{21a}@anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{21b}
25907@subsubsection Program and DLL Both Built with GCC/GNAT
25908
25909
25910This is the simplest case. Both the DLL and the program have @code{GDB}
25911compatible debugging information. It is then possible to break anywhere in
25912the process. Let's suppose here that the main procedure is named
25913@code{ada_main} and that in the DLL there is an entry point named
25914@code{ada_dll}.
25915
25916The DLL (@ref{1f1,,Introduction to Dynamic Link Libraries (DLLs)}) and
25917program must have been built with the debugging information (see GNAT -g
25918switch). Here are the step-by-step instructions for debugging it:
25919
25920
25921@itemize *
25922
25923@item
25924Launch @code{GDB} on the main program.
25925
25926@example
25927$ gdb -nw ada_main
25928@end example
25929
25930@item
25931Start the program and stop at the beginning of the main procedure
25932
25933@example
25934(gdb) start
25935@end example
25936
25937This step is required to be able to set a breakpoint inside the DLL. As long
25938as the program is not run, the DLL is not loaded. This has the
25939consequence that the DLL debugging information is also not loaded, so it is not
25940possible to set a breakpoint in the DLL.
25941
25942@item
25943Set a breakpoint inside the DLL
25944
25945@example
25946(gdb) break ada_dll
25947(gdb) cont
25948@end example
25949@end itemize
25950
25951At this stage a breakpoint is set inside the DLL. From there on
25952you can use the standard approach to debug the whole program
25953(@ref{24,,Running and Debugging Ada Programs}).
25954
25955@node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
25956@anchor{gnat_ugn/platform_specific_information program-built-with-foreign-tools-and-dll-built-with-gcc-gnat}@anchor{21c}@anchor{gnat_ugn/platform_specific_information id38}@anchor{21d}
25957@subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
25958
25959
25960In this case things are slightly more complex because it is not possible to
25961start the main program and then break at the beginning to load the DLL and the
25962associated DLL debugging information. It is not possible to break at the
25963beginning of the program because there is no @code{GDB} debugging information,
25964and therefore there is no direct way of getting initial control. This
25965section addresses this issue by describing some methods that can be used
25966to break somewhere in the DLL to debug it.
25967
25968First suppose that the main procedure is named @code{main} (this is for
25969example some C code built with Microsoft Visual C) and that there is a
25970DLL named @code{test.dll} containing an Ada entry point named
25971@code{ada_dll}.
25972
25973The DLL (see @ref{1f1,,Introduction to Dynamic Link Libraries (DLLs)}) must have
25974been built with debugging information (see the GNAT @code{-g} option).
25975
25976@subsubheading Debugging the DLL Directly
25977
25978
25979
25980@itemize *
25981
25982@item
25983Find out the executable starting address
25984
25985@example
25986$ objdump --file-header main.exe
25987@end example
25988
25989The starting address is reported on the last line. For example:
25990
25991@example
25992main.exe:     file format pei-i386
25993architecture: i386, flags 0x0000010a:
25994EXEC_P, HAS_DEBUG, D_PAGED
25995start address 0x00401010
25996@end example
25997
25998@item
25999Launch the debugger on the executable.
26000
26001@example
26002$ gdb main.exe
26003@end example
26004
26005@item
26006Set a breakpoint at the starting address, and launch the program.
26007
26008@example
26009$ (gdb) break *0x00401010
26010$ (gdb) run
26011@end example
26012
26013The program will stop at the given address.
26014
26015@item
26016Set a breakpoint on a DLL subroutine.
26017
26018@example
26019(gdb) break ada_dll.adb:45
26020@end example
26021
26022Or if you want to break using a symbol on the DLL, you need first to
26023select the Ada language (language used by the DLL).
26024
26025@example
26026(gdb) set language ada
26027(gdb) break ada_dll
26028@end example
26029
26030@item
26031Continue the program.
26032
26033@example
26034(gdb) cont
26035@end example
26036
26037This will run the program until it reaches the breakpoint that has been
26038set. From that point you can use the standard way to debug a program
26039as described in (@ref{24,,Running and Debugging Ada Programs}).
26040@end itemize
26041
26042It is also possible to debug the DLL by attaching to a running process.
26043
26044@subsubheading Attaching to a Running Process
26045
26046
26047@geindex DLL debugging
26048@geindex attach to process
26049
26050With @code{GDB} it is always possible to debug a running process by
26051attaching to it. It is possible to debug a DLL this way. The limitation
26052of this approach is that the DLL must run long enough to perform the
26053attach operation. It may be useful for instance to insert a time wasting
26054loop in the code of the DLL to meet this criterion.
26055
26056
26057@itemize *
26058
26059@item
26060Launch the main program @code{main.exe}.
26061
26062@example
26063$ main
26064@end example
26065
26066@item
26067Use the Windows @emph{Task Manager} to find the process ID. Let's say
26068that the process PID for @code{main.exe} is 208.
26069
26070@item
26071Launch gdb.
26072
26073@example
26074$ gdb
26075@end example
26076
26077@item
26078Attach to the running process to be debugged.
26079
26080@example
26081(gdb) attach 208
26082@end example
26083
26084@item
26085Load the process debugging information.
26086
26087@example
26088(gdb) symbol-file main.exe
26089@end example
26090
26091@item
26092Break somewhere in the DLL.
26093
26094@example
26095(gdb) break ada_dll
26096@end example
26097
26098@item
26099Continue process execution.
26100
26101@example
26102(gdb) cont
26103@end example
26104@end itemize
26105
26106This last step will resume the process execution, and stop at
26107the breakpoint we have set. From there you can use the standard
26108approach to debug a program as described in
26109@ref{24,,Running and Debugging Ada Programs}.
26110
26111@node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
26112@anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{136}@anchor{gnat_ugn/platform_specific_information id39}@anchor{21e}
26113@subsubsection Setting Stack Size from @code{gnatlink}
26114
26115
26116It is possible to specify the program stack size at link time. On modern
26117versions of Windows, starting with XP, this is mostly useful to set the size of
26118the main stack (environment task). The other task stacks are set with pragma
26119Storage_Size or with the @emph{gnatbind -d} command.
26120
26121Since older versions of Windows (2000, NT4, etc.) do not allow setting the
26122reserve size of individual tasks, the link-time stack size applies to all
26123tasks, and pragma Storage_Size has no effect.
26124In particular, Stack Overflow checks are made against this
26125link-time specified size.
26126
26127This setting can be done with @code{gnatlink} using either of the following:
26128
26129
26130@itemize *
26131
26132@item
26133@code{-Xlinker} linker option
26134
26135@example
26136$ gnatlink hello -Xlinker --stack=0x10000,0x1000
26137@end example
26138
26139This sets the stack reserve size to 0x10000 bytes and the stack commit
26140size to 0x1000 bytes.
26141
26142@item
26143@code{-Wl} linker option
26144
26145@example
26146$ gnatlink hello -Wl,--stack=0x1000000
26147@end example
26148
26149This sets the stack reserve size to 0x1000000 bytes. Note that with
26150@code{-Wl} option it is not possible to set the stack commit size
26151because the comma is a separator for this option.
26152@end itemize
26153
26154@node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
26155@anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{137}@anchor{gnat_ugn/platform_specific_information id40}@anchor{21f}
26156@subsubsection Setting Heap Size from @code{gnatlink}
26157
26158
26159Under Windows systems, it is possible to specify the program heap size from
26160@code{gnatlink} using either of the following:
26161
26162
26163@itemize *
26164
26165@item
26166@code{-Xlinker} linker option
26167
26168@example
26169$ gnatlink hello -Xlinker --heap=0x10000,0x1000
26170@end example
26171
26172This sets the heap reserve size to 0x10000 bytes and the heap commit
26173size to 0x1000 bytes.
26174
26175@item
26176@code{-Wl} linker option
26177
26178@example
26179$ gnatlink hello -Wl,--heap=0x1000000
26180@end example
26181
26182This sets the heap reserve size to 0x1000000 bytes. Note that with
26183@code{-Wl} option it is not possible to set the heap commit size
26184because the comma is a separator for this option.
26185@end itemize
26186
26187@node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
26188@anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{220}@anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{221}
26189@subsection Windows Specific Add-Ons
26190
26191
26192This section describes the Windows specific add-ons.
26193
26194@menu
26195* Win32Ada::
26196* wPOSIX::
26197
26198@end menu
26199
26200@node Win32Ada,wPOSIX,,Windows Specific Add-Ons
26201@anchor{gnat_ugn/platform_specific_information win32ada}@anchor{222}@anchor{gnat_ugn/platform_specific_information id41}@anchor{223}
26202@subsubsection Win32Ada
26203
26204
26205Win32Ada is a binding for the Microsoft Win32 API. This binding can be
26206easily installed from the provided installer. To use the Win32Ada
26207binding you need to use a project file, and adding a single with_clause
26208will give you full access to the Win32Ada binding sources and ensure
26209that the proper libraries are passed to the linker.
26210
26211@quotation
26212
26213@example
26214with "win32ada";
26215project P is
26216   for Sources use ...;
26217end P;
26218@end example
26219@end quotation
26220
26221To build the application you just need to call gprbuild for the
26222application's project, here p.gpr:
26223
26224@quotation
26225
26226@example
26227gprbuild p.gpr
26228@end example
26229@end quotation
26230
26231@node wPOSIX,,Win32Ada,Windows Specific Add-Ons
26232@anchor{gnat_ugn/platform_specific_information id42}@anchor{224}@anchor{gnat_ugn/platform_specific_information wposix}@anchor{225}
26233@subsubsection wPOSIX
26234
26235
26236wPOSIX is a minimal POSIX binding whose goal is to help with building
26237cross-platforms applications. This binding is not complete though, as
26238the Win32 API does not provide the necessary support for all POSIX APIs.
26239
26240To use the wPOSIX binding you need to use a project file, and adding
26241a single with_clause will give you full access to the wPOSIX binding
26242sources and ensure that the proper libraries are passed to the linker.
26243
26244@quotation
26245
26246@example
26247with "wposix";
26248project P is
26249   for Sources use ...;
26250end P;
26251@end example
26252@end quotation
26253
26254To build the application you just need to call gprbuild for the
26255application's project, here p.gpr:
26256
26257@quotation
26258
26259@example
26260gprbuild p.gpr
26261@end example
26262@end quotation
26263
26264@node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
26265@anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{2d}@anchor{gnat_ugn/platform_specific_information id43}@anchor{226}
26266@section Mac OS Topics
26267
26268
26269@geindex OS X
26270
26271This section describes topics that are specific to Apple's OS X
26272platform.
26273
26274@menu
26275* Codesigning the Debugger::
26276
26277@end menu
26278
26279@node Codesigning the Debugger,,,Mac OS Topics
26280@anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{227}
26281@subsection Codesigning the Debugger
26282
26283
26284The Darwin Kernel requires the debugger to have special permissions
26285before it is allowed to control other processes. These permissions
26286are granted by codesigning the GDB executable. Without these
26287permissions, the debugger will report error messages such as:
26288
26289@example
26290Starting program: /x/y/foo
26291Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
26292(please check gdb is codesigned - see taskgated(8))
26293@end example
26294
26295Codesigning requires a certificate.  The following procedure explains
26296how to create one:
26297
26298
26299@itemize *
26300
26301@item
26302Start the Keychain Access application (in
26303/Applications/Utilities/Keychain Access.app)
26304
26305@item
26306Select the Keychain Access -> Certificate Assistant ->
26307Create a Certificate... menu
26308
26309@item
26310Then:
26311
26312
26313@itemize *
26314
26315@item
26316Choose a name for the new certificate (this procedure will use
26317"gdb-cert" as an example)
26318
26319@item
26320Set "Identity Type" to "Self Signed Root"
26321
26322@item
26323Set "Certificate Type" to "Code Signing"
26324
26325@item
26326Activate the "Let me override defaults" option
26327@end itemize
26328
26329@item
26330Click several times on "Continue" until the "Specify a Location
26331For The Certificate" screen appears, then set "Keychain" to "System"
26332
26333@item
26334Click on "Continue" until the certificate is created
26335
26336@item
26337Finally, in the view, double-click on the new certificate,
26338and set "When using this certificate" to "Always Trust"
26339
26340@item
26341Exit the Keychain Access application and restart the computer
26342(this is unfortunately required)
26343@end itemize
26344
26345Once a certificate has been created, the debugger can be codesigned
26346as follow. In a Terminal, run the following command:
26347
26348@quotation
26349
26350@example
26351$ codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
26352@end example
26353@end quotation
26354
26355where "gdb-cert" should be replaced by the actual certificate
26356name chosen above, and <gnat_install_prefix> should be replaced by
26357the location where you installed GNAT.  Also, be sure that users are
26358in the Unix group @code{_developer}.
26359
26360@node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
26361@anchor{gnat_ugn/example_of_binder_output example-of-binder-output-file}@anchor{e}@anchor{gnat_ugn/example_of_binder_output doc}@anchor{228}@anchor{gnat_ugn/example_of_binder_output id1}@anchor{229}
26362@chapter Example of Binder Output File
26363
26364
26365@geindex Binder output (example)
26366
26367This Appendix displays the source code for the output file
26368generated by @emph{gnatbind} for a simple 'Hello World' program.
26369Comments have been added for clarification purposes.
26370
26371@example
26372--  The package is called Ada_Main unless this name is actually used
26373--  as a unit name in the partition, in which case some other unique
26374--  name is used.
26375
26376pragma Ada_95;
26377with System;
26378package ada_main is
26379   pragma Warnings (Off);
26380
26381   --  The main program saves the parameters (argument count,
26382   --  argument values, environment pointer) in global variables
26383   --  for later access by other units including
26384   --  Ada.Command_Line.
26385
26386   gnat_argc : Integer;
26387   gnat_argv : System.Address;
26388   gnat_envp : System.Address;
26389
26390   --  The actual variables are stored in a library routine. This
26391   --  is useful for some shared library situations, where there
26392   --  are problems if variables are not in the library.
26393
26394   pragma Import (C, gnat_argc);
26395   pragma Import (C, gnat_argv);
26396   pragma Import (C, gnat_envp);
26397
26398   --  The exit status is similarly an external location
26399
26400   gnat_exit_status : Integer;
26401   pragma Import (C, gnat_exit_status);
26402
26403   GNAT_Version : constant String :=
26404                    "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
26405   pragma Export (C, GNAT_Version, "__gnat_version");
26406
26407   Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
26408   pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
26409
26410   --  This is the generated adainit routine that performs
26411   --  initialization at the start of execution. In the case
26412   --  where Ada is the main program, this main program makes
26413   --  a call to adainit at program startup.
26414
26415   procedure adainit;
26416   pragma Export (C, adainit, "adainit");
26417
26418   --  This is the generated adafinal routine that performs
26419   --  finalization at the end of execution. In the case where
26420   --  Ada is the main program, this main program makes a call
26421   --  to adafinal at program termination.
26422
26423   procedure adafinal;
26424   pragma Export (C, adafinal, "adafinal");
26425
26426   --  This routine is called at the start of execution. It is
26427   --  a dummy routine that is used by the debugger to breakpoint
26428   --  at the start of execution.
26429
26430   --  This is the actual generated main program (it would be
26431   --  suppressed if the no main program switch were used). As
26432   --  required by standard system conventions, this program has
26433   --  the external name main.
26434
26435   function main
26436     (argc : Integer;
26437      argv : System.Address;
26438      envp : System.Address)
26439      return Integer;
26440   pragma Export (C, main, "main");
26441
26442   --  The following set of constants give the version
26443   --  identification values for every unit in the bound
26444   --  partition. This identification is computed from all
26445   --  dependent semantic units, and corresponds to the
26446   --  string that would be returned by use of the
26447   --  Body_Version or Version attributes.
26448
26449   --  The following Export pragmas export the version numbers
26450   --  with symbolic names ending in B (for body) or S
26451   --  (for spec) so that they can be located in a link. The
26452   --  information provided here is sufficient to track down
26453   --  the exact versions of units used in a given build.
26454
26455   type Version_32 is mod 2 ** 32;
26456   u00001 : constant Version_32 := 16#8ad6e54a#;
26457   pragma Export (C, u00001, "helloB");
26458   u00002 : constant Version_32 := 16#fbff4c67#;
26459   pragma Export (C, u00002, "system__standard_libraryB");
26460   u00003 : constant Version_32 := 16#1ec6fd90#;
26461   pragma Export (C, u00003, "system__standard_libraryS");
26462   u00004 : constant Version_32 := 16#3ffc8e18#;
26463   pragma Export (C, u00004, "adaS");
26464   u00005 : constant Version_32 := 16#28f088c2#;
26465   pragma Export (C, u00005, "ada__text_ioB");
26466   u00006 : constant Version_32 := 16#f372c8ac#;
26467   pragma Export (C, u00006, "ada__text_ioS");
26468   u00007 : constant Version_32 := 16#2c143749#;
26469   pragma Export (C, u00007, "ada__exceptionsB");
26470   u00008 : constant Version_32 := 16#f4f0cce8#;
26471   pragma Export (C, u00008, "ada__exceptionsS");
26472   u00009 : constant Version_32 := 16#a46739c0#;
26473   pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
26474   u00010 : constant Version_32 := 16#3aac8c92#;
26475   pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
26476   u00011 : constant Version_32 := 16#1d274481#;
26477   pragma Export (C, u00011, "systemS");
26478   u00012 : constant Version_32 := 16#a207fefe#;
26479   pragma Export (C, u00012, "system__soft_linksB");
26480   u00013 : constant Version_32 := 16#467d9556#;
26481   pragma Export (C, u00013, "system__soft_linksS");
26482   u00014 : constant Version_32 := 16#b01dad17#;
26483   pragma Export (C, u00014, "system__parametersB");
26484   u00015 : constant Version_32 := 16#630d49fe#;
26485   pragma Export (C, u00015, "system__parametersS");
26486   u00016 : constant Version_32 := 16#b19b6653#;
26487   pragma Export (C, u00016, "system__secondary_stackB");
26488   u00017 : constant Version_32 := 16#b6468be8#;
26489   pragma Export (C, u00017, "system__secondary_stackS");
26490   u00018 : constant Version_32 := 16#39a03df9#;
26491   pragma Export (C, u00018, "system__storage_elementsB");
26492   u00019 : constant Version_32 := 16#30e40e85#;
26493   pragma Export (C, u00019, "system__storage_elementsS");
26494   u00020 : constant Version_32 := 16#41837d1e#;
26495   pragma Export (C, u00020, "system__stack_checkingB");
26496   u00021 : constant Version_32 := 16#93982f69#;
26497   pragma Export (C, u00021, "system__stack_checkingS");
26498   u00022 : constant Version_32 := 16#393398c1#;
26499   pragma Export (C, u00022, "system__exception_tableB");
26500   u00023 : constant Version_32 := 16#b33e2294#;
26501   pragma Export (C, u00023, "system__exception_tableS");
26502   u00024 : constant Version_32 := 16#ce4af020#;
26503   pragma Export (C, u00024, "system__exceptionsB");
26504   u00025 : constant Version_32 := 16#75442977#;
26505   pragma Export (C, u00025, "system__exceptionsS");
26506   u00026 : constant Version_32 := 16#37d758f1#;
26507   pragma Export (C, u00026, "system__exceptions__machineS");
26508   u00027 : constant Version_32 := 16#b895431d#;
26509   pragma Export (C, u00027, "system__exceptions_debugB");
26510   u00028 : constant Version_32 := 16#aec55d3f#;
26511   pragma Export (C, u00028, "system__exceptions_debugS");
26512   u00029 : constant Version_32 := 16#570325c8#;
26513   pragma Export (C, u00029, "system__img_intB");
26514   u00030 : constant Version_32 := 16#1ffca443#;
26515   pragma Export (C, u00030, "system__img_intS");
26516   u00031 : constant Version_32 := 16#b98c3e16#;
26517   pragma Export (C, u00031, "system__tracebackB");
26518   u00032 : constant Version_32 := 16#831a9d5a#;
26519   pragma Export (C, u00032, "system__tracebackS");
26520   u00033 : constant Version_32 := 16#9ed49525#;
26521   pragma Export (C, u00033, "system__traceback_entriesB");
26522   u00034 : constant Version_32 := 16#1d7cb2f1#;
26523   pragma Export (C, u00034, "system__traceback_entriesS");
26524   u00035 : constant Version_32 := 16#8c33a517#;
26525   pragma Export (C, u00035, "system__wch_conB");
26526   u00036 : constant Version_32 := 16#065a6653#;
26527   pragma Export (C, u00036, "system__wch_conS");
26528   u00037 : constant Version_32 := 16#9721e840#;
26529   pragma Export (C, u00037, "system__wch_stwB");
26530   u00038 : constant Version_32 := 16#2b4b4a52#;
26531   pragma Export (C, u00038, "system__wch_stwS");
26532   u00039 : constant Version_32 := 16#92b797cb#;
26533   pragma Export (C, u00039, "system__wch_cnvB");
26534   u00040 : constant Version_32 := 16#09eddca0#;
26535   pragma Export (C, u00040, "system__wch_cnvS");
26536   u00041 : constant Version_32 := 16#6033a23f#;
26537   pragma Export (C, u00041, "interfacesS");
26538   u00042 : constant Version_32 := 16#ece6fdb6#;
26539   pragma Export (C, u00042, "system__wch_jisB");
26540   u00043 : constant Version_32 := 16#899dc581#;
26541   pragma Export (C, u00043, "system__wch_jisS");
26542   u00044 : constant Version_32 := 16#10558b11#;
26543   pragma Export (C, u00044, "ada__streamsB");
26544   u00045 : constant Version_32 := 16#2e6701ab#;
26545   pragma Export (C, u00045, "ada__streamsS");
26546   u00046 : constant Version_32 := 16#db5c917c#;
26547   pragma Export (C, u00046, "ada__io_exceptionsS");
26548   u00047 : constant Version_32 := 16#12c8cd7d#;
26549   pragma Export (C, u00047, "ada__tagsB");
26550   u00048 : constant Version_32 := 16#ce72c228#;
26551   pragma Export (C, u00048, "ada__tagsS");
26552   u00049 : constant Version_32 := 16#c3335bfd#;
26553   pragma Export (C, u00049, "system__htableB");
26554   u00050 : constant Version_32 := 16#99e5f76b#;
26555   pragma Export (C, u00050, "system__htableS");
26556   u00051 : constant Version_32 := 16#089f5cd0#;
26557   pragma Export (C, u00051, "system__string_hashB");
26558   u00052 : constant Version_32 := 16#3bbb9c15#;
26559   pragma Export (C, u00052, "system__string_hashS");
26560   u00053 : constant Version_32 := 16#807fe041#;
26561   pragma Export (C, u00053, "system__unsigned_typesS");
26562   u00054 : constant Version_32 := 16#d27be59e#;
26563   pragma Export (C, u00054, "system__val_lluB");
26564   u00055 : constant Version_32 := 16#fa8db733#;
26565   pragma Export (C, u00055, "system__val_lluS");
26566   u00056 : constant Version_32 := 16#27b600b2#;
26567   pragma Export (C, u00056, "system__val_utilB");
26568   u00057 : constant Version_32 := 16#b187f27f#;
26569   pragma Export (C, u00057, "system__val_utilS");
26570   u00058 : constant Version_32 := 16#d1060688#;
26571   pragma Export (C, u00058, "system__case_utilB");
26572   u00059 : constant Version_32 := 16#392e2d56#;
26573   pragma Export (C, u00059, "system__case_utilS");
26574   u00060 : constant Version_32 := 16#84a27f0d#;
26575   pragma Export (C, u00060, "interfaces__c_streamsB");
26576   u00061 : constant Version_32 := 16#8bb5f2c0#;
26577   pragma Export (C, u00061, "interfaces__c_streamsS");
26578   u00062 : constant Version_32 := 16#6db6928f#;
26579   pragma Export (C, u00062, "system__crtlS");
26580   u00063 : constant Version_32 := 16#4e6a342b#;
26581   pragma Export (C, u00063, "system__file_ioB");
26582   u00064 : constant Version_32 := 16#ba56a5e4#;
26583   pragma Export (C, u00064, "system__file_ioS");
26584   u00065 : constant Version_32 := 16#b7ab275c#;
26585   pragma Export (C, u00065, "ada__finalizationB");
26586   u00066 : constant Version_32 := 16#19f764ca#;
26587   pragma Export (C, u00066, "ada__finalizationS");
26588   u00067 : constant Version_32 := 16#95817ed8#;
26589   pragma Export (C, u00067, "system__finalization_rootB");
26590   u00068 : constant Version_32 := 16#52d53711#;
26591   pragma Export (C, u00068, "system__finalization_rootS");
26592   u00069 : constant Version_32 := 16#769e25e6#;
26593   pragma Export (C, u00069, "interfaces__cB");
26594   u00070 : constant Version_32 := 16#4a38bedb#;
26595   pragma Export (C, u00070, "interfaces__cS");
26596   u00071 : constant Version_32 := 16#07e6ee66#;
26597   pragma Export (C, u00071, "system__os_libB");
26598   u00072 : constant Version_32 := 16#d7b69782#;
26599   pragma Export (C, u00072, "system__os_libS");
26600   u00073 : constant Version_32 := 16#1a817b8e#;
26601   pragma Export (C, u00073, "system__stringsB");
26602   u00074 : constant Version_32 := 16#639855e7#;
26603   pragma Export (C, u00074, "system__stringsS");
26604   u00075 : constant Version_32 := 16#e0b8de29#;
26605   pragma Export (C, u00075, "system__file_control_blockS");
26606   u00076 : constant Version_32 := 16#b5b2aca1#;
26607   pragma Export (C, u00076, "system__finalization_mastersB");
26608   u00077 : constant Version_32 := 16#69316dc1#;
26609   pragma Export (C, u00077, "system__finalization_mastersS");
26610   u00078 : constant Version_32 := 16#57a37a42#;
26611   pragma Export (C, u00078, "system__address_imageB");
26612   u00079 : constant Version_32 := 16#bccbd9bb#;
26613   pragma Export (C, u00079, "system__address_imageS");
26614   u00080 : constant Version_32 := 16#7268f812#;
26615   pragma Export (C, u00080, "system__img_boolB");
26616   u00081 : constant Version_32 := 16#e8fe356a#;
26617   pragma Export (C, u00081, "system__img_boolS");
26618   u00082 : constant Version_32 := 16#d7aac20c#;
26619   pragma Export (C, u00082, "system__ioB");
26620   u00083 : constant Version_32 := 16#8365b3ce#;
26621   pragma Export (C, u00083, "system__ioS");
26622   u00084 : constant Version_32 := 16#6d4d969a#;
26623   pragma Export (C, u00084, "system__storage_poolsB");
26624   u00085 : constant Version_32 := 16#e87cc305#;
26625   pragma Export (C, u00085, "system__storage_poolsS");
26626   u00086 : constant Version_32 := 16#e34550ca#;
26627   pragma Export (C, u00086, "system__pool_globalB");
26628   u00087 : constant Version_32 := 16#c88d2d16#;
26629   pragma Export (C, u00087, "system__pool_globalS");
26630   u00088 : constant Version_32 := 16#9d39c675#;
26631   pragma Export (C, u00088, "system__memoryB");
26632   u00089 : constant Version_32 := 16#445a22b5#;
26633   pragma Export (C, u00089, "system__memoryS");
26634   u00090 : constant Version_32 := 16#6a859064#;
26635   pragma Export (C, u00090, "system__storage_pools__subpoolsB");
26636   u00091 : constant Version_32 := 16#e3b008dc#;
26637   pragma Export (C, u00091, "system__storage_pools__subpoolsS");
26638   u00092 : constant Version_32 := 16#63f11652#;
26639   pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
26640   u00093 : constant Version_32 := 16#fe2f4b3a#;
26641   pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
26642
26643   --  BEGIN ELABORATION ORDER
26644   --  ada%s
26645   --  interfaces%s
26646   --  system%s
26647   --  system.case_util%s
26648   --  system.case_util%b
26649   --  system.htable%s
26650   --  system.img_bool%s
26651   --  system.img_bool%b
26652   --  system.img_int%s
26653   --  system.img_int%b
26654   --  system.io%s
26655   --  system.io%b
26656   --  system.parameters%s
26657   --  system.parameters%b
26658   --  system.crtl%s
26659   --  interfaces.c_streams%s
26660   --  interfaces.c_streams%b
26661   --  system.standard_library%s
26662   --  system.exceptions_debug%s
26663   --  system.exceptions_debug%b
26664   --  system.storage_elements%s
26665   --  system.storage_elements%b
26666   --  system.stack_checking%s
26667   --  system.stack_checking%b
26668   --  system.string_hash%s
26669   --  system.string_hash%b
26670   --  system.htable%b
26671   --  system.strings%s
26672   --  system.strings%b
26673   --  system.os_lib%s
26674   --  system.traceback_entries%s
26675   --  system.traceback_entries%b
26676   --  ada.exceptions%s
26677   --  system.soft_links%s
26678   --  system.unsigned_types%s
26679   --  system.val_llu%s
26680   --  system.val_util%s
26681   --  system.val_util%b
26682   --  system.val_llu%b
26683   --  system.wch_con%s
26684   --  system.wch_con%b
26685   --  system.wch_cnv%s
26686   --  system.wch_jis%s
26687   --  system.wch_jis%b
26688   --  system.wch_cnv%b
26689   --  system.wch_stw%s
26690   --  system.wch_stw%b
26691   --  ada.exceptions.last_chance_handler%s
26692   --  ada.exceptions.last_chance_handler%b
26693   --  system.address_image%s
26694   --  system.exception_table%s
26695   --  system.exception_table%b
26696   --  ada.io_exceptions%s
26697   --  ada.tags%s
26698   --  ada.streams%s
26699   --  ada.streams%b
26700   --  interfaces.c%s
26701   --  system.exceptions%s
26702   --  system.exceptions%b
26703   --  system.exceptions.machine%s
26704   --  system.finalization_root%s
26705   --  system.finalization_root%b
26706   --  ada.finalization%s
26707   --  ada.finalization%b
26708   --  system.storage_pools%s
26709   --  system.storage_pools%b
26710   --  system.finalization_masters%s
26711   --  system.storage_pools.subpools%s
26712   --  system.storage_pools.subpools.finalization%s
26713   --  system.storage_pools.subpools.finalization%b
26714   --  system.memory%s
26715   --  system.memory%b
26716   --  system.standard_library%b
26717   --  system.pool_global%s
26718   --  system.pool_global%b
26719   --  system.file_control_block%s
26720   --  system.file_io%s
26721   --  system.secondary_stack%s
26722   --  system.file_io%b
26723   --  system.storage_pools.subpools%b
26724   --  system.finalization_masters%b
26725   --  interfaces.c%b
26726   --  ada.tags%b
26727   --  system.soft_links%b
26728   --  system.os_lib%b
26729   --  system.secondary_stack%b
26730   --  system.address_image%b
26731   --  system.traceback%s
26732   --  ada.exceptions%b
26733   --  system.traceback%b
26734   --  ada.text_io%s
26735   --  ada.text_io%b
26736   --  hello%b
26737   --  END ELABORATION ORDER
26738
26739end ada_main;
26740@end example
26741
26742@example
26743pragma Ada_95;
26744--  The following source file name pragmas allow the generated file
26745--  names to be unique for different main programs. They are needed
26746--  since the package name will always be Ada_Main.
26747
26748pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26749pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26750
26751pragma Suppress (Overflow_Check);
26752with Ada.Exceptions;
26753
26754--  Generated package body for Ada_Main starts here
26755
26756package body ada_main is
26757   pragma Warnings (Off);
26758
26759   --  These values are reference counter associated to units which have
26760   --  been elaborated. It is also used to avoid elaborating the
26761   --  same unit twice.
26762
26763   E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
26764   E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
26765   E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
26766   E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
26767   E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
26768   E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
26769   E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
26770   E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
26771   E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
26772   E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
26773   E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
26774   E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
26775   E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
26776   E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
26777   E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
26778   E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
26779   E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
26780   E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
26781
26782   Local_Priority_Specific_Dispatching : constant String := "";
26783   Local_Interrupt_States : constant String := "";
26784
26785   Is_Elaborated : Boolean := False;
26786
26787   procedure finalize_library is
26788   begin
26789      E06 := E06 - 1;
26790      declare
26791         procedure F1;
26792         pragma Import (Ada, F1, "ada__text_io__finalize_spec");
26793      begin
26794         F1;
26795      end;
26796      E77 := E77 - 1;
26797      E91 := E91 - 1;
26798      declare
26799         procedure F2;
26800         pragma Import (Ada, F2, "system__file_io__finalize_body");
26801      begin
26802         E64 := E64 - 1;
26803         F2;
26804      end;
26805      declare
26806         procedure F3;
26807         pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
26808      begin
26809         E75 := E75 - 1;
26810         F3;
26811      end;
26812      E87 := E87 - 1;
26813      declare
26814         procedure F4;
26815         pragma Import (Ada, F4, "system__pool_global__finalize_spec");
26816      begin
26817         F4;
26818      end;
26819      declare
26820         procedure F5;
26821         pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
26822      begin
26823         F5;
26824      end;
26825      declare
26826         procedure F6;
26827         pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
26828      begin
26829         F6;
26830      end;
26831      declare
26832         procedure Reraise_Library_Exception_If_Any;
26833         pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
26834      begin
26835         Reraise_Library_Exception_If_Any;
26836      end;
26837   end finalize_library;
26838
26839   -------------
26840   -- adainit --
26841   -------------
26842
26843   procedure adainit is
26844
26845      Main_Priority : Integer;
26846      pragma Import (C, Main_Priority, "__gl_main_priority");
26847      Time_Slice_Value : Integer;
26848      pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
26849      WC_Encoding : Character;
26850      pragma Import (C, WC_Encoding, "__gl_wc_encoding");
26851      Locking_Policy : Character;
26852      pragma Import (C, Locking_Policy, "__gl_locking_policy");
26853      Queuing_Policy : Character;
26854      pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
26855      Task_Dispatching_Policy : Character;
26856      pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
26857      Priority_Specific_Dispatching : System.Address;
26858      pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
26859      Num_Specific_Dispatching : Integer;
26860      pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
26861      Main_CPU : Integer;
26862      pragma Import (C, Main_CPU, "__gl_main_cpu");
26863      Interrupt_States : System.Address;
26864      pragma Import (C, Interrupt_States, "__gl_interrupt_states");
26865      Num_Interrupt_States : Integer;
26866      pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
26867      Unreserve_All_Interrupts : Integer;
26868      pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
26869      Detect_Blocking : Integer;
26870      pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
26871      Default_Stack_Size : Integer;
26872      pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
26873      Leap_Seconds_Support : Integer;
26874      pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
26875
26876      procedure Runtime_Initialize;
26877      pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
26878
26879      Finalize_Library_Objects : No_Param_Proc;
26880      pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
26881
26882   --  Start of processing for adainit
26883
26884   begin
26885
26886      --  Record various information for this partition.  The values
26887      --  are derived by the binder from information stored in the ali
26888      --  files by the compiler.
26889
26890      if Is_Elaborated then
26891         return;
26892      end if;
26893      Is_Elaborated := True;
26894      Main_Priority := -1;
26895      Time_Slice_Value := -1;
26896      WC_Encoding := 'b';
26897      Locking_Policy := ' ';
26898      Queuing_Policy := ' ';
26899      Task_Dispatching_Policy := ' ';
26900      Priority_Specific_Dispatching :=
26901        Local_Priority_Specific_Dispatching'Address;
26902      Num_Specific_Dispatching := 0;
26903      Main_CPU := -1;
26904      Interrupt_States := Local_Interrupt_States'Address;
26905      Num_Interrupt_States := 0;
26906      Unreserve_All_Interrupts := 0;
26907      Detect_Blocking := 0;
26908      Default_Stack_Size := -1;
26909      Leap_Seconds_Support := 0;
26910
26911      Runtime_Initialize;
26912
26913      Finalize_Library_Objects := finalize_library'access;
26914
26915      --  Now we have the elaboration calls for all units in the partition.
26916      --  The Elab_Spec and Elab_Body attributes generate references to the
26917      --  implicit elaboration procedures generated by the compiler for
26918      --  each unit that requires elaboration. Increment a counter of
26919      --  reference for each unit.
26920
26921      System.Soft_Links'Elab_Spec;
26922      System.Exception_Table'Elab_Body;
26923      E23 := E23 + 1;
26924      Ada.Io_Exceptions'Elab_Spec;
26925      E46 := E46 + 1;
26926      Ada.Tags'Elab_Spec;
26927      Ada.Streams'Elab_Spec;
26928      E45 := E45 + 1;
26929      Interfaces.C'Elab_Spec;
26930      System.Exceptions'Elab_Spec;
26931      E25 := E25 + 1;
26932      System.Finalization_Root'Elab_Spec;
26933      E68 := E68 + 1;
26934      Ada.Finalization'Elab_Spec;
26935      E66 := E66 + 1;
26936      System.Storage_Pools'Elab_Spec;
26937      E85 := E85 + 1;
26938      System.Finalization_Masters'Elab_Spec;
26939      System.Storage_Pools.Subpools'Elab_Spec;
26940      System.Pool_Global'Elab_Spec;
26941      E87 := E87 + 1;
26942      System.File_Control_Block'Elab_Spec;
26943      E75 := E75 + 1;
26944      System.File_Io'Elab_Body;
26945      E64 := E64 + 1;
26946      E91 := E91 + 1;
26947      System.Finalization_Masters'Elab_Body;
26948      E77 := E77 + 1;
26949      E70 := E70 + 1;
26950      Ada.Tags'Elab_Body;
26951      E48 := E48 + 1;
26952      System.Soft_Links'Elab_Body;
26953      E13 := E13 + 1;
26954      System.Os_Lib'Elab_Body;
26955      E72 := E72 + 1;
26956      System.Secondary_Stack'Elab_Body;
26957      E17 := E17 + 1;
26958      Ada.Text_Io'Elab_Spec;
26959      Ada.Text_Io'Elab_Body;
26960      E06 := E06 + 1;
26961   end adainit;
26962
26963   --------------
26964   -- adafinal --
26965   --------------
26966
26967   procedure adafinal is
26968      procedure s_stalib_adafinal;
26969      pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
26970
26971      procedure Runtime_Finalize;
26972      pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
26973
26974   begin
26975      if not Is_Elaborated then
26976         return;
26977      end if;
26978      Is_Elaborated := False;
26979      Runtime_Finalize;
26980      s_stalib_adafinal;
26981   end adafinal;
26982
26983   --  We get to the main program of the partition by using
26984   --  pragma Import because if we try to with the unit and
26985   --  call it Ada style, then not only do we waste time
26986   --  recompiling it, but also, we don't really know the right
26987   --  switches (e.g.@@: identifier character set) to be used
26988   --  to compile it.
26989
26990   procedure Ada_Main_Program;
26991   pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26992
26993   ----------
26994   -- main --
26995   ----------
26996
26997   --  main is actually a function, as in the ANSI C standard,
26998   --  defined to return the exit status. The three parameters
26999   --  are the argument count, argument values and environment
27000   --  pointer.
27001
27002   function main
27003     (argc : Integer;
27004      argv : System.Address;
27005      envp : System.Address)
27006      return Integer
27007   is
27008      --  The initialize routine performs low level system
27009      --  initialization using a standard library routine which
27010      --  sets up signal handling and performs any other
27011      --  required setup. The routine can be found in file
27012      --  a-init.c.
27013
27014      procedure initialize;
27015      pragma Import (C, initialize, "__gnat_initialize");
27016
27017      --  The finalize routine performs low level system
27018      --  finalization using a standard library routine. The
27019      --  routine is found in file a-final.c and in the standard
27020      --  distribution is a dummy routine that does nothing, so
27021      --  really this is a hook for special user finalization.
27022
27023      procedure finalize;
27024      pragma Import (C, finalize, "__gnat_finalize");
27025
27026      --  The following is to initialize the SEH exceptions
27027
27028      SEH : aliased array (1 .. 2) of Integer;
27029
27030      Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
27031      pragma Volatile (Ensure_Reference);
27032
27033   --  Start of processing for main
27034
27035   begin
27036      --  Save global variables
27037
27038      gnat_argc := argc;
27039      gnat_argv := argv;
27040      gnat_envp := envp;
27041
27042      --  Call low level system initialization
27043
27044      Initialize (SEH'Address);
27045
27046      --  Call our generated Ada initialization routine
27047
27048      adainit;
27049
27050      --  Now we call the main program of the partition
27051
27052      Ada_Main_Program;
27053
27054      --  Perform Ada finalization
27055
27056      adafinal;
27057
27058      --  Perform low level system finalization
27059
27060      Finalize;
27061
27062      --  Return the proper exit status
27063      return (gnat_exit_status);
27064   end;
27065
27066--  This section is entirely comments, so it has no effect on the
27067--  compilation of the Ada_Main package. It provides the list of
27068--  object files and linker options, as well as some standard
27069--  libraries needed for the link. The gnatlink utility parses
27070--  this b~hello.adb file to read these comment lines to generate
27071--  the appropriate command line arguments for the call to the
27072--  system linker. The BEGIN/END lines are used for sentinels for
27073--  this parsing operation.
27074
27075--  The exact file names will of course depend on the environment,
27076--  host/target and location of files on the host system.
27077
27078-- BEGIN Object file/option list
27079   --   ./hello.o
27080   --   -L./
27081   --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27082   --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27083-- END Object file/option list
27084
27085end ada_main;
27086@end example
27087
27088The Ada code in the above example is exactly what is generated by the
27089binder. We have added comments to more clearly indicate the function
27090of each part of the generated @code{Ada_Main} package.
27091
27092The code is standard Ada in all respects, and can be processed by any
27093tools that handle Ada. In particular, it is possible to use the debugger
27094in Ada mode to debug the generated @code{Ada_Main} package. For example,
27095suppose that for reasons that you do not understand, your program is crashing
27096during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27097you can place a breakpoint on the call:
27098
27099@quotation
27100
27101@example
27102Ada.Text_Io'Elab_Body;
27103@end example
27104@end quotation
27105
27106and trace the elaboration routine for this package to find out where
27107the problem might be (more usually of course you would be debugging
27108elaboration code in your own application).
27109
27110@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
27111
27112@node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
27113@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order-handling-in-gnat}@anchor{f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat doc}@anchor{22a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id1}@anchor{22b}
27114@chapter Elaboration Order Handling in GNAT
27115
27116
27117@geindex Order of elaboration
27118
27119@geindex Elaboration control
27120
27121This appendix describes the handling of elaboration code in Ada and GNAT, and
27122discusses how the order of elaboration of program units can be controlled in
27123GNAT, either automatically or with explicit programming features.
27124
27125@menu
27126* Elaboration Code::
27127* Elaboration Order::
27128* Checking the Elaboration Order::
27129* Controlling the Elaboration Order in Ada::
27130* Controlling the Elaboration Order in GNAT::
27131* Common Elaboration-model Traits::
27132* Dynamic Elaboration Model in GNAT::
27133* Static Elaboration Model in GNAT::
27134* SPARK Elaboration Model in GNAT::
27135* Legacy Elaboration Model in GNAT::
27136* Mixing Elaboration Models::
27137* Elaboration Circularities::
27138* Resolving Elaboration Circularities::
27139* Resolving Task Issues::
27140* Elaboration-related Compiler Switches::
27141* Summary of Procedures for Elaboration Control::
27142* Inspecting the Chosen Elaboration Order::
27143
27144@end menu
27145
27146@node Elaboration Code,Elaboration Order,,Elaboration Order Handling in GNAT
27147@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{22c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{22d}
27148@section Elaboration Code
27149
27150
27151Ada defines the term @emph{execution} as the process by which a construct achieves
27152its run-time effect. This process is also referred to as @strong{elaboration} for
27153declarations and @emph{evaluation} for expressions.
27154
27155The execution model in Ada allows for certain sections of an Ada program to be
27156executed prior to execution of the program itself, primarily with the intent of
27157initializing data. These sections are referred to as @strong{elaboration code}.
27158Elaboration code is executed as follows:
27159
27160
27161@itemize *
27162
27163@item
27164All partitions of an Ada program are executed in parallel with one another,
27165possibly in a separate address space, and possibly on a separate computer.
27166
27167@item
27168The execution of a partition involves running the environment task for that
27169partition.
27170
27171@item
27172The environment task executes all elaboration code (if available) for all
27173units within that partition. This code is said to be executed at
27174@strong{elaboration time}.
27175
27176@item
27177The environment task executes the Ada program (if available) for that
27178partition.
27179@end itemize
27180
27181In addition to the Ada terminology, this appendix defines the following terms:
27182
27183
27184@itemize *
27185
27186@item
27187@emph{Scenario}
27188
27189A construct that is elaborated or executed by elaboration code is referred to
27190as an @emph{elaboration scenario} or simply a @strong{scenario}. GNAT recognizes the
27191following scenarios:
27192
27193
27194@itemize -
27195
27196@item
27197@code{'Access} of entries, operators, and subprograms
27198
27199@item
27200Activation of tasks
27201
27202@item
27203Calls to entries, operators, and subprograms
27204
27205@item
27206Instantiations of generic templates
27207@end itemize
27208
27209@item
27210@emph{Target}
27211
27212A construct elaborated by a scenario is referred to as @emph{elaboration target}
27213or simply @strong{target}. GNAT recognizes the following targets:
27214
27215
27216@itemize -
27217
27218@item
27219For @code{'Access} of entries, operators, and subprograms, the target is the
27220entry, operator, or subprogram being aliased.
27221
27222@item
27223For activation of tasks, the target is the task body
27224
27225@item
27226For calls to entries, operators, and subprograms, the target is the entry,
27227operator, or subprogram being invoked.
27228
27229@item
27230For instantiations of generic templates, the target is the generic template
27231being instantiated.
27232@end itemize
27233@end itemize
27234
27235Elaboration code may appear in two distinct contexts:
27236
27237
27238@itemize *
27239
27240@item
27241@emph{Library level}
27242
27243A scenario appears at the library level when it is encapsulated by a package
27244[body] compilation unit, ignoring any other package [body] declarations in
27245between.
27246
27247@example
27248with Server;
27249package Client is
27250   procedure Proc;
27251
27252   package Nested is
27253      Val : ... := Server.Func;
27254   end Nested;
27255end Client;
27256@end example
27257
27258In the example above, the call to @code{Server.Func} is an elaboration scenario
27259because it appears at the library level of package @code{Client}. Note that the
27260declaration of package @code{Nested} is ignored according to the definition
27261given above. As a result, the call to @code{Server.Func} will be executed when
27262the spec of unit @code{Client} is elaborated.
27263
27264@item
27265@emph{Package body statements}
27266
27267A scenario appears within the statement sequence of a package body when it is
27268bounded by the region starting from the @code{begin} keyword of the package body
27269and ending at the @code{end} keyword of the package body.
27270
27271@example
27272package body Client is
27273   procedure Proc is
27274   begin
27275      ...
27276   end Proc;
27277begin
27278   Proc;
27279end Client;
27280@end example
27281
27282In the example above, the call to @code{Proc} is an elaboration scenario because
27283it appears within the statement sequence of package body @code{Client}. As a
27284result, the call to @code{Proc} will be executed when the body of @code{Client} is
27285elaborated.
27286@end itemize
27287
27288@node Elaboration Order,Checking the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
27289@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order}@anchor{22e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{22f}
27290@section Elaboration Order
27291
27292
27293The sequence by which the elaboration code of all units within a partition is
27294executed is referred to as @strong{elaboration order}.
27295
27296Within a single unit, elaboration code is executed in sequential order.
27297
27298@example
27299package body Client is
27300   Result : ... := Server.Func;
27301
27302   procedure Proc is
27303      package Inst is new Server.Gen;
27304   begin
27305      Inst.Eval (Result);
27306   end Proc;
27307begin
27308   Proc;
27309end Client;
27310@end example
27311
27312In the example above, the elaboration order within package body @code{Client} is
27313as follows:
27314
27315
27316@enumerate
27317
27318@item
27319The object declaration of @code{Result} is elaborated.
27320
27321
27322@itemize *
27323
27324@item
27325Function @code{Server.Func} is invoked.
27326@end itemize
27327
27328@item
27329The subprogram body of @code{Proc} is elaborated.
27330
27331@item
27332Procedure @code{Proc} is invoked.
27333
27334
27335@itemize *
27336
27337@item
27338Generic unit @code{Server.Gen} is instantiated as @code{Inst}.
27339
27340@item
27341Instance @code{Inst} is elaborated.
27342
27343@item
27344Procedure @code{Inst.Eval} is invoked.
27345@end itemize
27346@end enumerate
27347
27348The elaboration order of all units within a partition depends on the following
27349factors:
27350
27351
27352@itemize *
27353
27354@item
27355@emph{with}ed units
27356
27357@item
27358purity of units
27359
27360@item
27361preelaborability of units
27362
27363@item
27364presence of elaboration control pragmas
27365@end itemize
27366
27367A program may have several elaboration orders depending on its structure.
27368
27369@example
27370package Server is
27371   function Func (Index : Integer) return Integer;
27372end Server;
27373@end example
27374
27375@example
27376package body Server is
27377   Results : array (1 .. 5) of Integer := (1, 2, 3, 4, 5);
27378
27379   function Func (Index : Integer) return Integer is
27380   begin
27381      return Results (Index);
27382   end Func;
27383end Server;
27384@end example
27385
27386@example
27387with Server;
27388package Client is
27389   Val : constant Integer := Server.Func (3);
27390end Client;
27391@end example
27392
27393@example
27394with Client;
27395procedure Main is begin null; end Main;
27396@end example
27397
27398The following elaboration order exhibits a fundamental problem referred to as
27399@emph{access-before-elaboration} or simply @strong{ABE}.
27400
27401@example
27402spec of Server
27403spec of Client
27404body of Server
27405body of Main
27406@end example
27407
27408The elaboration of @code{Server}'s spec materializes function @code{Func}, making it
27409callable. The elaboration of @code{Client}'s spec elaborates the declaration of
27410@code{Val}. This invokes function @code{Server.Func}, however the body of
27411@code{Server.Func} has not been elaborated yet because @code{Server}'s body comes
27412after @code{Client}'s spec in the elaboration order. As a result, the value of
27413constant @code{Val} is now undefined.
27414
27415Without any guarantees from the language, an undetected ABE problem may hinder
27416proper initialization of data, which in turn may lead to undefined behavior at
27417run time. To prevent such ABE problems, Ada employs dynamic checks in the same
27418vein as index or null exclusion checks. A failed ABE check raises exception
27419@code{Program_Error}.
27420
27421The following elaboration order avoids the ABE problem and the program can be
27422successfully elaborated.
27423
27424@example
27425spec of Server
27426body of Server
27427spec of Client
27428body of Main
27429@end example
27430
27431Ada states that a total elaboration order must exist, but it does not define
27432what this order is. A compiler is thus tasked with choosing a suitable
27433elaboration order which satisfies the dependencies imposed by @emph{with} clauses,
27434unit categorization, and elaboration control pragmas. Ideally an order which
27435avoids ABE problems should be chosen, however a compiler may not always find
27436such an order due to complications with respect to control and data flow.
27437
27438@node Checking the Elaboration Order,Controlling the Elaboration Order in Ada,Elaboration Order,Elaboration Order Handling in GNAT
27439@anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{230}@anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{231}
27440@section Checking the Elaboration Order
27441
27442
27443To avoid placing the entire elaboration order burden on the programmer, Ada
27444provides three lines of defense:
27445
27446
27447@itemize *
27448
27449@item
27450@emph{Static semantics}
27451
27452Static semantic rules restrict the possible choice of elaboration order. For
27453instance, if unit Client @emph{with}s unit Server, then the spec of Server is
27454always elaborated prior to Client. The same principle applies to child units
27455- the spec of a parent unit is always elaborated prior to the child unit.
27456
27457@item
27458@emph{Dynamic semantics}
27459
27460Dynamic checks are performed at run time, to ensure that a target is
27461elaborated prior to a scenario that executes it, thus avoiding ABE problems.
27462A failed run-time check raises exception @code{Program_Error}. The following
27463restrictions apply:
27464
27465
27466@itemize -
27467
27468@item
27469@emph{Restrictions on calls}
27470
27471An entry, operator, or subprogram can be called from elaboration code only
27472when the corresponding body has been elaborated.
27473
27474@item
27475@emph{Restrictions on instantiations}
27476
27477A generic unit can be instantiated by elaboration code only when the
27478corresponding body has been elaborated.
27479
27480@item
27481@emph{Restrictions on task activation}
27482
27483A task can be activated by elaboration code only when the body of the
27484associated task type has been elaborated.
27485@end itemize
27486
27487The restrictions above can be summarized by the following rule:
27488
27489@emph{If a target has a body, then this body must be elaborated prior to the
27490execution of the scenario that invokes, instantiates, or activates the
27491target.}
27492
27493@item
27494@emph{Elaboration control}
27495
27496Pragmas are provided for the programmer to specify the desired elaboration
27497order.
27498@end itemize
27499
27500@node Controlling the Elaboration Order in Ada,Controlling the Elaboration Order in GNAT,Checking the Elaboration Order,Elaboration Order Handling in GNAT
27501@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-ada}@anchor{232}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{233}
27502@section Controlling the Elaboration Order in Ada
27503
27504
27505Ada provides several idioms and pragmas to aid the programmer with specifying
27506the desired elaboration order and avoiding ABE problems altogether.
27507
27508
27509@itemize *
27510
27511@item
27512@emph{Packages without a body}
27513
27514A library package which does not require a completing body does not suffer
27515from ABE problems.
27516
27517@example
27518package Pack is
27519   generic
27520      type Element is private;
27521   package Containers is
27522      type Element_Array is array (1 .. 10) of Element;
27523   end Containers;
27524end Pack;
27525@end example
27526
27527In the example above, package @code{Pack} does not require a body because it
27528does not contain any constructs which require completion in a body. As a
27529result, generic @code{Pack.Containers} can be instantiated without encountering
27530any ABE problems.
27531@end itemize
27532
27533@geindex pragma Pure
27534
27535
27536@itemize *
27537
27538@item
27539@emph{pragma Pure}
27540
27541Pragma @code{Pure} places sufficient restrictions on a unit to guarantee that no
27542scenario within the unit can result in an ABE problem.
27543@end itemize
27544
27545@geindex pragma Preelaborate
27546
27547
27548@itemize *
27549
27550@item
27551@emph{pragma Preelaborate}
27552
27553Pragma @code{Preelaborate} is slightly less restrictive than pragma @code{Pure},
27554but still strong enough to prevent ABE problems within a unit.
27555@end itemize
27556
27557@geindex pragma Elaborate_Body
27558
27559
27560@itemize *
27561
27562@item
27563@emph{pragma Elaborate_Body}
27564
27565Pragma @code{Elaborate_Body} requires that the body of a unit is elaborated
27566immediately after its spec. This restriction guarantees that no client
27567scenario can execute a server target before the target body has been
27568elaborated because the spec and body are effectively "glued" together.
27569
27570@example
27571package Server is
27572   pragma Elaborate_Body;
27573
27574   function Func return Integer;
27575end Server;
27576@end example
27577
27578@example
27579package body Server is
27580   function Func return Integer is
27581   begin
27582      ...
27583   end Func;
27584end Server;
27585@end example
27586
27587@example
27588with Server;
27589package Client is
27590   Val : constant Integer := Server.Func;
27591end Client;
27592@end example
27593
27594In the example above, pragma @code{Elaborate_Body} guarantees the following
27595elaboration order:
27596
27597@example
27598spec of Server
27599body of Server
27600spec of Client
27601@end example
27602
27603because the spec of @code{Server} must be elaborated prior to @code{Client} by
27604virtue of the @emph{with} clause, and in addition the body of @code{Server} must be
27605elaborated immediately after the spec of @code{Server}.
27606
27607Removing pragma @code{Elaborate_Body} could result in the following incorrect
27608elaboration order:
27609
27610@example
27611spec of Server
27612spec of Client
27613body of Server
27614@end example
27615
27616where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func} has
27617not been elaborated yet.
27618@end itemize
27619
27620The pragmas outlined above allow a server unit to guarantee safe elaboration
27621use by client units. Thus it is a good rule to mark units as @code{Pure} or
27622@code{Preelaborate}, and if this is not possible, mark them as @code{Elaborate_Body}.
27623
27624There are however situations where @code{Pure}, @code{Preelaborate}, and
27625@code{Elaborate_Body} are not applicable. Ada provides another set of pragmas for
27626use by client units to help ensure the elaboration safety of server units they
27627depend on.
27628
27629@geindex pragma Elaborate (Unit)
27630
27631
27632@itemize *
27633
27634@item
27635@emph{pragma Elaborate (Unit)}
27636
27637Pragma @code{Elaborate} can be placed in the context clauses of a unit, after a
27638@emph{with} clause. It guarantees that both the spec and body of its argument will
27639be elaborated prior to the unit with the pragma. Note that other unrelated
27640units may be elaborated in between the spec and the body.
27641
27642@example
27643package Server is
27644   function Func return Integer;
27645end Server;
27646@end example
27647
27648@example
27649package body Server is
27650   function Func return Integer is
27651   begin
27652      ...
27653   end Func;
27654end Server;
27655@end example
27656
27657@example
27658with Server;
27659pragma Elaborate (Server);
27660package Client is
27661   Val : constant Integer := Server.Func;
27662end Client;
27663@end example
27664
27665In the example above, pragma @code{Elaborate} guarantees the following
27666elaboration order:
27667
27668@example
27669spec of Server
27670body of Server
27671spec of Client
27672@end example
27673
27674Removing pragma @code{Elaborate} could result in the following incorrect
27675elaboration order:
27676
27677@example
27678spec of Server
27679spec of Client
27680body of Server
27681@end example
27682
27683where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func}
27684has not been elaborated yet.
27685@end itemize
27686
27687@geindex pragma Elaborate_All (Unit)
27688
27689
27690@itemize *
27691
27692@item
27693@emph{pragma Elaborate_All (Unit)}
27694
27695Pragma @code{Elaborate_All} is placed in the context clauses of a unit, after
27696a @emph{with} clause. It guarantees that both the spec and body of its argument
27697will be elaborated prior to the unit with the pragma, as well as all units
27698@emph{with}ed by the spec and body of the argument, recursively. Note that other
27699unrelated units may be elaborated in between the spec and the body.
27700
27701@example
27702package Math is
27703   function Factorial (Val : Natural) return Natural;
27704end Math;
27705@end example
27706
27707@example
27708package body Math is
27709   function Factorial (Val : Natural) return Natural is
27710   begin
27711      ...;
27712   end Factorial;
27713end Math;
27714@end example
27715
27716@example
27717package Computer is
27718   type Operation_Kind is (None, Op_Factorial);
27719
27720   function Compute
27721     (Val : Natural;
27722      Op  : Operation_Kind) return Natural;
27723end Computer;
27724@end example
27725
27726@example
27727with Math;
27728package body Computer is
27729   function Compute
27730     (Val : Natural;
27731      Op  : Operation_Kind) return Natural
27732   is
27733      if Op = Op_Factorial then
27734         return Math.Factorial (Val);
27735      end if;
27736
27737      return 0;
27738   end Compute;
27739end Computer;
27740@end example
27741
27742@example
27743with Computer;
27744pragma Elaborate_All (Computer);
27745package Client is
27746   Val : constant Natural :=
27747           Computer.Compute (123, Computer.Op_Factorial);
27748end Client;
27749@end example
27750
27751In the example above, pragma @code{Elaborate_All} can result in the following
27752elaboration order:
27753
27754@example
27755spec of Math
27756body of Math
27757spec of Computer
27758body of Computer
27759spec of Client
27760@end example
27761
27762Note that there are several allowable suborders for the specs and bodies of
27763@code{Math} and @code{Computer}, but the point is that these specs and bodies will
27764be elaborated prior to @code{Client}.
27765
27766Removing pragma @code{Elaborate_All} could result in the following incorrect
27767elaboration order
27768
27769@example
27770spec of Math
27771spec of Computer
27772body of Computer
27773spec of Client
27774body of Math
27775@end example
27776
27777where @code{Client} invokes @code{Computer.Compute}, which in turn invokes
27778@code{Math.Factorial}, but the body of @code{Math.Factorial} has not been
27779elaborated yet.
27780@end itemize
27781
27782All pragmas shown above can be summarized by the following rule:
27783
27784@emph{If a client unit elaborates a server target directly or indirectly, then if
27785the server unit requires a body and does not have pragma Pure, Preelaborate,
27786or Elaborate_Body, then the client unit should have pragma Elaborate or
27787Elaborate_All for the server unit.}
27788
27789If the rule outlined above is not followed, then a program may fall in one of
27790the following states:
27791
27792
27793@itemize *
27794
27795@item
27796@emph{No elaboration order exists}
27797
27798In this case a compiler must diagnose the situation, and refuse to build an
27799executable program.
27800
27801@item
27802@emph{One or more incorrect elaboration orders exist}
27803
27804In this case a compiler can build an executable program, but
27805@code{Program_Error} will be raised when the program is run.
27806
27807@item
27808@emph{Several elaboration orders exist, some correct, some incorrect}
27809
27810In this case the programmer has not controlled the elaboration order. As a
27811result, a compiler may or may not pick one of the correct orders, and the
27812program may or may not raise @code{Program_Error} when it is run. This is the
27813worst possible state because the program may fail on another compiler, or
27814even another version of the same compiler.
27815
27816@item
27817@emph{One or more correct orders exist}
27818
27819In this case a compiler can build an executable program, and the program is
27820run successfully. This state may be guaranteed by following the outlined
27821rules, or may be the result of good program architecture.
27822@end itemize
27823
27824Note that one additional advantage of using @code{Elaborate} and @code{Elaborate_All}
27825is that the program continues to stay in the last state (one or more correct
27826orders exist) even if maintenance changes the bodies of targets.
27827
27828@node Controlling the Elaboration Order in GNAT,Common Elaboration-model Traits,Controlling the Elaboration Order in Ada,Elaboration Order Handling in GNAT
27829@anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{234}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-gnat}@anchor{235}
27830@section Controlling the Elaboration Order in GNAT
27831
27832
27833In addition to Ada semantics and rules synthesized from them, GNAT offers
27834three elaboration models to aid the programmer with specifying the correct
27835elaboration order and to diagnose elaboration problems.
27836
27837@geindex Dynamic elaboration model
27838
27839
27840@itemize *
27841
27842@item
27843@emph{Dynamic elaboration model}
27844
27845This is the most permissive of the three elaboration models. When the
27846dynamic model is in effect, GNAT assumes that all code within all units in
27847a partition is elaboration code. GNAT performs very few diagnostics and
27848generates run-time checks to verify the elaboration order of a program. This
27849behavior is identical to that specified by the Ada Reference Manual. The
27850dynamic model is enabled with compiler switch @code{-gnatE}.
27851@end itemize
27852
27853@geindex Static elaboration model
27854
27855
27856@itemize *
27857
27858@item
27859@emph{Static elaboration model}
27860
27861This is the middle ground of the three models. When the static model is in
27862effect, GNAT performs extensive diagnostics on a unit-by-unit basis for all
27863scenarios that elaborate or execute internal targets. GNAT also generates
27864run-time checks for all external targets and for all scenarios that may
27865exhibit ABE problems. Finally, GNAT installs implicit @code{Elaborate} and
27866@code{Elaborate_All} pragmas for server units based on the dependencies of
27867client units. The static model is the default model in GNAT.
27868@end itemize
27869
27870@geindex SPARK elaboration model
27871
27872
27873@itemize *
27874
27875@item
27876@emph{SPARK elaboration model}
27877
27878This is the most conservative of the three models and enforces the SPARK
27879rules of elaboration as defined in the SPARK Reference Manual, section 7.7.
27880The SPARK model is in effect only when a scenario and a target reside in a
27881region subject to SPARK_Mode On, otherwise the dynamic or static model is in
27882effect.
27883@end itemize
27884
27885@geindex Legacy elaboration model
27886
27887
27888@itemize *
27889
27890@item
27891@emph{Legacy elaboration model}
27892
27893In addition to the three elaboration models outlined above, GNAT provides the
27894elaboration model of pre-18.x versions referred to as @cite{legacy elaboration model}. The legacy elaboration model is enabled with compiler switch
27895@code{-gnatH}.
27896@end itemize
27897
27898@geindex Relaxed elaboration mode
27899
27900The dynamic, legacy, and static models can be relaxed using compiler switch
27901@code{-gnatJ}, making them more permissive. Note that in this mode, GNAT
27902may not diagnose certain elaboration issues or install run-time checks.
27903
27904@node Common Elaboration-model Traits,Dynamic Elaboration Model in GNAT,Controlling the Elaboration Order in GNAT,Elaboration Order Handling in GNAT
27905@anchor{gnat_ugn/elaboration_order_handling_in_gnat common-elaboration-model-traits}@anchor{236}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{237}
27906@section Common Elaboration-model Traits
27907
27908
27909All three GNAT models are able to detect elaboration problems related to
27910dispatching calls and a particular kind of ABE referred to as @emph{guaranteed ABE}.
27911
27912
27913@itemize *
27914
27915@item
27916@emph{Dispatching calls}
27917
27918GNAT installs run-time checks for each primitive subprogram of each tagged
27919type defined in a partition on the assumption that a dispatching call
27920invoked at elaboration time will execute one of these primitives. As a
27921result, a dispatching call that executes a primitive whose body has not
27922been elaborated yet will raise exception @code{Program_Error} at run time. The
27923checks can be suppressed using pragma @code{Suppress (Elaboration_Check)}.
27924
27925@item
27926@emph{Guaranteed ABE}
27927
27928A guaranteed ABE arises when the body of a target is not elaborated early
27929enough, and causes all scenarios that directly execute the target to fail.
27930
27931@example
27932package body Guaranteed_ABE is
27933   function ABE return Integer;
27934
27935   Val : constant Integer := ABE;
27936
27937   function ABE return Integer is
27938   begin
27939      ...
27940   end ABE;
27941end Guaranteed_ABE;
27942@end example
27943
27944In the example above, the elaboration of @code{Guaranteed_ABE}'s body elaborates
27945the declaration of @code{Val}. This invokes function @code{ABE}, however the body
27946of @code{ABE} has not been elaborated yet. GNAT emits similar diagnostics in all
27947three models:
27948
27949@example
279501. package body Guaranteed_ABE is
279512.    function ABE return Integer;
279523.
279534.    Val : constant Integer := ABE;
27954                                |
27955   >>> warning: cannot call "ABE" before body seen
27956   >>> warning: Program_Error will be raised at run time
27957
279585.
279596.    function ABE return Integer is
279607.    begin
279618.       ...
279629.    end ABE;
2796310. end Guaranteed_ABE;
27964@end example
27965@end itemize
27966
27967Note that GNAT emits warnings rather than hard errors whenever it encounters an
27968elaboration problem. This is because the elaboration model in effect may be too
27969conservative, or a particular scenario may not be elaborated or executed due to
27970data and control flow. The warnings can be suppressed selectively with @code{pragma
27971Warnigns (Off)} or globally with compiler switch @code{-gnatwL}.
27972
27973@node Dynamic Elaboration Model in GNAT,Static Elaboration Model in GNAT,Common Elaboration-model Traits,Elaboration Order Handling in GNAT
27974@anchor{gnat_ugn/elaboration_order_handling_in_gnat dynamic-elaboration-model-in-gnat}@anchor{238}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{239}
27975@section Dynamic Elaboration Model in GNAT
27976
27977
27978The dynamic model assumes that all code within all units in a partition is
27979elaboration code. As a result, run-time checks are installed for each scenario
27980regardless of whether the target is internal or external. The checks can be
27981suppressed using pragma @code{Suppress (Elaboration_Check)}. This behavior is
27982identical to that specified by the Ada Reference Manual. The following example
27983showcases run-time checks installed by GNAT to verify the elaboration state of
27984package @code{Dynamic_Model}.
27985
27986@example
27987with Server;
27988package body Dynamic_Model is
27989   procedure API is
27990   begin
27991      ...
27992   end API;
27993
27994   <check that the body of Server.Gen is elaborated>
27995   package Inst is new Server.Gen;
27996
27997   T : Server.Task_Type;
27998
27999begin
28000   <check that the body of Server.Task_Type is elaborated>
28001
28002   <check that the body of Server.Proc is elaborated>
28003   Server.Proc;
28004end Dynamic_Model;
28005@end example
28006
28007The checks verify that the body of a target has been successfully elaborated
28008before a scenario activates, calls, or instantiates a target.
28009
28010Note that no scenario within package @code{Dynamic_Model} calls procedure @code{API}.
28011In fact, procedure @code{API} may not be invoked by elaboration code within the
28012partition, however the dynamic model assumes that this can happen.
28013
28014The dynamic model emits very few diagnostics, but can make suggestions on
28015missing @code{Elaborate} and @code{Elaborate_All} pragmas for library-level
28016scenarios. This information is available when compiler switch @code{-gnatel}
28017is in effect.
28018
28019@example
280201. with Server;
280212. package body Dynamic_Model is
280223.    Val : constant Integer := Server.Func;
28023                                      |
28024   >>> info: call to "Func" during elaboration
28025   >>> info: missing pragma "Elaborate_All" for unit "Server"
28026
280274. end Dynamic_Model;
28028@end example
28029
28030@node Static Elaboration Model in GNAT,SPARK Elaboration Model in GNAT,Dynamic Elaboration Model in GNAT,Elaboration Order Handling in GNAT
28031@anchor{gnat_ugn/elaboration_order_handling_in_gnat static-elaboration-model-in-gnat}@anchor{23a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{23b}
28032@section Static Elaboration Model in GNAT
28033
28034
28035In contrast to the dynamic model, the static model is more precise in its
28036analysis of elaboration code. The model makes a clear distinction between
28037internal and external targets, and resorts to different diagnostics and
28038run-time checks based on the nature of the target.
28039
28040
28041@itemize *
28042
28043@item
28044@emph{Internal targets}
28045
28046The static model performs extensive diagnostics on scenarios which elaborate
28047or execute internal targets. The warnings resulting from these diagnostics
28048are enabled by default, but can be suppressed selectively with @code{pragma
28049Warnings (Off)} or globally with compiler switch @code{-gnatwL}.
28050
28051@example
28052 1. package body Static_Model is
28053 2.    generic
28054 3.       with function Func return Integer;
28055 4.    package Gen is
28056 5.       Val : constant Integer := Func;
28057 6.    end Gen;
28058 7.
28059 8.    function ABE return Integer;
28060 9.
2806110.    function Cause_ABE return Boolean is
2806211.       package Inst is new Gen (ABE);
28063          |
28064    >>> warning: in instantiation at line 5
28065    >>> warning: cannot call "ABE" before body seen
28066    >>> warning: Program_Error may be raised at run time
28067    >>> warning:   body of unit "Static_Model" elaborated
28068    >>> warning:   function "Cause_ABE" called at line 16
28069    >>> warning:   function "ABE" called at line 5, instance at line 11
28070
2807112.    begin
2807213.       ...
2807314.    end Cause_ABE;
2807415.
2807516.    Val : constant Boolean := Cause_ABE;
2807617.
2807718.    function ABE return Integer is
2807819.    begin
2807920.       ...
2808021.    end ABE;
2808122. end Static_Model;
28082@end example
28083
28084The example above illustrates an ABE problem within package @code{Static_Model},
28085which is hidden by several layers of indirection. The elaboration of package
28086body @code{Static_Model} elaborates the declaration of @code{Val}. This invokes
28087function @code{Cause_ABE}, which instantiates generic unit @code{Gen} as @code{Inst}.
28088The elaboration of @code{Inst} invokes function @code{ABE}, however the body of
28089@code{ABE} has not been elaborated yet.
28090
28091@item
28092@emph{External targets}
28093
28094The static model installs run-time checks to verify the elaboration status
28095of server targets only when the scenario that elaborates or executes that
28096target is part of the elaboration code of the client unit. The checks can be
28097suppressed using pragma @code{Suppress (Elaboration_Check)}.
28098
28099@example
28100with Server;
28101package body Static_Model is
28102   generic
28103      with function Func return Integer;
28104   package Gen is
28105      Val : constant Integer := Func;
28106   end Gen;
28107
28108   function Call_Func return Boolean is
28109      <check that the body of Server.Func is elaborated>
28110      package Inst is new Gen (Server.Func);
28111   begin
28112      ...
28113   end Call_Func;
28114
28115   Val : constant Boolean := Call_Func;
28116end Static_Model;
28117@end example
28118
28119In the example above, the elaboration of package body @code{Static_Model}
28120elaborates the declaration of @code{Val}. This invokes function @code{Call_Func},
28121which instantiates generic unit @code{Gen} as @code{Inst}. The elaboration of
28122@code{Inst} invokes function @code{Server.Func}. Since @code{Server.Func} is an
28123external target, GNAT installs a run-time check to verify that its body has
28124been elaborated.
28125
28126In addition to checks, the static model installs implicit @code{Elaborate} and
28127@code{Elaborate_All} pragmas to guarantee safe elaboration use of server units.
28128This information is available when compiler switch @code{-gnatel} is in
28129effect.
28130
28131@example
28132 1. with Server;
28133 2. package body Static_Model is
28134 3.    generic
28135 4.       with function Func return Integer;
28136 5.    package Gen is
28137 6.       Val : constant Integer := Func;
28138 7.    end Gen;
28139 8.
28140 9.    function Call_Func return Boolean is
2814110.       package Inst is new Gen (Server.Func);
28142          |
28143    >>> info: instantiation of "Gen" during elaboration
28144    >>> info: in instantiation at line 6
28145    >>> info: call to "Func" during elaboration
28146    >>> info: in instantiation at line 6
28147    >>> info: implicit pragma "Elaborate_All" generated for unit "Server"
28148    >>> info:   body of unit "Static_Model" elaborated
28149    >>> info:   function "Call_Func" called at line 15
28150    >>> info:   function "Func" called at line 6, instance at line 10
28151
2815211.    begin
2815312.       ...
2815413.    end Call_Func;
2815514.
2815615.    Val : constant Boolean := Call_Func;
28157                                 |
28158    >>> info: call to "Call_Func" during elaboration
28159
2816016. end Static_Model;
28161@end example
28162
28163In the example above, the elaboration of package body @code{Static_Model}
28164elaborates the declaration of @code{Val}. This invokes function @code{Call_Func},
28165which instantiates generic unit @code{Gen} as @code{Inst}. The elaboration of
28166@code{Inst} invokes function @code{Server.Func}. Since @code{Server.Func} is an
28167external target, GNAT installs an implicit @code{Elaborate_All} pragma for unit
28168@code{Server}. The pragma guarantees that both the spec and body of @code{Server},
28169along with any additional dependencies that @code{Server} may require, are
28170elaborated prior to the body of @code{Static_Model}.
28171@end itemize
28172
28173@node SPARK Elaboration Model in GNAT,Legacy Elaboration Model in GNAT,Static Elaboration Model in GNAT,Elaboration Order Handling in GNAT
28174@anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{23c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat spark-elaboration-model-in-gnat}@anchor{23d}
28175@section SPARK Elaboration Model in GNAT
28176
28177
28178The SPARK model is identical to the static model in its handling of internal
28179targets. The SPARK model, however, requires explicit @code{Elaborate} or
28180@code{Elaborate_All} pragmas to be present in the program when a target is
28181external, and compiler switch @code{-gnatd.v} is in effect.
28182
28183@example
281841. with Server;
281852. package body SPARK_Model with SPARK_Mode is
281863.    Val : constant Integer := Server.Func;
28187                                      |
28188   >>> call to "Func" during elaboration in SPARK
28189   >>> unit "SPARK_Model" requires pragma "Elaborate_All" for "Server"
28190   >>>   body of unit "SPARK_Model" elaborated
28191   >>>   function "Func" called at line 3
28192
281934. end SPARK_Model;
28194@end example
28195
28196@node Legacy Elaboration Model in GNAT,Mixing Elaboration Models,SPARK Elaboration Model in GNAT,Elaboration Order Handling in GNAT
28197@anchor{gnat_ugn/elaboration_order_handling_in_gnat legacy-elaboration-model-in-gnat}@anchor{23e}
28198@section Legacy Elaboration Model in GNAT
28199
28200
28201The legacy elaboration model is provided for compatibility with code bases
28202developed with pre-18.x versions of GNAT. It is similar in functionality to
28203the dynamic and static models of post-18.x version of GNAT, but may differ
28204in terms of diagnostics and run-time checks. The legacy elaboration model is
28205enabled with compiler switch @code{-gnatH}.
28206
28207@node Mixing Elaboration Models,Elaboration Circularities,Legacy Elaboration Model in GNAT,Elaboration Order Handling in GNAT
28208@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{23f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{240}
28209@section Mixing Elaboration Models
28210
28211
28212It is possible to mix units compiled with a different elaboration model,
28213however the following rules must be observed:
28214
28215
28216@itemize *
28217
28218@item
28219A client unit compiled with the dynamic model can only @emph{with} a server unit
28220that meets at least one of the following criteria:
28221
28222
28223@itemize -
28224
28225@item
28226The server unit is compiled with the dynamic model.
28227
28228@item
28229The server unit is a GNAT implementation unit from the Ada, GNAT,
28230Interfaces, or System hierarchies.
28231
28232@item
28233The server unit has pragma @code{Pure} or @code{Preelaborate}.
28234
28235@item
28236The client unit has an explicit @code{Elaborate_All} pragma for the server
28237unit.
28238@end itemize
28239@end itemize
28240
28241These rules ensure that elaboration checks are not omitted. If the rules are
28242violated, the binder emits a warning:
28243
28244@example
28245warning: "x.ads" has dynamic elaboration checks and with's
28246warning:   "y.ads" which has static elaboration checks
28247@end example
28248
28249The warnings can be suppressed by binder switch @code{-ws}.
28250
28251@node Elaboration Circularities,Resolving Elaboration Circularities,Mixing Elaboration Models,Elaboration Order Handling in GNAT
28252@anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{241}@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-circularities}@anchor{242}
28253@section Elaboration Circularities
28254
28255
28256If the binder cannot find an acceptable elaboration order, it outputs detailed
28257diagnostics describing an @strong{elaboration circularity}.
28258
28259@example
28260package Server is
28261   function Func return Integer;
28262end Server;
28263@end example
28264
28265@example
28266with Client;
28267package body Server is
28268   function Func return Integer is
28269   begin
28270      ...
28271   end Func;
28272end Server;
28273@end example
28274
28275@example
28276with Server;
28277package Client is
28278   Val : constant Integer := Server.Func;
28279end Client;
28280@end example
28281
28282@example
28283with Client;
28284procedure Main is begin null; end Main;
28285@end example
28286
28287@example
28288error: elaboration circularity detected
28289info:    "server (body)" must be elaborated before "client (spec)"
28290info:       reason: implicit Elaborate_All in unit "client (spec)"
28291info:       recompile "client (spec)" with -gnatel for full details
28292info:          "server (body)"
28293info:             must be elaborated along with its spec:
28294info:          "server (spec)"
28295info:             which is withed by:
28296info:          "client (spec)"
28297info:    "client (spec)" must be elaborated before "server (body)"
28298info:       reason: with clause
28299@end example
28300
28301In the example above, @code{Client} must be elaborated prior to @code{Main} by virtue
28302of a @emph{with} clause. The elaboration of @code{Client} invokes @code{Server.Func}, and
28303static model generates an implicit @code{Elaborate_All} pragma for @code{Server}. The
28304pragma implies that both the spec and body of @code{Server}, along with any units
28305they @emph{with}, must be elaborated prior to @code{Client}. However, @code{Server}'s body
28306@emph{with}s @code{Client}, implying that @code{Client} must be elaborated prior to
28307@code{Server}. The end result is that @code{Client} must be elaborated prior to
28308@code{Client}, and this leads to a circularity.
28309
28310@node Resolving Elaboration Circularities,Resolving Task Issues,Elaboration Circularities,Elaboration Order Handling in GNAT
28311@anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{243}@anchor{gnat_ugn/elaboration_order_handling_in_gnat resolving-elaboration-circularities}@anchor{244}
28312@section Resolving Elaboration Circularities
28313
28314
28315When faced with an elaboration circularity, a programmer has several options
28316available.
28317
28318
28319@itemize *
28320
28321@item
28322@emph{Fix the program}
28323
28324The most desirable option from the point of view of long-term maintenance
28325is to rearrange the program so that the elaboration problems are avoided.
28326One useful technique is to place the elaboration code into separate child
28327packages. Another is to move some of the initialization code to explicitly
28328invoked subprograms, where the program controls the order of initialization
28329explicitly. Although this is the most desirable option, it may be impractical
28330and involve too much modification, especially in the case of complex legacy
28331code.
28332
28333@item
28334@emph{Switch to more permissive elaboration model}
28335
28336If the compilation was performed using the static model, enable the dynamic
28337model with compiler switch @code{-gnatE}. GNAT will no longer generate
28338implicit @code{Elaborate} and @code{Elaborate_All} pragmas, resulting in a behavior
28339identical to that specified by the Ada Reference Manual. The binder will
28340generate an executable program that may or may not raise @code{Program_Error},
28341and it is the programmer's responsibility to ensure that it does not raise
28342@code{Program_Error}.
28343
28344If the compilation was performed using a post-18.x version of GNAT, consider
28345using the legacy elaboration model, in the following order:
28346
28347
28348@itemize -
28349
28350@item
28351Use the legacy static elaboration model, with compiler switch
28352@code{-gnatH}.
28353
28354@item
28355Use the legacy dynamic elaboration model, with compiler switches
28356@code{-gnatH} @code{-gnatE}.
28357
28358@item
28359Use the relaxed legacy static elaboration model, with compiler switches
28360@code{-gnatH} @code{-gnatJ}.
28361
28362@item
28363Use the relaxed legacy dynamic elaboration model, with compiler switches
28364@code{-gnatH} @code{-gnatJ} @code{-gnatE}.
28365@end itemize
28366
28367@item
28368@emph{Suppress all elaboration checks}
28369
28370The drawback of run-time checks is that they generate overhead at run time,
28371both in space and time. If the programmer is absolutely sure that a program
28372will not raise an elaboration-related @code{Program_Error}, then using the
28373pragma @code{Suppress (Elaboration_Check)} globally (as a configuration pragma)
28374will eliminate all run-time checks.
28375
28376@item
28377@emph{Suppress elaboration checks selectively}
28378
28379If a scenario cannot possibly lead to an elaboration @code{Program_Error},
28380and the binder nevertheless complains about implicit @code{Elaborate} and
28381@code{Elaborate_All} pragmas that lead to elaboration circularities, it
28382is possible to suppress the generation of implicit @code{Elaborate} and
28383@code{Elaborate_All} pragmas, as well as run-time checks. Clearly this can
28384be unsafe, and it is the responsibility of the programmer to make sure
28385that the resulting program has no elaboration anomalies. Pragma
28386@code{Suppress (Elaboration_Check)} can be used with different levels of
28387granularity to achieve these effects.
28388
28389
28390@itemize -
28391
28392@item
28393@emph{Target suppression}
28394
28395When the pragma is placed in a declarative part, without a second argument
28396naming an entity, it will suppress implicit @code{Elaborate} and
28397@code{Elaborate_All} pragma generation, as well as run-time checks, on all
28398targets within the region.
28399
28400@example
28401package Range_Suppress is
28402   pragma Suppress (Elaboration_Check);
28403
28404   function Func return Integer;
28405
28406   generic
28407   procedure Gen;
28408
28409   pragma Unsuppress (Elaboration_Check);
28410
28411   task type Tsk;
28412end Range_Suppress;
28413@end example
28414
28415In the example above, a pair of Suppress/Unsuppress pragmas define a region
28416of suppression within package @code{Range_Suppress}. As a result, no implicit
28417@code{Elaborate} and @code{Elaborate_All} pragmas, nor any run-time checks, will
28418be generated by callers of @code{Func} and instantiators of @code{Gen}. Note that
28419task type @code{Tsk} is not within this region.
28420
28421An alternative to the region-based suppression is to use multiple
28422@code{Suppress} pragmas with arguments naming specific entities for which
28423elaboration checks should be suppressed:
28424
28425@example
28426package Range_Suppress is
28427   function Func return Integer;
28428   pragma Suppress (Elaboration_Check, Func);
28429
28430   generic
28431   procedure Gen;
28432   pragma Suppress (Elaboration_Check, Gen);
28433
28434   task type Tsk;
28435end Range_Suppress;
28436@end example
28437
28438@item
28439@emph{Scenario suppression}
28440
28441When the pragma @code{Suppress} is placed in a declarative or statement
28442part, without an entity argument, it will suppress implicit @code{Elaborate}
28443and @code{Elaborate_All} pragma generation, as well as run-time checks, on
28444all scenarios within the region.
28445
28446@example
28447with Server;
28448package body Range_Suppress is
28449   pragma Suppress (Elaboration_Check);
28450
28451   function Func return Integer is
28452   begin
28453      return Server.Func;
28454   end Func;
28455
28456   procedure Gen is
28457   begin
28458      Server.Proc;
28459   end Gen;
28460
28461   pragma Unsuppress (Elaboration_Check);
28462
28463   task body Tsk is
28464   begin
28465      Server.Proc;
28466   end Tsk;
28467end Range_Suppress;
28468@end example
28469
28470In the example above, a pair of Suppress/Unsuppress pragmas define a region
28471of suppression within package body @code{Range_Suppress}. As a result, the
28472calls to @code{Server.Func} in @code{Func} and @code{Server.Proc} in @code{Gen} will
28473not generate any implicit @code{Elaborate} and @code{Elaborate_All} pragmas or
28474run-time checks.
28475@end itemize
28476@end itemize
28477
28478@node Resolving Task Issues,Elaboration-related Compiler Switches,Resolving Elaboration Circularities,Elaboration Order Handling in GNAT
28479@anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{245}@anchor{gnat_ugn/elaboration_order_handling_in_gnat resolving-task-issues}@anchor{246}
28480@section Resolving Task Issues
28481
28482
28483The model of execution in Ada dictates that elaboration must first take place,
28484and only then can the main program be started. Tasks which are activated during
28485elaboration violate this model and may lead to serious concurrent problems at
28486elaboration time.
28487
28488A task can be activated in two different ways:
28489
28490
28491@itemize *
28492
28493@item
28494The task is created by an allocator in which case it is activated immediately
28495after the allocator is evaluated.
28496
28497@item
28498The task is declared at the library level or within some nested master in
28499which case it is activated before starting execution of the statement
28500sequence of the master defining the task.
28501@end itemize
28502
28503Since the elaboration of a partition is performed by the environment task
28504servicing that partition, any tasks activated during elaboration may be in
28505a race with the environment task, and lead to unpredictable state and behavior.
28506The static model seeks to avoid such interactions by assuming that all code in
28507the task body is executed at elaboration time, if the task was activated by
28508elaboration code.
28509
28510@example
28511package Decls is
28512   task Lib_Task is
28513      entry Start;
28514   end Lib_Task;
28515
28516   type My_Int is new Integer;
28517
28518   function Ident (M : My_Int) return My_Int;
28519end Decls;
28520@end example
28521
28522@example
28523with Utils;
28524package body Decls is
28525   task body Lib_Task is
28526   begin
28527      accept Start;
28528      Utils.Put_Val (2);
28529   end Lib_Task;
28530
28531   function Ident (M : My_Int) return My_Int is
28532   begin
28533      return M;
28534   end Ident;
28535end Decls;
28536@end example
28537
28538@example
28539with Decls;
28540package Utils is
28541   procedure Put_Val (Arg : Decls.My_Int);
28542end Utils;
28543@end example
28544
28545@example
28546with Ada.Text_IO; use Ada.Text_IO;
28547package body Utils is
28548   procedure Put_Val (Arg : Decls.My_Int) is
28549   begin
28550      Put_Line (Arg'Img);
28551   end Put_Val;
28552end Utils;
28553@end example
28554
28555@example
28556with Decls;
28557procedure Main is
28558begin
28559   Decls.Lib_Task.Start;
28560end Main;
28561@end example
28562
28563When the above example is compiled with the static model, an elaboration
28564circularity arises:
28565
28566@example
28567error: elaboration circularity detected
28568info:    "decls (body)" must be elaborated before "decls (body)"
28569info:       reason: implicit Elaborate_All in unit "decls (body)"
28570info:       recompile "decls (body)" with -gnatel for full details
28571info:          "decls (body)"
28572info:             must be elaborated along with its spec:
28573info:          "decls (spec)"
28574info:             which is withed by:
28575info:          "utils (spec)"
28576info:             which is withed by:
28577info:          "decls (body)"
28578@end example
28579
28580In the above example, @code{Decls} must be elaborated prior to @code{Main} by virtue
28581of a with clause. The elaboration of @code{Decls} activates task @code{Lib_Task}. The
28582static model conservatibely assumes that all code within the body of
28583@code{Lib_Task} is executed, and generates an implicit @code{Elaborate_All} pragma
28584for @code{Units} due to the call to @code{Utils.Put_Val}. The pragma implies that
28585both the spec and body of @code{Utils}, along with any units they @emph{with},
28586must be elaborated prior to @code{Decls}. However, @code{Utils}'s spec @emph{with}s
28587@code{Decls}, implying that @code{Decls} must be elaborated before @code{Utils}. The end
28588result is that @code{Utils} must be elaborated prior to @code{Utils}, and this
28589leads to a circularity.
28590
28591In reality, the example above will not exhibit an ABE problem at run time.
28592When the body of task @code{Lib_Task} is activated, execution will wait for entry
28593@code{Start} to be accepted, and the call to @code{Utils.Put_Val} will not take place
28594at elaboration time. Task @code{Lib_Task} will resume its execution after the main
28595program is executed because @code{Main} performs a rendezvous with
28596@code{Lib_Task.Start}, and at that point all units have already been elaborated.
28597As a result, the static model may seem overly conservative, partly because it
28598does not take control and data flow into account.
28599
28600When faced with a task elaboration circularity, a programmer has several
28601options available:
28602
28603
28604@itemize *
28605
28606@item
28607@emph{Use the dynamic model}
28608
28609The dynamic model does not generate implicit @code{Elaborate} and
28610@code{Elaborate_All} pragmas. Instead, it will install checks prior to every
28611call in the example above, thus verifying the successful elaboration of
28612@code{Utils.Put_Val} in case the call to it takes place at elaboration time.
28613The dynamic model is enabled with compiler switch @code{-gnatE}.
28614
28615@item
28616@emph{Isolate the tasks}
28617
28618Relocating tasks in their own separate package could decouple them from
28619dependencies that would otherwise cause an elaboration circularity. The
28620example above can be rewritten as follows:
28621
28622@example
28623package Decls1 is                --  new
28624   task Lib_Task is
28625      entry Start;
28626   end Lib_Task;
28627end Decls1;
28628@end example
28629
28630@example
28631with Utils;
28632package body Decls1 is           --  new
28633   task body Lib_Task is
28634   begin
28635      accept Start;
28636      Utils.Put_Val (2);
28637   end Lib_Task;
28638end Decls1;
28639@end example
28640
28641@example
28642package Decls2 is                --  new
28643   type My_Int is new Integer;
28644   function Ident (M : My_Int) return My_Int;
28645end Decls2;
28646@end example
28647
28648@example
28649with Utils;
28650package body Decls2 is           --  new
28651   function Ident (M : My_Int) return My_Int is
28652   begin
28653      return M;
28654   end Ident;
28655end Decls2;
28656@end example
28657
28658@example
28659with Decls2;
28660package Utils is
28661   procedure Put_Val (Arg : Decls2.My_Int);
28662end Utils;
28663@end example
28664
28665@example
28666with Ada.Text_IO; use Ada.Text_IO;
28667package body Utils is
28668   procedure Put_Val (Arg : Decls2.My_Int) is
28669   begin
28670      Put_Line (Arg'Img);
28671   end Put_Val;
28672end Utils;
28673@end example
28674
28675@example
28676with Decls1;
28677procedure Main is
28678begin
28679   Decls1.Lib_Task.Start;
28680end Main;
28681@end example
28682
28683@item
28684@emph{Declare the tasks}
28685
28686The original example uses a single task declaration for @code{Lib_Task}. An
28687explicit task type declaration and a properly placed task object could avoid
28688the dependencies that would otherwise cause an elaboration circularity. The
28689example can be rewritten as follows:
28690
28691@example
28692package Decls is
28693   task type Lib_Task is         --  new
28694      entry Start;
28695   end Lib_Task;
28696
28697   type My_Int is new Integer;
28698
28699   function Ident (M : My_Int) return My_Int;
28700end Decls;
28701@end example
28702
28703@example
28704with Utils;
28705package body Decls is
28706   task body Lib_Task is
28707   begin
28708      accept Start;
28709      Utils.Put_Val (2);
28710   end Lib_Task;
28711
28712   function Ident (M : My_Int) return My_Int is
28713   begin
28714      return M;
28715   end Ident;
28716end Decls;
28717@end example
28718
28719@example
28720with Decls;
28721package Utils is
28722   procedure Put_Val (Arg : Decls.My_Int);
28723end Utils;
28724@end example
28725
28726@example
28727with Ada.Text_IO; use Ada.Text_IO;
28728package body Utils is
28729   procedure Put_Val (Arg : Decls.My_Int) is
28730   begin
28731      Put_Line (Arg'Img);
28732   end Put_Val;
28733end Utils;
28734@end example
28735
28736@example
28737with Decls;
28738package Obj_Decls is             --  new
28739   Task_Obj : Decls.Lib_Task;
28740end Obj_Decls;
28741@end example
28742
28743@example
28744with Obj_Decls;
28745procedure Main is
28746begin
28747   Obj_Decls.Task_Obj.Start;     --  new
28748end Main;
28749@end example
28750
28751@item
28752@emph{Use restriction No_Entry_Calls_In_Elaboration_Code}
28753
28754The issue exhibited in the original example under this section revolves
28755around the body of @code{Lib_Task} blocking on an accept statement. There is
28756no rule to prevent elaboration code from performing entry calls, however in
28757practice this is highly unusual. In addition, the pattern of starting tasks
28758at elaboration time and then immediately blocking on accept or select
28759statements is quite common.
28760
28761If a programmer knows that elaboration code will not perform any entry
28762calls, then the programmer can indicate that the static model should not
28763process the remainder of a task body once an accept or select statement has
28764been encountered. This behavior can be specified by a configuration pragma:
28765
28766@example
28767pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28768@end example
28769
28770In addition to the change in behavior with respect to task bodies, the
28771static model will verify that no entry calls take place at elaboration time.
28772@end itemize
28773
28774@node Elaboration-related Compiler Switches,Summary of Procedures for Elaboration Control,Resolving Task Issues,Elaboration Order Handling in GNAT
28775@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-related-compiler-switches}@anchor{247}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id15}@anchor{248}
28776@section Elaboration-related Compiler Switches
28777
28778
28779GNAT has several switches that affect the elaboration model and consequently
28780the elaboration order chosen by the binder.
28781
28782@geindex -gnatE (gnat)
28783
28784
28785@table @asis
28786
28787@item @code{-gnatE}
28788
28789Dynamic elaboration checking mode enabled
28790
28791When this switch is in effect, GNAT activates the dynamic elaboration model.
28792@end table
28793
28794@geindex -gnatel (gnat)
28795
28796
28797@table @asis
28798
28799@item @code{-gnatel}
28800
28801Turn on info messages on generated Elaborate[_All] pragmas
28802
28803When this switch is in effect, GNAT will emit the following supplementary
28804information depending on the elaboration model in effect.
28805
28806
28807@itemize -
28808
28809@item
28810@emph{Dynamic model}
28811
28812GNAT will indicate missing @code{Elaborate} and @code{Elaborate_All} pragmas for
28813all library-level scenarios within the partition.
28814
28815@item
28816@emph{Static model}
28817
28818GNAT will indicate all scenarios executed during elaboration. In addition,
28819it will provide detailed traceback when an implicit @code{Elaborate} or
28820@code{Elaborate_All} pragma is generated.
28821
28822@item
28823@emph{SPARK model}
28824
28825GNAT will indicate how an elaboration requirement is met by the context of
28826a unit. This diagnostic requires compiler switch @code{-gnatd.v}.
28827
28828@example
288291. with Server; pragma Elaborate_All (Server);
288302. package Client with SPARK_Mode is
288313.    Val : constant Integer := Server.Func;
28832                                      |
28833   >>> info: call to "Func" during elaboration in SPARK
28834   >>> info: "Elaborate_All" requirement for unit "Server" met by pragma at line 1
28835
288364. end Client;
28837@end example
28838@end itemize
28839@end table
28840
28841@geindex -gnatH (gnat)
28842
28843
28844@table @asis
28845
28846@item @code{-gnatH}
28847
28848Legacy elaboration checking mode enabled
28849
28850When this switch is in effect, GNAT will utilize the pre-18.x elaboration
28851model.
28852@end table
28853
28854@geindex -gnatJ (gnat)
28855
28856
28857@table @asis
28858
28859@item @code{-gnatJ}
28860
28861Relaxed elaboration checking mode enabled
28862
28863When this switch is in effect, GNAT will not process certain scenarios,
28864resulting in a more permissive elaboration model. Note that this may
28865eliminate some diagnostics and run-time checks.
28866@end table
28867
28868@geindex -gnatw.f (gnat)
28869
28870
28871@table @asis
28872
28873@item @code{-gnatw.f}
28874
28875Turn on warnings for suspicious Subp'Access
28876
28877When this switch is in effect, GNAT will treat @code{'Access} of an entry,
28878operator, or subprogram as a potential call to the target and issue warnings:
28879
28880@example
28881 1. package body Attribute_Call is
28882 2.    function Func return Integer;
28883 3.    type Func_Ptr is access function return Integer;
28884 4.
28885 5.    Ptr : constant Func_Ptr := Func'Access;
28886                                      |
28887    >>> warning: "Access" attribute of "Func" before body seen
28888    >>> warning: possible Program_Error on later references
28889    >>> warning:   body of unit "Attribute_Call" elaborated
28890    >>> warning:   "Access" of "Func" taken at line 5
28891
28892 6.
28893 7.    function Func return Integer is
28894 8.    begin
28895 9.       ...
2889610.    end Func;
2889711. end Attribute_Call;
28898@end example
28899
28900In the example above, the elaboration of declaration @code{Ptr} is assigned
28901@code{Func'Access} before the body of @code{Func} has been elaborated.
28902@end table
28903
28904@geindex -gnatwl (gnat)
28905
28906
28907@table @asis
28908
28909@item @code{-gnatwl}
28910
28911Turn on warnings for elaboration problems
28912
28913When this switch is in effect, GNAT emits diagnostics in the form of warnings
28914concerning various elaboration problems. The warnings are enabled by default.
28915The switch is provided in case all warnings are suppressed, but elaboration
28916warnings are still desired.
28917
28918@item @code{-gnatwL}
28919
28920Turn off warnings for elaboration problems
28921
28922When this switch is in effect, GNAT no longer emits any diagnostics in the
28923form of warnings. Selective suppression of elaboration problems is possible
28924using @code{pragma Warnings (Off)}.
28925
28926@example
28927 1. package body Selective_Suppression is
28928 2.    function ABE return Integer;
28929 3.
28930 4.    Val_1 : constant Integer := ABE;
28931                                   |
28932    >>> warning: cannot call "ABE" before body seen
28933    >>> warning: Program_Error will be raised at run time
28934
28935 5.
28936 6.    pragma Warnings (Off);
28937 7.    Val_2 : constant Integer := ABE;
28938 8.    pragma Warnings (On);
28939 9.
2894010.    function ABE return Integer is
2894111.    begin
2894212.       ...
2894313.    end ABE;
2894414. end Selective_Suppression;
28945@end example
28946
28947Note that suppressing elaboration warnings does not eliminate run-time
28948checks. The example above will still fail at run time with an ABE.
28949@end table
28950
28951@node Summary of Procedures for Elaboration Control,Inspecting the Chosen Elaboration Order,Elaboration-related Compiler Switches,Elaboration Order Handling in GNAT
28952@anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{249}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id16}@anchor{24a}
28953@section Summary of Procedures for Elaboration Control
28954
28955
28956A programmer should first compile the program with the default options, using
28957none of the binder or compiler switches. If the binder succeeds in finding an
28958elaboration order, then apart from possible cases involing dispatching calls
28959and access-to-subprogram types, the program is free of elaboration errors.
28960
28961If it is important for the program to be portable to compilers other than GNAT,
28962then the programmer should use compiler switch @code{-gnatel} and consider
28963the messages about missing or implicitly created @code{Elaborate} and
28964@code{Elaborate_All} pragmas.
28965
28966If the binder reports an elaboration circularity, the programmer has several
28967options:
28968
28969
28970@itemize *
28971
28972@item
28973Ensure that elaboration warnings are enabled. This will allow the static
28974model to output trace information of elaboration issues. The trace
28975information could shed light on previously unforeseen dependencies, as well
28976as their origins. Elaboration warnings are enabled with compiler switch
28977@code{-gnatwl}.
28978
28979@item
28980Use switch @code{-gnatel} to obtain messages on generated implicit
28981@code{Elaborate} and @code{Elaborate_All} pragmas. The trace information could
28982indicate why a server unit must be elaborated prior to a client unit.
28983
28984@item
28985If the warnings produced by the static model indicate that a task is
28986involved, consider the options in section @ref{245,,Resolving Task Issues}.
28987
28988@item
28989If none of the steps outlined above resolve the circularity, use a more
28990permissive elaboration model, in the following order:
28991
28992
28993@itemize -
28994
28995@item
28996Use the dynamic elaboration model, with compiler switch @code{-gnatE}.
28997
28998@item
28999Use the legacy static elaboration model, with compiler switch
29000@code{-gnatH}.
29001
29002@item
29003Use the legacy dynamic elaboration model, with compiler switches
29004@code{-gnatH} @code{-gnatE}.
29005
29006@item
29007Use the relaxed legacy static elaboration model, with compiler switches
29008@code{-gnatH} @code{-gnatJ}.
29009
29010@item
29011Use the relaxed legacy dynamic elaboration model, with compiler switches
29012@code{-gnatH} @code{-gnatJ} @code{-gnatE}.
29013@end itemize
29014@end itemize
29015
29016@node Inspecting the Chosen Elaboration Order,,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
29017@anchor{gnat_ugn/elaboration_order_handling_in_gnat inspecting-the-chosen-elaboration-order}@anchor{24b}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id17}@anchor{24c}
29018@section Inspecting the Chosen Elaboration Order
29019
29020
29021To see the elaboration order chosen by the binder, inspect the contents of file
29022@cite{b~xxx.adb}. On certain targets, this file appears as @cite{b_xxx.adb}. The
29023elaboration order appears as a sequence of calls to @code{Elab_Body} and
29024@code{Elab_Spec}, interspersed with assignments to @cite{Exxx} which indicates that a
29025particular unit is elaborated. For example:
29026
29027@example
29028System.Soft_Links'Elab_Body;
29029E14 := True;
29030System.Secondary_Stack'Elab_Body;
29031E18 := True;
29032System.Exception_Table'Elab_Body;
29033E24 := True;
29034Ada.Io_Exceptions'Elab_Spec;
29035E67 := True;
29036Ada.Tags'Elab_Spec;
29037Ada.Streams'Elab_Spec;
29038E43 := True;
29039Interfaces.C'Elab_Spec;
29040E69 := True;
29041System.Finalization_Root'Elab_Spec;
29042E60 := True;
29043System.Os_Lib'Elab_Body;
29044E71 := True;
29045System.Finalization_Implementation'Elab_Spec;
29046System.Finalization_Implementation'Elab_Body;
29047E62 := True;
29048Ada.Finalization'Elab_Spec;
29049E58 := True;
29050Ada.Finalization.List_Controller'Elab_Spec;
29051E76 := True;
29052System.File_Control_Block'Elab_Spec;
29053E74 := True;
29054System.File_Io'Elab_Body;
29055E56 := True;
29056Ada.Tags'Elab_Body;
29057E45 := True;
29058Ada.Text_Io'Elab_Spec;
29059Ada.Text_Io'Elab_Body;
29060E07 := True;
29061@end example
29062
29063Note also binder switch @code{-l}, which outputs the chosen elaboration
29064order and provides a more readable form of the above:
29065
29066@example
29067ada (spec)
29068interfaces (spec)
29069system (spec)
29070system.case_util (spec)
29071system.case_util (body)
29072system.concat_2 (spec)
29073system.concat_2 (body)
29074system.concat_3 (spec)
29075system.concat_3 (body)
29076system.htable (spec)
29077system.parameters (spec)
29078system.parameters (body)
29079system.crtl (spec)
29080interfaces.c_streams (spec)
29081interfaces.c_streams (body)
29082system.restrictions (spec)
29083system.restrictions (body)
29084system.standard_library (spec)
29085system.exceptions (spec)
29086system.exceptions (body)
29087system.storage_elements (spec)
29088system.storage_elements (body)
29089system.secondary_stack (spec)
29090system.stack_checking (spec)
29091system.stack_checking (body)
29092system.string_hash (spec)
29093system.string_hash (body)
29094system.htable (body)
29095system.strings (spec)
29096system.strings (body)
29097system.traceback (spec)
29098system.traceback (body)
29099system.traceback_entries (spec)
29100system.traceback_entries (body)
29101ada.exceptions (spec)
29102ada.exceptions.last_chance_handler (spec)
29103system.soft_links (spec)
29104system.soft_links (body)
29105ada.exceptions.last_chance_handler (body)
29106system.secondary_stack (body)
29107system.exception_table (spec)
29108system.exception_table (body)
29109ada.io_exceptions (spec)
29110ada.tags (spec)
29111ada.streams (spec)
29112interfaces.c (spec)
29113interfaces.c (body)
29114system.finalization_root (spec)
29115system.finalization_root (body)
29116system.memory (spec)
29117system.memory (body)
29118system.standard_library (body)
29119system.os_lib (spec)
29120system.os_lib (body)
29121system.unsigned_types (spec)
29122system.stream_attributes (spec)
29123system.stream_attributes (body)
29124system.finalization_implementation (spec)
29125system.finalization_implementation (body)
29126ada.finalization (spec)
29127ada.finalization (body)
29128ada.finalization.list_controller (spec)
29129ada.finalization.list_controller (body)
29130system.file_control_block (spec)
29131system.file_io (spec)
29132system.file_io (body)
29133system.val_uns (spec)
29134system.val_util (spec)
29135system.val_util (body)
29136system.val_uns (body)
29137system.wch_con (spec)
29138system.wch_con (body)
29139system.wch_cnv (spec)
29140system.wch_jis (spec)
29141system.wch_jis (body)
29142system.wch_cnv (body)
29143system.wch_stw (spec)
29144system.wch_stw (body)
29145ada.tags (body)
29146ada.exceptions (body)
29147ada.text_io (spec)
29148ada.text_io (body)
29149text_io (spec)
29150gdbstr (body)
29151@end example
29152
29153@node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
29154@anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{10}@anchor{gnat_ugn/inline_assembler doc}@anchor{24d}@anchor{gnat_ugn/inline_assembler id1}@anchor{24e}
29155@chapter Inline Assembler
29156
29157
29158@geindex Inline Assembler
29159
29160If you need to write low-level software that interacts directly
29161with the hardware, Ada provides two ways to incorporate assembly
29162language code into your program.  First, you can import and invoke
29163external routines written in assembly language, an Ada feature fully
29164supported by GNAT.  However, for small sections of code it may be simpler
29165or more efficient to include assembly language statements directly
29166in your Ada source program, using the facilities of the implementation-defined
29167package @code{System.Machine_Code}, which incorporates the gcc
29168Inline Assembler.  The Inline Assembler approach offers a number of advantages,
29169including the following:
29170
29171
29172@itemize *
29173
29174@item
29175No need to use non-Ada tools
29176
29177@item
29178Consistent interface over different targets
29179
29180@item
29181Automatic usage of the proper calling conventions
29182
29183@item
29184Access to Ada constants and variables
29185
29186@item
29187Definition of intrinsic routines
29188
29189@item
29190Possibility of inlining a subprogram comprising assembler code
29191
29192@item
29193Code optimizer can take Inline Assembler code into account
29194@end itemize
29195
29196This appendix presents a series of examples to show you how to use
29197the Inline Assembler.  Although it focuses on the Intel x86,
29198the general approach applies also to other processors.
29199It is assumed that you are familiar with Ada
29200and with assembly language programming.
29201
29202@menu
29203* Basic Assembler Syntax::
29204* A Simple Example of Inline Assembler::
29205* Output Variables in Inline Assembler::
29206* Input Variables in Inline Assembler::
29207* Inlining Inline Assembler Code::
29208* Other Asm Functionality::
29209
29210@end menu
29211
29212@node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
29213@anchor{gnat_ugn/inline_assembler id2}@anchor{24f}@anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{250}
29214@section Basic Assembler Syntax
29215
29216
29217The assembler used by GNAT and gcc is based not on the Intel assembly
29218language, but rather on a language that descends from the AT&T Unix
29219assembler @code{as} (and which is often referred to as 'AT&T syntax').
29220The following table summarizes the main features of @code{as} syntax
29221and points out the differences from the Intel conventions.
29222See the gcc @code{as} and @code{gas} (an @code{as} macro
29223pre-processor) documentation for further information.
29224
29225
29226@display
29227@emph{Register names}@w{ }
29228@display
29229gcc / @code{as}: Prefix with '%'; for example @code{%eax}@w{ }
29230Intel: No extra punctuation; for example @code{eax}@w{ }
29231@end display
29232@end display
29233
29234
29235
29236
29237@display
29238@emph{Immediate operand}@w{ }
29239@display
29240gcc / @code{as}: Prefix with '$'; for example @code{$4}@w{ }
29241Intel: No extra punctuation; for example @code{4}@w{ }
29242@end display
29243@end display
29244
29245
29246
29247
29248@display
29249@emph{Address}@w{ }
29250@display
29251gcc / @code{as}: Prefix with '$'; for example @code{$loc}@w{ }
29252Intel: No extra punctuation; for example @code{loc}@w{ }
29253@end display
29254@end display
29255
29256
29257
29258
29259@display
29260@emph{Memory contents}@w{ }
29261@display
29262gcc / @code{as}: No extra punctuation; for example @code{loc}@w{ }
29263Intel: Square brackets; for example @code{[loc]}@w{ }
29264@end display
29265@end display
29266
29267
29268
29269
29270@display
29271@emph{Register contents}@w{ }
29272@display
29273gcc / @code{as}: Parentheses; for example @code{(%eax)}@w{ }
29274Intel: Square brackets; for example @code{[eax]}@w{ }
29275@end display
29276@end display
29277
29278
29279
29280
29281@display
29282@emph{Hexadecimal numbers}@w{ }
29283@display
29284gcc / @code{as}: Leading '0x' (C language syntax); for example @code{0xA0}@w{ }
29285Intel: Trailing 'h'; for example @code{A0h}@w{ }
29286@end display
29287@end display
29288
29289
29290
29291
29292@display
29293@emph{Operand size}@w{ }
29294@display
29295gcc / @code{as}: Explicit in op code; for example @code{movw} to move a 16-bit word@w{ }
29296Intel: Implicit, deduced by assembler; for example @code{mov}@w{ }
29297@end display
29298@end display
29299
29300
29301
29302
29303@display
29304@emph{Instruction repetition}@w{ }
29305@display
29306gcc / @code{as}: Split into two lines; for example@w{ }
29307@display
29308@code{rep}@w{ }
29309@code{stosl}@w{ }
29310@end display
29311Intel: Keep on one line; for example @code{rep stosl}@w{ }
29312@end display
29313@end display
29314
29315
29316
29317
29318@display
29319@emph{Order of operands}@w{ }
29320@display
29321gcc / @code{as}: Source first; for example @code{movw $4, %eax}@w{ }
29322Intel: Destination first; for example @code{mov eax, 4}@w{ }
29323@end display
29324@end display
29325
29326
29327
29328@node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
29329@anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{251}@anchor{gnat_ugn/inline_assembler id3}@anchor{252}
29330@section A Simple Example of Inline Assembler
29331
29332
29333The following example will generate a single assembly language statement,
29334@code{nop}, which does nothing.  Despite its lack of run-time effect,
29335the example will be useful in illustrating the basics of
29336the Inline Assembler facility.
29337
29338@quotation
29339
29340@example
29341with System.Machine_Code; use System.Machine_Code;
29342procedure Nothing is
29343begin
29344   Asm ("nop");
29345end Nothing;
29346@end example
29347@end quotation
29348
29349@code{Asm} is a procedure declared in package @code{System.Machine_Code};
29350here it takes one parameter, a @emph{template string} that must be a static
29351expression and that will form the generated instruction.
29352@code{Asm} may be regarded as a compile-time procedure that parses
29353the template string and additional parameters (none here),
29354from which it generates a sequence of assembly language instructions.
29355
29356The examples in this chapter will illustrate several of the forms
29357for invoking @code{Asm}; a complete specification of the syntax
29358is found in the @code{Machine_Code_Insertions} section of the
29359@cite{GNAT Reference Manual}.
29360
29361Under the standard GNAT conventions, the @code{Nothing} procedure
29362should be in a file named @code{nothing.adb}.
29363You can build the executable in the usual way:
29364
29365@quotation
29366
29367@example
29368$ gnatmake nothing
29369@end example
29370@end quotation
29371
29372However, the interesting aspect of this example is not its run-time behavior
29373but rather the generated assembly code.
29374To see this output, invoke the compiler as follows:
29375
29376@quotation
29377
29378@example
29379$  gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
29380@end example
29381@end quotation
29382
29383where the options are:
29384
29385
29386@itemize *
29387
29388@item
29389
29390@table @asis
29391
29392@item @code{-c}
29393
29394compile only (no bind or link)
29395@end table
29396
29397@item
29398
29399@table @asis
29400
29401@item @code{-S}
29402
29403generate assembler listing
29404@end table
29405
29406@item
29407
29408@table @asis
29409
29410@item @code{-fomit-frame-pointer}
29411
29412do not set up separate stack frames
29413@end table
29414
29415@item
29416
29417@table @asis
29418
29419@item @code{-gnatp}
29420
29421do not add runtime checks
29422@end table
29423@end itemize
29424
29425This gives a human-readable assembler version of the code. The resulting
29426file will have the same name as the Ada source file, but with a @code{.s}
29427extension. In our example, the file @code{nothing.s} has the following
29428contents:
29429
29430@quotation
29431
29432@example
29433.file "nothing.adb"
29434gcc2_compiled.:
29435___gnu_compiled_ada:
29436.text
29437   .align 4
29438.globl __ada_nothing
29439__ada_nothing:
29440#APP
29441   nop
29442#NO_APP
29443   jmp L1
29444   .align 2,0x90
29445L1:
29446   ret
29447@end example
29448@end quotation
29449
29450The assembly code you included is clearly indicated by
29451the compiler, between the @code{#APP} and @code{#NO_APP}
29452delimiters. The character before the 'APP' and 'NOAPP'
29453can differ on different targets. For example, GNU/Linux uses '#APP' while
29454on NT you will see '/APP'.
29455
29456If you make a mistake in your assembler code (such as using the
29457wrong size modifier, or using a wrong operand for the instruction) GNAT
29458will report this error in a temporary file, which will be deleted when
29459the compilation is finished.  Generating an assembler file will help
29460in such cases, since you can assemble this file separately using the
29461@code{as} assembler that comes with gcc.
29462
29463Assembling the file using the command
29464
29465@quotation
29466
29467@example
29468$ as nothing.s
29469@end example
29470@end quotation
29471
29472will give you error messages whose lines correspond to the assembler
29473input file, so you can easily find and correct any mistakes you made.
29474If there are no errors, @code{as} will generate an object file
29475@code{nothing.out}.
29476
29477@node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
29478@anchor{gnat_ugn/inline_assembler id4}@anchor{253}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{254}
29479@section Output Variables in Inline Assembler
29480
29481
29482The examples in this section, showing how to access the processor flags,
29483illustrate how to specify the destination operands for assembly language
29484statements.
29485
29486@quotation
29487
29488@example
29489with Interfaces; use Interfaces;
29490with Ada.Text_IO; use Ada.Text_IO;
29491with System.Machine_Code; use System.Machine_Code;
29492procedure Get_Flags is
29493   Flags : Unsigned_32;
29494   use ASCII;
29495begin
29496   Asm ("pushfl"          & LF & HT & -- push flags on stack
29497        "popl %%eax"      & LF & HT & -- load eax with flags
29498        "movl %%eax, %0",             -- store flags in variable
29499        Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29500   Put_Line ("Flags register:" & Flags'Img);
29501end Get_Flags;
29502@end example
29503@end quotation
29504
29505In order to have a nicely aligned assembly listing, we have separated
29506multiple assembler statements in the Asm template string with linefeed
29507(ASCII.LF) and horizontal tab (ASCII.HT) characters.
29508The resulting section of the assembly output file is:
29509
29510@quotation
29511
29512@example
29513#APP
29514   pushfl
29515   popl %eax
29516   movl %eax, -40(%ebp)
29517#NO_APP
29518@end example
29519@end quotation
29520
29521It would have been legal to write the Asm invocation as:
29522
29523@quotation
29524
29525@example
29526Asm ("pushfl popl %%eax movl %%eax, %0")
29527@end example
29528@end quotation
29529
29530but in the generated assembler file, this would come out as:
29531
29532@quotation
29533
29534@example
29535#APP
29536   pushfl popl %eax movl %eax, -40(%ebp)
29537#NO_APP
29538@end example
29539@end quotation
29540
29541which is not so convenient for the human reader.
29542
29543We use Ada comments
29544at the end of each line to explain what the assembler instructions
29545actually do.  This is a useful convention.
29546
29547When writing Inline Assembler instructions, you need to precede each register
29548and variable name with a percent sign.  Since the assembler already requires
29549a percent sign at the beginning of a register name, you need two consecutive
29550percent signs for such names in the Asm template string, thus @code{%%eax}.
29551In the generated assembly code, one of the percent signs will be stripped off.
29552
29553Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29554variables: operands you later define using @code{Input} or @code{Output}
29555parameters to @code{Asm}.
29556An output variable is illustrated in
29557the third statement in the Asm template string:
29558
29559@quotation
29560
29561@example
29562movl %%eax, %0
29563@end example
29564@end quotation
29565
29566The intent is to store the contents of the eax register in a variable that can
29567be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
29568necessarily work, since the compiler might optimize by using a register
29569to hold Flags, and the expansion of the @code{movl} instruction would not be
29570aware of this optimization.  The solution is not to store the result directly
29571but rather to advise the compiler to choose the correct operand form;
29572that is the purpose of the @code{%0} output variable.
29573
29574Information about the output variable is supplied in the @code{Outputs}
29575parameter to @code{Asm}:
29576
29577@quotation
29578
29579@example
29580Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29581@end example
29582@end quotation
29583
29584The output is defined by the @code{Asm_Output} attribute of the target type;
29585the general format is
29586
29587@quotation
29588
29589@example
29590Type'Asm_Output (constraint_string, variable_name)
29591@end example
29592@end quotation
29593
29594The constraint string directs the compiler how
29595to store/access the associated variable.  In the example
29596
29597@quotation
29598
29599@example
29600Unsigned_32'Asm_Output ("=m", Flags);
29601@end example
29602@end quotation
29603
29604the @code{"m"} (memory) constraint tells the compiler that the variable
29605@code{Flags} should be stored in a memory variable, thus preventing
29606the optimizer from keeping it in a register.  In contrast,
29607
29608@quotation
29609
29610@example
29611Unsigned_32'Asm_Output ("=r", Flags);
29612@end example
29613@end quotation
29614
29615uses the @code{"r"} (register) constraint, telling the compiler to
29616store the variable in a register.
29617
29618If the constraint is preceded by the equal character '=', it tells
29619the compiler that the variable will be used to store data into it.
29620
29621In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29622allowing the optimizer to choose whatever it deems best.
29623
29624There are a fairly large number of constraints, but the ones that are
29625most useful (for the Intel x86 processor) are the following:
29626
29627@quotation
29628
29629
29630@multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
29631@item
29632
29633@emph{=}
29634
29635@tab
29636
29637output constraint
29638
29639@item
29640
29641@emph{g}
29642
29643@tab
29644
29645global (i.e., can be stored anywhere)
29646
29647@item
29648
29649@emph{m}
29650
29651@tab
29652
29653in memory
29654
29655@item
29656
29657@emph{I}
29658
29659@tab
29660
29661a constant
29662
29663@item
29664
29665@emph{a}
29666
29667@tab
29668
29669use eax
29670
29671@item
29672
29673@emph{b}
29674
29675@tab
29676
29677use ebx
29678
29679@item
29680
29681@emph{c}
29682
29683@tab
29684
29685use ecx
29686
29687@item
29688
29689@emph{d}
29690
29691@tab
29692
29693use edx
29694
29695@item
29696
29697@emph{S}
29698
29699@tab
29700
29701use esi
29702
29703@item
29704
29705@emph{D}
29706
29707@tab
29708
29709use edi
29710
29711@item
29712
29713@emph{r}
29714
29715@tab
29716
29717use one of eax, ebx, ecx or edx
29718
29719@item
29720
29721@emph{q}
29722
29723@tab
29724
29725use one of eax, ebx, ecx, edx, esi or edi
29726
29727@end multitable
29728
29729@end quotation
29730
29731The full set of constraints is described in the gcc and @code{as}
29732documentation; note that it is possible to combine certain constraints
29733in one constraint string.
29734
29735You specify the association of an output variable with an assembler operand
29736through the @code{%@emph{n}} notation, where @emph{n} is a non-negative
29737integer.  Thus in
29738
29739@quotation
29740
29741@example
29742Asm ("pushfl"          & LF & HT & -- push flags on stack
29743     "popl %%eax"      & LF & HT & -- load eax with flags
29744     "movl %%eax, %0",             -- store flags in variable
29745     Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29746@end example
29747@end quotation
29748
29749@code{%0} will be replaced in the expanded code by the appropriate operand,
29750whatever
29751the compiler decided for the @code{Flags} variable.
29752
29753In general, you may have any number of output variables:
29754
29755
29756@itemize *
29757
29758@item
29759Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
29760
29761@item
29762Specify the @code{Outputs} parameter as a parenthesized comma-separated list
29763of @code{Asm_Output} attributes
29764@end itemize
29765
29766For example:
29767
29768@quotation
29769
29770@example
29771Asm ("movl %%eax, %0" & LF & HT &
29772     "movl %%ebx, %1" & LF & HT &
29773     "movl %%ecx, %2",
29774     Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
29775                 Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
29776                 Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
29777@end example
29778@end quotation
29779
29780where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
29781in the Ada program.
29782
29783As a variation on the @code{Get_Flags} example, we can use the constraints
29784string to direct the compiler to store the eax register into the @code{Flags}
29785variable, instead of including the store instruction explicitly in the
29786@code{Asm} template string:
29787
29788@quotation
29789
29790@example
29791with Interfaces; use Interfaces;
29792with Ada.Text_IO; use Ada.Text_IO;
29793with System.Machine_Code; use System.Machine_Code;
29794procedure Get_Flags_2 is
29795   Flags : Unsigned_32;
29796   use ASCII;
29797begin
29798   Asm ("pushfl"      & LF & HT & -- push flags on stack
29799        "popl %%eax",             -- save flags in eax
29800        Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29801   Put_Line ("Flags register:" & Flags'Img);
29802end Get_Flags_2;
29803@end example
29804@end quotation
29805
29806The @code{"a"} constraint tells the compiler that the @code{Flags}
29807variable will come from the eax register. Here is the resulting code:
29808
29809@quotation
29810
29811@example
29812#APP
29813   pushfl
29814   popl %eax
29815#NO_APP
29816   movl %eax,-40(%ebp)
29817@end example
29818@end quotation
29819
29820The compiler generated the store of eax into Flags after
29821expanding the assembler code.
29822
29823Actually, there was no need to pop the flags into the eax register;
29824more simply, we could just pop the flags directly into the program variable:
29825
29826@quotation
29827
29828@example
29829with Interfaces; use Interfaces;
29830with Ada.Text_IO; use Ada.Text_IO;
29831with System.Machine_Code; use System.Machine_Code;
29832procedure Get_Flags_3 is
29833   Flags : Unsigned_32;
29834   use ASCII;
29835begin
29836   Asm ("pushfl"  & LF & HT & -- push flags on stack
29837        "pop %0",             -- save flags in Flags
29838        Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29839   Put_Line ("Flags register:" & Flags'Img);
29840end Get_Flags_3;
29841@end example
29842@end quotation
29843
29844@node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
29845@anchor{gnat_ugn/inline_assembler id5}@anchor{255}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{256}
29846@section Input Variables in Inline Assembler
29847
29848
29849The example in this section illustrates how to specify the source operands
29850for assembly language statements.
29851The program simply increments its input value by 1:
29852
29853@quotation
29854
29855@example
29856with Interfaces; use Interfaces;
29857with Ada.Text_IO; use Ada.Text_IO;
29858with System.Machine_Code; use System.Machine_Code;
29859procedure Increment is
29860
29861   function Incr (Value : Unsigned_32) return Unsigned_32 is
29862      Result : Unsigned_32;
29863   begin
29864      Asm ("incl %0",
29865           Outputs => Unsigned_32'Asm_Output ("=a", Result),
29866           Inputs  => Unsigned_32'Asm_Input ("a", Value));
29867      return Result;
29868   end Incr;
29869
29870   Value : Unsigned_32;
29871
29872begin
29873   Value := 5;
29874   Put_Line ("Value before is" & Value'Img);
29875   Value := Incr (Value);
29876  Put_Line ("Value after is" & Value'Img);
29877end Increment;
29878@end example
29879@end quotation
29880
29881The @code{Outputs} parameter to @code{Asm} specifies
29882that the result will be in the eax register and that it is to be stored
29883in the @code{Result} variable.
29884
29885The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
29886but with an @code{Asm_Input} attribute.
29887The @code{"="} constraint, indicating an output value, is not present.
29888
29889You can have multiple input variables, in the same way that you can have more
29890than one output variable.
29891
29892The parameter count (%0, %1) etc, still starts at the first output statement,
29893and continues with the input statements.
29894
29895Just as the @code{Outputs} parameter causes the register to be stored into the
29896target variable after execution of the assembler statements, so does the
29897@code{Inputs} parameter cause its variable to be loaded into the register
29898before execution of the assembler statements.
29899
29900Thus the effect of the @code{Asm} invocation is:
29901
29902
29903@itemize *
29904
29905@item
29906load the 32-bit value of @code{Value} into eax
29907
29908@item
29909execute the @code{incl %eax} instruction
29910
29911@item
29912store the contents of eax into the @code{Result} variable
29913@end itemize
29914
29915The resulting assembler file (with @code{-O2} optimization) contains:
29916
29917@quotation
29918
29919@example
29920_increment__incr.1:
29921   subl $4,%esp
29922   movl 8(%esp),%eax
29923#APP
29924   incl %eax
29925#NO_APP
29926   movl %eax,%edx
29927   movl %ecx,(%esp)
29928   addl $4,%esp
29929   ret
29930@end example
29931@end quotation
29932
29933@node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
29934@anchor{gnat_ugn/inline_assembler id6}@anchor{257}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{258}
29935@section Inlining Inline Assembler Code
29936
29937
29938For a short subprogram such as the @code{Incr} function in the previous
29939section, the overhead of the call and return (creating / deleting the stack
29940frame) can be significant, compared to the amount of code in the subprogram
29941body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
29942which directs the compiler to expand invocations of the subprogram at the
29943point(s) of call, instead of setting up a stack frame for out-of-line calls.
29944Here is the resulting program:
29945
29946@quotation
29947
29948@example
29949with Interfaces; use Interfaces;
29950with Ada.Text_IO; use Ada.Text_IO;
29951with System.Machine_Code; use System.Machine_Code;
29952procedure Increment_2 is
29953
29954   function Incr (Value : Unsigned_32) return Unsigned_32 is
29955      Result : Unsigned_32;
29956   begin
29957      Asm ("incl %0",
29958           Outputs => Unsigned_32'Asm_Output ("=a", Result),
29959           Inputs  => Unsigned_32'Asm_Input ("a", Value));
29960      return Result;
29961   end Incr;
29962   pragma Inline (Increment);
29963
29964   Value : Unsigned_32;
29965
29966begin
29967   Value := 5;
29968   Put_Line ("Value before is" & Value'Img);
29969   Value := Increment (Value);
29970   Put_Line ("Value after is" & Value'Img);
29971end Increment_2;
29972@end example
29973@end quotation
29974
29975Compile the program with both optimization (@code{-O2}) and inlining
29976(@code{-gnatn}) enabled.
29977
29978The @code{Incr} function is still compiled as usual, but at the
29979point in @code{Increment} where our function used to be called:
29980
29981@quotation
29982
29983@example
29984pushl %edi
29985call _increment__incr.1
29986@end example
29987@end quotation
29988
29989the code for the function body directly appears:
29990
29991@quotation
29992
29993@example
29994movl %esi,%eax
29995#APP
29996   incl %eax
29997#NO_APP
29998   movl %eax,%edx
29999@end example
30000@end quotation
30001
30002thus saving the overhead of stack frame setup and an out-of-line call.
30003
30004@node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
30005@anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{259}@anchor{gnat_ugn/inline_assembler id7}@anchor{25a}
30006@section Other @code{Asm} Functionality
30007
30008
30009This section describes two important parameters to the @code{Asm}
30010procedure: @code{Clobber}, which identifies register usage;
30011and @code{Volatile}, which inhibits unwanted optimizations.
30012
30013@menu
30014* The Clobber Parameter::
30015* The Volatile Parameter::
30016
30017@end menu
30018
30019@node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
30020@anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{25b}@anchor{gnat_ugn/inline_assembler id8}@anchor{25c}
30021@subsection The @code{Clobber} Parameter
30022
30023
30024One of the dangers of intermixing assembly language and a compiled language
30025such as Ada is that the compiler needs to be aware of which registers are
30026being used by the assembly code.  In some cases, such as the earlier examples,
30027the constraint string is sufficient to indicate register usage (e.g.,
30028@code{"a"} for
30029the eax register).  But more generally, the compiler needs an explicit
30030identification of the registers that are used by the Inline Assembly
30031statements.
30032
30033Using a register that the compiler doesn't know about
30034could be a side effect of an instruction (like @code{mull}
30035storing its result in both eax and edx).
30036It can also arise from explicit register usage in your
30037assembly code; for example:
30038
30039@quotation
30040
30041@example
30042Asm ("movl %0, %%ebx" & LF & HT &
30043     "movl %%ebx, %1",
30044     Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30045     Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
30046@end example
30047@end quotation
30048
30049where the compiler (since it does not analyze the @code{Asm} template string)
30050does not know you are using the ebx register.
30051
30052In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30053to identify the registers that will be used by your assembly code:
30054
30055@quotation
30056
30057@example
30058Asm ("movl %0, %%ebx" & LF & HT &
30059     "movl %%ebx, %1",
30060     Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30061     Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30062     Clobber => "ebx");
30063@end example
30064@end quotation
30065
30066The Clobber parameter is a static string expression specifying the
30067register(s) you are using.  Note that register names are @emph{not} prefixed
30068by a percent sign. Also, if more than one register is used then their names
30069are separated by commas; e.g., @code{"eax, ebx"}
30070
30071The @code{Clobber} parameter has several additional uses:
30072
30073
30074@itemize *
30075
30076@item
30077Use 'register' name @code{cc} to indicate that flags might have changed
30078
30079@item
30080Use 'register' name @code{memory} if you changed a memory location
30081@end itemize
30082
30083@node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
30084@anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{25d}@anchor{gnat_ugn/inline_assembler id9}@anchor{25e}
30085@subsection The @code{Volatile} Parameter
30086
30087
30088@geindex Volatile parameter
30089
30090Compiler optimizations in the presence of Inline Assembler may sometimes have
30091unwanted effects.  For example, when an @code{Asm} invocation with an input
30092variable is inside a loop, the compiler might move the loading of the input
30093variable outside the loop, regarding it as a one-time initialization.
30094
30095If this effect is not desired, you can disable such optimizations by setting
30096the @code{Volatile} parameter to @code{True}; for example:
30097
30098@quotation
30099
30100@example
30101Asm ("movl %0, %%ebx" & LF & HT &
30102     "movl %%ebx, %1",
30103     Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
30104     Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
30105     Clobber  => "ebx",
30106     Volatile => True);
30107@end example
30108@end quotation
30109
30110By default, @code{Volatile} is set to @code{False} unless there is no
30111@code{Outputs} parameter.
30112
30113Although setting @code{Volatile} to @code{True} prevents unwanted
30114optimizations, it will also disable other optimizations that might be
30115important for efficiency. In general, you should set @code{Volatile}
30116to @code{True} only if the compiler's optimizations have created
30117problems.
30118
30119@node GNU Free Documentation License,Index,Inline Assembler,Top
30120@anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license doc}@anchor{25f}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{260}
30121@chapter GNU Free Documentation License
30122
30123
30124Version 1.3, 3 November 2008
30125
30126Copyright  2000, 2001, 2002, 2007, 2008  Free Software Foundation, Inc
30127@indicateurl{http://fsf.org/}
30128
30129Everyone is permitted to copy and distribute verbatim copies of this
30130license document, but changing it is not allowed.
30131
30132@strong{Preamble}
30133
30134The purpose of this License is to make a manual, textbook, or other
30135functional and useful document "free" in the sense of freedom: to
30136assure everyone the effective freedom to copy and redistribute it,
30137with or without modifying it, either commercially or noncommercially.
30138Secondarily, this License preserves for the author and publisher a way
30139to get credit for their work, while not being considered responsible
30140for modifications made by others.
30141
30142This License is a kind of "copyleft", which means that derivative
30143works of the document must themselves be free in the same sense.  It
30144complements the GNU General Public License, which is a copyleft
30145license designed for free software.
30146
30147We have designed this License in order to use it for manuals for free
30148software, because free software needs free documentation: a free
30149program should come with manuals providing the same freedoms that the
30150software does.  But this License is not limited to software manuals;
30151it can be used for any textual work, regardless of subject matter or
30152whether it is published as a printed book.  We recommend this License
30153principally for works whose purpose is instruction or reference.
30154
30155@strong{1. APPLICABILITY AND DEFINITIONS}
30156
30157This License applies to any manual or other work, in any medium, that
30158contains a notice placed by the copyright holder saying it can be
30159distributed under the terms of this License.  Such a notice grants a
30160world-wide, royalty-free license, unlimited in duration, to use that
30161work under the conditions stated herein.  The @strong{Document}, below,
30162refers to any such manual or work.  Any member of the public is a
30163licensee, and is addressed as "@strong{you}".  You accept the license if you
30164copy, modify or distribute the work in a way requiring permission
30165under copyright law.
30166
30167A "@strong{Modified Version}" of the Document means any work containing the
30168Document or a portion of it, either copied verbatim, or with
30169modifications and/or translated into another language.
30170
30171A "@strong{Secondary Section}" is a named appendix or a front-matter section of
30172the Document that deals exclusively with the relationship of the
30173publishers or authors of the Document to the Document's overall subject
30174(or to related matters) and contains nothing that could fall directly
30175within that overall subject.  (Thus, if the Document is in part a
30176textbook of mathematics, a Secondary Section may not explain any
30177mathematics.)  The relationship could be a matter of historical
30178connection with the subject or with related matters, or of legal,
30179commercial, philosophical, ethical or political position regarding
30180them.
30181
30182The "@strong{Invariant Sections}" are certain Secondary Sections whose titles
30183are designated, as being those of Invariant Sections, in the notice
30184that says that the Document is released under this License.  If a
30185section does not fit the above definition of Secondary then it is not
30186allowed to be designated as Invariant.  The Document may contain zero
30187Invariant Sections.  If the Document does not identify any Invariant
30188Sections then there are none.
30189
30190The "@strong{Cover Texts}" are certain short passages of text that are listed,
30191as Front-Cover Texts or Back-Cover Texts, in the notice that says that
30192the Document is released under this License.  A Front-Cover Text may
30193be at most 5 words, and a Back-Cover Text may be at most 25 words.
30194
30195A "@strong{Transparent}" copy of the Document means a machine-readable copy,
30196represented in a format whose specification is available to the
30197general public, that is suitable for revising the document
30198straightforwardly with generic text editors or (for images composed of
30199pixels) generic paint programs or (for drawings) some widely available
30200drawing editor, and that is suitable for input to text formatters or
30201for automatic translation to a variety of formats suitable for input
30202to text formatters.  A copy made in an otherwise Transparent file
30203format whose markup, or absence of markup, has been arranged to thwart
30204or discourage subsequent modification by readers is not Transparent.
30205An image format is not Transparent if used for any substantial amount
30206of text.  A copy that is not "Transparent" is called @strong{Opaque}.
30207
30208Examples of suitable formats for Transparent copies include plain
30209ASCII without markup, Texinfo input format, LaTeX input format, SGML
30210or XML using a publicly available DTD, and standard-conforming simple
30211HTML, PostScript or PDF designed for human modification.  Examples of
30212transparent image formats include PNG, XCF and JPG.  Opaque formats
30213include proprietary formats that can be read and edited only by
30214proprietary word processors, SGML or XML for which the DTD and/or
30215processing tools are not generally available, and the
30216machine-generated HTML, PostScript or PDF produced by some word
30217processors for output purposes only.
30218
30219The "@strong{Title Page}" means, for a printed book, the title page itself,
30220plus such following pages as are needed to hold, legibly, the material
30221this License requires to appear in the title page.  For works in
30222formats which do not have any title page as such, "Title Page" means
30223the text near the most prominent appearance of the work's title,
30224preceding the beginning of the body of the text.
30225
30226The "@strong{publisher}" means any person or entity that distributes
30227copies of the Document to the public.
30228
30229A section "@strong{Entitled XYZ}" means a named subunit of the Document whose
30230title either is precisely XYZ or contains XYZ in parentheses following
30231text that translates XYZ in another language.  (Here XYZ stands for a
30232specific section name mentioned below, such as "@strong{Acknowledgements}",
30233"@strong{Dedications}", "@strong{Endorsements}", or "@strong{History}".)
30234To "@strong{Preserve the Title}"
30235of such a section when you modify the Document means that it remains a
30236section "Entitled XYZ" according to this definition.
30237
30238The Document may include Warranty Disclaimers next to the notice which
30239states that this License applies to the Document.  These Warranty
30240Disclaimers are considered to be included by reference in this
30241License, but only as regards disclaiming warranties: any other
30242implication that these Warranty Disclaimers may have is void and has
30243no effect on the meaning of this License.
30244
30245@strong{2. VERBATIM COPYING}
30246
30247You may copy and distribute the Document in any medium, either
30248commercially or noncommercially, provided that this License, the
30249copyright notices, and the license notice saying this License applies
30250to the Document are reproduced in all copies, and that you add no other
30251conditions whatsoever to those of this License.  You may not use
30252technical measures to obstruct or control the reading or further
30253copying of the copies you make or distribute.  However, you may accept
30254compensation in exchange for copies.  If you distribute a large enough
30255number of copies you must also follow the conditions in section 3.
30256
30257You may also lend copies, under the same conditions stated above, and
30258you may publicly display copies.
30259
30260@strong{3. COPYING IN QUANTITY}
30261
30262If you publish printed copies (or copies in media that commonly have
30263printed covers) of the Document, numbering more than 100, and the
30264Document's license notice requires Cover Texts, you must enclose the
30265copies in covers that carry, clearly and legibly, all these Cover
30266Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
30267the back cover.  Both covers must also clearly and legibly identify
30268you as the publisher of these copies.  The front cover must present
30269the full title with all words of the title equally prominent and
30270visible.  You may add other material on the covers in addition.
30271Copying with changes limited to the covers, as long as they preserve
30272the title of the Document and satisfy these conditions, can be treated
30273as verbatim copying in other respects.
30274
30275If the required texts for either cover are too voluminous to fit
30276legibly, you should put the first ones listed (as many as fit
30277reasonably) on the actual cover, and continue the rest onto adjacent
30278pages.
30279
30280If you publish or distribute Opaque copies of the Document numbering
30281more than 100, you must either include a machine-readable Transparent
30282copy along with each Opaque copy, or state in or with each Opaque copy
30283a computer-network location from which the general network-using
30284public has access to download using public-standard network protocols
30285a complete Transparent copy of the Document, free of added material.
30286If you use the latter option, you must take reasonably prudent steps,
30287when you begin distribution of Opaque copies in quantity, to ensure
30288that this Transparent copy will remain thus accessible at the stated
30289location until at least one year after the last time you distribute an
30290Opaque copy (directly or through your agents or retailers) of that
30291edition to the public.
30292
30293It is requested, but not required, that you contact the authors of the
30294Document well before redistributing any large number of copies, to give
30295them a chance to provide you with an updated version of the Document.
30296
30297@strong{4. MODIFICATIONS}
30298
30299You may copy and distribute a Modified Version of the Document under
30300the conditions of sections 2 and 3 above, provided that you release
30301the Modified Version under precisely this License, with the Modified
30302Version filling the role of the Document, thus licensing distribution
30303and modification of the Modified Version to whoever possesses a copy
30304of it.  In addition, you must do these things in the Modified Version:
30305
30306
30307@enumerate A
30308
30309@item
30310Use in the Title Page (and on the covers, if any) a title distinct
30311from that of the Document, and from those of previous versions
30312(which should, if there were any, be listed in the History section
30313of the Document).  You may use the same title as a previous version
30314if the original publisher of that version gives permission.
30315
30316@item
30317List on the Title Page, as authors, one or more persons or entities
30318responsible for authorship of the modifications in the Modified
30319Version, together with at least five of the principal authors of the
30320Document (all of its principal authors, if it has fewer than five),
30321unless they release you from this requirement.
30322
30323@item
30324State on the Title page the name of the publisher of the
30325Modified Version, as the publisher.
30326
30327@item
30328Preserve all the copyright notices of the Document.
30329
30330@item
30331Add an appropriate copyright notice for your modifications
30332adjacent to the other copyright notices.
30333
30334@item
30335Include, immediately after the copyright notices, a license notice
30336giving the public permission to use the Modified Version under the
30337terms of this License, in the form shown in the Addendum below.
30338
30339@item
30340Preserve in that license notice the full lists of Invariant Sections
30341and required Cover Texts given in the Document's license notice.
30342
30343@item
30344Include an unaltered copy of this License.
30345
30346@item
30347Preserve the section Entitled "History", Preserve its Title, and add
30348to it an item stating at least the title, year, new authors, and
30349publisher of the Modified Version as given on the Title Page.  If
30350there is no section Entitled "History" in the Document, create one
30351stating the title, year, authors, and publisher of the Document as
30352given on its Title Page, then add an item describing the Modified
30353Version as stated in the previous sentence.
30354
30355@item
30356Preserve the network location, if any, given in the Document for
30357public access to a Transparent copy of the Document, and likewise
30358the network locations given in the Document for previous versions
30359it was based on.  These may be placed in the "History" section.
30360You may omit a network location for a work that was published at
30361least four years before the Document itself, or if the original
30362publisher of the version it refers to gives permission.
30363
30364@item
30365For any section Entitled "Acknowledgements" or "Dedications",
30366Preserve the Title of the section, and preserve in the section all
30367the substance and tone of each of the contributor acknowledgements
30368and/or dedications given therein.
30369
30370@item
30371Preserve all the Invariant Sections of the Document,
30372unaltered in their text and in their titles.  Section numbers
30373or the equivalent are not considered part of the section titles.
30374
30375@item
30376Delete any section Entitled "Endorsements".  Such a section
30377may not be included in the Modified Version.
30378
30379@item
30380Do not retitle any existing section to be Entitled "Endorsements"
30381or to conflict in title with any Invariant Section.
30382
30383@item
30384Preserve any Warranty Disclaimers.
30385@end enumerate
30386
30387If the Modified Version includes new front-matter sections or
30388appendices that qualify as Secondary Sections and contain no material
30389copied from the Document, you may at your option designate some or all
30390of these sections as invariant.  To do this, add their titles to the
30391list of Invariant Sections in the Modified Version's license notice.
30392These titles must be distinct from any other section titles.
30393
30394You may add a section Entitled "Endorsements", provided it contains
30395nothing but endorsements of your Modified Version by various
30396parties---for example, statements of peer review or that the text has
30397been approved by an organization as the authoritative definition of a
30398standard.
30399
30400You may add a passage of up to five words as a Front-Cover Text, and a
30401passage of up to 25 words as a Back-Cover Text, to the end of the list
30402of Cover Texts in the Modified Version.  Only one passage of
30403Front-Cover Text and one of Back-Cover Text may be added by (or
30404through arrangements made by) any one entity.  If the Document already
30405includes a cover text for the same cover, previously added by you or
30406by arrangement made by the same entity you are acting on behalf of,
30407you may not add another; but you may replace the old one, on explicit
30408permission from the previous publisher that added the old one.
30409
30410The author(s) and publisher(s) of the Document do not by this License
30411give permission to use their names for publicity for or to assert or
30412imply endorsement of any Modified Version.
30413
30414@strong{5. COMBINING DOCUMENTS}
30415
30416You may combine the Document with other documents released under this
30417License, under the terms defined in section 4 above for modified
30418versions, provided that you include in the combination all of the
30419Invariant Sections of all of the original documents, unmodified, and
30420list them all as Invariant Sections of your combined work in its
30421license notice, and that you preserve all their Warranty Disclaimers.
30422
30423The combined work need only contain one copy of this License, and
30424multiple identical Invariant Sections may be replaced with a single
30425copy.  If there are multiple Invariant Sections with the same name but
30426different contents, make the title of each such section unique by
30427adding at the end of it, in parentheses, the name of the original
30428author or publisher of that section if known, or else a unique number.
30429Make the same adjustment to the section titles in the list of
30430Invariant Sections in the license notice of the combined work.
30431
30432In the combination, you must combine any sections Entitled "History"
30433in the various original documents, forming one section Entitled
30434"History"; likewise combine any sections Entitled "Acknowledgements",
30435and any sections Entitled "Dedications".  You must delete all sections
30436Entitled "Endorsements".
30437
30438@strong{6. COLLECTIONS OF DOCUMENTS}
30439
30440You may make a collection consisting of the Document and other documents
30441released under this License, and replace the individual copies of this
30442License in the various documents with a single copy that is included in
30443the collection, provided that you follow the rules of this License for
30444verbatim copying of each of the documents in all other respects.
30445
30446You may extract a single document from such a collection, and distribute
30447it individually under this License, provided you insert a copy of this
30448License into the extracted document, and follow this License in all
30449other respects regarding verbatim copying of that document.
30450
30451@strong{7. AGGREGATION WITH INDEPENDENT WORKS}
30452
30453A compilation of the Document or its derivatives with other separate
30454and independent documents or works, in or on a volume of a storage or
30455distribution medium, is called an "aggregate" if the copyright
30456resulting from the compilation is not used to limit the legal rights
30457of the compilation's users beyond what the individual works permit.
30458When the Document is included in an aggregate, this License does not
30459apply to the other works in the aggregate which are not themselves
30460derivative works of the Document.
30461
30462If the Cover Text requirement of section 3 is applicable to these
30463copies of the Document, then if the Document is less than one half of
30464the entire aggregate, the Document's Cover Texts may be placed on
30465covers that bracket the Document within the aggregate, or the
30466electronic equivalent of covers if the Document is in electronic form.
30467Otherwise they must appear on printed covers that bracket the whole
30468aggregate.
30469
30470@strong{8. TRANSLATION}
30471
30472Translation is considered a kind of modification, so you may
30473distribute translations of the Document under the terms of section 4.
30474Replacing Invariant Sections with translations requires special
30475permission from their copyright holders, but you may include
30476translations of some or all Invariant Sections in addition to the
30477original versions of these Invariant Sections.  You may include a
30478translation of this License, and all the license notices in the
30479Document, and any Warranty Disclaimers, provided that you also include
30480the original English version of this License and the original versions
30481of those notices and disclaimers.  In case of a disagreement between
30482the translation and the original version of this License or a notice
30483or disclaimer, the original version will prevail.
30484
30485If a section in the Document is Entitled "Acknowledgements",
30486"Dedications", or "History", the requirement (section 4) to Preserve
30487its Title (section 1) will typically require changing the actual
30488title.
30489
30490@strong{9. TERMINATION}
30491
30492You may not copy, modify, sublicense, or distribute the Document
30493except as expressly provided under this License.  Any attempt
30494otherwise to copy, modify, sublicense, or distribute it is void, and
30495will automatically terminate your rights under this License.
30496
30497However, if you cease all violation of this License, then your license
30498from a particular copyright holder is reinstated (a) provisionally,
30499unless and until the copyright holder explicitly and finally
30500terminates your license, and (b) permanently, if the copyright holder
30501fails to notify you of the violation by some reasonable means prior to
3050260 days after the cessation.
30503
30504Moreover, your license from a particular copyright holder is
30505reinstated permanently if the copyright holder notifies you of the
30506violation by some reasonable means, this is the first time you have
30507received notice of violation of this License (for any work) from that
30508copyright holder, and you cure the violation prior to 30 days after
30509your receipt of the notice.
30510
30511Termination of your rights under this section does not terminate the
30512licenses of parties who have received copies or rights from you under
30513this License.  If your rights have been terminated and not permanently
30514reinstated, receipt of a copy of some or all of the same material does
30515not give you any rights to use it.
30516
30517@strong{10. FUTURE REVISIONS OF THIS LICENSE}
30518
30519The Free Software Foundation may publish new, revised versions
30520of the GNU Free Documentation License from time to time.  Such new
30521versions will be similar in spirit to the present version, but may
30522differ in detail to address new problems or concerns.  See
30523@indicateurl{http://www.gnu.org/copyleft/}.
30524
30525Each version of the License is given a distinguishing version number.
30526If the Document specifies that a particular numbered version of this
30527License "or any later version" applies to it, you have the option of
30528following the terms and conditions either of that specified version or
30529of any later version that has been published (not as a draft) by the
30530Free Software Foundation.  If the Document does not specify a version
30531number of this License, you may choose any version ever published (not
30532as a draft) by the Free Software Foundation.  If the Document
30533specifies that a proxy can decide which future versions of this
30534License can be used, that proxy's public statement of acceptance of a
30535version permanently authorizes you to choose that version for the
30536Document.
30537
30538@strong{11. RELICENSING}
30539
30540"Massive Multiauthor Collaboration Site" (or "MMC Site") means any
30541World Wide Web server that publishes copyrightable works and also
30542provides prominent facilities for anybody to edit those works.  A
30543public wiki that anybody can edit is an example of such a server.  A
30544"Massive Multiauthor Collaboration" (or "MMC") contained in the
30545site means any set of copyrightable works thus published on the MMC
30546site.
30547
30548"CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0
30549license published by Creative Commons Corporation, a not-for-profit
30550corporation with a principal place of business in San Francisco,
30551California, as well as future copyleft versions of that license
30552published by that same organization.
30553
30554"Incorporate" means to publish or republish a Document, in whole or
30555in part, as part of another Document.
30556
30557An MMC is "eligible for relicensing" if it is licensed under this
30558License, and if all works that were first published under this License
30559somewhere other than this MMC, and subsequently incorporated in whole
30560or in part into the MMC, (1) had no cover texts or invariant sections,
30561and (2) were thus incorporated prior to November 1, 2008.
30562
30563The operator of an MMC Site may republish an MMC contained in the site
30564under CC-BY-SA on the same site at any time before August 1, 2009,
30565provided the MMC is eligible for relicensing.
30566
30567@strong{ADDENDUM: How to use this License for your documents}
30568
30569To use this License in a document you have written, include a copy of
30570the License in the document and put the following copyright and
30571license notices just after the title page:
30572
30573@quotation
30574
30575Copyright © YEAR  YOUR NAME.
30576Permission is granted to copy, distribute and/or modify this document
30577under the terms of the GNU Free Documentation License, Version 1.3
30578or any later version published by the Free Software Foundation;
30579with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
30580A copy of the license is included in the section entitled "GNU
30581Free Documentation License".
30582@end quotation
30583
30584If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
30585replace the "with ... Texts." line with this:
30586
30587@quotation
30588
30589with the Invariant Sections being LIST THEIR TITLES, with the
30590Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
30591@end quotation
30592
30593If you have Invariant Sections without Cover Texts, or some other
30594combination of the three, merge those two alternatives to suit the
30595situation.
30596
30597If your document contains nontrivial examples of program code, we
30598recommend releasing these examples in parallel under your choice of
30599free software license, such as the GNU General Public License,
30600to permit their use in free software.
30601
30602@node Index,,GNU Free Documentation License,Top
30603@unnumbered Index
30604
30605
30606@printindex ge
30607
30608@anchor{de}@w{                              }
30609@anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{                              }
30610
30611@c %**end of body
30612@bye
30613