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.3.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 , April 25, 2018
25
26AdaCore
27
28Copyright @copyright{} 2008-2018, 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* Code Coverage and Profiling::
353* Improving Performance::
354* Overflow Check Handling in GNAT::
355* Performing Dimensionality Analysis in GNAT::
356* Stack Related Facilities::
357* Memory Management Issues::
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
382Code Coverage and Profiling
383
384* Code Coverage of Ada Programs with gcov::
385* Profiling an Ada Program with gprof::
386
387Code Coverage of Ada Programs with gcov
388
389* Quick startup guide::
390* GNAT specifics::
391
392Profiling an Ada Program with gprof
393
394* Compilation for profiling::
395* Program execution::
396* Running gprof::
397* Interpretation of profiling results::
398
399Improving Performance
400
401* Performance Considerations::
402* Text_IO Suggestions::
403* Reducing Size of Executables with Unused Subprogram/Data Elimination::
404
405Performance Considerations
406
407* Controlling Run-Time Checks::
408* Use of Restrictions::
409* Optimization Levels::
410* Debugging Optimized Code::
411* Inlining of Subprograms::
412* Floating_Point_Operations::
413* Vectorization of loops::
414* Other Optimization Switches::
415* Optimization and Strict Aliasing::
416* Aliased Variables and Optimization::
417* Atomic Variables and Optimization::
418* Passive Task Optimization::
419
420Reducing Size of Executables with Unused Subprogram/Data Elimination
421
422* About unused subprogram/data elimination::
423* Compilation options::
424* Example of unused subprogram/data elimination::
425
426Overflow Check Handling in GNAT
427
428* Background::
429* Management of Overflows in GNAT::
430* Specifying the Desired Mode::
431* Default Settings::
432* Implementation Notes::
433
434Stack Related Facilities
435
436* Stack Overflow Checking::
437* Static Stack Usage Analysis::
438* Dynamic Stack Usage Analysis::
439
440Memory Management Issues
441
442* Some Useful Memory Pools::
443* The GNAT Debug Pool Facility::
444
445Platform-Specific Information
446
447* Run-Time Libraries::
448* Specifying a Run-Time Library::
449* GNU/Linux Topics::
450* Microsoft Windows Topics::
451* Mac OS Topics::
452
453Run-Time Libraries
454
455* Summary of Run-Time Configurations::
456
457Specifying a Run-Time Library
458
459* Choosing the Scheduling Policy::
460
461GNU/Linux Topics
462
463* Required Packages on GNU/Linux::
464
465Microsoft Windows Topics
466
467* Using GNAT on Windows::
468* Using a network installation of GNAT::
469* CONSOLE and WINDOWS subsystems::
470* Temporary Files::
471* Disabling Command Line Argument Expansion::
472* Mixed-Language Programming on Windows::
473* Windows Specific Add-Ons::
474
475Mixed-Language Programming on Windows
476
477* Windows Calling Conventions::
478* Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs.
479* Using DLLs with GNAT::
480* Building DLLs with GNAT Project files::
481* Building DLLs with GNAT::
482* Building DLLs with gnatdll::
483* Ada DLLs and Finalization::
484* Creating a Spec for Ada DLLs::
485* GNAT and Windows Resources::
486* Using GNAT DLLs from Microsoft Visual Studio Applications::
487* Debugging a DLL::
488* Setting Stack Size from gnatlink::
489* Setting Heap Size from gnatlink::
490
491Windows Calling Conventions
492
493* C Calling Convention::
494* Stdcall Calling Convention::
495* Win32 Calling Convention::
496* DLL Calling Convention::
497
498Using DLLs with GNAT
499
500* Creating an Ada Spec for the DLL Services::
501* Creating an Import Library::
502
503Building DLLs with gnatdll
504
505* Limitations When Using Ada DLLs from Ada::
506* Exporting Ada Entities::
507* Ada DLLs and Elaboration::
508
509Creating a Spec for Ada DLLs
510
511* Creating the Definition File::
512* Using gnatdll::
513
514GNAT and Windows Resources
515
516* Building Resources::
517* Compiling Resources::
518* Using Resources::
519
520Debugging a DLL
521
522* Program and DLL Both Built with GCC/GNAT::
523* Program Built with Foreign Tools and DLL Built with GCC/GNAT::
524
525Windows Specific Add-Ons
526
527* Win32Ada::
528* wPOSIX::
529
530Mac OS Topics
531
532* Codesigning the Debugger::
533
534Elaboration Order Handling in GNAT
535
536* Elaboration Code::
537* Elaboration Order::
538* Checking the Elaboration Order::
539* Controlling the Elaboration Order in Ada::
540* Controlling the Elaboration Order in GNAT::
541* Common Elaboration-model Traits::
542* Dynamic Elaboration Model in GNAT::
543* Static Elaboration Model in GNAT::
544* SPARK Elaboration Model in GNAT::
545* Legacy Elaboration Model in GNAT::
546* Mixing Elaboration Models::
547* Elaboration Circularities::
548* Resolving Elaboration Circularities::
549* Resolving Task Issues::
550* Elaboration-related Compiler Switches::
551* Summary of Procedures for Elaboration Control::
552* Inspecting the Chosen Elaboration Order::
553
554Inline Assembler
555
556* Basic Assembler Syntax::
557* A Simple Example of Inline Assembler::
558* Output Variables in Inline Assembler::
559* Input Variables in Inline Assembler::
560* Inlining Inline Assembler Code::
561* Other Asm Functionality::
562
563Other Asm Functionality
564
565* The Clobber Parameter::
566* The Volatile Parameter::
567
568@end detailmenu
569@end menu
570
571@node About This Guide,Getting Started with GNAT,Top,Top
572@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}
573@chapter About This Guide
574
575
576
577This guide describes the use of GNAT,
578a compiler and software development
579toolset for the full Ada programming language.
580It documents the features of the compiler and tools, and explains
581how to use them to build Ada applications.
582
583GNAT implements Ada 95, Ada 2005 and Ada 2012, and it may also be
584invoked in Ada 83 compatibility mode.
585By default, GNAT assumes Ada 2012, but you can override with a
586compiler switch (@ref{6,,Compiling Different Versions of Ada})
587to explicitly specify the language version.
588Throughout this manual, references to 'Ada' without a year suffix
589apply to all Ada 95/2005/2012 versions of the language.
590
591@menu
592* What This Guide Contains::
593* What You Should Know before Reading This Guide::
594* Related Information::
595* A Note to Readers of Previous Versions of the Manual::
596* Conventions::
597
598@end menu
599
600@node What This Guide Contains,What You Should Know before Reading This Guide,,About This Guide
601@anchor{gnat_ugn/about_this_guide what-this-guide-contains}@anchor{7}
602@section What This Guide Contains
603
604
605This guide contains the following chapters:
606
607
608@itemize *
609
610@item
611@ref{8,,Getting Started with GNAT} describes how to get started compiling
612and running Ada programs with the GNAT Ada programming environment.
613
614@item
615@ref{9,,The GNAT Compilation Model} describes the compilation model used
616by GNAT.
617
618@item
619@ref{a,,Building Executable Programs with GNAT} describes how to use the
620main GNAT tools to build executable programs, and it also gives examples of
621using the GNU make utility with GNAT.
622
623@item
624@ref{b,,GNAT Utility Programs} explains the various utility programs that
625are included in the GNAT environment
626
627@item
628@ref{c,,GNAT and Program Execution} covers a number of topics related to
629running, debugging, and tuning the performace of programs developed
630with GNAT
631@end itemize
632
633Appendices cover several additional topics:
634
635
636@itemize *
637
638@item
639@ref{d,,Platform-Specific Information} describes the different run-time
640library implementations and also presents information on how to use
641GNAT on several specific platforms
642
643@item
644@ref{e,,Example of Binder Output File} shows the source code for the binder
645output file for a sample program.
646
647@item
648@ref{f,,Elaboration Order Handling in GNAT} describes how GNAT helps
649you deal with elaboration order issues.
650
651@item
652@ref{10,,Inline Assembler} shows how to use the inline assembly facility
653in an Ada program.
654@end itemize
655
656@node What You Should Know before Reading This Guide,Related Information,What This Guide Contains,About This Guide
657@anchor{gnat_ugn/about_this_guide what-you-should-know-before-reading-this-guide}@anchor{11}
658@section What You Should Know before Reading This Guide
659
660
661@geindex Ada 95 Language Reference Manual
662
663@geindex Ada 2005 Language Reference Manual
664
665This guide assumes a basic familiarity with the Ada 95 language, as
666described in the International Standard ANSI/ISO/IEC-8652:1995, January
6671995.
668It does not require knowledge of the features introduced by Ada 2005
669or Ada 2012.
670Reference manuals for Ada 95, Ada 2005, and Ada 2012 are included in
671the GNAT documentation package.
672
673@node Related Information,A Note to Readers of Previous Versions of the Manual,What You Should Know before Reading This Guide,About This Guide
674@anchor{gnat_ugn/about_this_guide related-information}@anchor{12}
675@section Related Information
676
677
678For further information about Ada and related tools, please refer to the
679following documents:
680
681
682@itemize *
683
684@item
685@cite{Ada 95 Reference Manual}, @cite{Ada 2005 Reference Manual}, and
686@cite{Ada 2012 Reference Manual}, which contain reference
687material for the several revisions of the Ada language standard.
688
689@item
690@cite{GNAT Reference_Manual}, which contains all reference material for the GNAT
691implementation of Ada.
692
693@item
694@cite{Using the GNAT Programming Studio}, which describes the GPS
695Integrated Development Environment.
696
697@item
698@cite{GNAT Programming Studio Tutorial}, which introduces the
699main GPS features through examples.
700
701@item
702@cite{Debugging with GDB},
703for all details on the use of the GNU source-level debugger.
704
705@item
706@cite{GNU Emacs Manual},
707for full information on the extensible editor and programming
708environment Emacs.
709@end itemize
710
711@node A Note to Readers of Previous Versions of the Manual,Conventions,Related Information,About This Guide
712@anchor{gnat_ugn/about_this_guide a-note-to-readers-of-previous-versions-of-the-manual}@anchor{13}
713@section A Note to Readers of Previous Versions of the Manual
714
715
716In early 2015 the GNAT manuals were transitioned to the
717reStructuredText (rst) / Sphinx documentation generator technology.
718During that process the @cite{GNAT User's Guide} was reorganized
719so that related topics would be described together in the same chapter
720or appendix.  Here's a summary of the major changes realized in
721the new document structure.
722
723
724@itemize *
725
726@item
727@ref{9,,The GNAT Compilation Model} has been extended so that it now covers
728the following material:
729
730
731@itemize -
732
733@item
734The @code{gnatname}, @code{gnatkr}, and @code{gnatchop} tools
735
736@item
737@ref{14,,Configuration Pragmas}
738
739@item
740@ref{15,,GNAT and Libraries}
741
742@item
743@ref{16,,Conditional Compilation} including @ref{17,,Preprocessing with gnatprep}
744and @ref{18,,Integrated Preprocessing}
745
746@item
747@ref{19,,Generating Ada Bindings for C and C++ headers}
748
749@item
750@ref{1a,,Using GNAT Files with External Tools}
751@end itemize
752
753@item
754@ref{a,,Building Executable Programs with GNAT} is a new chapter consolidating
755the following content:
756
757
758@itemize -
759
760@item
761@ref{1b,,Building with gnatmake}
762
763@item
764@ref{1c,,Compiling with gcc}
765
766@item
767@ref{1d,,Binding with gnatbind}
768
769@item
770@ref{1e,,Linking with gnatlink}
771
772@item
773@ref{1f,,Using the GNU make Utility}
774@end itemize
775
776@item
777@ref{b,,GNAT Utility Programs} is a new chapter consolidating the information about several
778GNAT tools:
779
780
781
782@itemize -
783
784@item
785@ref{20,,The File Cleanup Utility gnatclean}
786
787@item
788@ref{21,,The GNAT Library Browser gnatls}
789
790@item
791@ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
792
793@item
794@ref{23,,The Ada to HTML Converter gnathtml}
795@end itemize
796
797@item
798@ref{c,,GNAT and Program Execution} is a new chapter consolidating the following:
799
800
801@itemize -
802
803@item
804@ref{24,,Running and Debugging Ada Programs}
805
806@item
807@ref{25,,Code Coverage and Profiling}
808
809@item
810@ref{26,,Improving Performance}
811
812@item
813@ref{27,,Overflow Check Handling in GNAT}
814
815@item
816@ref{28,,Performing Dimensionality Analysis in GNAT}
817
818@item
819@ref{29,,Stack Related Facilities}
820
821@item
822@ref{2a,,Memory Management Issues}
823@end itemize
824
825@item
826@ref{d,,Platform-Specific Information} is a new appendix consolidating the following:
827
828
829@itemize -
830
831@item
832@ref{2b,,Run-Time Libraries}
833
834@item
835@ref{2c,,Microsoft Windows Topics}
836
837@item
838@ref{2d,,Mac OS Topics}
839@end itemize
840
841@item
842The @emph{Compatibility and Porting Guide} appendix has been moved to the
843@cite{GNAT Reference Manual}. It now includes a section
844@emph{Writing Portable Fixed-Point Declarations} which was previously
845a separate chapter in the @cite{GNAT User's Guide}.
846@end itemize
847
848@node Conventions,,A Note to Readers of Previous Versions of the Manual,About This Guide
849@anchor{gnat_ugn/about_this_guide conventions}@anchor{2e}
850@section Conventions
851
852
853@geindex Conventions
854@geindex typographical
855
856@geindex Typographical conventions
857
858Following are examples of the typographical and graphic conventions used
859in this guide:
860
861
862@itemize *
863
864@item
865@code{Functions}, @code{utility program names}, @code{standard names},
866and @code{classes}.
867
868@item
869@code{Option flags}
870
871@item
872@code{File names}
873
874@item
875@code{Variables}
876
877@item
878@emph{Emphasis}
879
880@item
881[optional information or parameters]
882
883@item
884Examples are described by text
885
886@example
887and then shown this way.
888@end example
889
890@item
891Commands that are entered by the user are shown as preceded by a prompt string
892comprising the @code{$} character followed by a space.
893
894@item
895Full file names are shown with the '/' character
896as the directory separator; e.g., @code{parent-dir/subdir/myfile.adb}.
897If you are using GNAT on a Windows platform, please note that
898the '\' character should be used instead.
899@end itemize
900
901@node Getting Started with GNAT,The GNAT Compilation Model,About This Guide,Top
902@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}
903@chapter Getting Started with GNAT
904
905
906This chapter describes how to use GNAT's command line interface to build
907executable Ada programs.
908On most platforms a visually oriented Integrated Development Environment
909is also available, the GNAT Programming Studio (GPS).
910GPS offers a graphical "look and feel", support for development in
911other programming languages, comprehensive browsing features, and
912many other capabilities.
913For information on GPS please refer to
914@cite{Using the GNAT Programming Studio}.
915
916@menu
917* Running GNAT::
918* Running a Simple Ada Program::
919* Running a Program with Multiple Units::
920* Using the gnatmake Utility::
921
922@end menu
923
924@node Running GNAT,Running a Simple Ada Program,,Getting Started with GNAT
925@anchor{gnat_ugn/getting_started_with_gnat running-gnat}@anchor{31}@anchor{gnat_ugn/getting_started_with_gnat id2}@anchor{32}
926@section Running GNAT
927
928
929Three steps are needed to create an executable file from an Ada source
930file:
931
932
933@itemize *
934
935@item
936The source file(s) must be compiled.
937
938@item
939The file(s) must be bound using the GNAT binder.
940
941@item
942All appropriate object files must be linked to produce an executable.
943@end itemize
944
945All three steps are most commonly handled by using the @code{gnatmake}
946utility program that, given the name of the main program, automatically
947performs the necessary compilation, binding and linking steps.
948
949@node Running a Simple Ada Program,Running a Program with Multiple Units,Running GNAT,Getting Started with GNAT
950@anchor{gnat_ugn/getting_started_with_gnat running-a-simple-ada-program}@anchor{33}@anchor{gnat_ugn/getting_started_with_gnat id3}@anchor{34}
951@section Running a Simple Ada Program
952
953
954Any text editor may be used to prepare an Ada program.
955(If Emacs is used, the optional Ada mode may be helpful in laying out the
956program.)
957The program text is a normal text file. We will assume in our initial
958example that you have used your editor to prepare the following
959standard format text file:
960
961@example
962with Ada.Text_IO; use Ada.Text_IO;
963procedure Hello is
964begin
965   Put_Line ("Hello WORLD!");
966end Hello;
967@end example
968
969This file should be named @code{hello.adb}.
970With the normal default file naming conventions, GNAT requires
971that each file
972contain a single compilation unit whose file name is the
973unit name,
974with periods replaced by hyphens; the
975extension is @code{ads} for a
976spec and @code{adb} for a body.
977You can override this default file naming convention by use of the
978special pragma @code{Source_File_Name} (for further information please
979see @ref{35,,Using Other File Names}).
980Alternatively, if you want to rename your files according to this default
981convention, which is probably more convenient if you will be using GNAT
982for all your compilations, then the @code{gnatchop} utility
983can be used to generate correctly-named source files
984(see @ref{36,,Renaming Files with gnatchop}).
985
986You can compile the program using the following command (@code{$} is used
987as the command prompt in the examples in this document):
988
989@example
990$ gcc -c hello.adb
991@end example
992
993@code{gcc} is the command used to run the compiler. This compiler is
994capable of compiling programs in several languages, including Ada and
995C. It assumes that you have given it an Ada program if the file extension is
996either @code{.ads} or @code{.adb}, and it will then call
997the GNAT compiler to compile the specified file.
998
999The @code{-c} switch is required. It tells @code{gcc} to only do a
1000compilation. (For C programs, @code{gcc} can also do linking, but this
1001capability is not used directly for Ada programs, so the @code{-c}
1002switch must always be present.)
1003
1004This compile command generates a file
1005@code{hello.o}, which is the object
1006file corresponding to your Ada program. It also generates
1007an 'Ada Library Information' file @code{hello.ali},
1008which contains additional information used to check
1009that an Ada program is consistent.
1010To build an executable file,
1011use @code{gnatbind} to bind the program
1012and @code{gnatlink} to link it. The
1013argument to both @code{gnatbind} and @code{gnatlink} is the name of the
1014@code{ALI} file, but the default extension of @code{.ali} can
1015be omitted. This means that in the most common case, the argument
1016is simply the name of the main program:
1017
1018@example
1019$ gnatbind hello
1020$ gnatlink hello
1021@end example
1022
1023A simpler method of carrying out these steps is to use @code{gnatmake},
1024a master program that invokes all the required
1025compilation, binding and linking tools in the correct order. In particular,
1026@code{gnatmake} automatically recompiles any sources that have been
1027modified since they were last compiled, or sources that depend
1028on such modified sources, so that 'version skew' is avoided.
1029
1030@geindex Version skew (avoided by `@w{`}gnatmake`@w{`})
1031
1032@example
1033$ gnatmake hello.adb
1034@end example
1035
1036The result is an executable program called @code{hello}, which can be
1037run by entering:
1038
1039@example
1040$ hello
1041@end example
1042
1043assuming that the current directory is on the search path
1044for executable programs.
1045
1046and, if all has gone well, you will see:
1047
1048@example
1049Hello WORLD!
1050@end example
1051
1052appear in response to this command.
1053
1054@node Running a Program with Multiple Units,Using the gnatmake Utility,Running a Simple Ada Program,Getting Started with GNAT
1055@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}
1056@section Running a Program with Multiple Units
1057
1058
1059Consider a slightly more complicated example that has three files: a
1060main program, and the spec and body of a package:
1061
1062@example
1063package Greetings is
1064   procedure Hello;
1065   procedure Goodbye;
1066end Greetings;
1067
1068with Ada.Text_IO; use Ada.Text_IO;
1069package body Greetings is
1070   procedure Hello is
1071   begin
1072      Put_Line ("Hello WORLD!");
1073   end Hello;
1074
1075   procedure Goodbye is
1076   begin
1077      Put_Line ("Goodbye WORLD!");
1078   end Goodbye;
1079end Greetings;
1080
1081with Greetings;
1082procedure Gmain is
1083begin
1084   Greetings.Hello;
1085   Greetings.Goodbye;
1086end Gmain;
1087@end example
1088
1089Following the one-unit-per-file rule, place this program in the
1090following three separate files:
1091
1092
1093@table @asis
1094
1095@item @emph{greetings.ads}
1096
1097spec of package @code{Greetings}
1098
1099@item @emph{greetings.adb}
1100
1101body of package @code{Greetings}
1102
1103@item @emph{gmain.adb}
1104
1105body of main program
1106@end table
1107
1108To build an executable version of
1109this program, we could use four separate steps to compile, bind, and link
1110the program, as follows:
1111
1112@example
1113$ gcc -c gmain.adb
1114$ gcc -c greetings.adb
1115$ gnatbind gmain
1116$ gnatlink gmain
1117@end example
1118
1119Note that there is no required order of compilation when using GNAT.
1120In particular it is perfectly fine to compile the main program first.
1121Also, it is not necessary to compile package specs in the case where
1122there is an accompanying body; you only need to compile the body. If you want
1123to submit these files to the compiler for semantic checking and not code
1124generation, then use the @code{-gnatc} switch:
1125
1126@example
1127$ gcc -c greetings.ads -gnatc
1128@end example
1129
1130Although the compilation can be done in separate steps as in the
1131above example, in practice it is almost always more convenient
1132to use the @code{gnatmake} tool. All you need to know in this case
1133is the name of the main program's source file. The effect of the above four
1134commands can be achieved with a single one:
1135
1136@example
1137$ gnatmake gmain.adb
1138@end example
1139
1140In the next section we discuss the advantages of using @code{gnatmake} in
1141more detail.
1142
1143@node Using the gnatmake Utility,,Running a Program with Multiple Units,Getting Started with GNAT
1144@anchor{gnat_ugn/getting_started_with_gnat using-the-gnatmake-utility}@anchor{39}@anchor{gnat_ugn/getting_started_with_gnat id5}@anchor{3a}
1145@section Using the @code{gnatmake} Utility
1146
1147
1148If you work on a program by compiling single components at a time using
1149@code{gcc}, you typically keep track of the units you modify. In order to
1150build a consistent system, you compile not only these units, but also any
1151units that depend on the units you have modified.
1152For example, in the preceding case,
1153if you edit @code{gmain.adb}, you only need to recompile that file. But if
1154you edit @code{greetings.ads}, you must recompile both
1155@code{greetings.adb} and @code{gmain.adb}, because both files contain
1156units that depend on @code{greetings.ads}.
1157
1158@code{gnatbind} will warn you if you forget one of these compilation
1159steps, so that it is impossible to generate an inconsistent program as a
1160result of forgetting to do a compilation. Nevertheless it is tedious and
1161error-prone to keep track of dependencies among units.
1162One approach to handle the dependency-bookkeeping is to use a
1163makefile. However, makefiles present maintenance problems of their own:
1164if the dependencies change as you change the program, you must make
1165sure that the makefile is kept up-to-date manually, which is also an
1166error-prone process.
1167
1168The @code{gnatmake} utility takes care of these details automatically.
1169Invoke it using either one of the following forms:
1170
1171@example
1172$ gnatmake gmain.adb
1173$ gnatmake gmain
1174@end example
1175
1176The argument is the name of the file containing the main program;
1177you may omit the extension. @code{gnatmake}
1178examines the environment, automatically recompiles any files that need
1179recompiling, and binds and links the resulting set of object files,
1180generating the executable file, @code{gmain}.
1181In a large program, it
1182can be extremely helpful to use @code{gnatmake}, because working out by hand
1183what needs to be recompiled can be difficult.
1184
1185Note that @code{gnatmake} takes into account all the Ada rules that
1186establish dependencies among units. These include dependencies that result
1187from inlining subprogram bodies, and from
1188generic instantiation. Unlike some other
1189Ada make tools, @code{gnatmake} does not rely on the dependencies that were
1190found by the compiler on a previous compilation, which may possibly
1191be wrong when sources change. @code{gnatmake} determines the exact set of
1192dependencies from scratch each time it is run.
1193
1194@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
1195
1196@node The GNAT Compilation Model,Building Executable Programs with GNAT,Getting Started with GNAT,Top
1197@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}
1198@chapter The GNAT Compilation Model
1199
1200
1201@geindex GNAT compilation model
1202
1203@geindex Compilation model
1204
1205This chapter describes the compilation model used by GNAT. Although
1206similar to that used by other languages such as C and C++, this model
1207is substantially different from the traditional Ada compilation models,
1208which are based on a centralized program library. The chapter covers
1209the following material:
1210
1211
1212@itemize *
1213
1214@item
1215Topics related to source file makeup and naming
1216
1217
1218@itemize *
1219
1220@item
1221@ref{3d,,Source Representation}
1222
1223@item
1224@ref{3e,,Foreign Language Representation}
1225
1226@item
1227@ref{3f,,File Naming Topics and Utilities}
1228@end itemize
1229
1230@item
1231@ref{14,,Configuration Pragmas}
1232
1233@item
1234@ref{40,,Generating Object Files}
1235
1236@item
1237@ref{41,,Source Dependencies}
1238
1239@item
1240@ref{42,,The Ada Library Information Files}
1241
1242@item
1243@ref{43,,Binding an Ada Program}
1244
1245@item
1246@ref{15,,GNAT and Libraries}
1247
1248@item
1249@ref{16,,Conditional Compilation}
1250
1251@item
1252@ref{44,,Mixed Language Programming}
1253
1254@item
1255@ref{45,,GNAT and Other Compilation Models}
1256
1257@item
1258@ref{1a,,Using GNAT Files with External Tools}
1259@end itemize
1260
1261@menu
1262* Source Representation::
1263* Foreign Language Representation::
1264* File Naming Topics and Utilities::
1265* Configuration Pragmas::
1266* Generating Object Files::
1267* Source Dependencies::
1268* The Ada Library Information Files::
1269* Binding an Ada Program::
1270* GNAT and Libraries::
1271* Conditional Compilation::
1272* Mixed Language Programming::
1273* GNAT and Other Compilation Models::
1274* Using GNAT Files with External Tools::
1275
1276@end menu
1277
1278@node Source Representation,Foreign Language Representation,,The GNAT Compilation Model
1279@anchor{gnat_ugn/the_gnat_compilation_model source-representation}@anchor{3d}@anchor{gnat_ugn/the_gnat_compilation_model id2}@anchor{46}
1280@section Source Representation
1281
1282
1283@geindex Latin-1
1284
1285@geindex VT
1286@geindex HT
1287@geindex CR
1288@geindex LF
1289@geindex FF
1290
1291Ada source programs are represented in standard text files, using
1292Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
12937-bit ASCII set, plus additional characters used for
1294representing foreign languages (see @ref{3e,,Foreign Language Representation}
1295for support of non-USA character sets). The format effector characters
1296are represented using their standard ASCII encodings, as follows:
1297
1298@quotation
1299
1300
1301@multitable {xxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxx}
1302@item
1303
1304Character
1305
1306@tab
1307
1308Effect
1309
1310@tab
1311
1312Code
1313
1314@item
1315
1316@code{VT}
1317
1318@tab
1319
1320Vertical tab
1321
1322@tab
1323
1324@code{16#0B#}
1325
1326@item
1327
1328@code{HT}
1329
1330@tab
1331
1332Horizontal tab
1333
1334@tab
1335
1336@code{16#09#}
1337
1338@item
1339
1340@code{CR}
1341
1342@tab
1343
1344Carriage return
1345
1346@tab
1347
1348@code{16#0D#}
1349
1350@item
1351
1352@code{LF}
1353
1354@tab
1355
1356Line feed
1357
1358@tab
1359
1360@code{16#0A#}
1361
1362@item
1363
1364@code{FF}
1365
1366@tab
1367
1368Form feed
1369
1370@tab
1371
1372@code{16#0C#}
1373
1374@end multitable
1375
1376@end quotation
1377
1378Source files are in standard text file format. In addition, GNAT will
1379recognize a wide variety of stream formats, in which the end of
1380physical lines is marked by any of the following sequences:
1381@code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1382in accommodating files that are imported from other operating systems.
1383
1384@geindex End of source file; Source file@comma{} end
1385
1386@geindex SUB (control character)
1387
1388The end of a source file is normally represented by the physical end of
1389file. However, the control character @code{16#1A#} (@code{SUB}) is also
1390recognized as signalling the end of the source file. Again, this is
1391provided for compatibility with other operating systems where this
1392code is used to represent the end of file.
1393
1394@geindex spec (definition)
1395@geindex compilation (definition)
1396
1397Each file contains a single Ada compilation unit, including any pragmas
1398associated with the unit. For example, this means you must place a
1399package declaration (a package @emph{spec}) and the corresponding body in
1400separate files. An Ada @emph{compilation} (which is a sequence of
1401compilation units) is represented using a sequence of files. Similarly,
1402you will place each subunit or child unit in a separate file.
1403
1404@node Foreign Language Representation,File Naming Topics and Utilities,Source Representation,The GNAT Compilation Model
1405@anchor{gnat_ugn/the_gnat_compilation_model foreign-language-representation}@anchor{3e}@anchor{gnat_ugn/the_gnat_compilation_model id3}@anchor{47}
1406@section Foreign Language Representation
1407
1408
1409GNAT supports the standard character sets defined in Ada as well as
1410several other non-standard character sets for use in localized versions
1411of the compiler (@ref{48,,Character Set Control}).
1412
1413@menu
1414* Latin-1::
1415* Other 8-Bit Codes::
1416* Wide_Character Encodings::
1417* Wide_Wide_Character Encodings::
1418
1419@end menu
1420
1421@node Latin-1,Other 8-Bit Codes,,Foreign Language Representation
1422@anchor{gnat_ugn/the_gnat_compilation_model id4}@anchor{49}@anchor{gnat_ugn/the_gnat_compilation_model latin-1}@anchor{4a}
1423@subsection Latin-1
1424
1425
1426@geindex Latin-1
1427
1428The basic character set is Latin-1. This character set is defined by ISO
1429standard 8859, part 1. The lower half (character codes @code{16#00#}
1430... @code{16#7F#)} is identical to standard ASCII coding, but the upper
1431half is used to represent additional characters. These include extended letters
1432used by European languages, such as French accents, the vowels with umlauts
1433used in German, and the extra letter A-ring used in Swedish.
1434
1435@geindex Ada.Characters.Latin_1
1436
1437For a complete list of Latin-1 codes and their encodings, see the source
1438file of library unit @code{Ada.Characters.Latin_1} in file
1439@code{a-chlat1.ads}.
1440You may use any of these extended characters freely in character or
1441string literals. In addition, the extended characters that represent
1442letters can be used in identifiers.
1443
1444@node Other 8-Bit Codes,Wide_Character Encodings,Latin-1,Foreign Language Representation
1445@anchor{gnat_ugn/the_gnat_compilation_model other-8-bit-codes}@anchor{4b}@anchor{gnat_ugn/the_gnat_compilation_model id5}@anchor{4c}
1446@subsection Other 8-Bit Codes
1447
1448
1449GNAT also supports several other 8-bit coding schemes:
1450
1451@geindex Latin-2
1452
1453@geindex ISO 8859-2
1454
1455
1456@table @asis
1457
1458@item @emph{ISO 8859-2 (Latin-2)}
1459
1460Latin-2 letters allowed in identifiers, with uppercase and lowercase
1461equivalence.
1462@end table
1463
1464@geindex Latin-3
1465
1466@geindex ISO 8859-3
1467
1468
1469@table @asis
1470
1471@item @emph{ISO 8859-3 (Latin-3)}
1472
1473Latin-3 letters allowed in identifiers, with uppercase and lowercase
1474equivalence.
1475@end table
1476
1477@geindex Latin-4
1478
1479@geindex ISO 8859-4
1480
1481
1482@table @asis
1483
1484@item @emph{ISO 8859-4 (Latin-4)}
1485
1486Latin-4 letters allowed in identifiers, with uppercase and lowercase
1487equivalence.
1488@end table
1489
1490@geindex ISO 8859-5
1491
1492@geindex Cyrillic
1493
1494
1495@table @asis
1496
1497@item @emph{ISO 8859-5 (Cyrillic)}
1498
1499ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1500lowercase equivalence.
1501@end table
1502
1503@geindex ISO 8859-15
1504
1505@geindex Latin-9
1506
1507
1508@table @asis
1509
1510@item @emph{ISO 8859-15 (Latin-9)}
1511
1512ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1513lowercase equivalence
1514@end table
1515
1516@geindex code page 437 (IBM PC)
1517
1518
1519@table @asis
1520
1521@item @emph{IBM PC (code page 437)}
1522
1523This code page is the normal default for PCs in the U.S. It corresponds
1524to the original IBM PC character set. This set has some, but not all, of
1525the extended Latin-1 letters, but these letters do not have the same
1526encoding as Latin-1. In this mode, these letters are allowed in
1527identifiers with uppercase and lowercase equivalence.
1528@end table
1529
1530@geindex code page 850 (IBM PC)
1531
1532
1533@table @asis
1534
1535@item @emph{IBM PC (code page 850)}
1536
1537This code page is a modification of 437 extended to include all the
1538Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1539mode, all these letters are allowed in identifiers with uppercase and
1540lowercase equivalence.
1541
1542@item @emph{Full Upper 8-bit}
1543
1544Any character in the range 80-FF allowed in identifiers, and all are
1545considered distinct. In other words, there are no uppercase and lowercase
1546equivalences in this range. This is useful in conjunction with
1547certain encoding schemes used for some foreign character sets (e.g.,
1548the typical method of representing Chinese characters on the PC).
1549
1550@item @emph{No Upper-Half}
1551
1552No upper-half characters in the range 80-FF are allowed in identifiers.
1553This gives Ada 83 compatibility for identifier names.
1554@end table
1555
1556For precise data on the encodings permitted, and the uppercase and lowercase
1557equivalences that are recognized, see the file @code{csets.adb} in
1558the GNAT compiler sources. You will need to obtain a full source release
1559of GNAT to obtain this file.
1560
1561@node Wide_Character Encodings,Wide_Wide_Character Encodings,Other 8-Bit Codes,Foreign Language Representation
1562@anchor{gnat_ugn/the_gnat_compilation_model id6}@anchor{4d}@anchor{gnat_ugn/the_gnat_compilation_model wide-character-encodings}@anchor{4e}
1563@subsection Wide_Character Encodings
1564
1565
1566GNAT allows wide character codes to appear in character and string
1567literals, and also optionally in identifiers, by means of the following
1568possible encoding schemes:
1569
1570
1571@table @asis
1572
1573@item @emph{Hex Coding}
1574
1575In this encoding, a wide character is represented by the following five
1576character sequence:
1577
1578@example
1579ESC a b c d
1580@end example
1581
1582where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1583characters (using uppercase letters) of the wide character code. For
1584example, ESC A345 is used to represent the wide character with code
1585@code{16#A345#}.
1586This scheme is compatible with use of the full Wide_Character set.
1587
1588@item @emph{Upper-Half Coding}
1589
1590@geindex Upper-Half Coding
1591
1592The wide character with encoding @code{16#abcd#} where the upper bit is on
1593(in other words, 'a' is in the range 8-F) is represented as two bytes,
1594@code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1595character, but is not required to be in the upper half. This method can
1596be also used for shift-JIS or EUC, where the internal coding matches the
1597external coding.
1598
1599@item @emph{Shift JIS Coding}
1600
1601@geindex Shift JIS Coding
1602
1603A wide character is represented by a two-character sequence,
1604@code{16#ab#} and
1605@code{16#cd#}, with the restrictions described for upper-half encoding as
1606described above. The internal character code is the corresponding JIS
1607character according to the standard algorithm for Shift-JIS
1608conversion. Only characters defined in the JIS code set table can be
1609used with this encoding method.
1610
1611@item @emph{EUC Coding}
1612
1613@geindex EUC Coding
1614
1615A wide character is represented by a two-character sequence
1616@code{16#ab#} and
1617@code{16#cd#}, with both characters being in the upper half. The internal
1618character code is the corresponding JIS character according to the EUC
1619encoding algorithm. Only characters defined in the JIS code set table
1620can be used with this encoding method.
1621
1622@item @emph{UTF-8 Coding}
1623
1624A wide character is represented using
1625UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
162610646-1/Am.2. Depending on the character value, the representation
1627is a one, two, or three byte sequence:
1628
1629@example
163016#0000#-16#007f#: 2#0xxxxxxx#
163116#0080#-16#07ff#: 2#110xxxxx# 2#10xxxxxx#
163216#0800#-16#ffff#: 2#1110xxxx# 2#10xxxxxx# 2#10xxxxxx#
1633@end example
1634
1635where the @code{xxx} bits correspond to the left-padded bits of the
163616-bit character value. Note that all lower half ASCII characters
1637are represented as ASCII bytes and all upper half characters and
1638other wide characters are represented as sequences of upper-half
1639(The full UTF-8 scheme allows for encoding 31-bit characters as
16406-byte sequences, and in the following section on wide wide
1641characters, the use of these sequences is documented).
1642
1643@item @emph{Brackets Coding}
1644
1645In this encoding, a wide character is represented by the following eight
1646character sequence:
1647
1648@example
1649[ " a b c d " ]
1650@end example
1651
1652where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1653characters (using uppercase letters) of the wide character code. For
1654example, ['A345'] is used to represent the wide character with code
1655@code{16#A345#}. It is also possible (though not required) to use the
1656Brackets coding for upper half characters. For example, the code
1657@code{16#A3#} can be represented as @code{['A3']}.
1658
1659This scheme is compatible with use of the full Wide_Character set,
1660and is also the method used for wide character encoding in some standard
1661ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1662@end table
1663
1664@cartouche
1665@quotation Note
1666Some of these coding schemes do not permit the full use of the
1667Ada character set. For example, neither Shift JIS nor EUC allow the
1668use of the upper half of the Latin-1 set.
1669@end quotation
1670@end cartouche
1671
1672@node Wide_Wide_Character Encodings,,Wide_Character Encodings,Foreign Language Representation
1673@anchor{gnat_ugn/the_gnat_compilation_model id7}@anchor{4f}@anchor{gnat_ugn/the_gnat_compilation_model wide-wide-character-encodings}@anchor{50}
1674@subsection Wide_Wide_Character Encodings
1675
1676
1677GNAT allows wide wide character codes to appear in character and string
1678literals, and also optionally in identifiers, by means of the following
1679possible encoding schemes:
1680
1681
1682@table @asis
1683
1684@item @emph{UTF-8 Coding}
1685
1686A wide character is represented using
1687UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
168810646-1/Am.2. Depending on the character value, the representation
1689of character codes with values greater than 16#FFFF# is a
1690is a four, five, or six byte sequence:
1691
1692@example
169316#01_0000#-16#10_FFFF#:     11110xxx 10xxxxxx 10xxxxxx
1694                             10xxxxxx
169516#0020_0000#-16#03FF_FFFF#: 111110xx 10xxxxxx 10xxxxxx
1696                             10xxxxxx 10xxxxxx
169716#0400_0000#-16#7FFF_FFFF#: 1111110x 10xxxxxx 10xxxxxx
1698                             10xxxxxx 10xxxxxx 10xxxxxx
1699@end example
1700
1701where the @code{xxx} bits correspond to the left-padded bits of the
170232-bit character value.
1703
1704@item @emph{Brackets Coding}
1705
1706In this encoding, a wide wide character is represented by the following ten or
1707twelve byte character sequence:
1708
1709@example
1710[ " a b c d e f " ]
1711[ " a b c d e f g h " ]
1712@end example
1713
1714where @code{a-h} are the six or eight hexadecimal
1715characters (using uppercase letters) of the wide wide character code. For
1716example, ["1F4567"] is used to represent the wide wide character with code
1717@code{16#001F_4567#}.
1718
1719This scheme is compatible with use of the full Wide_Wide_Character set,
1720and is also the method used for wide wide character encoding in some standard
1721ACATS (Ada Conformity Assessment Test Suite) test suite distributions.
1722@end table
1723
1724@node File Naming Topics and Utilities,Configuration Pragmas,Foreign Language Representation,The GNAT Compilation Model
1725@anchor{gnat_ugn/the_gnat_compilation_model id8}@anchor{51}@anchor{gnat_ugn/the_gnat_compilation_model file-naming-topics-and-utilities}@anchor{3f}
1726@section File Naming Topics and Utilities
1727
1728
1729GNAT has a default file naming scheme and also provides the user with
1730a high degree of control over how the names and extensions of the
1731source files correspond to the Ada compilation units that they contain.
1732
1733@menu
1734* File Naming Rules::
1735* Using Other File Names::
1736* Alternative File Naming Schemes::
1737* Handling Arbitrary File Naming Conventions with gnatname::
1738* File Name Krunching with gnatkr::
1739* Renaming Files with gnatchop::
1740
1741@end menu
1742
1743@node File Naming Rules,Using Other File Names,,File Naming Topics and Utilities
1744@anchor{gnat_ugn/the_gnat_compilation_model file-naming-rules}@anchor{52}@anchor{gnat_ugn/the_gnat_compilation_model id9}@anchor{53}
1745@subsection File Naming Rules
1746
1747
1748The default file name is determined by the name of the unit that the
1749file contains. The name is formed by taking the full expanded name of
1750the unit and replacing the separating dots with hyphens and using
1751lowercase for all letters.
1752
1753An exception arises if the file name generated by the above rules starts
1754with one of the characters
1755@code{a}, @code{g}, @code{i}, or @code{s}, and the second character is a
1756minus. In this case, the character tilde is used in place
1757of the minus. The reason for this special rule is to avoid clashes with
1758the standard names for child units of the packages System, Ada,
1759Interfaces, and GNAT, which use the prefixes
1760@code{s-}, @code{a-}, @code{i-}, and @code{g-},
1761respectively.
1762
1763The file extension is @code{.ads} for a spec and
1764@code{.adb} for a body. The following table shows some
1765examples of these rules.
1766
1767@quotation
1768
1769
1770@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
1771@item
1772
1773Source File
1774
1775@tab
1776
1777Ada Compilation Unit
1778
1779@item
1780
1781@code{main.ads}
1782
1783@tab
1784
1785Main (spec)
1786
1787@item
1788
1789@code{main.adb}
1790
1791@tab
1792
1793Main (body)
1794
1795@item
1796
1797@code{arith_functions.ads}
1798
1799@tab
1800
1801Arith_Functions (package spec)
1802
1803@item
1804
1805@code{arith_functions.adb}
1806
1807@tab
1808
1809Arith_Functions (package body)
1810
1811@item
1812
1813@code{func-spec.ads}
1814
1815@tab
1816
1817Func.Spec (child package spec)
1818
1819@item
1820
1821@code{func-spec.adb}
1822
1823@tab
1824
1825Func.Spec (child package body)
1826
1827@item
1828
1829@code{main-sub.adb}
1830
1831@tab
1832
1833Sub (subunit of Main)
1834
1835@item
1836
1837@code{a~bad.adb}
1838
1839@tab
1840
1841A.Bad (child package body)
1842
1843@end multitable
1844
1845@end quotation
1846
1847Following these rules can result in excessively long
1848file names if corresponding
1849unit names are long (for example, if child units or subunits are
1850heavily nested). An option is available to shorten such long file names
1851(called file name 'krunching'). This may be particularly useful when
1852programs being developed with GNAT are to be used on operating systems
1853with limited file name lengths. @ref{54,,Using gnatkr}.
1854
1855Of course, no file shortening algorithm can guarantee uniqueness over
1856all possible unit names; if file name krunching is used, it is your
1857responsibility to ensure no name clashes occur. Alternatively you
1858can specify the exact file names that you want used, as described
1859in the next section. Finally, if your Ada programs are migrating from a
1860compiler with a different naming convention, you can use the gnatchop
1861utility to produce source files that follow the GNAT naming conventions.
1862(For details see @ref{36,,Renaming Files with gnatchop}.)
1863
1864Note: in the case of Windows or Mac OS operating systems, case is not
1865significant. So for example on Windows if the canonical name is
1866@code{main-sub.adb}, you can use the file name @code{Main-Sub.adb} instead.
1867However, case is significant for other operating systems, so for example,
1868if you want to use other than canonically cased file names on a Unix system,
1869you need to follow the procedures described in the next section.
1870
1871@node Using Other File Names,Alternative File Naming Schemes,File Naming Rules,File Naming Topics and Utilities
1872@anchor{gnat_ugn/the_gnat_compilation_model id10}@anchor{55}@anchor{gnat_ugn/the_gnat_compilation_model using-other-file-names}@anchor{35}
1873@subsection Using Other File Names
1874
1875
1876@geindex File names
1877
1878In the previous section, we have described the default rules used by
1879GNAT to determine the file name in which a given unit resides. It is
1880often convenient to follow these default rules, and if you follow them,
1881the compiler knows without being explicitly told where to find all
1882the files it needs.
1883
1884@geindex Source_File_Name pragma
1885
1886However, in some cases, particularly when a program is imported from
1887another Ada compiler environment, it may be more convenient for the
1888programmer to specify which file names contain which units. GNAT allows
1889arbitrary file names to be used by means of the Source_File_Name pragma.
1890The form of this pragma is as shown in the following examples:
1891
1892@example
1893pragma Source_File_Name (My_Utilities.Stacks,
1894  Spec_File_Name => "myutilst_a.ada");
1895pragma Source_File_name (My_Utilities.Stacks,
1896  Body_File_Name => "myutilst.ada");
1897@end example
1898
1899As shown in this example, the first argument for the pragma is the unit
1900name (in this example a child unit). The second argument has the form
1901of a named association. The identifier
1902indicates whether the file name is for a spec or a body;
1903the file name itself is given by a string literal.
1904
1905The source file name pragma is a configuration pragma, which means that
1906normally it will be placed in the @code{gnat.adc}
1907file used to hold configuration
1908pragmas that apply to a complete compilation environment.
1909For more details on how the @code{gnat.adc} file is created and used
1910see @ref{56,,Handling of Configuration Pragmas}.
1911
1912@geindex gnat.adc
1913
1914GNAT allows completely arbitrary file names to be specified using the
1915source file name pragma. However, if the file name specified has an
1916extension other than @code{.ads} or @code{.adb} it is necessary to use
1917a special syntax when compiling the file. The name in this case must be
1918preceded by the special sequence @code{-x} followed by a space and the name
1919of the language, here @code{ada}, as in:
1920
1921@example
1922$ gcc -c -x ada peculiar_file_name.sim
1923@end example
1924
1925@code{gnatmake} handles non-standard file names in the usual manner (the
1926non-standard file name for the main program is simply used as the
1927argument to gnatmake). Note that if the extension is also non-standard,
1928then it must be included in the @code{gnatmake} command, it may not
1929be omitted.
1930
1931@node Alternative File Naming Schemes,Handling Arbitrary File Naming Conventions with gnatname,Using Other File Names,File Naming Topics and Utilities
1932@anchor{gnat_ugn/the_gnat_compilation_model id11}@anchor{57}@anchor{gnat_ugn/the_gnat_compilation_model alternative-file-naming-schemes}@anchor{58}
1933@subsection Alternative File Naming Schemes
1934
1935
1936@geindex File naming schemes
1937@geindex alternative
1938
1939@geindex File names
1940
1941The previous section described the use of the @code{Source_File_Name}
1942pragma to allow arbitrary names to be assigned to individual source files.
1943However, this approach requires one pragma for each file, and especially in
1944large systems can result in very long @code{gnat.adc} files, and also create
1945a maintenance problem.
1946
1947@geindex Source_File_Name pragma
1948
1949GNAT also provides a facility for specifying systematic file naming schemes
1950other than the standard default naming scheme previously described. An
1951alternative scheme for naming is specified by the use of
1952@code{Source_File_Name} pragmas having the following format:
1953
1954@example
1955pragma Source_File_Name (
1956   Spec_File_Name  => FILE_NAME_PATTERN
1957 [ , Casing          => CASING_SPEC]
1958 [ , Dot_Replacement => STRING_LITERAL ] );
1959
1960pragma Source_File_Name (
1961   Body_File_Name  => FILE_NAME_PATTERN
1962 [ , Casing          => CASING_SPEC ]
1963 [ , Dot_Replacement => STRING_LITERAL ] ) ;
1964
1965pragma Source_File_Name (
1966   Subunit_File_Name  => FILE_NAME_PATTERN
1967 [ , Casing          => CASING_SPEC ]
1968 [ , Dot_Replacement => STRING_LITERAL ] ) ;
1969
1970FILE_NAME_PATTERN ::= STRING_LITERAL
1971CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1972@end example
1973
1974The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1975It contains a single asterisk character, and the unit name is substituted
1976systematically for this asterisk. The optional parameter
1977@code{Casing} indicates
1978whether the unit name is to be all upper-case letters, all lower-case letters,
1979or mixed-case. If no
1980@code{Casing} parameter is used, then the default is all
1981lower-case.
1982
1983The optional @code{Dot_Replacement} string is used to replace any periods
1984that occur in subunit or child unit names. If no @code{Dot_Replacement}
1985argument is used then separating dots appear unchanged in the resulting
1986file name.
1987Although the above syntax indicates that the
1988@code{Casing} argument must appear
1989before the @code{Dot_Replacement} argument, but it
1990is also permissible to write these arguments in the opposite order.
1991
1992As indicated, it is possible to specify different naming schemes for
1993bodies, specs, and subunits. Quite often the rule for subunits is the
1994same as the rule for bodies, in which case, there is no need to give
1995a separate @code{Subunit_File_Name} rule, and in this case the
1996@code{Body_File_name} rule is used for subunits as well.
1997
1998The separate rule for subunits can also be used to implement the rather
1999unusual case of a compilation environment (e.g., a single directory) which
2000contains a subunit and a child unit with the same unit name. Although
2001both units cannot appear in the same partition, the Ada Reference Manual
2002allows (but does not require) the possibility of the two units coexisting
2003in the same environment.
2004
2005The file name translation works in the following steps:
2006
2007
2008@itemize *
2009
2010@item
2011If there is a specific @code{Source_File_Name} pragma for the given unit,
2012then this is always used, and any general pattern rules are ignored.
2013
2014@item
2015If there is a pattern type @code{Source_File_Name} pragma that applies to
2016the unit, then the resulting file name will be used if the file exists. If
2017more than one pattern matches, the latest one will be tried first, and the
2018first attempt resulting in a reference to a file that exists will be used.
2019
2020@item
2021If no pattern type @code{Source_File_Name} pragma that applies to the unit
2022for which the corresponding file exists, then the standard GNAT default
2023naming rules are used.
2024@end itemize
2025
2026As an example of the use of this mechanism, consider a commonly used scheme
2027in which file names are all lower case, with separating periods copied
2028unchanged to the resulting file name, and specs end with @code{.1.ada}, and
2029bodies end with @code{.2.ada}. GNAT will follow this scheme if the following
2030two pragmas appear:
2031
2032@example
2033pragma Source_File_Name
2034  (Spec_File_Name => ".1.ada");
2035pragma Source_File_Name
2036  (Body_File_Name => ".2.ada");
2037@end example
2038
2039The default GNAT scheme is actually implemented by providing the following
2040default pragmas internally:
2041
2042@example
2043pragma Source_File_Name
2044  (Spec_File_Name => ".ads", Dot_Replacement => "-");
2045pragma Source_File_Name
2046  (Body_File_Name => ".adb", Dot_Replacement => "-");
2047@end example
2048
2049Our final example implements a scheme typically used with one of the
2050Ada 83 compilers, where the separator character for subunits was '__'
2051(two underscores), specs were identified by adding @code{_.ADA}, bodies
2052by adding @code{.ADA}, and subunits by
2053adding @code{.SEP}. All file names were
2054upper case. Child units were not present of course since this was an
2055Ada 83 compiler, but it seems reasonable to extend this scheme to use
2056the same double underscore separator for child units.
2057
2058@example
2059pragma Source_File_Name
2060  (Spec_File_Name => "_.ADA",
2061   Dot_Replacement => "__",
2062   Casing = Uppercase);
2063pragma Source_File_Name
2064  (Body_File_Name => ".ADA",
2065   Dot_Replacement => "__",
2066   Casing = Uppercase);
2067pragma Source_File_Name
2068  (Subunit_File_Name => ".SEP",
2069   Dot_Replacement => "__",
2070   Casing = Uppercase);
2071@end example
2072
2073@geindex gnatname
2074
2075@node Handling Arbitrary File Naming Conventions with gnatname,File Name Krunching with gnatkr,Alternative File Naming Schemes,File Naming Topics and Utilities
2076@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}
2077@subsection Handling Arbitrary File Naming Conventions with @code{gnatname}
2078
2079
2080@geindex File Naming Conventions
2081
2082@menu
2083* Arbitrary File Naming Conventions::
2084* Running gnatname::
2085* Switches for gnatname::
2086* Examples of gnatname Usage::
2087
2088@end menu
2089
2090@node Arbitrary File Naming Conventions,Running gnatname,,Handling Arbitrary File Naming Conventions with gnatname
2091@anchor{gnat_ugn/the_gnat_compilation_model arbitrary-file-naming-conventions}@anchor{5b}@anchor{gnat_ugn/the_gnat_compilation_model id13}@anchor{5c}
2092@subsubsection Arbitrary File Naming Conventions
2093
2094
2095The GNAT compiler must be able to know the source file name of a compilation
2096unit.  When using the standard GNAT default file naming conventions
2097(@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
2098does not need additional information.
2099
2100When the source file names do not follow the standard GNAT default file naming
2101conventions, the GNAT compiler must be given additional information through
2102a configuration pragmas file (@ref{14,,Configuration Pragmas})
2103or a project file.
2104When the non-standard file naming conventions are well-defined,
2105a small number of pragmas @code{Source_File_Name} specifying a naming pattern
2106(@ref{58,,Alternative File Naming Schemes}) may be sufficient. However,
2107if the file naming conventions are irregular or arbitrary, a number
2108of pragma @code{Source_File_Name} for individual compilation units
2109must be defined.
2110To help maintain the correspondence between compilation unit names and
2111source file names within the compiler,
2112GNAT provides a tool @code{gnatname} to generate the required pragmas for a
2113set of files.
2114
2115@node Running gnatname,Switches for gnatname,Arbitrary File Naming Conventions,Handling Arbitrary File Naming Conventions with gnatname
2116@anchor{gnat_ugn/the_gnat_compilation_model running-gnatname}@anchor{5d}@anchor{gnat_ugn/the_gnat_compilation_model id14}@anchor{5e}
2117@subsubsection Running @code{gnatname}
2118
2119
2120The usual form of the @code{gnatname} command is:
2121
2122@example
2123$ gnatname [ switches ]  naming_pattern  [ naming_patterns ]
2124    [--and [ switches ]  naming_pattern  [ naming_patterns ]]
2125@end example
2126
2127All of the arguments are optional. If invoked without any argument,
2128@code{gnatname} will display its usage.
2129
2130When used with at least one naming pattern, @code{gnatname} will attempt to
2131find all the compilation units in files that follow at least one of the
2132naming patterns. To find these compilation units,
2133@code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
2134regular files.
2135
2136One or several Naming Patterns may be given as arguments to @code{gnatname}.
2137Each Naming Pattern is enclosed between double quotes (or single
2138quotes on Windows).
2139A Naming Pattern is a regular expression similar to the wildcard patterns
2140used in file names by the Unix shells or the DOS prompt.
2141
2142@code{gnatname} may be called with several sections of directories/patterns.
2143Sections are separated by the switch @code{--and}. In each section, there must be
2144at least one pattern. If no directory is specified in a section, the current
2145directory (or the project directory if @code{-P} is used) is implied.
2146The options other that the directory switches and the patterns apply globally
2147even if they are in different sections.
2148
2149Examples of Naming Patterns are:
2150
2151@example
2152"*.[12].ada"
2153"*.ad[sb]*"
2154"body_*"    "spec_*"
2155@end example
2156
2157For a more complete description of the syntax of Naming Patterns,
2158see the second kind of regular expressions described in @code{g-regexp.ads}
2159(the 'Glob' regular expressions).
2160
2161When invoked without the switch @code{-P}, @code{gnatname} will create a
2162configuration pragmas file @code{gnat.adc} in the current working directory,
2163with pragmas @code{Source_File_Name} for each file that contains a valid Ada
2164unit.
2165
2166@node Switches for gnatname,Examples of gnatname Usage,Running gnatname,Handling Arbitrary File Naming Conventions with gnatname
2167@anchor{gnat_ugn/the_gnat_compilation_model id15}@anchor{5f}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatname}@anchor{60}
2168@subsubsection Switches for @code{gnatname}
2169
2170
2171Switches for @code{gnatname} must precede any specified Naming Pattern.
2172
2173You may specify any of the following switches to @code{gnatname}:
2174
2175@geindex --version (gnatname)
2176
2177
2178@table @asis
2179
2180@item @code{--version}
2181
2182Display Copyright and version, then exit disregarding all other options.
2183@end table
2184
2185@geindex --help (gnatname)
2186
2187
2188@table @asis
2189
2190@item @code{--help}
2191
2192If @code{--version} was not used, display usage, then exit disregarding
2193all other options.
2194
2195@item @code{--subdirs=@emph{dir}}
2196
2197Real object, library or exec directories are subdirectories <dir> of the
2198specified ones.
2199
2200@item @code{--no-backup}
2201
2202Do not create a backup copy of an existing project file.
2203
2204@item @code{--and}
2205
2206Start another section of directories/patterns.
2207@end table
2208
2209@geindex -c (gnatname)
2210
2211
2212@table @asis
2213
2214@item @code{-c@emph{filename}}
2215
2216Create a configuration pragmas file @code{filename} (instead of the default
2217@code{gnat.adc}).
2218There may be zero, one or more space between @code{-c} and
2219@code{filename}.
2220@code{filename} may include directory information. @code{filename} must be
2221writable. There may be only one switch @code{-c}.
2222When a switch @code{-c} is
2223specified, no switch @code{-P} may be specified (see below).
2224@end table
2225
2226@geindex -d (gnatname)
2227
2228
2229@table @asis
2230
2231@item @code{-d@emph{dir}}
2232
2233Look for source files in directory @code{dir}. There may be zero, one or more
2234spaces between @code{-d} and @code{dir}.
2235@code{dir} may end with @code{/**}, that is it may be of the form
2236@code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
2237subdirectories, recursively, have to be searched for sources.
2238When a switch @code{-d}
2239is specified, the current working directory will not be searched for source
2240files, unless it is explicitly specified with a @code{-d}
2241or @code{-D} switch.
2242Several switches @code{-d} may be specified.
2243If @code{dir} is a relative path, it is relative to the directory of
2244the configuration pragmas file specified with switch
2245@code{-c},
2246or to the directory of the project file specified with switch
2247@code{-P} or,
2248if neither switch @code{-c}
2249nor switch @code{-P} are specified, it is relative to the
2250current working directory. The directory
2251specified with switch @code{-d} must exist and be readable.
2252@end table
2253
2254@geindex -D (gnatname)
2255
2256
2257@table @asis
2258
2259@item @code{-D@emph{filename}}
2260
2261Look for source files in all directories listed in text file @code{filename}.
2262There may be zero, one or more spaces between @code{-D}
2263and @code{filename}.
2264@code{filename} must be an existing, readable text file.
2265Each nonempty line in @code{filename} must be a directory.
2266Specifying switch @code{-D} is equivalent to specifying as many
2267switches @code{-d} as there are nonempty lines in
2268@code{file}.
2269
2270@item @code{-eL}
2271
2272Follow symbolic links when processing project files.
2273
2274@geindex -f (gnatname)
2275
2276@item @code{-f@emph{pattern}}
2277
2278Foreign patterns. Using this switch, it is possible to add sources of languages
2279other than Ada to the list of sources of a project file.
2280It is only useful if a -P switch is used.
2281For example,
2282
2283@example
2284gnatname -Pprj -f"*.c" "*.ada"
2285@end example
2286
2287will look for Ada units in all files with the @code{.ada} extension,
2288and will add to the list of file for project @code{prj.gpr} the C files
2289with extension @code{.c}.
2290
2291@geindex -h (gnatname)
2292
2293@item @code{-h}
2294
2295Output usage (help) information. The output is written to @code{stdout}.
2296
2297@geindex -P (gnatname)
2298
2299@item @code{-P@emph{proj}}
2300
2301Create or update project file @code{proj}. There may be zero, one or more space
2302between @code{-P} and @code{proj}. @code{proj} may include directory
2303information. @code{proj} must be writable.
2304There may be only one switch @code{-P}.
2305When a switch @code{-P} is specified,
2306no switch @code{-c} may be specified.
2307On all platforms, except on VMS, when @code{gnatname} is invoked for an
2308existing project file <proj>.gpr, a backup copy of the project file is created
2309in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
2310non negative number that makes this backup copy a new file.
2311
2312@geindex -v (gnatname)
2313
2314@item @code{-v}
2315
2316Verbose mode. Output detailed explanation of behavior to @code{stdout}.
2317This includes name of the file written, the name of the directories to search
2318and, for each file in those directories whose name matches at least one of
2319the Naming Patterns, an indication of whether the file contains a unit,
2320and if so the name of the unit.
2321@end table
2322
2323@geindex -v -v (gnatname)
2324
2325
2326@table @asis
2327
2328@item @code{-v -v}
2329
2330Very Verbose mode. In addition to the output produced in verbose mode,
2331for each file in the searched directories whose name matches none of
2332the Naming Patterns, an indication is given that there is no match.
2333
2334@geindex -x (gnatname)
2335
2336@item @code{-x@emph{pattern}}
2337
2338Excluded patterns. Using this switch, it is possible to exclude some files
2339that would match the name patterns. For example,
2340
2341@example
2342gnatname -x "*_nt.ada" "*.ada"
2343@end example
2344
2345will look for Ada units in all files with the @code{.ada} extension,
2346except those whose names end with @code{_nt.ada}.
2347@end table
2348
2349@node Examples of gnatname Usage,,Switches for gnatname,Handling Arbitrary File Naming Conventions with gnatname
2350@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatname-usage}@anchor{61}@anchor{gnat_ugn/the_gnat_compilation_model id16}@anchor{62}
2351@subsubsection Examples of @code{gnatname} Usage
2352
2353
2354@example
2355$ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
2356@end example
2357
2358In this example, the directory @code{/home/me} must already exist
2359and be writable. In addition, the directory
2360@code{/home/me/sources} (specified by
2361@code{-d sources}) must exist and be readable.
2362
2363Note the optional spaces after @code{-c} and @code{-d}.
2364
2365@example
2366$ gnatname -P/home/me/proj -x "*_nt_body.ada"
2367-dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
2368@end example
2369
2370Note that several switches @code{-d} may be used,
2371even in conjunction with one or several switches
2372@code{-D}. Several Naming Patterns and one excluded pattern
2373are used in this example.
2374
2375@node File Name Krunching with gnatkr,Renaming Files with gnatchop,Handling Arbitrary File Naming Conventions with gnatname,File Naming Topics and Utilities
2376@anchor{gnat_ugn/the_gnat_compilation_model file-name-krunching-with-gnatkr}@anchor{63}@anchor{gnat_ugn/the_gnat_compilation_model id17}@anchor{64}
2377@subsection File Name Krunching with @code{gnatkr}
2378
2379
2380@geindex gnatkr
2381
2382This section discusses the method used by the compiler to shorten
2383the default file names chosen for Ada units so that they do not
2384exceed the maximum length permitted. It also describes the
2385@code{gnatkr} utility that can be used to determine the result of
2386applying this shortening.
2387
2388@menu
2389* About gnatkr::
2390* Using gnatkr::
2391* Krunching Method::
2392* Examples of gnatkr Usage::
2393
2394@end menu
2395
2396@node About gnatkr,Using gnatkr,,File Name Krunching with gnatkr
2397@anchor{gnat_ugn/the_gnat_compilation_model id18}@anchor{65}@anchor{gnat_ugn/the_gnat_compilation_model about-gnatkr}@anchor{66}
2398@subsubsection About @code{gnatkr}
2399
2400
2401The default file naming rule in GNAT
2402is that the file name must be derived from
2403the unit name. The exact default rule is as follows:
2404
2405
2406@itemize *
2407
2408@item
2409Take the unit name and replace all dots by hyphens.
2410
2411@item
2412If such a replacement occurs in the
2413second character position of a name, and the first character is
2414@code{a}, @code{g}, @code{s}, or @code{i},
2415then replace the dot by the character
2416@code{~} (tilde)
2417instead of a minus.
2418
2419The reason for this exception is to avoid clashes
2420with the standard names for children of System, Ada, Interfaces,
2421and GNAT, which use the prefixes
2422@code{s-}, @code{a-}, @code{i-}, and @code{g-},
2423respectively.
2424@end itemize
2425
2426The @code{-gnatk@emph{nn}}
2427switch of the compiler activates a 'krunching'
2428circuit that limits file names to nn characters (where nn is a decimal
2429integer).
2430
2431The @code{gnatkr} utility can be used to determine the krunched name for
2432a given file, when krunched to a specified maximum length.
2433
2434@node Using gnatkr,Krunching Method,About gnatkr,File Name Krunching with gnatkr
2435@anchor{gnat_ugn/the_gnat_compilation_model id19}@anchor{67}@anchor{gnat_ugn/the_gnat_compilation_model using-gnatkr}@anchor{54}
2436@subsubsection Using @code{gnatkr}
2437
2438
2439The @code{gnatkr} command has the form:
2440
2441@example
2442$ gnatkr name [ length ]
2443@end example
2444
2445@code{name} is the uncrunched file name, derived from the name of the unit
2446in the standard manner described in the previous section (i.e., in particular
2447all dots are replaced by hyphens). The file name may or may not have an
2448extension (defined as a suffix of the form period followed by arbitrary
2449characters other than period). If an extension is present then it will
2450be preserved in the output. For example, when krunching @code{hellofile.ads}
2451to eight characters, the result will be hellofil.ads.
2452
2453Note: for compatibility with previous versions of @code{gnatkr} dots may
2454appear in the name instead of hyphens, but the last dot will always be
2455taken as the start of an extension. So if @code{gnatkr} is given an argument
2456such as @code{Hello.World.adb} it will be treated exactly as if the first
2457period had been a hyphen, and for example krunching to eight characters
2458gives the result @code{hellworl.adb}.
2459
2460Note that the result is always all lower case.
2461Characters of the other case are folded as required.
2462
2463@code{length} represents the length of the krunched name. The default
2464when no argument is given is 8 characters. A length of zero stands for
2465unlimited, in other words do not chop except for system files where the
2466implied crunching length is always eight characters.
2467
2468The output is the krunched name. The output has an extension only if the
2469original argument was a file name with an extension.
2470
2471@node Krunching Method,Examples of gnatkr Usage,Using gnatkr,File Name Krunching with gnatkr
2472@anchor{gnat_ugn/the_gnat_compilation_model id20}@anchor{68}@anchor{gnat_ugn/the_gnat_compilation_model krunching-method}@anchor{69}
2473@subsubsection Krunching Method
2474
2475
2476The initial file name is determined by the name of the unit that the file
2477contains. The name is formed by taking the full expanded name of the
2478unit and replacing the separating dots with hyphens and
2479using lowercase
2480for all letters, except that a hyphen in the second character position is
2481replaced by a tilde if the first character is
2482@code{a}, @code{i}, @code{g}, or @code{s}.
2483The extension is @code{.ads} for a
2484spec and @code{.adb} for a body.
2485Krunching does not affect the extension, but the file name is shortened to
2486the specified length by following these rules:
2487
2488
2489@itemize *
2490
2491@item
2492The name is divided into segments separated by hyphens, tildes or
2493underscores and all hyphens, tildes, and underscores are
2494eliminated. If this leaves the name short enough, we are done.
2495
2496@item
2497If the name is too long, the longest segment is located (left-most
2498if there are two of equal length), and shortened by dropping
2499its last character. This is repeated until the name is short enough.
2500
2501As an example, consider the krunching of @code{our-strings-wide_fixed.adb}
2502to fit the name into 8 characters as required by some operating systems:
2503
2504@example
2505our-strings-wide_fixed 22
2506our strings wide fixed 19
2507our string  wide fixed 18
2508our strin   wide fixed 17
2509our stri    wide fixed 16
2510our stri    wide fixe  15
2511our str     wide fixe  14
2512our str     wid  fixe  13
2513our str     wid  fix   12
2514ou  str     wid  fix   11
2515ou  st      wid  fix   10
2516ou  st      wi   fix   9
2517ou  st      wi   fi    8
2518Final file name: oustwifi.adb
2519@end example
2520
2521@item
2522The file names for all predefined units are always krunched to eight
2523characters. The krunching of these predefined units uses the following
2524special prefix replacements:
2525
2526
2527@multitable {xxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx}
2528@item
2529
2530Prefix
2531
2532@tab
2533
2534Replacement
2535
2536@item
2537
2538@code{ada-}
2539
2540@tab
2541
2542@code{a-}
2543
2544@item
2545
2546@code{gnat-}
2547
2548@tab
2549
2550@code{g-}
2551
2552@item
2553
2554@code{interfac es-}
2555
2556@tab
2557
2558@code{i-}
2559
2560@item
2561
2562@code{system-}
2563
2564@tab
2565
2566@code{s-}
2567
2568@end multitable
2569
2570
2571These system files have a hyphen in the second character position. That
2572is why normal user files replace such a character with a
2573tilde, to avoid confusion with system file names.
2574
2575As an example of this special rule, consider
2576@code{ada-strings-wide_fixed.adb}, which gets krunched as follows:
2577
2578@example
2579ada-strings-wide_fixed 22
2580a-  strings wide fixed 18
2581a-  string  wide fixed 17
2582a-  strin   wide fixed 16
2583a-  stri    wide fixed 15
2584a-  stri    wide fixe  14
2585a-  str     wide fixe  13
2586a-  str     wid  fixe  12
2587a-  str     wid  fix   11
2588a-  st      wid  fix   10
2589a-  st      wi   fix   9
2590a-  st      wi   fi    8
2591Final file name: a-stwifi.adb
2592@end example
2593@end itemize
2594
2595Of course no file shortening algorithm can guarantee uniqueness over all
2596possible unit names, and if file name krunching is used then it is your
2597responsibility to ensure that no name clashes occur. The utility
2598program @code{gnatkr} is supplied for conveniently determining the
2599krunched name of a file.
2600
2601@node Examples of gnatkr Usage,,Krunching Method,File Name Krunching with gnatkr
2602@anchor{gnat_ugn/the_gnat_compilation_model id21}@anchor{6a}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatkr-usage}@anchor{6b}
2603@subsubsection Examples of @code{gnatkr} Usage
2604
2605
2606@example
2607$ gnatkr very_long_unit_name.ads      --> velounna.ads
2608$ gnatkr grandparent-parent-child.ads --> grparchi.ads
2609$ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
2610$ gnatkr grandparent-parent-child     --> grparchi
2611$ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
2612$ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
2613@end example
2614
2615@node Renaming Files with gnatchop,,File Name Krunching with gnatkr,File Naming Topics and Utilities
2616@anchor{gnat_ugn/the_gnat_compilation_model id22}@anchor{6c}@anchor{gnat_ugn/the_gnat_compilation_model renaming-files-with-gnatchop}@anchor{36}
2617@subsection Renaming Files with @code{gnatchop}
2618
2619
2620@geindex gnatchop
2621
2622This section discusses how to handle files with multiple units by using
2623the @code{gnatchop} utility. This utility is also useful in renaming
2624files to meet the standard GNAT default file naming conventions.
2625
2626@menu
2627* Handling Files with Multiple Units::
2628* Operating gnatchop in Compilation Mode::
2629* Command Line for gnatchop::
2630* Switches for gnatchop::
2631* Examples of gnatchop Usage::
2632
2633@end menu
2634
2635@node Handling Files with Multiple Units,Operating gnatchop in Compilation Mode,,Renaming Files with gnatchop
2636@anchor{gnat_ugn/the_gnat_compilation_model id23}@anchor{6d}@anchor{gnat_ugn/the_gnat_compilation_model handling-files-with-multiple-units}@anchor{6e}
2637@subsubsection Handling Files with Multiple Units
2638
2639
2640The basic compilation model of GNAT requires that a file submitted to the
2641compiler have only one unit and there be a strict correspondence
2642between the file name and the unit name.
2643
2644The @code{gnatchop} utility allows both of these rules to be relaxed,
2645allowing GNAT to process files which contain multiple compilation units
2646and files with arbitrary file names. @code{gnatchop}
2647reads the specified file and generates one or more output files,
2648containing one unit per file. The unit and the file name correspond,
2649as required by GNAT.
2650
2651If you want to permanently restructure a set of 'foreign' files so that
2652they match the GNAT rules, and do the remaining development using the
2653GNAT structure, you can simply use @code{gnatchop} once, generate the
2654new set of files and work with them from that point on.
2655
2656Alternatively, if you want to keep your files in the 'foreign' format,
2657perhaps to maintain compatibility with some other Ada compilation
2658system, you can set up a procedure where you use @code{gnatchop} each
2659time you compile, regarding the source files that it writes as temporary
2660files that you throw away.
2661
2662Note that if your file containing multiple units starts with a byte order
2663mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
2664will each start with a copy of this BOM, meaning that they can be compiled
2665automatically in UTF-8 mode without needing to specify an explicit encoding.
2666
2667@node Operating gnatchop in Compilation Mode,Command Line for gnatchop,Handling Files with Multiple Units,Renaming Files with gnatchop
2668@anchor{gnat_ugn/the_gnat_compilation_model operating-gnatchop-in-compilation-mode}@anchor{6f}@anchor{gnat_ugn/the_gnat_compilation_model id24}@anchor{70}
2669@subsubsection Operating gnatchop in Compilation Mode
2670
2671
2672The basic function of @code{gnatchop} is to take a file with multiple units
2673and split it into separate files. The boundary between files is reasonably
2674clear, except for the issue of comments and pragmas. In default mode, the
2675rule is that any pragmas between units belong to the previous unit, except
2676that configuration pragmas always belong to the following unit. Any comments
2677belong to the following unit. These rules
2678almost always result in the right choice of
2679the split point without needing to mark it explicitly and most users will
2680find this default to be what they want. In this default mode it is incorrect to
2681submit a file containing only configuration pragmas, or one that ends in
2682configuration pragmas, to @code{gnatchop}.
2683
2684However, using a special option to activate 'compilation mode',
2685@code{gnatchop}
2686can perform another function, which is to provide exactly the semantics
2687required by the RM for handling of configuration pragmas in a compilation.
2688In the absence of configuration pragmas (at the main file level), this
2689option has no effect, but it causes such configuration pragmas to be handled
2690in a quite different manner.
2691
2692First, in compilation mode, if @code{gnatchop} is given a file that consists of
2693only configuration pragmas, then this file is appended to the
2694@code{gnat.adc} file in the current directory. This behavior provides
2695the required behavior described in the RM for the actions to be taken
2696on submitting such a file to the compiler, namely that these pragmas
2697should apply to all subsequent compilations in the same compilation
2698environment. Using GNAT, the current directory, possibly containing a
2699@code{gnat.adc} file is the representation
2700of a compilation environment. For more information on the
2701@code{gnat.adc} file, see @ref{56,,Handling of Configuration Pragmas}.
2702
2703Second, in compilation mode, if @code{gnatchop}
2704is given a file that starts with
2705configuration pragmas, and contains one or more units, then these
2706configuration pragmas are prepended to each of the chopped files. This
2707behavior provides the required behavior described in the RM for the
2708actions to be taken on compiling such a file, namely that the pragmas
2709apply to all units in the compilation, but not to subsequently compiled
2710units.
2711
2712Finally, if configuration pragmas appear between units, they are appended
2713to the previous unit. This results in the previous unit being illegal,
2714since the compiler does not accept configuration pragmas that follow
2715a unit. This provides the required RM behavior that forbids configuration
2716pragmas other than those preceding the first compilation unit of a
2717compilation.
2718
2719For most purposes, @code{gnatchop} will be used in default mode. The
2720compilation mode described above is used only if you need exactly
2721accurate behavior with respect to compilations, and you have files
2722that contain multiple units and configuration pragmas. In this
2723circumstance the use of @code{gnatchop} with the compilation mode
2724switch provides the required behavior, and is for example the mode
2725in which GNAT processes the ACVC tests.
2726
2727@node Command Line for gnatchop,Switches for gnatchop,Operating gnatchop in Compilation Mode,Renaming Files with gnatchop
2728@anchor{gnat_ugn/the_gnat_compilation_model id25}@anchor{71}@anchor{gnat_ugn/the_gnat_compilation_model command-line-for-gnatchop}@anchor{72}
2729@subsubsection Command Line for @code{gnatchop}
2730
2731
2732The @code{gnatchop} command has the form:
2733
2734@example
2735$ gnatchop switches file_name [file_name ...]
2736      [directory]
2737@end example
2738
2739The only required argument is the file name of the file to be chopped.
2740There are no restrictions on the form of this file name. The file itself
2741contains one or more Ada units, in normal GNAT format, concatenated
2742together. As shown, more than one file may be presented to be chopped.
2743
2744When run in default mode, @code{gnatchop} generates one output file in
2745the current directory for each unit in each of the files.
2746
2747@code{directory}, if specified, gives the name of the directory to which
2748the output files will be written. If it is not specified, all files are
2749written to the current directory.
2750
2751For example, given a
2752file called @code{hellofiles} containing
2753
2754@example
2755procedure Hello;
2756
2757with Ada.Text_IO; use Ada.Text_IO;
2758procedure Hello is
2759begin
2760   Put_Line ("Hello");
2761end Hello;
2762@end example
2763
2764the command
2765
2766@example
2767$ gnatchop hellofiles
2768@end example
2769
2770generates two files in the current directory, one called
2771@code{hello.ads} containing the single line that is the procedure spec,
2772and the other called @code{hello.adb} containing the remaining text. The
2773original file is not affected. The generated files can be compiled in
2774the normal manner.
2775
2776When gnatchop is invoked on a file that is empty or that contains only empty
2777lines and/or comments, gnatchop will not fail, but will not produce any
2778new sources.
2779
2780For example, given a
2781file called @code{toto.txt} containing
2782
2783@example
2784--  Just a comment
2785@end example
2786
2787the command
2788
2789@example
2790$ gnatchop toto.txt
2791@end example
2792
2793will not produce any new file and will result in the following warnings:
2794
2795@example
2796toto.txt:1:01: warning: empty file, contains no compilation units
2797no compilation units found
2798no source files written
2799@end example
2800
2801@node Switches for gnatchop,Examples of gnatchop Usage,Command Line for gnatchop,Renaming Files with gnatchop
2802@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatchop}@anchor{73}@anchor{gnat_ugn/the_gnat_compilation_model id26}@anchor{74}
2803@subsubsection Switches for @code{gnatchop}
2804
2805
2806@code{gnatchop} recognizes the following switches:
2807
2808@geindex --version (gnatchop)
2809
2810
2811@table @asis
2812
2813@item @code{--version}
2814
2815Display Copyright and version, then exit disregarding all other options.
2816@end table
2817
2818@geindex --help (gnatchop)
2819
2820
2821@table @asis
2822
2823@item @code{--help}
2824
2825If @code{--version} was not used, display usage, then exit disregarding
2826all other options.
2827@end table
2828
2829@geindex -c (gnatchop)
2830
2831
2832@table @asis
2833
2834@item @code{-c}
2835
2836Causes @code{gnatchop} to operate in compilation mode, in which
2837configuration pragmas are handled according to strict RM rules. See
2838previous section for a full description of this mode.
2839
2840@item @code{-gnat@emph{xxx}}
2841
2842This passes the given @code{-gnat@emph{xxx}} switch to @code{gnat} which is
2843used to parse the given file. Not all @emph{xxx} options make sense,
2844but for example, the use of @code{-gnati2} allows @code{gnatchop} to
2845process a source file that uses Latin-2 coding for identifiers.
2846
2847@item @code{-h}
2848
2849Causes @code{gnatchop} to generate a brief help summary to the standard
2850output file showing usage information.
2851@end table
2852
2853@geindex -k (gnatchop)
2854
2855
2856@table @asis
2857
2858@item @code{-k@emph{mm}}
2859
2860Limit generated file names to the specified number @code{mm}
2861of characters.
2862This is useful if the
2863resulting set of files is required to be interoperable with systems
2864which limit the length of file names.
2865No space is allowed between the @code{-k} and the numeric value. The numeric
2866value may be omitted in which case a default of @code{-k8},
2867suitable for use
2868with DOS-like file systems, is used. If no @code{-k} switch
2869is present then
2870there is no limit on the length of file names.
2871@end table
2872
2873@geindex -p (gnatchop)
2874
2875
2876@table @asis
2877
2878@item @code{-p}
2879
2880Causes the file modification time stamp of the input file to be
2881preserved and used for the time stamp of the output file(s). This may be
2882useful for preserving coherency of time stamps in an environment where
2883@code{gnatchop} is used as part of a standard build process.
2884@end table
2885
2886@geindex -q (gnatchop)
2887
2888
2889@table @asis
2890
2891@item @code{-q}
2892
2893Causes output of informational messages indicating the set of generated
2894files to be suppressed. Warnings and error messages are unaffected.
2895@end table
2896
2897@geindex -r (gnatchop)
2898
2899@geindex Source_Reference pragmas
2900
2901
2902@table @asis
2903
2904@item @code{-r}
2905
2906Generate @code{Source_Reference} pragmas. Use this switch if the output
2907files are regarded as temporary and development is to be done in terms
2908of the original unchopped file. This switch causes
2909@code{Source_Reference} pragmas to be inserted into each of the
2910generated files to refers back to the original file name and line number.
2911The result is that all error messages refer back to the original
2912unchopped file.
2913In addition, the debugging information placed into the object file (when
2914the @code{-g} switch of @code{gcc} or @code{gnatmake} is
2915specified)
2916also refers back to this original file so that tools like profilers and
2917debuggers will give information in terms of the original unchopped file.
2918
2919If the original file to be chopped itself contains
2920a @code{Source_Reference}
2921pragma referencing a third file, then gnatchop respects
2922this pragma, and the generated @code{Source_Reference} pragmas
2923in the chopped file refer to the original file, with appropriate
2924line numbers. This is particularly useful when @code{gnatchop}
2925is used in conjunction with @code{gnatprep} to compile files that
2926contain preprocessing statements and multiple units.
2927@end table
2928
2929@geindex -v (gnatchop)
2930
2931
2932@table @asis
2933
2934@item @code{-v}
2935
2936Causes @code{gnatchop} to operate in verbose mode. The version
2937number and copyright notice are output, as well as exact copies of
2938the gnat1 commands spawned to obtain the chop control information.
2939@end table
2940
2941@geindex -w (gnatchop)
2942
2943
2944@table @asis
2945
2946@item @code{-w}
2947
2948Overwrite existing file names. Normally @code{gnatchop} regards it as a
2949fatal error if there is already a file with the same name as a
2950file it would otherwise output, in other words if the files to be
2951chopped contain duplicated units. This switch bypasses this
2952check, and causes all but the last instance of such duplicated
2953units to be skipped.
2954@end table
2955
2956@geindex --GCC= (gnatchop)
2957
2958
2959@table @asis
2960
2961@item @code{--GCC=@emph{xxxx}}
2962
2963Specify the path of the GNAT parser to be used. When this switch is used,
2964no attempt is made to add the prefix to the GNAT parser executable.
2965@end table
2966
2967@node Examples of gnatchop Usage,,Switches for gnatchop,Renaming Files with gnatchop
2968@anchor{gnat_ugn/the_gnat_compilation_model id27}@anchor{75}@anchor{gnat_ugn/the_gnat_compilation_model examples-of-gnatchop-usage}@anchor{76}
2969@subsubsection Examples of @code{gnatchop} Usage
2970
2971
2972@example
2973$ gnatchop -w hello_s.ada prerelease/files
2974@end example
2975
2976Chops the source file @code{hello_s.ada}. The output files will be
2977placed in the directory @code{prerelease/files},
2978overwriting any
2979files with matching names in that directory (no files in the current
2980directory are modified).
2981
2982@example
2983$ gnatchop archive
2984@end example
2985
2986Chops the source file @code{archive}
2987into the current directory. One
2988useful application of @code{gnatchop} is in sending sets of sources
2989around, for example in email messages. The required sources are simply
2990concatenated (for example, using a Unix @code{cat}
2991command), and then
2992@code{gnatchop} is used at the other end to reconstitute the original
2993file names.
2994
2995@example
2996$ gnatchop file1 file2 file3 direc
2997@end example
2998
2999Chops all units in files @code{file1}, @code{file2}, @code{file3}, placing
3000the resulting files in the directory @code{direc}. Note that if any units
3001occur more than once anywhere within this set of files, an error message
3002is generated, and no files are written. To override this check, use the
3003@code{-w} switch,
3004in which case the last occurrence in the last file will
3005be the one that is output, and earlier duplicate occurrences for a given
3006unit will be skipped.
3007
3008@node Configuration Pragmas,Generating Object Files,File Naming Topics and Utilities,The GNAT Compilation Model
3009@anchor{gnat_ugn/the_gnat_compilation_model id28}@anchor{77}@anchor{gnat_ugn/the_gnat_compilation_model configuration-pragmas}@anchor{14}
3010@section Configuration Pragmas
3011
3012
3013@geindex Configuration pragmas
3014
3015@geindex Pragmas
3016@geindex configuration
3017
3018Configuration pragmas include those pragmas described as
3019such in the Ada Reference Manual, as well as
3020implementation-dependent pragmas that are configuration pragmas.
3021See the @code{Implementation_Defined_Pragmas} chapter in the
3022@cite{GNAT_Reference_Manual} for details on these
3023additional GNAT-specific configuration pragmas.
3024Most notably, the pragma @code{Source_File_Name}, which allows
3025specifying non-default names for source files, is a configuration
3026pragma. The following is a complete list of configuration pragmas
3027recognized by GNAT:
3028
3029@example
3030Ada_83
3031Ada_95
3032Ada_05
3033Ada_2005
3034Ada_12
3035Ada_2012
3036Allow_Integer_Address
3037Annotate
3038Assertion_Policy
3039Assume_No_Invalid_Values
3040C_Pass_By_Copy
3041Check_Float_Overflow
3042Check_Name
3043Check_Policy
3044Compile_Time_Error
3045Compile_Time_Warning
3046Compiler_Unit
3047Compiler_Unit_Warning
3048Component_Alignment
3049Convention_Identifier
3050Debug_Policy
3051Detect_Blocking
3052Default_Scalar_Storage_Order
3053Default_Storage_Pool
3054Disable_Atomic_Synchronization
3055Discard_Names
3056Elaboration_Checks
3057Eliminate
3058Enable_Atomic_Synchronization
3059Extend_System
3060Extensions_Allowed
3061External_Name_Casing
3062Fast_Math
3063Favor_Top_Level
3064Ignore_Pragma
3065Implicit_Packing
3066Initialize_Scalars
3067Interrupt_State
3068License
3069Locking_Policy
3070No_Component_Reordering
3071No_Heap_Finalization
3072No_Run_Time
3073No_Strict_Aliasing
3074Normalize_Scalars
3075Optimize_Alignment
3076Overflow_Mode
3077Overriding_Renamings
3078Partition_Elaboration_Policy
3079Persistent_BSS
3080Polling
3081Prefix_Exception_Messages
3082Priority_Specific_Dispatching
3083Profile
3084Profile_Warnings
3085Propagate_Exceptions
3086Queuing_Policy
3087Rational
3088Ravenscar
3089Rename_Pragma
3090Restricted_Run_Time
3091Restrictions
3092Restrictions_Warnings
3093Reviewable
3094Short_Circuit_And_Or
3095Short_Descriptors
3096Source_File_Name
3097Source_File_Name_Project
3098SPARK_Mode
3099Style_Checks
3100Suppress
3101Suppress_Exception_Locations
3102Task_Dispatching_Policy
3103Unevaluated_Use_Of_Old
3104Universal_Data
3105Unsuppress
3106Use_VADS_Size
3107Validity_Checks
3108Warning_As_Error
3109Warnings
3110Wide_Character_Encoding
3111@end example
3112
3113@menu
3114* Handling of Configuration Pragmas::
3115* The Configuration Pragmas Files::
3116
3117@end menu
3118
3119@node Handling of Configuration Pragmas,The Configuration Pragmas Files,,Configuration Pragmas
3120@anchor{gnat_ugn/the_gnat_compilation_model id29}@anchor{78}@anchor{gnat_ugn/the_gnat_compilation_model handling-of-configuration-pragmas}@anchor{56}
3121@subsection Handling of Configuration Pragmas
3122
3123
3124Configuration pragmas may either appear at the start of a compilation
3125unit, or they can appear in a configuration pragma file to apply to
3126all compilations performed in a given compilation environment.
3127
3128GNAT also provides the @code{gnatchop} utility to provide an automatic
3129way to handle configuration pragmas following the semantics for
3130compilations (that is, files with multiple units), described in the RM.
3131See @ref{6f,,Operating gnatchop in Compilation Mode} for details.
3132However, for most purposes, it will be more convenient to edit the
3133@code{gnat.adc} file that contains configuration pragmas directly,
3134as described in the following section.
3135
3136In the case of @code{Restrictions} pragmas appearing as configuration
3137pragmas in individual compilation units, the exact handling depends on
3138the type of restriction.
3139
3140Restrictions that require partition-wide consistency (like
3141@code{No_Tasking}) are
3142recognized wherever they appear
3143and can be freely inherited, e.g. from a @emph{with}ed unit to the @emph{with}ing
3144unit. This makes sense since the binder will in any case insist on seeing
3145consistent use, so any unit not conforming to any restrictions that are
3146anywhere in the partition will be rejected, and you might as well find
3147that out at compile time rather than at bind time.
3148
3149For restrictions that do not require partition-wide consistency, e.g.
3150SPARK or No_Implementation_Attributes, in general the restriction applies
3151only to the unit in which the pragma appears, and not to any other units.
3152
3153The exception is No_Elaboration_Code which always applies to the entire
3154object file from a compilation, i.e. to the body, spec, and all subunits.
3155This restriction can be specified in a configuration pragma file, or it
3156can be on the body and/or the spec (in eithe case it applies to all the
3157relevant units). It can appear on a subunit only if it has previously
3158appeared in the body of spec.
3159
3160@node The Configuration Pragmas Files,,Handling of Configuration Pragmas,Configuration Pragmas
3161@anchor{gnat_ugn/the_gnat_compilation_model the-configuration-pragmas-files}@anchor{79}@anchor{gnat_ugn/the_gnat_compilation_model id30}@anchor{7a}
3162@subsection The Configuration Pragmas Files
3163
3164
3165@geindex gnat.adc
3166
3167In GNAT a compilation environment is defined by the current
3168directory at the time that a compile command is given. This current
3169directory is searched for a file whose name is @code{gnat.adc}. If
3170this file is present, it is expected to contain one or more
3171configuration pragmas that will be applied to the current compilation.
3172However, if the switch @code{-gnatA} is used, @code{gnat.adc} is not
3173considered. When taken into account, @code{gnat.adc} is added to the
3174dependencies, so that if @code{gnat.adc} is modified later, an invocation of
3175@code{gnatmake} will recompile the source.
3176
3177Configuration pragmas may be entered into the @code{gnat.adc} file
3178either by running @code{gnatchop} on a source file that consists only of
3179configuration pragmas, or more conveniently by direct editing of the
3180@code{gnat.adc} file, which is a standard format source file.
3181
3182Besides @code{gnat.adc}, additional files containing configuration
3183pragmas may be applied to the current compilation using the switch
3184@code{-gnatec=@emph{path}} where @code{path} must designate an existing file that
3185contains only configuration pragmas. These configuration pragmas are
3186in addition to those found in @code{gnat.adc} (provided @code{gnat.adc}
3187is present and switch @code{-gnatA} is not used).
3188
3189It is allowable to specify several switches @code{-gnatec=}, all of which
3190will be taken into account.
3191
3192Files containing configuration pragmas specified with switches
3193@code{-gnatec=} are added to the dependencies, unless they are
3194temporary files. A file is considered temporary if its name ends in
3195@code{.tmp} or @code{.TMP}. Certain tools follow this naming
3196convention because they pass information to @code{gcc} via
3197temporary files that are immediately deleted; it doesn't make sense to
3198depend on a file that no longer exists. Such tools include
3199@code{gprbuild}, @code{gnatmake}, and @code{gnatcheck}.
3200
3201If you are using project file, a separate mechanism is provided using
3202project attributes.
3203
3204@c --Comment
3205@c See :ref:`Specifying_Configuration_Pragmas` for more details.
3206
3207@node Generating Object Files,Source Dependencies,Configuration Pragmas,The GNAT Compilation Model
3208@anchor{gnat_ugn/the_gnat_compilation_model generating-object-files}@anchor{40}@anchor{gnat_ugn/the_gnat_compilation_model id31}@anchor{7b}
3209@section Generating Object Files
3210
3211
3212An Ada program consists of a set of source files, and the first step in
3213compiling the program is to generate the corresponding object files.
3214These are generated by compiling a subset of these source files.
3215The files you need to compile are the following:
3216
3217
3218@itemize *
3219
3220@item
3221If a package spec has no body, compile the package spec to produce the
3222object file for the package.
3223
3224@item
3225If a package has both a spec and a body, compile the body to produce the
3226object file for the package. The source file for the package spec need
3227not be compiled in this case because there is only one object file, which
3228contains the code for both the spec and body of the package.
3229
3230@item
3231For a subprogram, compile the subprogram body to produce the object file
3232for the subprogram. The spec, if one is present, is as usual in a
3233separate file, and need not be compiled.
3234@end itemize
3235
3236@geindex Subunits
3237
3238
3239@itemize *
3240
3241@item
3242In the case of subunits, only compile the parent unit. A single object
3243file is generated for the entire subunit tree, which includes all the
3244subunits.
3245
3246@item
3247Compile child units independently of their parent units
3248(though, of course, the spec of all the ancestor unit must be present in order
3249to compile a child unit).
3250
3251@geindex Generics
3252
3253@item
3254Compile generic units in the same manner as any other units. The object
3255files in this case are small dummy files that contain at most the
3256flag used for elaboration checking. This is because GNAT always handles generic
3257instantiation by means of macro expansion. However, it is still necessary to
3258compile generic units, for dependency checking and elaboration purposes.
3259@end itemize
3260
3261The preceding rules describe the set of files that must be compiled to
3262generate the object files for a program. Each object file has the same
3263name as the corresponding source file, except that the extension is
3264@code{.o} as usual.
3265
3266You may wish to compile other files for the purpose of checking their
3267syntactic and semantic correctness. For example, in the case where a
3268package has a separate spec and body, you would not normally compile the
3269spec. However, it is convenient in practice to compile the spec to make
3270sure it is error-free before compiling clients of this spec, because such
3271compilations will fail if there is an error in the spec.
3272
3273GNAT provides an option for compiling such files purely for the
3274purposes of checking correctness; such compilations are not required as
3275part of the process of building a program. To compile a file in this
3276checking mode, use the @code{-gnatc} switch.
3277
3278@node Source Dependencies,The Ada Library Information Files,Generating Object Files,The GNAT Compilation Model
3279@anchor{gnat_ugn/the_gnat_compilation_model id32}@anchor{7c}@anchor{gnat_ugn/the_gnat_compilation_model source-dependencies}@anchor{41}
3280@section Source Dependencies
3281
3282
3283A given object file clearly depends on the source file which is compiled
3284to produce it. Here we are using "depends" in the sense of a typical
3285@code{make} utility; in other words, an object file depends on a source
3286file if changes to the source file require the object file to be
3287recompiled.
3288In addition to this basic dependency, a given object may depend on
3289additional source files as follows:
3290
3291
3292@itemize *
3293
3294@item
3295If a file being compiled @emph{with}s a unit @code{X}, the object file
3296depends on the file containing the spec of unit @code{X}. This includes
3297files that are @emph{with}ed implicitly either because they are parents
3298of @emph{with}ed child units or they are run-time units required by the
3299language constructs used in a particular unit.
3300
3301@item
3302If a file being compiled instantiates a library level generic unit, the
3303object file depends on both the spec and body files for this generic
3304unit.
3305
3306@item
3307If a file being compiled instantiates a generic unit defined within a
3308package, the object file depends on the body file for the package as
3309well as the spec file.
3310@end itemize
3311
3312@geindex Inline
3313
3314@geindex -gnatn switch
3315
3316
3317@itemize *
3318
3319@item
3320If a file being compiled contains a call to a subprogram for which
3321pragma @code{Inline} applies and inlining is activated with the
3322@code{-gnatn} switch, the object file depends on the file containing the
3323body of this subprogram as well as on the file containing the spec. Note
3324that for inlining to actually occur as a result of the use of this switch,
3325it is necessary to compile in optimizing mode.
3326
3327@geindex -gnatN switch
3328
3329The use of @code{-gnatN} activates  inlining optimization
3330that is performed by the front end of the compiler. This inlining does
3331not require that the code generation be optimized. Like @code{-gnatn},
3332the use of this switch generates additional dependencies.
3333
3334When using a gcc-based back end (in practice this means using any version
3335of GNAT other than for the JVM, .NET or GNAAMP platforms), then the use of
3336@code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
3337Historically front end inlining was more extensive than the gcc back end
3338inlining, but that is no longer the case.
3339
3340@item
3341If an object file @code{O} depends on the proper body of a subunit through
3342inlining or instantiation, it depends on the parent unit of the subunit.
3343This means that any modification of the parent unit or one of its subunits
3344affects the compilation of @code{O}.
3345
3346@item
3347The object file for a parent unit depends on all its subunit body files.
3348
3349@item
3350The previous two rules meant that for purposes of computing dependencies and
3351recompilation, a body and all its subunits are treated as an indivisible whole.
3352
3353These rules are applied transitively: if unit @code{A} @emph{with}s
3354unit @code{B}, whose elaboration calls an inlined procedure in package
3355@code{C}, the object file for unit @code{A} will depend on the body of
3356@code{C}, in file @code{c.adb}.
3357
3358The set of dependent files described by these rules includes all the
3359files on which the unit is semantically dependent, as dictated by the
3360Ada language standard. However, it is a superset of what the
3361standard describes, because it includes generic, inline, and subunit
3362dependencies.
3363
3364An object file must be recreated by recompiling the corresponding source
3365file if any of the source files on which it depends are modified. For
3366example, if the @code{make} utility is used to control compilation,
3367the rule for an Ada object file must mention all the source files on
3368which the object file depends, according to the above definition.
3369The determination of the necessary
3370recompilations is done automatically when one uses @code{gnatmake}.
3371@end itemize
3372
3373@node The Ada Library Information Files,Binding an Ada Program,Source Dependencies,The GNAT Compilation Model
3374@anchor{gnat_ugn/the_gnat_compilation_model id33}@anchor{7d}@anchor{gnat_ugn/the_gnat_compilation_model the-ada-library-information-files}@anchor{42}
3375@section The Ada Library Information Files
3376
3377
3378@geindex Ada Library Information files
3379
3380@geindex ALI files
3381
3382Each compilation actually generates two output files. The first of these
3383is the normal object file that has a @code{.o} extension. The second is a
3384text file containing full dependency information. It has the same
3385name as the source file, but an @code{.ali} extension.
3386This file is known as the Ada Library Information (@code{ALI}) file.
3387The following information is contained in the @code{ALI} file.
3388
3389
3390@itemize *
3391
3392@item
3393Version information (indicates which version of GNAT was used to compile
3394the unit(s) in question)
3395
3396@item
3397Main program information (including priority and time slice settings,
3398as well as the wide character encoding used during compilation).
3399
3400@item
3401List of arguments used in the @code{gcc} command for the compilation
3402
3403@item
3404Attributes of the unit, including configuration pragmas used, an indication
3405of whether the compilation was successful, exception model used etc.
3406
3407@item
3408A list of relevant restrictions applying to the unit (used for consistency)
3409checking.
3410
3411@item
3412Categorization information (e.g., use of pragma @code{Pure}).
3413
3414@item
3415Information on all @emph{with}ed units, including presence of
3416@code{Elaborate} or @code{Elaborate_All} pragmas.
3417
3418@item
3419Information from any @code{Linker_Options} pragmas used in the unit
3420
3421@item
3422Information on the use of @code{Body_Version} or @code{Version}
3423attributes in the unit.
3424
3425@item
3426Dependency information. This is a list of files, together with
3427time stamp and checksum information. These are files on which
3428the unit depends in the sense that recompilation is required
3429if any of these units are modified.
3430
3431@item
3432Cross-reference data. Contains information on all entities referenced
3433in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
3434provide cross-reference information.
3435@end itemize
3436
3437For a full detailed description of the format of the @code{ALI} file,
3438see the source of the body of unit @code{Lib.Writ}, contained in file
3439@code{lib-writ.adb} in the GNAT compiler sources.
3440
3441@node Binding an Ada Program,GNAT and Libraries,The Ada Library Information Files,The GNAT Compilation Model
3442@anchor{gnat_ugn/the_gnat_compilation_model id34}@anchor{7e}@anchor{gnat_ugn/the_gnat_compilation_model binding-an-ada-program}@anchor{43}
3443@section Binding an Ada Program
3444
3445
3446When using languages such as C and C++, once the source files have been
3447compiled the only remaining step in building an executable program
3448is linking the object modules together. This means that it is possible to
3449link an inconsistent version of a program, in which two units have
3450included different versions of the same header.
3451
3452The rules of Ada do not permit such an inconsistent program to be built.
3453For example, if two clients have different versions of the same package,
3454it is illegal to build a program containing these two clients.
3455These rules are enforced by the GNAT binder, which also determines an
3456elaboration order consistent with the Ada rules.
3457
3458The GNAT binder is run after all the object files for a program have
3459been created. It is given the name of the main program unit, and from
3460this it determines the set of units required by the program, by reading the
3461corresponding ALI files. It generates error messages if the program is
3462inconsistent or if no valid order of elaboration exists.
3463
3464If no errors are detected, the binder produces a main program, in Ada by
3465default, that contains calls to the elaboration procedures of those
3466compilation unit that require them, followed by
3467a call to the main program. This Ada program is compiled to generate the
3468object file for the main program. The name of
3469the Ada file is @code{b~xxx}.adb` (with the corresponding spec
3470@code{b~xxx}.ads`) where @code{xxx} is the name of the
3471main program unit.
3472
3473Finally, the linker is used to build the resulting executable program,
3474using the object from the main program from the bind step as well as the
3475object files for the Ada units of the program.
3476
3477@node GNAT and Libraries,Conditional Compilation,Binding an Ada Program,The GNAT Compilation Model
3478@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-libraries}@anchor{15}@anchor{gnat_ugn/the_gnat_compilation_model id35}@anchor{7f}
3479@section GNAT and Libraries
3480
3481
3482@geindex Library building and using
3483
3484This section describes how to build and use libraries with GNAT, and also shows
3485how to recompile the GNAT run-time library. You should be familiar with the
3486Project Manager facility (see the @emph{GNAT_Project_Manager} chapter of the
3487@emph{GPRbuild User's Guide}) before reading this chapter.
3488
3489@menu
3490* Introduction to Libraries in GNAT::
3491* General Ada Libraries::
3492* Stand-alone Ada Libraries::
3493* Rebuilding the GNAT Run-Time Library::
3494
3495@end menu
3496
3497@node Introduction to Libraries in GNAT,General Ada Libraries,,GNAT and Libraries
3498@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-libraries-in-gnat}@anchor{80}@anchor{gnat_ugn/the_gnat_compilation_model id36}@anchor{81}
3499@subsection Introduction to Libraries in GNAT
3500
3501
3502A library is, conceptually, a collection of objects which does not have its
3503own main thread of execution, but rather provides certain services to the
3504applications that use it. A library can be either statically linked with the
3505application, in which case its code is directly included in the application,
3506or, on platforms that support it, be dynamically linked, in which case
3507its code is shared by all applications making use of this library.
3508
3509GNAT supports both types of libraries.
3510In the static case, the compiled code can be provided in different ways. The
3511simplest approach is to provide directly the set of objects resulting from
3512compilation of the library source files. Alternatively, you can group the
3513objects into an archive using whatever commands are provided by the operating
3514system. For the latter case, the objects are grouped into a shared library.
3515
3516In the GNAT environment, a library has three types of components:
3517
3518
3519@itemize *
3520
3521@item
3522Source files,
3523
3524@item
3525@code{ALI} files (see @ref{42,,The Ada Library Information Files}), and
3526
3527@item
3528Object files, an archive or a shared library.
3529@end itemize
3530
3531A GNAT library may expose all its source files, which is useful for
3532documentation purposes. Alternatively, it may expose only the units needed by
3533an external user to make use of the library. That is to say, the specs
3534reflecting the library services along with all the units needed to compile
3535those specs, which can include generic bodies or any body implementing an
3536inlined routine. In the case of @emph{stand-alone libraries} those exposed
3537units are called @emph{interface units} (@ref{82,,Stand-alone Ada Libraries}).
3538
3539All compilation units comprising an application, including those in a library,
3540need to be elaborated in an order partially defined by Ada's semantics. GNAT
3541computes the elaboration order from the @code{ALI} files and this is why they
3542constitute a mandatory part of GNAT libraries.
3543@emph{Stand-alone libraries} are the exception to this rule because a specific
3544library elaboration routine is produced independently of the application(s)
3545using the library.
3546
3547@node General Ada Libraries,Stand-alone Ada Libraries,Introduction to Libraries in GNAT,GNAT and Libraries
3548@anchor{gnat_ugn/the_gnat_compilation_model general-ada-libraries}@anchor{83}@anchor{gnat_ugn/the_gnat_compilation_model id37}@anchor{84}
3549@subsection General Ada Libraries
3550
3551
3552@menu
3553* Building a library::
3554* Installing a library::
3555* Using a library::
3556
3557@end menu
3558
3559@node Building a library,Installing a library,,General Ada Libraries
3560@anchor{gnat_ugn/the_gnat_compilation_model building-a-library}@anchor{85}@anchor{gnat_ugn/the_gnat_compilation_model id38}@anchor{86}
3561@subsubsection Building a library
3562
3563
3564The easiest way to build a library is to use the Project Manager,
3565which supports a special type of project called a @emph{Library Project}
3566(see the @emph{Library Projects} section in the @emph{GNAT Project Manager}
3567chapter of the @emph{GPRbuild User's Guide}).
3568
3569A project is considered a library project, when two project-level attributes
3570are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
3571control different aspects of library configuration, additional optional
3572project-level attributes can be specified:
3573
3574
3575@itemize *
3576
3577@item
3578
3579@table @asis
3580
3581@item @code{Library_Kind}
3582
3583This attribute controls whether the library is to be static or dynamic
3584@end table
3585
3586@item
3587
3588@table @asis
3589
3590@item @code{Library_Version}
3591
3592This attribute specifies the library version; this value is used
3593during dynamic linking of shared libraries to determine if the currently
3594installed versions of the binaries are compatible.
3595@end table
3596
3597@item
3598@code{Library_Options}
3599
3600@item
3601
3602@table @asis
3603
3604@item @code{Library_GCC}
3605
3606These attributes specify additional low-level options to be used during
3607library generation, and redefine the actual application used to generate
3608library.
3609@end table
3610@end itemize
3611
3612The GNAT Project Manager takes full care of the library maintenance task,
3613including recompilation of the source files for which objects do not exist
3614or are not up to date, assembly of the library archive, and installation of
3615the library (i.e., copying associated source, object and @code{ALI} files
3616to the specified location).
3617
3618Here is a simple library project file:
3619
3620@example
3621project My_Lib is
3622  for Source_Dirs use ("src1", "src2");
3623  for Object_Dir use "obj";
3624  for Library_Name use "mylib";
3625  for Library_Dir use "lib";
3626  for Library_Kind use "dynamic";
3627end My_lib;
3628@end example
3629
3630and the compilation command to build and install the library:
3631
3632@example
3633$ gnatmake -Pmy_lib
3634@end example
3635
3636It is not entirely trivial to perform manually all the steps required to
3637produce a library. We recommend that you use the GNAT Project Manager
3638for this task. In special cases where this is not desired, the necessary
3639steps are discussed below.
3640
3641There are various possibilities for compiling the units that make up the
3642library: for example with a Makefile (@ref{1f,,Using the GNU make Utility}) or
3643with a conventional script. For simple libraries, it is also possible to create
3644a dummy main program which depends upon all the packages that comprise the
3645interface of the library. This dummy main program can then be given to
3646@code{gnatmake}, which will ensure that all necessary objects are built.
3647
3648After this task is accomplished, you should follow the standard procedure
3649of the underlying operating system to produce the static or shared library.
3650
3651Here is an example of such a dummy program:
3652
3653@example
3654with My_Lib.Service1;
3655with My_Lib.Service2;
3656with My_Lib.Service3;
3657procedure My_Lib_Dummy is
3658begin
3659   null;
3660end;
3661@end example
3662
3663Here are the generic commands that will build an archive or a shared library.
3664
3665@example
3666# compiling the library
3667$ gnatmake -c my_lib_dummy.adb
3668
3669# we don't need the dummy object itself
3670$ rm my_lib_dummy.o my_lib_dummy.ali
3671
3672# create an archive with the remaining objects
3673$ ar rc libmy_lib.a *.o
3674# some systems may require "ranlib" to be run as well
3675
3676# or create a shared library
3677$ gcc -shared -o libmy_lib.so *.o
3678# some systems may require the code to have been compiled with -fPIC
3679
3680# remove the object files that are now in the library
3681$ rm *.o
3682
3683# Make the ALI files read-only so that gnatmake will not try to
3684# regenerate the objects that are in the library
3685$ chmod -w *.ali
3686@end example
3687
3688Please note that the library must have a name of the form @code{lib@emph{xxx}.a}
3689or @code{lib@emph{xxx}.so} (or @code{lib@emph{xxx}.dll} on Windows) in order to
3690be accessed by the directive @code{-l@emph{xxx}} at link time.
3691
3692@node Installing a library,Using a library,Building a library,General Ada Libraries
3693@anchor{gnat_ugn/the_gnat_compilation_model installing-a-library}@anchor{87}@anchor{gnat_ugn/the_gnat_compilation_model id39}@anchor{88}
3694@subsubsection Installing a library
3695
3696
3697@geindex ADA_PROJECT_PATH
3698
3699@geindex GPR_PROJECT_PATH
3700
3701If you use project files, library installation is part of the library build
3702process (see the @emph{Installing a Library with Project Files} section of the
3703@emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}).
3704
3705When project files are not an option, it is also possible, but not recommended,
3706to install the library so that the sources needed to use the library are on the
3707Ada source path and the ALI files & libraries be on the Ada Object path (see
3708@ref{89,,Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
3709administrator can place general-purpose libraries in the default compiler
3710paths, by specifying the libraries' location in the configuration files
3711@code{ada_source_path} and @code{ada_object_path}. These configuration files
3712must be located in the GNAT installation tree at the same place as the gcc spec
3713file. The location of the gcc spec file can be determined as follows:
3714
3715@example
3716$ gcc -v
3717@end example
3718
3719The configuration files mentioned above have a simple format: each line
3720must contain one unique directory name.
3721Those names are added to the corresponding path
3722in their order of appearance in the file. The names can be either absolute
3723or relative; in the latter case, they are relative to where theses files
3724are located.
3725
3726The files @code{ada_source_path} and @code{ada_object_path} might not be
3727present in a
3728GNAT installation, in which case, GNAT will look for its run-time library in
3729the directories @code{adainclude} (for the sources) and @code{adalib} (for the
3730objects and @code{ALI} files). When the files exist, the compiler does not
3731look in @code{adainclude} and @code{adalib}, and thus the
3732@code{ada_source_path} file
3733must contain the location for the GNAT run-time sources (which can simply
3734be @code{adainclude}). In the same way, the @code{ada_object_path} file must
3735contain the location for the GNAT run-time objects (which can simply
3736be @code{adalib}).
3737
3738You can also specify a new default path to the run-time library at compilation
3739time with the switch @code{--RTS=rts-path}. You can thus choose / change
3740the run-time library you want your program to be compiled with. This switch is
3741recognized by @code{gcc}, @code{gnatmake}, @code{gnatbind},
3742@code{gnatls}, @code{gnatfind} and @code{gnatxref}.
3743
3744It is possible to install a library before or after the standard GNAT
3745library, by reordering the lines in the configuration files. In general, a
3746library must be installed before the GNAT library if it redefines
3747any part of it.
3748
3749@node Using a library,,Installing a library,General Ada Libraries
3750@anchor{gnat_ugn/the_gnat_compilation_model using-a-library}@anchor{8a}@anchor{gnat_ugn/the_gnat_compilation_model id40}@anchor{8b}
3751@subsubsection Using a library
3752
3753
3754Once again, the project facility greatly simplifies the use of
3755libraries. In this context, using a library is just a matter of adding a
3756@emph{with} clause in the user project. For instance, to make use of the
3757library @code{My_Lib} shown in examples in earlier sections, you can
3758write:
3759
3760@example
3761with "my_lib";
3762project My_Proj is
3763  ...
3764end My_Proj;
3765@end example
3766
3767Even if you have a third-party, non-Ada library, you can still use GNAT's
3768Project Manager facility to provide a wrapper for it. For example, the
3769following project, when @emph{with}ed by your main project, will link with the
3770third-party library @code{liba.a}:
3771
3772@example
3773project Liba is
3774   for Externally_Built use "true";
3775   for Source_Files use ();
3776   for Library_Dir use "lib";
3777   for Library_Name use "a";
3778   for Library_Kind use "static";
3779end Liba;
3780@end example
3781
3782This is an alternative to the use of @code{pragma Linker_Options}. It is
3783especially interesting in the context of systems with several interdependent
3784static libraries where finding a proper linker order is not easy and best be
3785left to the tools having visibility over project dependence information.
3786
3787In order to use an Ada library manually, you need to make sure that this
3788library is on both your source and object path
3789(see @ref{89,,Search Paths and the Run-Time Library (RTL)}
3790and @ref{8c,,Search Paths for gnatbind}). Furthermore, when the objects are grouped
3791in an archive or a shared library, you need to specify the desired
3792library at link time.
3793
3794For example, you can use the library @code{mylib} installed in
3795@code{/dir/my_lib_src} and @code{/dir/my_lib_obj} with the following commands:
3796
3797@example
3798$ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \\
3799  -largs -lmy_lib
3800@end example
3801
3802This can be expressed more simply:
3803
3804@example
3805$ gnatmake my_appl
3806@end example
3807
3808when the following conditions are met:
3809
3810
3811@itemize *
3812
3813@item
3814@code{/dir/my_lib_src} has been added by the user to the environment
3815variable
3816@geindex ADA_INCLUDE_PATH
3817@geindex environment variable; ADA_INCLUDE_PATH
3818@code{ADA_INCLUDE_PATH}, or by the administrator to the file
3819@code{ada_source_path}
3820
3821@item
3822@code{/dir/my_lib_obj} has been added by the user to the environment
3823variable
3824@geindex ADA_OBJECTS_PATH
3825@geindex environment variable; ADA_OBJECTS_PATH
3826@code{ADA_OBJECTS_PATH}, or by the administrator to the file
3827@code{ada_object_path}
3828
3829@item
3830a pragma @code{Linker_Options} has been added to one of the sources.
3831For example:
3832
3833@example
3834pragma Linker_Options ("-lmy_lib");
3835@end example
3836@end itemize
3837
3838Note that you may also load a library dynamically at
3839run time given its filename, as illustrated in the GNAT @code{plugins} example
3840in the directory @code{share/examples/gnat/plugins} within the GNAT
3841install area.
3842
3843@node Stand-alone Ada Libraries,Rebuilding the GNAT Run-Time Library,General Ada Libraries,GNAT and Libraries
3844@anchor{gnat_ugn/the_gnat_compilation_model stand-alone-ada-libraries}@anchor{82}@anchor{gnat_ugn/the_gnat_compilation_model id41}@anchor{8d}
3845@subsection Stand-alone Ada Libraries
3846
3847
3848@geindex Stand-alone libraries
3849
3850@menu
3851* Introduction to Stand-alone Libraries::
3852* Building a Stand-alone Library::
3853* Creating a Stand-alone Library to be used in a non-Ada context::
3854* Restrictions in Stand-alone Libraries::
3855
3856@end menu
3857
3858@node Introduction to Stand-alone Libraries,Building a Stand-alone Library,,Stand-alone Ada Libraries
3859@anchor{gnat_ugn/the_gnat_compilation_model introduction-to-stand-alone-libraries}@anchor{8e}@anchor{gnat_ugn/the_gnat_compilation_model id42}@anchor{8f}
3860@subsubsection Introduction to Stand-alone Libraries
3861
3862
3863A Stand-alone Library (abbreviated 'SAL') is a library that contains the
3864necessary code to
3865elaborate the Ada units that are included in the library. In contrast with
3866an ordinary library, which consists of all sources, objects and @code{ALI}
3867files of the
3868library, a SAL may specify a restricted subset of compilation units
3869to serve as a library interface. In this case, the fully
3870self-sufficient set of files will normally consist of an objects
3871archive, the sources of interface units' specs, and the @code{ALI}
3872files of interface units.
3873If an interface spec contains a generic unit or an inlined subprogram,
3874the body's
3875source must also be provided; if the units that must be provided in the source
3876form depend on other units, the source and @code{ALI} files of those must
3877also be provided.
3878
3879The main purpose of a SAL is to minimize the recompilation overhead of client
3880applications when a new version of the library is installed. Specifically,
3881if the interface sources have not changed, client applications do not need to
3882be recompiled. If, furthermore, a SAL is provided in the shared form and its
3883version, controlled by @code{Library_Version} attribute, is not changed,
3884then the clients do not need to be relinked.
3885
3886SALs also allow the library providers to minimize the amount of library source
3887text exposed to the clients.  Such 'information hiding' might be useful or
3888necessary for various reasons.
3889
3890Stand-alone libraries are also well suited to be used in an executable whose
3891main routine is not written in Ada.
3892
3893@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
3894@anchor{gnat_ugn/the_gnat_compilation_model id43}@anchor{90}@anchor{gnat_ugn/the_gnat_compilation_model building-a-stand-alone-library}@anchor{91}
3895@subsubsection Building a Stand-alone Library
3896
3897
3898GNAT's Project facility provides a simple way of building and installing
3899stand-alone libraries; see the @emph{Stand-alone Library Projects} section
3900in the @emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}.
3901To be a Stand-alone Library Project, in addition to the two attributes
3902that make a project a Library Project (@code{Library_Name} and
3903@code{Library_Dir}; see the @emph{Library Projects} section in the
3904@emph{GNAT Project Manager} chapter of the @emph{GPRbuild User's Guide}),
3905the attribute @code{Library_Interface} must be defined.  For example:
3906
3907@example
3908for Library_Dir use "lib_dir";
3909for Library_Name use "dummy";
3910for Library_Interface use ("int1", "int1.child");
3911@end example
3912
3913Attribute @code{Library_Interface} has a non-empty string list value,
3914each string in the list designating a unit contained in an immediate source
3915of the project file.
3916
3917When a Stand-alone Library is built, first the binder is invoked to build
3918a package whose name depends on the library name
3919(@code{b~dummy.ads/b} in the example above).
3920This binder-generated package includes initialization and
3921finalization procedures whose
3922names depend on the library name (@code{dummyinit} and @code{dummyfinal}
3923in the example
3924above). The object corresponding to this package is included in the library.
3925
3926You must ensure timely (e.g., prior to any use of interfaces in the SAL)
3927calling of these procedures if a static SAL is built, or if a shared SAL
3928is built
3929with the project-level attribute @code{Library_Auto_Init} set to
3930@code{"false"}.
3931
3932For a Stand-Alone Library, only the @code{ALI} files of the Interface Units
3933(those that are listed in attribute @code{Library_Interface}) are copied to
3934the Library Directory. As a consequence, only the Interface Units may be
3935imported from Ada units outside of the library. If other units are imported,
3936the binding phase will fail.
3937
3938It is also possible to build an encapsulated library where not only
3939the code to elaborate and finalize the library is embedded but also
3940ensuring that the library is linked only against static
3941libraries. So an encapsulated library only depends on system
3942libraries, all other code, including the GNAT runtime, is embedded. To
3943build an encapsulated library the attribute
3944@code{Library_Standalone} must be set to @code{encapsulated}:
3945
3946@example
3947for Library_Dir use "lib_dir";
3948for Library_Name use "dummy";
3949for Library_Kind use "dynamic";
3950for Library_Interface use ("int1", "int1.child");
3951for Library_Standalone use "encapsulated";
3952@end example
3953
3954The default value for this attribute is @code{standard} in which case
3955a stand-alone library is built.
3956
3957The attribute @code{Library_Src_Dir} may be specified for a
3958Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
3959single string value. Its value must be the path (absolute or relative to the
3960project directory) of an existing directory. This directory cannot be the
3961object directory or one of the source directories, but it can be the same as
3962the library directory. The sources of the Interface
3963Units of the library that are needed by an Ada client of the library will be
3964copied to the designated directory, called the Interface Copy directory.
3965These sources include the specs of the Interface Units, but they may also
3966include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
3967are used, or when there is a generic unit in the spec. Before the sources
3968are copied to the Interface Copy directory, an attempt is made to delete all
3969files in the Interface Copy directory.
3970
3971Building stand-alone libraries by hand is somewhat tedious, but for those
3972occasions when it is necessary here are the steps that you need to perform:
3973
3974
3975@itemize *
3976
3977@item
3978Compile all library sources.
3979
3980@item
3981Invoke the binder with the switch @code{-n} (No Ada main program),
3982with all the @code{ALI} files of the interfaces, and
3983with the switch @code{-L} to give specific names to the @code{init}
3984and @code{final} procedures.  For example:
3985
3986@example
3987$ gnatbind -n int1.ali int2.ali -Lsal1
3988@end example
3989
3990@item
3991Compile the binder generated file:
3992
3993@example
3994$ gcc -c b~int2.adb
3995@end example
3996
3997@item
3998Link the dynamic library with all the necessary object files,
3999indicating to the linker the names of the @code{init} (and possibly
4000@code{final}) procedures for automatic initialization (and finalization).
4001The built library should be placed in a directory different from
4002the object directory.
4003
4004@item
4005Copy the @code{ALI} files of the interface to the library directory,
4006add in this copy an indication that it is an interface to a SAL
4007(i.e., add a word @code{SL} on the line in the @code{ALI} file that starts
4008with letter 'P') and make the modified copy of the @code{ALI} file
4009read-only.
4010@end itemize
4011
4012Using SALs is not different from using other libraries
4013(see @ref{8a,,Using a library}).
4014
4015@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
4016@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}
4017@subsubsection Creating a Stand-alone Library to be used in a non-Ada context
4018
4019
4020It is easy to adapt the SAL build procedure discussed above for use of a SAL in
4021a non-Ada context.
4022
4023The only extra step required is to ensure that library interface subprograms
4024are compatible with the main program, by means of @code{pragma Export}
4025or @code{pragma Convention}.
4026
4027Here is an example of simple library interface for use with C main program:
4028
4029@example
4030package My_Package is
4031
4032   procedure Do_Something;
4033   pragma Export (C, Do_Something, "do_something");
4034
4035   procedure Do_Something_Else;
4036   pragma Export (C, Do_Something_Else, "do_something_else");
4037
4038end My_Package;
4039@end example
4040
4041On the foreign language side, you must provide a 'foreign' view of the
4042library interface; remember that it should contain elaboration routines in
4043addition to interface subprograms.
4044
4045The example below shows the content of @code{mylib_interface.h} (note
4046that there is no rule for the naming of this file, any name can be used)
4047
4048@example
4049/* the library elaboration procedure */
4050extern void mylibinit (void);
4051
4052/* the library finalization procedure */
4053extern void mylibfinal (void);
4054
4055/* the interface exported by the library */
4056extern void do_something (void);
4057extern void do_something_else (void);
4058@end example
4059
4060Libraries built as explained above can be used from any program, provided
4061that the elaboration procedures (named @code{mylibinit} in the previous
4062example) are called before the library services are used. Any number of
4063libraries can be used simultaneously, as long as the elaboration
4064procedure of each library is called.
4065
4066Below is an example of a C program that uses the @code{mylib} library.
4067
4068@example
4069#include "mylib_interface.h"
4070
4071int
4072main (void)
4073@{
4074   /* First, elaborate the library before using it */
4075   mylibinit ();
4076
4077   /* Main program, using the library exported entities */
4078   do_something ();
4079   do_something_else ();
4080
4081   /* Library finalization at the end of the program */
4082   mylibfinal ();
4083   return 0;
4084@}
4085@end example
4086
4087Note that invoking any library finalization procedure generated by
4088@code{gnatbind} shuts down the Ada run-time environment.
4089Consequently, the
4090finalization of all Ada libraries must be performed at the end of the program.
4091No call to these libraries or to the Ada run-time library should be made
4092after the finalization phase.
4093
4094Note also that special care must be taken with multi-tasks
4095applications. The initialization and finalization routines are not
4096protected against concurrent access. If such requirement is needed it
4097must be ensured at the application level using a specific operating
4098system services like a mutex or a critical-section.
4099
4100@node Restrictions in Stand-alone Libraries,,Creating a Stand-alone Library to be used in a non-Ada context,Stand-alone Ada Libraries
4101@anchor{gnat_ugn/the_gnat_compilation_model id45}@anchor{94}@anchor{gnat_ugn/the_gnat_compilation_model restrictions-in-stand-alone-libraries}@anchor{95}
4102@subsubsection Restrictions in Stand-alone Libraries
4103
4104
4105The pragmas listed below should be used with caution inside libraries,
4106as they can create incompatibilities with other Ada libraries:
4107
4108
4109@itemize *
4110
4111@item
4112pragma @code{Locking_Policy}
4113
4114@item
4115pragma @code{Partition_Elaboration_Policy}
4116
4117@item
4118pragma @code{Queuing_Policy}
4119
4120@item
4121pragma @code{Task_Dispatching_Policy}
4122
4123@item
4124pragma @code{Unreserve_All_Interrupts}
4125@end itemize
4126
4127When using a library that contains such pragmas, the user must make sure
4128that all libraries use the same pragmas with the same values. Otherwise,
4129@code{Program_Error} will
4130be raised during the elaboration of the conflicting
4131libraries. The usage of these pragmas and its consequences for the user
4132should therefore be well documented.
4133
4134Similarly, the traceback in the exception occurrence mechanism should be
4135enabled or disabled in a consistent manner across all libraries.
4136Otherwise, Program_Error will be raised during the elaboration of the
4137conflicting libraries.
4138
4139If the @code{Version} or @code{Body_Version}
4140attributes are used inside a library, then you need to
4141perform a @code{gnatbind} step that specifies all @code{ALI} files in all
4142libraries, so that version identifiers can be properly computed.
4143In practice these attributes are rarely used, so this is unlikely
4144to be a consideration.
4145
4146@node Rebuilding the GNAT Run-Time Library,,Stand-alone Ada Libraries,GNAT and Libraries
4147@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}
4148@subsection Rebuilding the GNAT Run-Time Library
4149
4150
4151@geindex GNAT Run-Time Library
4152@geindex rebuilding
4153
4154@geindex Building the GNAT Run-Time Library
4155
4156@geindex Rebuilding the GNAT Run-Time Library
4157
4158@geindex Run-Time Library
4159@geindex rebuilding
4160
4161It may be useful to recompile the GNAT library in various contexts, the
4162most important one being the use of partition-wide configuration pragmas
4163such as @code{Normalize_Scalars}. A special Makefile called
4164@code{Makefile.adalib} is provided to that effect and can be found in
4165the directory containing the GNAT library. The location of this
4166directory depends on the way the GNAT environment has been installed and can
4167be determined by means of the command:
4168
4169@example
4170$ gnatls -v
4171@end example
4172
4173The last entry in the object search path usually contains the
4174gnat library. This Makefile contains its own documentation and in
4175particular the set of instructions needed to rebuild a new library and
4176to use it.
4177
4178@geindex Conditional compilation
4179
4180@node Conditional Compilation,Mixed Language Programming,GNAT and Libraries,The GNAT Compilation Model
4181@anchor{gnat_ugn/the_gnat_compilation_model id47}@anchor{98}@anchor{gnat_ugn/the_gnat_compilation_model conditional-compilation}@anchor{16}
4182@section Conditional Compilation
4183
4184
4185This section presents some guidelines for modeling conditional compilation in Ada and describes the
4186gnatprep preprocessor utility.
4187
4188@geindex Conditional compilation
4189
4190@menu
4191* Modeling Conditional Compilation in Ada::
4192* Preprocessing with gnatprep::
4193* Integrated Preprocessing::
4194
4195@end menu
4196
4197@node Modeling Conditional Compilation in Ada,Preprocessing with gnatprep,,Conditional Compilation
4198@anchor{gnat_ugn/the_gnat_compilation_model modeling-conditional-compilation-in-ada}@anchor{99}@anchor{gnat_ugn/the_gnat_compilation_model id48}@anchor{9a}
4199@subsection Modeling Conditional Compilation in Ada
4200
4201
4202It is often necessary to arrange for a single source program
4203to serve multiple purposes, where it is compiled in different
4204ways to achieve these different goals. Some examples of the
4205need for this feature are
4206
4207
4208@itemize *
4209
4210@item
4211Adapting a program to a different hardware environment
4212
4213@item
4214Adapting a program to a different target architecture
4215
4216@item
4217Turning debugging features on and off
4218
4219@item
4220Arranging for a program to compile with different compilers
4221@end itemize
4222
4223In C, or C++, the typical approach would be to use the preprocessor
4224that is defined as part of the language. The Ada language does not
4225contain such a feature. This is not an oversight, but rather a very
4226deliberate design decision, based on the experience that overuse of
4227the preprocessing features in C and C++ can result in programs that
4228are extremely difficult to maintain. For example, if we have ten
4229switches that can be on or off, this means that there are a thousand
4230separate programs, any one of which might not even be syntactically
4231correct, and even if syntactically correct, the resulting program
4232might not work correctly. Testing all combinations can quickly become
4233impossible.
4234
4235Nevertheless, the need to tailor programs certainly exists, and in
4236this section we will discuss how this can
4237be achieved using Ada in general, and GNAT in particular.
4238
4239@menu
4240* Use of Boolean Constants::
4241* Debugging - A Special Case::
4242* Conditionalizing Declarations::
4243* Use of Alternative Implementations::
4244* Preprocessing::
4245
4246@end menu
4247
4248@node Use of Boolean Constants,Debugging - A Special Case,,Modeling Conditional Compilation in Ada
4249@anchor{gnat_ugn/the_gnat_compilation_model id49}@anchor{9b}@anchor{gnat_ugn/the_gnat_compilation_model use-of-boolean-constants}@anchor{9c}
4250@subsubsection Use of Boolean Constants
4251
4252
4253In the case where the difference is simply which code
4254sequence is executed, the cleanest solution is to use Boolean
4255constants to control which code is executed.
4256
4257@example
4258FP_Initialize_Required : constant Boolean := True;
4259...
4260if FP_Initialize_Required then
4261...
4262end if;
4263@end example
4264
4265Not only will the code inside the @code{if} statement not be executed if
4266the constant Boolean is @code{False}, but it will also be completely
4267deleted from the program.
4268However, the code is only deleted after the @code{if} statement
4269has been checked for syntactic and semantic correctness.
4270(In contrast, with preprocessors the code is deleted before the
4271compiler ever gets to see it, so it is not checked until the switch
4272is turned on.)
4273
4274@geindex Preprocessors (contrasted with conditional compilation)
4275
4276Typically the Boolean constants will be in a separate package,
4277something like:
4278
4279@example
4280package Config is
4281   FP_Initialize_Required : constant Boolean := True;
4282   Reset_Available        : constant Boolean := False;
4283   ...
4284end Config;
4285@end example
4286
4287The @code{Config} package exists in multiple forms for the various targets,
4288with an appropriate script selecting the version of @code{Config} needed.
4289Then any other unit requiring conditional compilation can do a @emph{with}
4290of @code{Config} to make the constants visible.
4291
4292@node Debugging - A Special Case,Conditionalizing Declarations,Use of Boolean Constants,Modeling Conditional Compilation in Ada
4293@anchor{gnat_ugn/the_gnat_compilation_model debugging-a-special-case}@anchor{9d}@anchor{gnat_ugn/the_gnat_compilation_model id50}@anchor{9e}
4294@subsubsection Debugging - A Special Case
4295
4296
4297A common use of conditional code is to execute statements (for example
4298dynamic checks, or output of intermediate results) under control of a
4299debug switch, so that the debugging behavior can be turned on and off.
4300This can be done using a Boolean constant to control whether the code
4301is active:
4302
4303@example
4304if Debugging then
4305   Put_Line ("got to the first stage!");
4306end if;
4307@end example
4308
4309or
4310
4311@example
4312if Debugging and then Temperature > 999.0 then
4313   raise Temperature_Crazy;
4314end if;
4315@end example
4316
4317@geindex pragma Assert
4318
4319Since this is a common case, there are special features to deal with
4320this in a convenient manner. For the case of tests, Ada 2005 has added
4321a pragma @code{Assert} that can be used for such tests. This pragma is modeled
4322on the @code{Assert} pragma that has always been available in GNAT, so this
4323feature may be used with GNAT even if you are not using Ada 2005 features.
4324The use of pragma @code{Assert} is described in the
4325@cite{GNAT_Reference_Manual}, but as an
4326example, the last test could be written:
4327
4328@example
4329pragma Assert (Temperature <= 999.0, "Temperature Crazy");
4330@end example
4331
4332or simply
4333
4334@example
4335pragma Assert (Temperature <= 999.0);
4336@end example
4337
4338In both cases, if assertions are active and the temperature is excessive,
4339the exception @code{Assert_Failure} will be raised, with the given string in
4340the first case or a string indicating the location of the pragma in the second
4341case used as the exception message.
4342
4343@geindex pragma Assertion_Policy
4344
4345You can turn assertions on and off by using the @code{Assertion_Policy}
4346pragma.
4347
4348@geindex -gnata switch
4349
4350This is an Ada 2005 pragma which is implemented in all modes by
4351GNAT. Alternatively, you can use the @code{-gnata} switch
4352to enable assertions from the command line, which applies to
4353all versions of Ada.
4354
4355@geindex pragma Debug
4356
4357For the example above with the @code{Put_Line}, the GNAT-specific pragma
4358@code{Debug} can be used:
4359
4360@example
4361pragma Debug (Put_Line ("got to the first stage!"));
4362@end example
4363
4364If debug pragmas are enabled, the argument, which must be of the form of
4365a procedure call, is executed (in this case, @code{Put_Line} will be called).
4366Only one call can be present, but of course a special debugging procedure
4367containing any code you like can be included in the program and then
4368called in a pragma @code{Debug} argument as needed.
4369
4370One advantage of pragma @code{Debug} over the @code{if Debugging then}
4371construct is that pragma @code{Debug} can appear in declarative contexts,
4372such as at the very beginning of a procedure, before local declarations have
4373been elaborated.
4374
4375@geindex pragma Debug_Policy
4376
4377Debug pragmas are enabled using either the @code{-gnata} switch that also
4378controls assertions, or with a separate Debug_Policy pragma.
4379
4380The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
4381in Ada 95 and Ada 83 programs as well), and is analogous to
4382pragma @code{Assertion_Policy} to control assertions.
4383
4384@code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
4385and thus they can appear in @code{gnat.adc} if you are not using a
4386project file, or in the file designated to contain configuration pragmas
4387in a project file.
4388They then apply to all subsequent compilations. In practice the use of
4389the @code{-gnata} switch is often the most convenient method of controlling
4390the status of these pragmas.
4391
4392Note that a pragma is not a statement, so in contexts where a statement
4393sequence is required, you can't just write a pragma on its own. You have
4394to add a @code{null} statement.
4395
4396@example
4397if ... then
4398   ... -- some statements
4399else
4400   pragma Assert (Num_Cases < 10);
4401   null;
4402end if;
4403@end example
4404
4405@node Conditionalizing Declarations,Use of Alternative Implementations,Debugging - A Special Case,Modeling Conditional Compilation in Ada
4406@anchor{gnat_ugn/the_gnat_compilation_model conditionalizing-declarations}@anchor{9f}@anchor{gnat_ugn/the_gnat_compilation_model id51}@anchor{a0}
4407@subsubsection Conditionalizing Declarations
4408
4409
4410In some cases it may be necessary to conditionalize declarations to meet
4411different requirements. For example we might want a bit string whose length
4412is set to meet some hardware message requirement.
4413
4414This may be possible using declare blocks controlled
4415by conditional constants:
4416
4417@example
4418if Small_Machine then
4419   declare
4420      X : Bit_String (1 .. 10);
4421   begin
4422      ...
4423   end;
4424else
4425   declare
4426      X : Large_Bit_String (1 .. 1000);
4427   begin
4428      ...
4429   end;
4430end if;
4431@end example
4432
4433Note that in this approach, both declarations are analyzed by the
4434compiler so this can only be used where both declarations are legal,
4435even though one of them will not be used.
4436
4437Another approach is to define integer constants, e.g., @code{Bits_Per_Word},
4438or Boolean constants, e.g., @code{Little_Endian}, and then write declarations
4439that are parameterized by these constants. For example
4440
4441@example
4442for Rec use
4443  Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
4444end record;
4445@end example
4446
4447If @code{Bits_Per_Word} is set to 32, this generates either
4448
4449@example
4450for Rec use
4451  Field1 at 0 range 0 .. 32;
4452end record;
4453@end example
4454
4455for the big endian case, or
4456
4457@example
4458for Rec use record
4459    Field1 at 0 range 10 .. 32;
4460end record;
4461@end example
4462
4463for the little endian case. Since a powerful subset of Ada expression
4464notation is usable for creating static constants, clever use of this
4465feature can often solve quite difficult problems in conditionalizing
4466compilation (note incidentally that in Ada 95, the little endian
4467constant was introduced as @code{System.Default_Bit_Order}, so you do not
4468need to define this one yourself).
4469
4470@node Use of Alternative Implementations,Preprocessing,Conditionalizing Declarations,Modeling Conditional Compilation in Ada
4471@anchor{gnat_ugn/the_gnat_compilation_model use-of-alternative-implementations}@anchor{a1}@anchor{gnat_ugn/the_gnat_compilation_model id52}@anchor{a2}
4472@subsubsection Use of Alternative Implementations
4473
4474
4475In some cases, none of the approaches described above are adequate. This
4476can occur for example if the set of declarations required is radically
4477different for two different configurations.
4478
4479In this situation, the official Ada way of dealing with conditionalizing
4480such code is to write separate units for the different cases. As long as
4481this does not result in excessive duplication of code, this can be done
4482without creating maintenance problems. The approach is to share common
4483code as far as possible, and then isolate the code and declarations
4484that are different. Subunits are often a convenient method for breaking
4485out a piece of a unit that is to be conditionalized, with separate files
4486for different versions of the subunit for different targets, where the
4487build script selects the right one to give to the compiler.
4488
4489@geindex Subunits (and conditional compilation)
4490
4491As an example, consider a situation where a new feature in Ada 2005
4492allows something to be done in a really nice way. But your code must be able
4493to compile with an Ada 95 compiler. Conceptually you want to say:
4494
4495@example
4496if Ada_2005 then
4497   ... neat Ada 2005 code
4498else
4499   ... not quite as neat Ada 95 code
4500end if;
4501@end example
4502
4503where @code{Ada_2005} is a Boolean constant.
4504
4505But this won't work when @code{Ada_2005} is set to @code{False},
4506since the @code{then} clause will be illegal for an Ada 95 compiler.
4507(Recall that although such unreachable code would eventually be deleted
4508by the compiler, it still needs to be legal.  If it uses features
4509introduced in Ada 2005, it will be illegal in Ada 95.)
4510
4511So instead we write
4512
4513@example
4514procedure Insert is separate;
4515@end example
4516
4517Then we have two files for the subunit @code{Insert}, with the two sets of
4518code.
4519If the package containing this is called @code{File_Queries}, then we might
4520have two files
4521
4522
4523@itemize *
4524
4525@item
4526@code{file_queries-insert-2005.adb}
4527
4528@item
4529@code{file_queries-insert-95.adb}
4530@end itemize
4531
4532and the build script renames the appropriate file to @code{file_queries-insert.adb} and then carries out the compilation.
4533
4534This can also be done with project files' naming schemes. For example:
4535
4536@example
4537for body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
4538@end example
4539
4540Note also that with project files it is desirable to use a different extension
4541than @code{ads} / @code{adb} for alternative versions. Otherwise a naming
4542conflict may arise through another commonly used feature: to declare as part
4543of the project a set of directories containing all the sources obeying the
4544default naming scheme.
4545
4546The use of alternative units is certainly feasible in all situations,
4547and for example the Ada part of the GNAT run-time is conditionalized
4548based on the target architecture using this approach. As a specific example,
4549consider the implementation of the AST feature in VMS. There is one
4550spec: @code{s-asthan.ads} which is the same for all architectures, and three
4551bodies:
4552
4553
4554@itemize *
4555
4556@item
4557
4558@table @asis
4559
4560@item @code{s-asthan.adb}
4561
4562used for all non-VMS operating systems
4563@end table
4564
4565@item
4566
4567@table @asis
4568
4569@item @code{s-asthan-vms-alpha.adb}
4570
4571used for VMS on the Alpha
4572@end table
4573
4574@item
4575
4576@table @asis
4577
4578@item @code{s-asthan-vms-ia64.adb}
4579
4580used for VMS on the ia64
4581@end table
4582@end itemize
4583
4584The dummy version @code{s-asthan.adb} simply raises exceptions noting that
4585this operating system feature is not available, and the two remaining
4586versions interface with the corresponding versions of VMS to provide
4587VMS-compatible AST handling. The GNAT build script knows the architecture
4588and operating system, and automatically selects the right version,
4589renaming it if necessary to @code{s-asthan.adb} before the run-time build.
4590
4591Another style for arranging alternative implementations is through Ada's
4592access-to-subprogram facility.
4593In case some functionality is to be conditionally included,
4594you can declare an access-to-procedure variable @code{Ref} that is initialized
4595to designate a 'do nothing' procedure, and then invoke @code{Ref.all}
4596when appropriate.
4597In some library package, set @code{Ref} to @code{Proc'Access} for some
4598procedure @code{Proc} that performs the relevant processing.
4599The initialization only occurs if the library package is included in the
4600program.
4601The same idea can also be implemented using tagged types and dispatching
4602calls.
4603
4604@node Preprocessing,,Use of Alternative Implementations,Modeling Conditional Compilation in Ada
4605@anchor{gnat_ugn/the_gnat_compilation_model preprocessing}@anchor{a3}@anchor{gnat_ugn/the_gnat_compilation_model id53}@anchor{a4}
4606@subsubsection Preprocessing
4607
4608
4609@geindex Preprocessing
4610
4611Although it is quite possible to conditionalize code without the use of
4612C-style preprocessing, as described earlier in this section, it is
4613nevertheless convenient in some cases to use the C approach. Moreover,
4614older Ada compilers have often provided some preprocessing capability,
4615so legacy code may depend on this approach, even though it is not
4616standard.
4617
4618To accommodate such use, GNAT provides a preprocessor (modeled to a large
4619extent on the various preprocessors that have been used
4620with legacy code on other compilers, to enable easier transition).
4621
4622@geindex gnatprep
4623
4624The preprocessor may be used in two separate modes. It can be used quite
4625separately from the compiler, to generate a separate output source file
4626that is then fed to the compiler as a separate step. This is the
4627@code{gnatprep} utility, whose use is fully described in
4628@ref{17,,Preprocessing with gnatprep}.
4629
4630The preprocessing language allows such constructs as
4631
4632@example
4633#if DEBUG or else (PRIORITY > 4) then
4634   sequence of declarations
4635#else
4636   completely different sequence of declarations
4637#end if;
4638@end example
4639
4640The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
4641defined either on the command line or in a separate file.
4642
4643The other way of running the preprocessor is even closer to the C style and
4644often more convenient. In this approach the preprocessing is integrated into
4645the compilation process. The compiler is given the preprocessor input which
4646includes @code{#if} lines etc, and then the compiler carries out the
4647preprocessing internally and processes the resulting output.
4648For more details on this approach, see @ref{18,,Integrated Preprocessing}.
4649
4650@node Preprocessing with gnatprep,Integrated Preprocessing,Modeling Conditional Compilation in Ada,Conditional Compilation
4651@anchor{gnat_ugn/the_gnat_compilation_model id54}@anchor{a5}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-with-gnatprep}@anchor{17}
4652@subsection Preprocessing with @code{gnatprep}
4653
4654
4655@geindex gnatprep
4656
4657@geindex Preprocessing (gnatprep)
4658
4659This section discusses how to use GNAT's @code{gnatprep} utility for simple
4660preprocessing.
4661Although designed for use with GNAT, @code{gnatprep} does not depend on any
4662special GNAT features.
4663For further discussion of conditional compilation in general, see
4664@ref{16,,Conditional Compilation}.
4665
4666@menu
4667* Preprocessing Symbols::
4668* Using gnatprep::
4669* Switches for gnatprep::
4670* Form of Definitions File::
4671* Form of Input Text for gnatprep::
4672
4673@end menu
4674
4675@node Preprocessing Symbols,Using gnatprep,,Preprocessing with gnatprep
4676@anchor{gnat_ugn/the_gnat_compilation_model id55}@anchor{a6}@anchor{gnat_ugn/the_gnat_compilation_model preprocessing-symbols}@anchor{a7}
4677@subsubsection Preprocessing Symbols
4678
4679
4680Preprocessing symbols are defined in @emph{definition files} and referenced in the
4681sources to be preprocessed. A preprocessing symbol is an identifier, following
4682normal Ada (case-insensitive) rules for its syntax, with the restriction that
4683all characters need to be in the ASCII set (no accented letters).
4684
4685@node Using gnatprep,Switches for gnatprep,Preprocessing Symbols,Preprocessing with gnatprep
4686@anchor{gnat_ugn/the_gnat_compilation_model using-gnatprep}@anchor{a8}@anchor{gnat_ugn/the_gnat_compilation_model id56}@anchor{a9}
4687@subsubsection Using @code{gnatprep}
4688
4689
4690To call @code{gnatprep} use:
4691
4692@example
4693$ gnatprep [ switches ] infile outfile [ deffile ]
4694@end example
4695
4696where
4697
4698
4699@itemize *
4700
4701@item
4702
4703@table @asis
4704
4705@item @emph{switches}
4706
4707is an optional sequence of switches as described in the next section.
4708@end table
4709
4710@item
4711
4712@table @asis
4713
4714@item @emph{infile}
4715
4716is the full name of the input file, which is an Ada source
4717file containing preprocessor directives.
4718@end table
4719
4720@item
4721
4722@table @asis
4723
4724@item @emph{outfile}
4725
4726is the full name of the output file, which is an Ada source
4727in standard Ada form. When used with GNAT, this file name will
4728normally have an @code{ads} or @code{adb} suffix.
4729@end table
4730
4731@item
4732
4733@table @asis
4734
4735@item @code{deffile}
4736
4737is the full name of a text file containing definitions of
4738preprocessing symbols to be referenced by the preprocessor. This argument is
4739optional, and can be replaced by the use of the @code{-D} switch.
4740@end table
4741@end itemize
4742
4743@node Switches for gnatprep,Form of Definitions File,Using gnatprep,Preprocessing with gnatprep
4744@anchor{gnat_ugn/the_gnat_compilation_model switches-for-gnatprep}@anchor{aa}@anchor{gnat_ugn/the_gnat_compilation_model id57}@anchor{ab}
4745@subsubsection Switches for @code{gnatprep}
4746
4747
4748@geindex --version (gnatprep)
4749
4750
4751@table @asis
4752
4753@item @code{--version}
4754
4755Display Copyright and version, then exit disregarding all other options.
4756@end table
4757
4758@geindex --help (gnatprep)
4759
4760
4761@table @asis
4762
4763@item @code{--help}
4764
4765If @code{--version} was not used, display usage and then exit disregarding
4766all other options.
4767@end table
4768
4769@geindex -b (gnatprep)
4770
4771
4772@table @asis
4773
4774@item @code{-b}
4775
4776Causes both preprocessor lines and the lines deleted by
4777preprocessing to be replaced by blank lines in the output source file,
4778preserving line numbers in the output file.
4779@end table
4780
4781@geindex -c (gnatprep)
4782
4783
4784@table @asis
4785
4786@item @code{-c}
4787
4788Causes both preprocessor lines and the lines deleted
4789by preprocessing to be retained in the output source as comments marked
4790with the special string @code{"--! "}. This option will result in line numbers
4791being preserved in the output file.
4792@end table
4793
4794@geindex -C (gnatprep)
4795
4796
4797@table @asis
4798
4799@item @code{-C}
4800
4801Causes comments to be scanned. Normally comments are ignored by gnatprep.
4802If this option is specified, then comments are scanned and any $symbol
4803substitutions performed as in program text. This is particularly useful
4804when structured comments are used (e.g., for programs written in a
4805pre-2014 version of the SPARK Ada subset). Note that this switch is not
4806available when  doing integrated preprocessing (it would be useless in
4807this context since comments are ignored by the compiler in any case).
4808@end table
4809
4810@geindex -D (gnatprep)
4811
4812
4813@table @asis
4814
4815@item @code{-D@emph{symbol}[=@emph{value}]}
4816
4817Defines a new preprocessing symbol with the specified value. If no value is given
4818on the command line, then symbol is considered to be @code{True}. This switch
4819can be used in place of a definition file.
4820@end table
4821
4822@geindex -r (gnatprep)
4823
4824
4825@table @asis
4826
4827@item @code{-r}
4828
4829Causes a @code{Source_Reference} pragma to be generated that
4830references the original input file, so that error messages will use
4831the file name of this original file. The use of this switch implies
4832that preprocessor lines are not to be removed from the file, so its
4833use will force @code{-b} mode if @code{-c}
4834has not been specified explicitly.
4835
4836Note that if the file to be preprocessed contains multiple units, then
4837it will be necessary to @code{gnatchop} the output file from
4838@code{gnatprep}. If a @code{Source_Reference} pragma is present
4839in the preprocessed file, it will be respected by
4840@code{gnatchop -r}
4841so that the final chopped files will correctly refer to the original
4842input source file for @code{gnatprep}.
4843@end table
4844
4845@geindex -s (gnatprep)
4846
4847
4848@table @asis
4849
4850@item @code{-s}
4851
4852Causes a sorted list of symbol names and values to be
4853listed on the standard output file.
4854@end table
4855
4856@geindex -T (gnatprep)
4857
4858
4859@table @asis
4860
4861@item @code{-T}
4862
4863Use LF as line terminators when writing files. By default the line terminator
4864of the host (LF under unix, CR/LF under Windows) is used.
4865@end table
4866
4867@geindex -u (gnatprep)
4868
4869
4870@table @asis
4871
4872@item @code{-u}
4873
4874Causes undefined symbols to be treated as having the value FALSE in the context
4875of a preprocessor test. In the absence of this option, an undefined symbol in
4876a @code{#if} or @code{#elsif} test will be treated as an error.
4877@end table
4878
4879@geindex -v (gnatprep)
4880
4881
4882@table @asis
4883
4884@item @code{-v}
4885
4886Verbose mode: generates more output about work done.
4887@end table
4888
4889Note: if neither @code{-b} nor @code{-c} is present,
4890then preprocessor lines and
4891deleted lines are completely removed from the output, unless -r is
4892specified, in which case -b is assumed.
4893
4894@node Form of Definitions File,Form of Input Text for gnatprep,Switches for gnatprep,Preprocessing with gnatprep
4895@anchor{gnat_ugn/the_gnat_compilation_model form-of-definitions-file}@anchor{ac}@anchor{gnat_ugn/the_gnat_compilation_model id58}@anchor{ad}
4896@subsubsection Form of Definitions File
4897
4898
4899The definitions file contains lines of the form:
4900
4901@example
4902symbol := value
4903@end example
4904
4905where @code{symbol} is a preprocessing symbol, and @code{value} is one of the following:
4906
4907
4908@itemize *
4909
4910@item
4911Empty, corresponding to a null substitution,
4912
4913@item
4914A string literal using normal Ada syntax, or
4915
4916@item
4917Any sequence of characters from the set @{letters, digits, period, underline@}.
4918@end itemize
4919
4920Comment lines may also appear in the definitions file, starting with
4921the usual @code{--},
4922and comments may be added to the definitions lines.
4923
4924@node Form of Input Text for gnatprep,,Form of Definitions File,Preprocessing with gnatprep
4925@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}
4926@subsubsection Form of Input Text for @code{gnatprep}
4927
4928
4929The input text may contain preprocessor conditional inclusion lines,
4930as well as general symbol substitution sequences.
4931
4932The preprocessor conditional inclusion commands have the form:
4933
4934@example
4935#if <expression> [then]
4936   lines
4937#elsif <expression> [then]
4938   lines
4939#elsif <expression> [then]
4940   lines
4941...
4942#else
4943   lines
4944#end if;
4945@end example
4946
4947In this example, <expression> is defined by the following grammar:
4948
4949@example
4950<expression> ::=  <symbol>
4951<expression> ::=  <symbol> = "<value>"
4952<expression> ::=  <symbol> = <symbol>
4953<expression> ::=  <symbol> = <integer>
4954<expression> ::=  <symbol> > <integer>
4955<expression> ::=  <symbol> >= <integer>
4956<expression> ::=  <symbol> < <integer>
4957<expression> ::=  <symbol> <= <integer>
4958<expression> ::=  <symbol> 'Defined
4959<expression> ::=  not <expression>
4960<expression> ::=  <expression> and <expression>
4961<expression> ::=  <expression> or <expression>
4962<expression> ::=  <expression> and then <expression>
4963<expression> ::=  <expression> or else <expression>
4964<expression> ::=  ( <expression> )
4965@end example
4966
4967Note the following restriction: it is not allowed to have "and" or "or"
4968following "not" in the same expression without parentheses. For example, this
4969is not allowed:
4970
4971@example
4972not X or Y
4973@end example
4974
4975This can be expressed instead as one of the following forms:
4976
4977@example
4978(not X) or Y
4979not (X or Y)
4980@end example
4981
4982For the first test (<expression> ::= <symbol>) the symbol must have
4983either the value true or false, that is to say the right-hand of the
4984symbol definition must be one of the (case-insensitive) literals
4985@code{True} or @code{False}. If the value is true, then the
4986corresponding lines are included, and if the value is false, they are
4987excluded.
4988
4989When comparing a symbol to an integer, the integer is any non negative
4990literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
49912#11#. The symbol value must also be a non negative integer. Integer values
4992in the range 0 .. 2**31-1 are supported.
4993
4994The test (<expression> ::= <symbol>'Defined) is true only if
4995the symbol has been defined in the definition file or by a @code{-D}
4996switch on the command line. Otherwise, the test is false.
4997
4998The equality tests are case insensitive, as are all the preprocessor lines.
4999
5000If the symbol referenced is not defined in the symbol definitions file,
5001then the effect depends on whether or not switch @code{-u}
5002is specified. If so, then the symbol is treated as if it had the value
5003false and the test fails. If this switch is not specified, then
5004it is an error to reference an undefined symbol. It is also an error to
5005reference a symbol that is defined with a value other than @code{True}
5006or @code{False}.
5007
5008The use of the @code{not} operator inverts the sense of this logical test.
5009The @code{not} operator cannot be combined with the @code{or} or @code{and}
5010operators, without parentheses. For example, "if not X or Y then" is not
5011allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
5012
5013The @code{then} keyword is optional as shown
5014
5015The @code{#} must be the first non-blank character on a line, but
5016otherwise the format is free form. Spaces or tabs may appear between
5017the @code{#} and the keyword. The keywords and the symbols are case
5018insensitive as in normal Ada code. Comments may be used on a
5019preprocessor line, but other than that, no other tokens may appear on a
5020preprocessor line. Any number of @code{elsif} clauses can be present,
5021including none at all. The @code{else} is optional, as in Ada.
5022
5023The @code{#} marking the start of a preprocessor line must be the first
5024non-blank character on the line, i.e., it must be preceded only by
5025spaces or horizontal tabs.
5026
5027Symbol substitution outside of preprocessor lines is obtained by using
5028the sequence:
5029
5030@example
5031$symbol
5032@end example
5033
5034anywhere within a source line, except in a comment or within a
5035string literal. The identifier
5036following the @code{$} must match one of the symbols defined in the symbol
5037definition file, and the result is to substitute the value of the
5038symbol in place of @code{$symbol} in the output file.
5039
5040Note that although the substitution of strings within a string literal
5041is not possible, it is possible to have a symbol whose defined value is
5042a string literal. So instead of setting XYZ to @code{hello} and writing:
5043
5044@example
5045Header : String := "$XYZ";
5046@end example
5047
5048you should set XYZ to @code{"hello"} and write:
5049
5050@example
5051Header : String := $XYZ;
5052@end example
5053
5054and then the substitution will occur as desired.
5055
5056@node Integrated Preprocessing,,Preprocessing with gnatprep,Conditional Compilation
5057@anchor{gnat_ugn/the_gnat_compilation_model id60}@anchor{b0}@anchor{gnat_ugn/the_gnat_compilation_model integrated-preprocessing}@anchor{18}
5058@subsection Integrated Preprocessing
5059
5060
5061As noted above, a file to be preprocessed consists of Ada source code
5062in which preprocessing lines have been inserted. However,
5063instead of using @code{gnatprep} to explicitly preprocess a file as a separate
5064step before compilation, you can carry out the preprocessing implicitly
5065as part of compilation. Such @emph{integrated preprocessing}, which is the common
5066style with C, is performed when either or both of the following switches
5067are passed to the compiler:
5068
5069@quotation
5070
5071
5072@itemize *
5073
5074@item
5075@code{-gnatep}, which specifies the @emph{preprocessor data file}.
5076This file dictates how the source files will be preprocessed (e.g., which
5077symbol definition files apply to which sources).
5078
5079@item
5080@code{-gnateD}, which defines values for preprocessing symbols.
5081@end itemize
5082@end quotation
5083
5084Integrated preprocessing applies only to Ada source files, it is
5085not available for configuration pragma files.
5086
5087With integrated preprocessing, the output from the preprocessor is not,
5088by default, written to any external file. Instead it is passed
5089internally to the compiler. To preserve the result of
5090preprocessing in a file, either run @code{gnatprep}
5091in standalone mode or else supply the @code{-gnateG} switch
5092(described below) to the compiler.
5093
5094When using project files:
5095
5096@quotation
5097
5098
5099@itemize *
5100
5101@item
5102the builder switch @code{-x} should be used if any Ada source is
5103compiled with @code{gnatep=}, so that the compiler finds the
5104@emph{preprocessor data file}.
5105
5106@item
5107the preprocessing data file and the symbol definition files should be
5108located in the source directories of the project.
5109@end itemize
5110@end quotation
5111
5112Note that the @code{gnatmake} switch @code{-m} will almost
5113always trigger recompilation for sources that are preprocessed,
5114because @code{gnatmake} cannot compute the checksum of the source after
5115preprocessing.
5116
5117The actual preprocessing function is described in detail in
5118@ref{17,,Preprocessing with gnatprep}. This section explains the switches
5119that relate to integrated preprocessing.
5120
5121@geindex -gnatep (gcc)
5122
5123
5124@table @asis
5125
5126@item @code{-gnatep=@emph{preprocessor_data_file}}
5127
5128This switch specifies the file name (without directory
5129information) of the preprocessor data file. Either place this file
5130in one of the source directories, or, when using project
5131files, reference the project file's directory via the
5132@code{project_name'Project_Dir} project attribute; e.g:
5133
5134@quotation
5135
5136@example
5137project Prj is
5138   package Compiler is
5139      for Switches ("Ada") use
5140        ("-gnatep=" & Prj'Project_Dir & "prep.def");
5141   end Compiler;
5142end Prj;
5143@end example
5144@end quotation
5145
5146A preprocessor data file is a text file that contains @emph{preprocessor
5147control lines}.  A preprocessor control line directs the preprocessing of
5148either a particular source file, or, analogous to @code{others} in Ada,
5149all sources not specified elsewhere in  the preprocessor data file.
5150A preprocessor control line
5151can optionally identify a @emph{definition file} that assigns values to
5152preprocessor symbols, as well as a list of switches that relate to
5153preprocessing.
5154Empty lines and comments (using Ada syntax) are also permitted, with no
5155semantic effect.
5156
5157Here's an example of a preprocessor data file:
5158
5159@quotation
5160
5161@example
5162"toto.adb"  "prep.def" -u
5163--  Preprocess toto.adb, using definition file prep.def
5164--  Undefined symbols are treated as False
5165
5166* -c -DVERSION=V101
5167--  Preprocess all other sources without using a definition file
5168--  Suppressed lined are commented
5169--  Symbol VERSION has the value V101
5170
5171"tata.adb" "prep2.def" -s
5172--  Preprocess tata.adb, using definition file prep2.def
5173--  List all symbols with their values
5174@end example
5175@end quotation
5176
5177A preprocessor control line has the following syntax:
5178
5179@quotation
5180
5181@example
5182<preprocessor_control_line> ::=
5183   <preprocessor_input> [ <definition_file_name> ] @{ <switch> @}
5184
5185<preprocessor_input> ::= <source_file_name> | '*'
5186
5187<definition_file_name> ::= <string_literal>
5188
5189<source_file_name> := <string_literal>
5190
5191<switch> := (See below for list)
5192@end example
5193@end quotation
5194
5195Thus  each preprocessor control line starts with either a literal string or
5196the character '*':
5197
5198
5199@itemize *
5200
5201@item
5202A literal string is the file name (without directory information) of the source
5203file that will be input to the preprocessor.
5204
5205@item
5206The character '*' is a wild-card indicator; the additional parameters on the line
5207indicate the preprocessing for all the sources
5208that are not specified explicitly on other lines (the order of the lines is not
5209significant).
5210@end itemize
5211
5212It is an error to have two lines with the same file name or two
5213lines starting with the character '*'.
5214
5215After the file name or '*', an optional literal string specifies the name of
5216the definition file to be used for preprocessing
5217(@ref{ac,,Form of Definitions File}). The definition files are found by the
5218compiler in one of the source directories. In some cases, when compiling
5219a source in a directory other than the current directory, if the definition
5220file is in the current directory, it may be necessary to add the current
5221directory as a source directory through the @code{-I} switch; otherwise
5222the compiler would not find the definition file.
5223
5224Finally, switches similar to those of @code{gnatprep} may optionally appear:
5225
5226
5227@table @asis
5228
5229@item @code{-b}
5230
5231Causes both preprocessor lines and the lines deleted by
5232preprocessing to be replaced by blank lines, preserving the line number.
5233This switch is always implied; however, if specified after @code{-c}
5234it cancels the effect of @code{-c}.
5235
5236@item @code{-c}
5237
5238Causes both preprocessor lines and the lines deleted
5239by preprocessing to be retained as comments marked
5240with the special string '@cite{--!}'.
5241
5242@item @code{-D@emph{symbol}=@emph{new_value}}
5243
5244Define or redefine @code{symbol} to have @code{new_value} as its value.
5245The permitted form for @code{symbol} is either an Ada identifier, or any Ada reserved word
5246aside from @code{if},
5247@code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5248The permitted form for @code{new_value} is a literal string, an Ada identifier or any Ada reserved
5249word. A symbol declared with this switch replaces a symbol with the
5250same name defined in a definition file.
5251
5252@item @code{-s}
5253
5254Causes a sorted list of symbol names and values to be
5255listed on the standard output file.
5256
5257@item @code{-u}
5258
5259Causes undefined symbols to be treated as having the value @code{FALSE}
5260in the context
5261of a preprocessor test. In the absence of this option, an undefined symbol in
5262a @code{#if} or @code{#elsif} test will be treated as an error.
5263@end table
5264@end table
5265
5266@geindex -gnateD (gcc)
5267
5268
5269@table @asis
5270
5271@item @code{-gnateD@emph{symbol}[=@emph{new_value}]}
5272
5273Define or redefine @code{symbol} to have @code{new_value} as its value. If no value
5274is supplied, then the value of @code{symbol} is @code{True}.
5275The form of @code{symbol} is an identifier, following normal Ada (case-insensitive)
5276rules for its syntax, and @code{new_value} is either an arbitrary string between double
5277quotes or any sequence (including an empty sequence) of characters from the
5278set (letters, digits, period, underline).
5279Ada reserved words may be used as symbols, with the exceptions of @code{if},
5280@code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
5281
5282Examples:
5283
5284@quotation
5285
5286@example
5287-gnateDToto=Tata
5288-gnateDFoo
5289-gnateDFoo=\"Foo-Bar\"
5290@end example
5291@end quotation
5292
5293A symbol declared with this switch on the command line replaces a
5294symbol with the same name either in a definition file or specified with a
5295switch @code{-D} in the preprocessor data file.
5296
5297This switch is similar to switch @code{-D} of @code{gnatprep}.
5298
5299@item @code{-gnateG}
5300
5301When integrated preprocessing is performed on source file @code{filename.extension},
5302create or overwrite @code{filename.extension.prep} to contain
5303the result of the preprocessing.
5304For example if the source file is @code{foo.adb} then
5305the output file will be @code{foo.adb.prep}.
5306@end table
5307
5308@node Mixed Language Programming,GNAT and Other Compilation Models,Conditional Compilation,The GNAT Compilation Model
5309@anchor{gnat_ugn/the_gnat_compilation_model mixed-language-programming}@anchor{44}@anchor{gnat_ugn/the_gnat_compilation_model id61}@anchor{b1}
5310@section Mixed Language Programming
5311
5312
5313@geindex Mixed Language Programming
5314
5315This section describes how to develop a mixed-language program,
5316with a focus on combining Ada with C or C++.
5317
5318@menu
5319* Interfacing to C::
5320* Calling Conventions::
5321* Building Mixed Ada and C++ Programs::
5322* Generating Ada Bindings for C and C++ headers::
5323* Generating C Headers for Ada Specifications::
5324
5325@end menu
5326
5327@node Interfacing to C,Calling Conventions,,Mixed Language Programming
5328@anchor{gnat_ugn/the_gnat_compilation_model interfacing-to-c}@anchor{b2}@anchor{gnat_ugn/the_gnat_compilation_model id62}@anchor{b3}
5329@subsection Interfacing to C
5330
5331
5332Interfacing Ada with a foreign language such as C involves using
5333compiler directives to import and/or export entity definitions in each
5334language -- using @code{extern} statements in C, for instance, and the
5335@code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
5336A full treatment of these topics is provided in Appendix B, section 1
5337of the Ada Reference Manual.
5338
5339There are two ways to build a program using GNAT that contains some Ada
5340sources and some foreign language sources, depending on whether or not
5341the main subprogram is written in Ada.  Here is a source example with
5342the main subprogram in Ada:
5343
5344@example
5345/* file1.c */
5346#include <stdio.h>
5347
5348void print_num (int num)
5349@{
5350  printf ("num is %d.\\n", num);
5351  return;
5352@}
5353@end example
5354
5355@example
5356/* file2.c */
5357
5358/* num_from_Ada is declared in my_main.adb */
5359extern int num_from_Ada;
5360
5361int get_num (void)
5362@{
5363  return num_from_Ada;
5364@}
5365@end example
5366
5367@example
5368--  my_main.adb
5369procedure My_Main is
5370
5371   --  Declare then export an Integer entity called num_from_Ada
5372   My_Num : Integer := 10;
5373   pragma Export (C, My_Num, "num_from_Ada");
5374
5375   --  Declare an Ada function spec for Get_Num, then use
5376   --  C function get_num for the implementation.
5377   function Get_Num return Integer;
5378   pragma Import (C, Get_Num, "get_num");
5379
5380   --  Declare an Ada procedure spec for Print_Num, then use
5381   --  C function print_num for the implementation.
5382   procedure Print_Num (Num : Integer);
5383   pragma Import (C, Print_Num, "print_num");
5384
5385begin
5386   Print_Num (Get_Num);
5387end My_Main;
5388@end example
5389
5390To build this example:
5391
5392
5393@itemize *
5394
5395@item
5396First compile the foreign language files to
5397generate object files:
5398
5399@example
5400$ gcc -c file1.c
5401$ gcc -c file2.c
5402@end example
5403
5404@item
5405Then, compile the Ada units to produce a set of object files and ALI
5406files:
5407
5408@example
5409$ gnatmake -c my_main.adb
5410@end example
5411
5412@item
5413Run the Ada binder on the Ada main program:
5414
5415@example
5416$ gnatbind my_main.ali
5417@end example
5418
5419@item
5420Link the Ada main program, the Ada objects and the other language
5421objects:
5422
5423@example
5424$ gnatlink my_main.ali file1.o file2.o
5425@end example
5426@end itemize
5427
5428The last three steps can be grouped in a single command:
5429
5430@example
5431$ gnatmake my_main.adb -largs file1.o file2.o
5432@end example
5433
5434@geindex Binder output file
5435
5436If the main program is in a language other than Ada, then you may have
5437more than one entry point into the Ada subsystem. You must use a special
5438binder option to generate callable routines that initialize and
5439finalize the Ada units (@ref{b4,,Binding with Non-Ada Main Programs}).
5440Calls to the initialization and finalization routines must be inserted
5441in the main program, or some other appropriate point in the code. The
5442call to initialize the Ada units must occur before the first Ada
5443subprogram is called, and the call to finalize the Ada units must occur
5444after the last Ada subprogram returns. The binder will place the
5445initialization and finalization subprograms into the
5446@code{b~xxx.adb} file where they can be accessed by your C
5447sources.  To illustrate, we have the following example:
5448
5449@example
5450/* main.c */
5451extern void adainit (void);
5452extern void adafinal (void);
5453extern int add (int, int);
5454extern int sub (int, int);
5455
5456int main (int argc, char *argv[])
5457@{
5458   int a = 21, b = 7;
5459
5460   adainit();
5461
5462   /* Should print "21 + 7 = 28" */
5463   printf ("%d + %d = %d\\n", a, b, add (a, b));
5464
5465   /* Should print "21 - 7 = 14" */
5466   printf ("%d - %d = %d\\n", a, b, sub (a, b));
5467
5468   adafinal();
5469@}
5470@end example
5471
5472@example
5473--  unit1.ads
5474package Unit1 is
5475   function Add (A, B : Integer) return Integer;
5476   pragma Export (C, Add, "add");
5477end Unit1;
5478@end example
5479
5480@example
5481--  unit1.adb
5482package body Unit1 is
5483   function Add (A, B : Integer) return Integer is
5484   begin
5485      return A + B;
5486   end Add;
5487end Unit1;
5488@end example
5489
5490@example
5491--  unit2.ads
5492package Unit2 is
5493   function Sub (A, B : Integer) return Integer;
5494   pragma Export (C, Sub, "sub");
5495end Unit2;
5496@end example
5497
5498@example
5499--  unit2.adb
5500package body Unit2 is
5501   function Sub (A, B : Integer) return Integer is
5502   begin
5503      return A - B;
5504   end Sub;
5505end Unit2;
5506@end example
5507
5508The build procedure for this application is similar to the last
5509example's:
5510
5511
5512@itemize *
5513
5514@item
5515First, compile the foreign language files to generate object files:
5516
5517@example
5518$ gcc -c main.c
5519@end example
5520
5521@item
5522Next, compile the Ada units to produce a set of object files and ALI
5523files:
5524
5525@example
5526$ gnatmake -c unit1.adb
5527$ gnatmake -c unit2.adb
5528@end example
5529
5530@item
5531Run the Ada binder on every generated ALI file.  Make sure to use the
5532@code{-n} option to specify a foreign main program:
5533
5534@example
5535$ gnatbind -n unit1.ali unit2.ali
5536@end example
5537
5538@item
5539Link the Ada main program, the Ada objects and the foreign language
5540objects. You need only list the last ALI file here:
5541
5542@example
5543$ gnatlink unit2.ali main.o -o exec_file
5544@end example
5545
5546This procedure yields a binary executable called @code{exec_file}.
5547@end itemize
5548
5549Depending on the circumstances (for example when your non-Ada main object
5550does not provide symbol @code{main}), you may also need to instruct the
5551GNAT linker not to include the standard startup objects by passing the
5552@code{-nostartfiles} switch to @code{gnatlink}.
5553
5554@node Calling Conventions,Building Mixed Ada and C++ Programs,Interfacing to C,Mixed Language Programming
5555@anchor{gnat_ugn/the_gnat_compilation_model calling-conventions}@anchor{b5}@anchor{gnat_ugn/the_gnat_compilation_model id63}@anchor{b6}
5556@subsection Calling Conventions
5557
5558
5559@geindex Foreign Languages
5560
5561@geindex Calling Conventions
5562
5563GNAT follows standard calling sequence conventions and will thus interface
5564to any other language that also follows these conventions. The following
5565Convention identifiers are recognized by GNAT:
5566
5567@geindex Interfacing to Ada
5568
5569@geindex Other Ada compilers
5570
5571@geindex Convention Ada
5572
5573
5574@table @asis
5575
5576@item @code{Ada}
5577
5578This indicates that the standard Ada calling sequence will be
5579used and all Ada data items may be passed without any limitations in the
5580case where GNAT is used to generate both the caller and callee. It is also
5581possible to mix GNAT generated code and code generated by another Ada
5582compiler. In this case, the data types should be restricted to simple
5583cases, including primitive types. Whether complex data types can be passed
5584depends on the situation. Probably it is safe to pass simple arrays, such
5585as arrays of integers or floats. Records may or may not work, depending
5586on whether both compilers lay them out identically. Complex structures
5587involving variant records, access parameters, tasks, or protected types,
5588are unlikely to be able to be passed.
5589
5590Note that in the case of GNAT running
5591on a platform that supports HP Ada 83, a higher degree of compatibility
5592can be guaranteed, and in particular records are laid out in an identical
5593manner in the two compilers. Note also that if output from two different
5594compilers is mixed, the program is responsible for dealing with elaboration
5595issues. Probably the safest approach is to write the main program in the
5596version of Ada other than GNAT, so that it takes care of its own elaboration
5597requirements, and then call the GNAT-generated adainit procedure to ensure
5598elaboration of the GNAT components. Consult the documentation of the other
5599Ada compiler for further details on elaboration.
5600
5601However, it is not possible to mix the tasking run time of GNAT and
5602HP Ada 83, All the tasking operations must either be entirely within
5603GNAT compiled sections of the program, or entirely within HP Ada 83
5604compiled sections of the program.
5605@end table
5606
5607@geindex Interfacing to Assembly
5608
5609@geindex Convention Assembler
5610
5611
5612@table @asis
5613
5614@item @code{Assembler}
5615
5616Specifies assembler as the convention. In practice this has the
5617same effect as convention Ada (but is not equivalent in the sense of being
5618considered the same convention).
5619@end table
5620
5621@geindex Convention Asm
5622
5623@geindex Asm
5624
5625
5626@table @asis
5627
5628@item @code{Asm}
5629
5630Equivalent to Assembler.
5631
5632@geindex Interfacing to COBOL
5633
5634@geindex Convention COBOL
5635@end table
5636
5637@geindex COBOL
5638
5639
5640@table @asis
5641
5642@item @code{COBOL}
5643
5644Data will be passed according to the conventions described
5645in section B.4 of the Ada Reference Manual.
5646@end table
5647
5648@geindex C
5649
5650@geindex Interfacing to C
5651
5652@geindex Convention C
5653
5654
5655@table @asis
5656
5657@item @code{C}
5658
5659Data will be passed according to the conventions described
5660in section B.3 of the Ada Reference Manual.
5661
5662A note on interfacing to a C 'varargs' function:
5663
5664@quotation
5665
5666@geindex C varargs function
5667
5668@geindex Interfacing to C varargs function
5669
5670@geindex varargs function interfaces
5671
5672In C, @code{varargs} allows a function to take a variable number of
5673arguments. There is no direct equivalent in this to Ada. One
5674approach that can be used is to create a C wrapper for each
5675different profile and then interface to this C wrapper. For
5676example, to print an @code{int} value using @code{printf},
5677create a C function @code{printfi} that takes two arguments, a
5678pointer to a string and an int, and calls @code{printf}.
5679Then in the Ada program, use pragma @code{Import} to
5680interface to @code{printfi}.
5681
5682It may work on some platforms to directly interface to
5683a @code{varargs} function by providing a specific Ada profile
5684for a particular call. However, this does not work on
5685all platforms, since there is no guarantee that the
5686calling sequence for a two argument normal C function
5687is the same as for calling a @code{varargs} C function with
5688the same two arguments.
5689@end quotation
5690@end table
5691
5692@geindex Convention Default
5693
5694@geindex Default
5695
5696
5697@table @asis
5698
5699@item @code{Default}
5700
5701Equivalent to C.
5702@end table
5703
5704@geindex Convention External
5705
5706@geindex External
5707
5708
5709@table @asis
5710
5711@item @code{External}
5712
5713Equivalent to C.
5714@end table
5715
5716@geindex C++
5717
5718@geindex Interfacing to C++
5719
5720@geindex Convention C++
5721
5722
5723@table @asis
5724
5725@item @code{C_Plus_Plus} (or @code{CPP})
5726
5727This stands for C++. For most purposes this is identical to C.
5728See the separate description of the specialized GNAT pragmas relating to
5729C++ interfacing for further details.
5730@end table
5731
5732@geindex Fortran
5733
5734@geindex Interfacing to Fortran
5735
5736@geindex Convention Fortran
5737
5738
5739@table @asis
5740
5741@item @code{Fortran}
5742
5743Data will be passed according to the conventions described
5744in section B.5 of the Ada Reference Manual.
5745
5746@item @code{Intrinsic}
5747
5748This applies to an intrinsic operation, as defined in the Ada
5749Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
5750this means that the body of the subprogram is provided by the compiler itself,
5751usually by means of an efficient code sequence, and that the user does not
5752supply an explicit body for it. In an application program, the pragma may
5753be applied to the following sets of names:
5754
5755
5756@itemize *
5757
5758@item
5759Rotate_Left, Rotate_Right, Shift_Left, Shift_Right, Shift_Right_Arithmetic.
5760The corresponding subprogram declaration must have
5761two formal parameters. The
5762first one must be a signed integer type or a modular type with a binary
5763modulus, and the second parameter must be of type Natural.
5764The return type must be the same as the type of the first argument. The size
5765of this type can only be 8, 16, 32, or 64.
5766
5767@item
5768Binary arithmetic operators: '+', '-', '*', '/'.
5769The corresponding operator declaration must have parameters and result type
5770that have the same root numeric type (for example, all three are long_float
5771types). This simplifies the definition of operations that use type checking
5772to perform dimensional checks:
5773@end itemize
5774
5775@example
5776  type Distance is new Long_Float;
5777  type Time     is new Long_Float;
5778  type Velocity is new Long_Float;
5779  function "/" (D : Distance; T : Time)
5780    return Velocity;
5781  pragma Import (Intrinsic, "/");
5782
5783This common idiom is often programmed with a generic definition and an
5784explicit body. The pragma makes it simpler to introduce such declarations.
5785It incurs no overhead in compilation time or code size, because it is
5786implemented as a single machine instruction.
5787@end example
5788
5789
5790@itemize *
5791
5792@item
5793General subprogram entities. This is used  to bind an Ada subprogram
5794declaration to
5795a compiler builtin by name with back-ends where such interfaces are
5796available. A typical example is the set of @code{__builtin} functions
5797exposed by the GCC back-end, as in the following example:
5798
5799@example
5800function builtin_sqrt (F : Float) return Float;
5801pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
5802@end example
5803
5804Most of the GCC builtins are accessible this way, and as for other
5805import conventions (e.g. C), it is the user's responsibility to ensure
5806that the Ada subprogram profile matches the underlying builtin
5807expectations.
5808@end itemize
5809@end table
5810
5811@geindex Stdcall
5812
5813@geindex Convention Stdcall
5814
5815
5816@table @asis
5817
5818@item @code{Stdcall}
5819
5820This is relevant only to Windows implementations of GNAT,
5821and specifies that the @code{Stdcall} calling sequence will be used,
5822as defined by the NT API. Nevertheless, to ease building
5823cross-platform bindings this convention will be handled as a @code{C} calling
5824convention on non-Windows platforms.
5825@end table
5826
5827@geindex DLL
5828
5829@geindex Convention DLL
5830
5831
5832@table @asis
5833
5834@item @code{DLL}
5835
5836This is equivalent to @code{Stdcall}.
5837@end table
5838
5839@geindex Win32
5840
5841@geindex Convention Win32
5842
5843
5844@table @asis
5845
5846@item @code{Win32}
5847
5848This is equivalent to @code{Stdcall}.
5849@end table
5850
5851@geindex Stubbed
5852
5853@geindex Convention Stubbed
5854
5855
5856@table @asis
5857
5858@item @code{Stubbed}
5859
5860This is a special convention that indicates that the compiler
5861should provide a stub body that raises @code{Program_Error}.
5862@end table
5863
5864GNAT additionally provides a useful pragma @code{Convention_Identifier}
5865that can be used to parameterize conventions and allow additional synonyms
5866to be specified. For example if you have legacy code in which the convention
5867identifier Fortran77 was used for Fortran, you can use the configuration
5868pragma:
5869
5870@example
5871pragma Convention_Identifier (Fortran77, Fortran);
5872@end example
5873
5874And from now on the identifier Fortran77 may be used as a convention
5875identifier (for example in an @code{Import} pragma) with the same
5876meaning as Fortran.
5877
5878@node Building Mixed Ada and C++ Programs,Generating Ada Bindings for C and C++ headers,Calling Conventions,Mixed Language Programming
5879@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}
5880@subsection Building Mixed Ada and C++ Programs
5881
5882
5883A programmer inexperienced with mixed-language development may find that
5884building an application containing both Ada and C++ code can be a
5885challenge.  This section gives a few hints that should make this task easier.
5886
5887@menu
5888* Interfacing to C++::
5889* Linking a Mixed C++ & Ada Program::
5890* A Simple Example::
5891* Interfacing with C++ constructors::
5892* Interfacing with C++ at the Class Level::
5893
5894@end menu
5895
5896@node Interfacing to C++,Linking a Mixed C++ & Ada Program,,Building Mixed Ada and C++ Programs
5897@anchor{gnat_ugn/the_gnat_compilation_model id65}@anchor{b9}@anchor{gnat_ugn/the_gnat_compilation_model id66}@anchor{ba}
5898@subsubsection Interfacing to C++
5899
5900
5901GNAT supports interfacing with the G++ compiler (or any C++ compiler
5902generating code that is compatible with the G++ Application Binary
5903Interface ---see @indicateurl{http://www.codesourcery.com/archives/cxx-abi}).
5904
5905Interfacing can be done at 3 levels: simple data, subprograms, and
5906classes. In the first two cases, GNAT offers a specific @code{Convention C_Plus_Plus}
5907(or @code{CPP}) that behaves exactly like @code{Convention C}.
5908Usually, C++ mangles the names of subprograms. To generate proper mangled
5909names automatically, see @ref{19,,Generating Ada Bindings for C and C++ headers}).
5910This problem can also be addressed manually in two ways:
5911
5912
5913@itemize *
5914
5915@item
5916by modifying the C++ code in order to force a C convention using
5917the @code{extern "C"} syntax.
5918
5919@item
5920by figuring out the mangled name (using e.g. @code{nm}) and using it as the
5921Link_Name argument of the pragma import.
5922@end itemize
5923
5924Interfacing at the class level can be achieved by using the GNAT specific
5925pragmas such as @code{CPP_Constructor}.  See the @cite{GNAT_Reference_Manual} for additional information.
5926
5927@node Linking a Mixed C++ & Ada Program,A Simple Example,Interfacing to C++,Building Mixed Ada and C++ Programs
5928@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}
5929@subsubsection Linking a Mixed C++ & Ada Program
5930
5931
5932Usually the linker of the C++ development system must be used to link
5933mixed applications because most C++ systems will resolve elaboration
5934issues (such as calling constructors on global class instances)
5935transparently during the link phase. GNAT has been adapted to ease the
5936use of a foreign linker for the last phase. Three cases can be
5937considered:
5938
5939
5940@itemize *
5941
5942@item
5943Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
5944The C++ linker can simply be called by using the C++ specific driver
5945called @code{g++}.
5946
5947Note that if the C++ code uses inline functions, you will need to
5948compile your C++ code with the @code{-fkeep-inline-functions} switch in
5949order to provide an existing function implementation that the Ada code can
5950link with.
5951
5952@example
5953$ g++ -c -fkeep-inline-functions file1.C
5954$ g++ -c -fkeep-inline-functions file2.C
5955$ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
5956@end example
5957
5958@item
5959Using GNAT and G++ from two different GCC installations: If both
5960compilers are on the :envvar`PATH`, the previous method may be used. It is
5961important to note that environment variables such as
5962@geindex C_INCLUDE_PATH
5963@geindex environment variable; C_INCLUDE_PATH
5964@code{C_INCLUDE_PATH},
5965@geindex GCC_EXEC_PREFIX
5966@geindex environment variable; GCC_EXEC_PREFIX
5967@code{GCC_EXEC_PREFIX},
5968@geindex BINUTILS_ROOT
5969@geindex environment variable; BINUTILS_ROOT
5970@code{BINUTILS_ROOT}, and
5971@geindex GCC_ROOT
5972@geindex environment variable; GCC_ROOT
5973@code{GCC_ROOT} will affect both compilers
5974at the same time and may make one of the two compilers operate
5975improperly if set during invocation of the wrong compiler.  It is also
5976very important that the linker uses the proper @code{libgcc.a} GCC
5977library -- that is, the one from the C++ compiler installation. The
5978implicit link command as suggested in the @code{gnatmake} command
5979from the former example can be replaced by an explicit link command with
5980the full-verbosity option in order to verify which library is used:
5981
5982@example
5983$ gnatbind ada_unit
5984$ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
5985@end example
5986
5987If there is a problem due to interfering environment variables, it can
5988be worked around by using an intermediate script. The following example
5989shows the proper script to use when GNAT has not been installed at its
5990default location and g++ has been installed at its default location:
5991
5992@example
5993$ cat ./my_script
5994#!/bin/sh
5995unset BINUTILS_ROOT
5996unset GCC_ROOT
5997c++ $*
5998$ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
5999@end example
6000
6001@item
6002Using a non-GNU C++ compiler: The commands previously described can be
6003used to insure that the C++ linker is used. Nonetheless, you need to add
6004a few more parameters to the link command line, depending on the exception
6005mechanism used.
6006
6007If the @code{setjmp} / @code{longjmp} exception mechanism is used, only the paths
6008to the @code{libgcc} libraries are required:
6009
6010@example
6011$ cat ./my_script
6012#!/bin/sh
6013CC $* gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a
6014$ gnatlink ada_unit file1.o file2.o --LINK=./my_script
6015@end example
6016
6017where CC is the name of the non-GNU C++ compiler.
6018
6019If the "zero cost" exception mechanism is used, and the platform
6020supports automatic registration of exception tables (e.g., Solaris),
6021paths to more objects are required:
6022
6023@example
6024$ cat ./my_script
6025#!/bin/sh
6026CC gcc -print-file-name=crtbegin.o $* \\
6027gcc -print-file-name=libgcc.a gcc -print-file-name=libgcc_eh.a \\
6028gcc -print-file-name=crtend.o
6029$ gnatlink ada_unit file1.o file2.o --LINK=./my_script
6030@end example
6031
6032If the "zero cost exception" mechanism is used, and the platform
6033doesn't support automatic registration of exception tables (e.g., HP-UX
6034or AIX), the simple approach described above will not work and
6035a pre-linking phase using GNAT will be necessary.
6036@end itemize
6037
6038Another alternative is to use the @code{gprbuild} multi-language builder
6039which has a large knowledge base and knows how to link Ada and C++ code
6040together automatically in most cases.
6041
6042@node A Simple Example,Interfacing with C++ constructors,Linking a Mixed C++ & Ada Program,Building Mixed Ada and C++ Programs
6043@anchor{gnat_ugn/the_gnat_compilation_model id67}@anchor{bd}@anchor{gnat_ugn/the_gnat_compilation_model a-simple-example}@anchor{be}
6044@subsubsection A Simple Example
6045
6046
6047The following example, provided as part of the GNAT examples, shows how
6048to achieve procedural interfacing between Ada and C++ in both
6049directions. The C++ class A has two methods. The first method is exported
6050to Ada by the means of an extern C wrapper function. The second method
6051calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
6052a limited record with a layout comparable to the C++ class. The Ada
6053subprogram, in turn, calls the C++ method. So, starting from the C++
6054main program, the process passes back and forth between the two
6055languages.
6056
6057Here are the compilation commands:
6058
6059@example
6060$ gnatmake -c simple_cpp_interface
6061$ g++ -c cpp_main.C
6062$ g++ -c ex7.C
6063$ gnatbind -n simple_cpp_interface
6064$ gnatlink simple_cpp_interface -o cpp_main --LINK=g++ -lstdc++ ex7.o cpp_main.o
6065@end example
6066
6067Here are the corresponding sources:
6068
6069@example
6070//cpp_main.C
6071
6072#include "ex7.h"
6073
6074extern "C" @{
6075  void adainit (void);
6076  void adafinal (void);
6077  void method1 (A *t);
6078@}
6079
6080void method1 (A *t)
6081@{
6082  t->method1 ();
6083@}
6084
6085int main ()
6086@{
6087  A obj;
6088  adainit ();
6089  obj.method2 (3030);
6090  adafinal ();
6091@}
6092@end example
6093
6094@example
6095//ex7.h
6096
6097class Origin @{
6098 public:
6099  int o_value;
6100@};
6101class A : public Origin @{
6102 public:
6103  void method1 (void);
6104  void method2 (int v);
6105  A();
6106  int   a_value;
6107@};
6108@end example
6109
6110@example
6111//ex7.C
6112
6113#include "ex7.h"
6114#include <stdio.h>
6115
6116extern "C" @{ void ada_method2 (A *t, int v);@}
6117
6118void A::method1 (void)
6119@{
6120  a_value = 2020;
6121  printf ("in A::method1, a_value = %d \\n",a_value);
6122@}
6123
6124void A::method2 (int v)
6125@{
6126   ada_method2 (this, v);
6127   printf ("in A::method2, a_value = %d \\n",a_value);
6128@}
6129
6130A::A(void)
6131@{
6132   a_value = 1010;
6133  printf ("in A::A, a_value = %d \\n",a_value);
6134@}
6135@end example
6136
6137@example
6138-- simple_cpp_interface.ads
6139with System;
6140package Simple_Cpp_Interface is
6141   type A is limited
6142      record
6143         Vptr    : System.Address;
6144         O_Value : Integer;
6145         A_Value : Integer;
6146      end record;
6147   pragma Convention (C, A);
6148
6149   procedure Method1 (This : in out A);
6150   pragma Import (C, Method1);
6151
6152   procedure Ada_Method2 (This : in out A; V : Integer);
6153   pragma Export (C, Ada_Method2);
6154
6155end Simple_Cpp_Interface;
6156@end example
6157
6158@example
6159-- simple_cpp_interface.adb
6160package body Simple_Cpp_Interface is
6161
6162   procedure Ada_Method2 (This : in out A; V : Integer) is
6163   begin
6164      Method1 (This);
6165      This.A_Value := V;
6166   end Ada_Method2;
6167
6168end Simple_Cpp_Interface;
6169@end example
6170
6171@node Interfacing with C++ constructors,Interfacing with C++ at the Class Level,A Simple Example,Building Mixed Ada and C++ Programs
6172@anchor{gnat_ugn/the_gnat_compilation_model id68}@anchor{bf}@anchor{gnat_ugn/the_gnat_compilation_model interfacing-with-c-constructors}@anchor{c0}
6173@subsubsection Interfacing with C++ constructors
6174
6175
6176In order to interface with C++ constructors GNAT provides the
6177@code{pragma CPP_Constructor} (see the @cite{GNAT_Reference_Manual}
6178for additional information).
6179In this section we present some common uses of C++ constructors
6180in mixed-languages programs in GNAT.
6181
6182Let us assume that we need to interface with the following
6183C++ class:
6184
6185@example
6186class Root @{
6187public:
6188  int  a_value;
6189  int  b_value;
6190  virtual int Get_Value ();
6191  Root();              // Default constructor
6192  Root(int v);         // 1st non-default constructor
6193  Root(int v, int w);  // 2nd non-default constructor
6194@};
6195@end example
6196
6197For this purpose we can write the following package spec (further
6198information on how to build this spec is available in
6199@ref{c1,,Interfacing with C++ at the Class Level} and
6200@ref{19,,Generating Ada Bindings for C and C++ headers}).
6201
6202@example
6203with Interfaces.C; use Interfaces.C;
6204package Pkg_Root is
6205  type Root is tagged limited record
6206     A_Value : int;
6207     B_Value : int;
6208  end record;
6209  pragma Import (CPP, Root);
6210
6211  function Get_Value (Obj : Root) return int;
6212  pragma Import (CPP, Get_Value);
6213
6214  function Constructor return Root;
6215  pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
6216
6217  function Constructor (v : Integer) return Root;
6218  pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
6219
6220  function Constructor (v, w : Integer) return Root;
6221  pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
6222end Pkg_Root;
6223@end example
6224
6225On the Ada side the constructor is represented by a function (whose
6226name is arbitrary) that returns the classwide type corresponding to
6227the imported C++ class. Although the constructor is described as a
6228function, it is typically a procedure with an extra implicit argument
6229(the object being initialized) at the implementation level. GNAT
6230issues the appropriate call, whatever it is, to get the object
6231properly initialized.
6232
6233Constructors can only appear in the following contexts:
6234
6235
6236@itemize *
6237
6238@item
6239On the right side of an initialization of an object of type @code{T}.
6240
6241@item
6242On the right side of an initialization of a record component of type @code{T}.
6243
6244@item
6245In an Ada 2005 limited aggregate.
6246
6247@item
6248In an Ada 2005 nested limited aggregate.
6249
6250@item
6251In an Ada 2005 limited aggregate that initializes an object built in
6252place by an extended return statement.
6253@end itemize
6254
6255In a declaration of an object whose type is a class imported from C++,
6256either the default C++ constructor is implicitly called by GNAT, or
6257else the required C++ constructor must be explicitly called in the
6258expression that initializes the object. For example:
6259
6260@example
6261Obj1 : Root;
6262Obj2 : Root := Constructor;
6263Obj3 : Root := Constructor (v => 10);
6264Obj4 : Root := Constructor (30, 40);
6265@end example
6266
6267The first two declarations are equivalent: in both cases the default C++
6268constructor is invoked (in the former case the call to the constructor is
6269implicit, and in the latter case the call is explicit in the object
6270declaration). @code{Obj3} is initialized by the C++ non-default constructor
6271that takes an integer argument, and @code{Obj4} is initialized by the
6272non-default C++ constructor that takes two integers.
6273
6274Let us derive the imported C++ class in the Ada side. For example:
6275
6276@example
6277type DT is new Root with record
6278   C_Value : Natural := 2009;
6279end record;
6280@end example
6281
6282In this case the components DT inherited from the C++ side must be
6283initialized by a C++ constructor, and the additional Ada components
6284of type DT are initialized by GNAT. The initialization of such an
6285object is done either by default, or by means of a function returning
6286an aggregate of type DT, or by means of an extension aggregate.
6287
6288@example
6289Obj5 : DT;
6290Obj6 : DT := Function_Returning_DT (50);
6291Obj7 : DT := (Constructor (30,40) with C_Value => 50);
6292@end example
6293
6294The declaration of @code{Obj5} invokes the default constructors: the
6295C++ default constructor of the parent type takes care of the initialization
6296of the components inherited from Root, and GNAT takes care of the default
6297initialization of the additional Ada components of type DT (that is,
6298@code{C_Value} is initialized to value 2009). The order of invocation of
6299the constructors is consistent with the order of elaboration required by
6300Ada and C++. That is, the constructor of the parent type is always called
6301before the constructor of the derived type.
6302
6303Let us now consider a record that has components whose type is imported
6304from C++. For example:
6305
6306@example
6307type Rec1 is limited record
6308   Data1 : Root := Constructor (10);
6309   Value : Natural := 1000;
6310end record;
6311
6312type Rec2 (D : Integer := 20) is limited record
6313   Rec   : Rec1;
6314   Data2 : Root := Constructor (D, 30);
6315end record;
6316@end example
6317
6318The initialization of an object of type @code{Rec2} will call the
6319non-default C++ constructors specified for the imported components.
6320For example:
6321
6322@example
6323Obj8 : Rec2 (40);
6324@end example
6325
6326Using Ada 2005 we can use limited aggregates to initialize an object
6327invoking C++ constructors that differ from those specified in the type
6328declarations. For example:
6329
6330@example
6331Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
6332                        others => <>),
6333                others => <>);
6334@end example
6335
6336The above declaration uses an Ada 2005 limited aggregate to
6337initialize @code{Obj9}, and the C++ constructor that has two integer
6338arguments is invoked to initialize the @code{Data1} component instead
6339of the constructor specified in the declaration of type @code{Rec1}. In
6340Ada 2005 the box in the aggregate indicates that unspecified components
6341are initialized using the expression (if any) available in the component
6342declaration. That is, in this case discriminant @code{D} is initialized
6343to value @code{20}, @code{Value} is initialized to value 1000, and the
6344non-default C++ constructor that handles two integers takes care of
6345initializing component @code{Data2} with values @code{20,30}.
6346
6347In Ada 2005 we can use the extended return statement to build the Ada
6348equivalent to C++ non-default constructors. For example:
6349
6350@example
6351function Constructor (V : Integer) return Rec2 is
6352begin
6353   return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
6354                                 others => <>),
6355                         others => <>) do
6356      --  Further actions required for construction of
6357      --  objects of type Rec2
6358      ...
6359   end record;
6360end Constructor;
6361@end example
6362
6363In this example the extended return statement construct is used to
6364build in place the returned object whose components are initialized
6365by means of a limited aggregate. Any further action associated with
6366the constructor can be placed inside the construct.
6367
6368@node Interfacing with C++ at the Class Level,,Interfacing with C++ constructors,Building Mixed Ada and C++ Programs
6369@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}
6370@subsubsection Interfacing with C++ at the Class Level
6371
6372
6373In this section we demonstrate the GNAT features for interfacing with
6374C++ by means of an example making use of Ada 2005 abstract interface
6375types. This example consists of a classification of animals; classes
6376have been used to model our main classification of animals, and
6377interfaces provide support for the management of secondary
6378classifications. We first demonstrate a case in which the types and
6379constructors are defined on the C++ side and imported from the Ada
6380side, and latter the reverse case.
6381
6382The root of our derivation will be the @code{Animal} class, with a
6383single private attribute (the @code{Age} of the animal), a constructor,
6384and two public primitives to set and get the value of this attribute.
6385
6386@example
6387class Animal @{
6388 public:
6389   virtual void Set_Age (int New_Age);
6390   virtual int Age ();
6391   Animal() @{Age_Count = 0;@};
6392 private:
6393   int Age_Count;
6394@};
6395@end example
6396
6397Abstract interface types are defined in C++ by means of classes with pure
6398virtual functions and no data members. In our example we will use two
6399interfaces that provide support for the common management of @code{Carnivore}
6400and @code{Domestic} animals:
6401
6402@example
6403class Carnivore @{
6404public:
6405   virtual int Number_Of_Teeth () = 0;
6406@};
6407
6408class Domestic @{
6409public:
6410   virtual void Set_Owner (char* Name) = 0;
6411@};
6412@end example
6413
6414Using these declarations, we can now say that a @code{Dog} is an animal that is
6415both Carnivore and Domestic, that is:
6416
6417@example
6418class Dog : Animal, Carnivore, Domestic @{
6419 public:
6420   virtual int  Number_Of_Teeth ();
6421   virtual void Set_Owner (char* Name);
6422
6423   Dog(); // Constructor
6424 private:
6425   int  Tooth_Count;
6426   char *Owner;
6427@};
6428@end example
6429
6430In the following examples we will assume that the previous declarations are
6431located in a file named @code{animals.h}. The following package demonstrates
6432how to import these C++ declarations from the Ada side:
6433
6434@example
6435with Interfaces.C.Strings; use Interfaces.C.Strings;
6436package Animals is
6437  type Carnivore is limited interface;
6438  pragma Convention (C_Plus_Plus, Carnivore);
6439  function Number_Of_Teeth (X : Carnivore)
6440     return Natural is abstract;
6441
6442  type Domestic is limited interface;
6443  pragma Convention (C_Plus_Plus, Domestic);
6444  procedure Set_Owner
6445    (X    : in out Domestic;
6446     Name : Chars_Ptr) is abstract;
6447
6448  type Animal is tagged limited record
6449    Age : Natural;
6450  end record;
6451  pragma Import (C_Plus_Plus, Animal);
6452
6453  procedure Set_Age (X : in out Animal; Age : Integer);
6454  pragma Import (C_Plus_Plus, Set_Age);
6455
6456  function Age (X : Animal) return Integer;
6457  pragma Import (C_Plus_Plus, Age);
6458
6459  function New_Animal return Animal;
6460  pragma CPP_Constructor (New_Animal);
6461  pragma Import (CPP, New_Animal, "_ZN6AnimalC1Ev");
6462
6463  type Dog is new Animal and Carnivore and Domestic with record
6464    Tooth_Count : Natural;
6465    Owner       : Chars_Ptr;
6466  end record;
6467  pragma Import (C_Plus_Plus, Dog);
6468
6469  function Number_Of_Teeth (A : Dog) return Natural;
6470  pragma Import (C_Plus_Plus, Number_Of_Teeth);
6471
6472  procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6473  pragma Import (C_Plus_Plus, Set_Owner);
6474
6475  function New_Dog return Dog;
6476  pragma CPP_Constructor (New_Dog);
6477  pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
6478end Animals;
6479@end example
6480
6481Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
6482interfacing with these C++ classes is easy. The only requirement is that all
6483the primitives and components must be declared exactly in the same order in
6484the two languages.
6485
6486Regarding the abstract interfaces, we must indicate to the GNAT compiler by
6487means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
6488the arguments to the called primitives will be the same as for C++. For the
6489imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
6490to indicate that they have been defined on the C++ side; this is required
6491because the dispatch table associated with these tagged types will be built
6492in the C++ side and therefore will not contain the predefined Ada primitives
6493which Ada would otherwise expect.
6494
6495As the reader can see there is no need to indicate the C++ mangled names
6496associated with each subprogram because it is assumed that all the calls to
6497these primitives will be dispatching calls. The only exception is the
6498constructor, which must be registered with the compiler by means of
6499@code{pragma CPP_Constructor} and needs to provide its associated C++
6500mangled name because the Ada compiler generates direct calls to it.
6501
6502With the above packages we can now declare objects of type Dog on the Ada side
6503and dispatch calls to the corresponding subprograms on the C++ side. We can
6504also extend the tagged type Dog with further fields and primitives, and
6505override some of its C++ primitives on the Ada side. For example, here we have
6506a type derivation defined on the Ada side that inherits all the dispatching
6507primitives of the ancestor from the C++ side.
6508
6509@example
6510with Animals; use Animals;
6511package Vaccinated_Animals is
6512  type Vaccinated_Dog is new Dog with null record;
6513  function Vaccination_Expired (A : Vaccinated_Dog) return Boolean;
6514end Vaccinated_Animals;
6515@end example
6516
6517It is important to note that, because of the ABI compatibility, the programmer
6518does not need to add any further information to indicate either the object
6519layout or the dispatch table entry associated with each dispatching operation.
6520
6521Now let us define all the types and constructors on the Ada side and export
6522them to C++, using the same hierarchy of our previous example:
6523
6524@example
6525with Interfaces.C.Strings;
6526use Interfaces.C.Strings;
6527package Animals is
6528  type Carnivore is limited interface;
6529  pragma Convention (C_Plus_Plus, Carnivore);
6530  function Number_Of_Teeth (X : Carnivore)
6531     return Natural is abstract;
6532
6533  type Domestic is limited interface;
6534  pragma Convention (C_Plus_Plus, Domestic);
6535  procedure Set_Owner
6536    (X    : in out Domestic;
6537     Name : Chars_Ptr) is abstract;
6538
6539  type Animal is tagged record
6540    Age : Natural;
6541  end record;
6542  pragma Convention (C_Plus_Plus, Animal);
6543
6544  procedure Set_Age (X : in out Animal; Age : Integer);
6545  pragma Export (C_Plus_Plus, Set_Age);
6546
6547  function Age (X : Animal) return Integer;
6548  pragma Export (C_Plus_Plus, Age);
6549
6550  function New_Animal return Animal'Class;
6551  pragma Export (C_Plus_Plus, New_Animal);
6552
6553  type Dog is new Animal and Carnivore and Domestic with record
6554    Tooth_Count : Natural;
6555    Owner       : String (1 .. 30);
6556  end record;
6557  pragma Convention (C_Plus_Plus, Dog);
6558
6559  function Number_Of_Teeth (A : Dog) return Natural;
6560  pragma Export (C_Plus_Plus, Number_Of_Teeth);
6561
6562  procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
6563  pragma Export (C_Plus_Plus, Set_Owner);
6564
6565  function New_Dog return Dog'Class;
6566  pragma Export (C_Plus_Plus, New_Dog);
6567end Animals;
6568@end example
6569
6570Compared with our previous example the only differences are the use of
6571@code{pragma Convention} (instead of @code{pragma Import}), and the use of
6572@code{pragma Export} to indicate to the GNAT compiler that the primitives will
6573be available to C++. Thanks to the ABI compatibility, on the C++ side there is
6574nothing else to be done; as explained above, the only requirement is that all
6575the primitives and components are declared in exactly the same order.
6576
6577For completeness, let us see a brief C++ main program that uses the
6578declarations available in @code{animals.h} (presented in our first example) to
6579import and use the declarations from the Ada side, properly initializing and
6580finalizing the Ada run-time system along the way:
6581
6582@example
6583#include "animals.h"
6584#include <iostream>
6585using namespace std;
6586
6587void Check_Carnivore (Carnivore *obj) @{...@}
6588void Check_Domestic (Domestic *obj)   @{...@}
6589void Check_Animal (Animal *obj)       @{...@}
6590void Check_Dog (Dog *obj)             @{...@}
6591
6592extern "C" @{
6593  void adainit (void);
6594  void adafinal (void);
6595  Dog* new_dog ();
6596@}
6597
6598void test ()
6599@{
6600  Dog *obj = new_dog();  // Ada constructor
6601  Check_Carnivore (obj); // Check secondary DT
6602  Check_Domestic (obj);  // Check secondary DT
6603  Check_Animal (obj);    // Check primary DT
6604  Check_Dog (obj);       // Check primary DT
6605@}
6606
6607int main ()
6608@{
6609  adainit ();  test();  adafinal ();
6610  return 0;
6611@}
6612@end example
6613
6614@node Generating Ada Bindings for C and C++ headers,Generating C Headers for Ada Specifications,Building Mixed Ada and C++ Programs,Mixed Language Programming
6615@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}
6616@subsection Generating Ada Bindings for C and C++ headers
6617
6618
6619@geindex Binding generation (for C and C++ headers)
6620
6621@geindex C headers (binding generation)
6622
6623@geindex C++ headers (binding generation)
6624
6625GNAT includes a binding generator for C and C++ headers which is
6626intended to do 95% of the tedious work of generating Ada specs from C
6627or C++ header files.
6628
6629Note that this capability is not intended to generate 100% correct Ada specs,
6630and will is some cases require manual adjustments, although it can often
6631be used out of the box in practice.
6632
6633Some of the known limitations include:
6634
6635
6636@itemize *
6637
6638@item
6639only very simple character constant macros are translated into Ada
6640constants. Function macros (macros with arguments) are partially translated
6641as comments, to be completed manually if needed.
6642
6643@item
6644some extensions (e.g. vector types) are not supported
6645
6646@item
6647pointers to pointers or complex structures are mapped to System.Address
6648
6649@item
6650identifiers with identical name (except casing) will generate compilation
6651errors (e.g. @code{shm_get} vs @code{SHM_GET}).
6652@end itemize
6653
6654The code generated is using the Ada 2005 syntax, which makes it
6655easier to interface with other languages than previous versions of Ada.
6656
6657@menu
6658* Running the Binding Generator::
6659* Generating Bindings for C++ Headers::
6660* Switches::
6661
6662@end menu
6663
6664@node Running the Binding Generator,Generating Bindings for C++ Headers,,Generating Ada Bindings for C and C++ headers
6665@anchor{gnat_ugn/the_gnat_compilation_model id71}@anchor{c4}@anchor{gnat_ugn/the_gnat_compilation_model running-the-binding-generator}@anchor{c5}
6666@subsubsection Running the Binding Generator
6667
6668
6669The binding generator is part of the @code{gcc} compiler and can be
6670invoked via the @code{-fdump-ada-spec} switch, which will generate Ada
6671spec files for the header files specified on the command line, and all
6672header files needed by these files transitively. For example:
6673
6674@example
6675$ g++ -c -fdump-ada-spec -C /usr/include/time.h
6676$ gcc -c -gnat05 *.ads
6677@end example
6678
6679will generate, under GNU/Linux, the following files: @code{time_h.ads},
6680@code{bits_time_h.ads}, @code{stddef_h.ads}, @code{bits_types_h.ads} which
6681correspond to the files @code{/usr/include/time.h},
6682@code{/usr/include/bits/time.h}, etc..., and will then compile these Ada specs
6683in Ada 2005 mode.
6684
6685The @code{-C} switch tells @code{gcc} to extract comments from headers,
6686and will attempt to generate corresponding Ada comments.
6687
6688If you want to generate a single Ada file and not the transitive closure, you
6689can use instead the @code{-fdump-ada-spec-slim} switch.
6690
6691You can optionally specify a parent unit, of which all generated units will
6692be children, using @code{-fada-spec-parent=@emph{unit}}.
6693
6694Note that we recommend when possible to use the @emph{g++} driver to
6695generate bindings, even for most C headers, since this will in general
6696generate better Ada specs. For generating bindings for C++ headers, it is
6697mandatory to use the @emph{g++} command, or @emph{gcc -x c++} which
6698is equivalent in this case. If @emph{g++} cannot work on your C headers
6699because of incompatibilities between C and C++, then you can fallback to
6700@code{gcc} instead.
6701
6702For an example of better bindings generated from the C++ front-end,
6703the name of the parameters (when available) are actually ignored by the C
6704front-end. Consider the following C header:
6705
6706@example
6707extern void foo (int variable);
6708@end example
6709
6710with the C front-end, @code{variable} is ignored, and the above is handled as:
6711
6712@example
6713extern void foo (int);
6714@end example
6715
6716generating a generic:
6717
6718@example
6719procedure foo (param1 : int);
6720@end example
6721
6722with the C++ front-end, the name is available, and we generate:
6723
6724@example
6725procedure foo (variable : int);
6726@end example
6727
6728In some cases, the generated bindings will be more complete or more meaningful
6729when defining some macros, which you can do via the @code{-D} switch. This
6730is for example the case with @code{Xlib.h} under GNU/Linux:
6731
6732@example
6733$ g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
6734@end example
6735
6736The above will generate more complete bindings than a straight call without
6737the @code{-DXLIB_ILLEGAL_ACCESS} switch.
6738
6739In other cases, it is not possible to parse a header file in a stand-alone
6740manner, because other include files need to be included first. In this
6741case, the solution is to create a small header file including the needed
6742@code{#include} and possible @code{#define} directives. For example, to
6743generate Ada bindings for @code{readline/readline.h}, you need to first
6744include @code{stdio.h}, so you can create a file with the following two
6745lines in e.g. @code{readline1.h}:
6746
6747@example
6748#include <stdio.h>
6749#include <readline/readline.h>
6750@end example
6751
6752and then generate Ada bindings from this file:
6753
6754@example
6755$ g++ -c -fdump-ada-spec readline1.h
6756@end example
6757
6758@node Generating Bindings for C++ Headers,Switches,Running the Binding Generator,Generating Ada Bindings for C and C++ headers
6759@anchor{gnat_ugn/the_gnat_compilation_model id72}@anchor{c6}@anchor{gnat_ugn/the_gnat_compilation_model generating-bindings-for-c-headers}@anchor{c7}
6760@subsubsection Generating Bindings for C++ Headers
6761
6762
6763Generating bindings for C++ headers is done using the same options, always
6764with the @emph{g++} compiler. Note that generating Ada spec from C++ headers is a
6765much more complex job and support for C++ headers is much more limited that
6766support for C headers. As a result, you will need to modify the resulting
6767bindings by hand more extensively when using C++ headers.
6768
6769In this mode, C++ classes will be mapped to Ada tagged types, constructors
6770will be mapped using the @code{CPP_Constructor} pragma, and when possible,
6771multiple inheritance of abstract classes will be mapped to Ada interfaces
6772(see the @emph{Interfacing to C++} section in the @cite{GNAT Reference Manual}
6773for additional information on interfacing to C++).
6774
6775For example, given the following C++ header file:
6776
6777@example
6778class Carnivore @{
6779public:
6780   virtual int Number_Of_Teeth () = 0;
6781@};
6782
6783class Domestic @{
6784public:
6785   virtual void Set_Owner (char* Name) = 0;
6786@};
6787
6788class Animal @{
6789public:
6790  int Age_Count;
6791  virtual void Set_Age (int New_Age);
6792@};
6793
6794class Dog : Animal, Carnivore, Domestic @{
6795 public:
6796  int  Tooth_Count;
6797  char *Owner;
6798
6799  virtual int  Number_Of_Teeth ();
6800  virtual void Set_Owner (char* Name);
6801
6802  Dog();
6803@};
6804@end example
6805
6806The corresponding Ada code is generated:
6807
6808@example
6809package Class_Carnivore is
6810  type Carnivore is limited interface;
6811  pragma Import (CPP, Carnivore);
6812
6813  function Number_Of_Teeth (this : access Carnivore) return int is abstract;
6814end;
6815use Class_Carnivore;
6816
6817package Class_Domestic is
6818  type Domestic is limited interface;
6819  pragma Import (CPP, Domestic);
6820
6821  procedure Set_Owner
6822    (this : access Domestic;
6823     Name : Interfaces.C.Strings.chars_ptr) is abstract;
6824end;
6825use Class_Domestic;
6826
6827package Class_Animal is
6828  type Animal is tagged limited record
6829    Age_Count : aliased int;
6830  end record;
6831  pragma Import (CPP, Animal);
6832
6833  procedure Set_Age (this : access Animal; New_Age : int);
6834  pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
6835end;
6836use Class_Animal;
6837
6838package Class_Dog is
6839  type Dog is new Animal and Carnivore and Domestic with record
6840    Tooth_Count : aliased int;
6841    Owner : Interfaces.C.Strings.chars_ptr;
6842  end record;
6843  pragma Import (CPP, Dog);
6844
6845  function Number_Of_Teeth (this : access Dog) return int;
6846  pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
6847
6848  procedure Set_Owner
6849    (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
6850  pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
6851
6852  function New_Dog return Dog;
6853  pragma CPP_Constructor (New_Dog);
6854  pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
6855end;
6856use Class_Dog;
6857@end example
6858
6859@node Switches,,Generating Bindings for C++ Headers,Generating Ada Bindings for C and C++ headers
6860@anchor{gnat_ugn/the_gnat_compilation_model switches}@anchor{c8}@anchor{gnat_ugn/the_gnat_compilation_model switches-for-ada-binding-generation}@anchor{c9}
6861@subsubsection Switches
6862
6863
6864@geindex -fdump-ada-spec (gcc)
6865
6866
6867@table @asis
6868
6869@item @code{-fdump-ada-spec}
6870
6871Generate Ada spec files for the given header files transitively (including
6872all header files that these headers depend upon).
6873@end table
6874
6875@geindex -fdump-ada-spec-slim (gcc)
6876
6877
6878@table @asis
6879
6880@item @code{-fdump-ada-spec-slim}
6881
6882Generate Ada spec files for the header files specified on the command line
6883only.
6884@end table
6885
6886@geindex -fada-spec-parent (gcc)
6887
6888
6889@table @asis
6890
6891@item @code{-fada-spec-parent=@emph{unit}}
6892
6893Specifies that all files generated by @code{-fdump-ada-spec} are
6894to be child units of the specified parent unit.
6895@end table
6896
6897@geindex -C (gcc)
6898
6899
6900@table @asis
6901
6902@item @code{-C}
6903
6904Extract comments from headers and generate Ada comments in the Ada spec files.
6905@end table
6906
6907@node Generating C Headers for Ada Specifications,,Generating Ada Bindings for C and C++ headers,Mixed Language Programming
6908@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}
6909@subsection Generating C Headers for Ada Specifications
6910
6911
6912@geindex Binding generation (for Ada specs)
6913
6914@geindex C headers (binding generation)
6915
6916GNAT includes a C header generator for Ada specifications which supports
6917Ada types that have a direct mapping to C types. This includes in particular
6918support for:
6919
6920
6921@itemize *
6922
6923@item
6924Scalar types
6925
6926@item
6927Constrained arrays
6928
6929@item
6930Records (untagged)
6931
6932@item
6933Composition of the above types
6934
6935@item
6936Constant declarations
6937
6938@item
6939Object declarations
6940
6941@item
6942Subprogram declarations
6943@end itemize
6944
6945@menu
6946* Running the C Header Generator::
6947
6948@end menu
6949
6950@node Running the C Header Generator,,,Generating C Headers for Ada Specifications
6951@anchor{gnat_ugn/the_gnat_compilation_model running-the-c-header-generator}@anchor{cc}
6952@subsubsection Running the C Header Generator
6953
6954
6955The C header generator is part of the GNAT compiler and can be invoked via
6956the @code{-gnatceg} combination of switches, which will generate a @code{.h}
6957file corresponding to the given input file (Ada spec or body). Note that
6958only spec files are processed in any case, so giving a spec or a body file
6959as input is equivalent. For example:
6960
6961@example
6962$ gcc -c -gnatceg pack1.ads
6963@end example
6964
6965will generate a self-contained file called @code{pack1.h} including
6966common definitions from the Ada Standard package, followed by the
6967definitions included in @code{pack1.ads}, as well as all the other units
6968withed by this file.
6969
6970For instance, given the following Ada files:
6971
6972@example
6973package Pack2 is
6974   type Int is range 1 .. 10;
6975end Pack2;
6976@end example
6977
6978@example
6979with Pack2;
6980
6981package Pack1 is
6982   type Rec is record
6983      Field1, Field2 : Pack2.Int;
6984   end record;
6985
6986   Global : Rec := (1, 2);
6987
6988   procedure Proc1 (R : Rec);
6989   procedure Proc2 (R : in out Rec);
6990end Pack1;
6991@end example
6992
6993The above @code{gcc} command will generate the following @code{pack1.h} file:
6994
6995@example
6996/* Standard definitions skipped */
6997#ifndef PACK2_ADS
6998#define PACK2_ADS
6999typedef short_short_integer pack2__TintB;
7000typedef pack2__TintB pack2__int;
7001#endif /* PACK2_ADS */
7002
7003#ifndef PACK1_ADS
7004#define PACK1_ADS
7005typedef struct _pack1__rec @{
7006  pack2__int field1;
7007  pack2__int field2;
7008@} pack1__rec;
7009extern pack1__rec pack1__global;
7010extern void pack1__proc1(const pack1__rec r);
7011extern void pack1__proc2(pack1__rec *r);
7012#endif /* PACK1_ADS */
7013@end example
7014
7015You can then @code{include} @code{pack1.h} from a C source file and use the types,
7016call subprograms, reference objects, and constants.
7017
7018@node GNAT and Other Compilation Models,Using GNAT Files with External Tools,Mixed Language Programming,The GNAT Compilation Model
7019@anchor{gnat_ugn/the_gnat_compilation_model id74}@anchor{cd}@anchor{gnat_ugn/the_gnat_compilation_model gnat-and-other-compilation-models}@anchor{45}
7020@section GNAT and Other Compilation Models
7021
7022
7023This section compares the GNAT model with the approaches taken in
7024other environents, first the C/C++ model and then the mechanism that
7025has been used in other Ada systems, in particular those traditionally
7026used for Ada 83.
7027
7028@menu
7029* Comparison between GNAT and C/C++ Compilation Models::
7030* Comparison between GNAT and Conventional Ada Library Models::
7031
7032@end menu
7033
7034@node Comparison between GNAT and C/C++ Compilation Models,Comparison between GNAT and Conventional Ada Library Models,,GNAT and Other Compilation Models
7035@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}
7036@subsection Comparison between GNAT and C/C++ Compilation Models
7037
7038
7039The GNAT model of compilation is close to the C and C++ models. You can
7040think of Ada specs as corresponding to header files in C. As in C, you
7041don't need to compile specs; they are compiled when they are used. The
7042Ada @emph{with} is similar in effect to the @code{#include} of a C
7043header.
7044
7045One notable difference is that, in Ada, you may compile specs separately
7046to check them for semantic and syntactic accuracy. This is not always
7047possible with C headers because they are fragments of programs that have
7048less specific syntactic or semantic rules.
7049
7050The other major difference is the requirement for running the binder,
7051which performs two important functions. First, it checks for
7052consistency. In C or C++, the only defense against assembling
7053inconsistent programs lies outside the compiler, in a makefile, for
7054example. The binder satisfies the Ada requirement that it be impossible
7055to construct an inconsistent program when the compiler is used in normal
7056mode.
7057
7058@geindex Elaboration order control
7059
7060The other important function of the binder is to deal with elaboration
7061issues. There are also elaboration issues in C++ that are handled
7062automatically. This automatic handling has the advantage of being
7063simpler to use, but the C++ programmer has no control over elaboration.
7064Where @code{gnatbind} might complain there was no valid order of
7065elaboration, a C++ compiler would simply construct a program that
7066malfunctioned at run time.
7067
7068@node Comparison between GNAT and Conventional Ada Library Models,,Comparison between GNAT and C/C++ Compilation Models,GNAT and Other Compilation Models
7069@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}
7070@subsection Comparison between GNAT and Conventional Ada Library Models
7071
7072
7073This section is intended for Ada programmers who have
7074used an Ada compiler implementing the traditional Ada library
7075model, as described in the Ada Reference Manual.
7076
7077@geindex GNAT library
7078
7079In GNAT, there is no 'library' in the normal sense. Instead, the set of
7080source files themselves acts as the library. Compiling Ada programs does
7081not generate any centralized information, but rather an object file and
7082a ALI file, which are of interest only to the binder and linker.
7083In a traditional system, the compiler reads information not only from
7084the source file being compiled, but also from the centralized library.
7085This means that the effect of a compilation depends on what has been
7086previously compiled. In particular:
7087
7088
7089@itemize *
7090
7091@item
7092When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7093to the version of the unit most recently compiled into the library.
7094
7095@item
7096Inlining is effective only if the necessary body has already been
7097compiled into the library.
7098
7099@item
7100Compiling a unit may obsolete other units in the library.
7101@end itemize
7102
7103In GNAT, compiling one unit never affects the compilation of any other
7104units because the compiler reads only source files. Only changes to source
7105files can affect the results of a compilation. In particular:
7106
7107
7108@itemize *
7109
7110@item
7111When a unit is @emph{with}ed, the unit seen by the compiler corresponds
7112to the source version of the unit that is currently accessible to the
7113compiler.
7114
7115@geindex Inlining
7116
7117@item
7118Inlining requires the appropriate source files for the package or
7119subprogram bodies to be available to the compiler. Inlining is always
7120effective, independent of the order in which units are compiled.
7121
7122@item
7123Compiling a unit never affects any other compilations. The editing of
7124sources may cause previous compilations to be out of date if they
7125depended on the source file being modified.
7126@end itemize
7127
7128The most important result of these differences is that order of compilation
7129is never significant in GNAT. There is no situation in which one is
7130required to do one compilation before another. What shows up as order of
7131compilation requirements in the traditional Ada library becomes, in
7132GNAT, simple source dependencies; in other words, there is only a set
7133of rules saying what source files must be present when a file is
7134compiled.
7135
7136@node Using GNAT Files with External Tools,,GNAT and Other Compilation Models,The GNAT Compilation Model
7137@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}
7138@section Using GNAT Files with External Tools
7139
7140
7141This section explains how files that are produced by GNAT may be
7142used with tools designed for other languages.
7143
7144@menu
7145* Using Other Utility Programs with GNAT::
7146* The External Symbol Naming Scheme of GNAT::
7147
7148@end menu
7149
7150@node Using Other Utility Programs with GNAT,The External Symbol Naming Scheme of GNAT,,Using GNAT Files with External Tools
7151@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}
7152@subsection Using Other Utility Programs with GNAT
7153
7154
7155The object files generated by GNAT are in standard system format and in
7156particular the debugging information uses this format. This means
7157programs generated by GNAT can be used with existing utilities that
7158depend on these formats.
7159
7160In general, any utility program that works with C will also often work with
7161Ada programs generated by GNAT. This includes software utilities such as
7162gprof (a profiling program), gdb (the FSF debugger), and utilities such
7163as Purify.
7164
7165@node The External Symbol Naming Scheme of GNAT,,Using Other Utility Programs with GNAT,Using GNAT Files with External Tools
7166@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}
7167@subsection The External Symbol Naming Scheme of GNAT
7168
7169
7170In order to interpret the output from GNAT, when using tools that are
7171originally intended for use with other languages, it is useful to
7172understand the conventions used to generate link names from the Ada
7173entity names.
7174
7175All link names are in all lowercase letters. With the exception of library
7176procedure names, the mechanism used is simply to use the full expanded
7177Ada name with dots replaced by double underscores. For example, suppose
7178we have the following package spec:
7179
7180@example
7181package QRS is
7182   MN : Integer;
7183end QRS;
7184@end example
7185
7186@geindex pragma Export
7187
7188The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
7189the corresponding link name is @code{qrs__mn}.
7190Of course if a @code{pragma Export} is used this may be overridden:
7191
7192@example
7193package Exports is
7194   Var1 : Integer;
7195   pragma Export (Var1, C, External_Name => "var1_name");
7196   Var2 : Integer;
7197   pragma Export (Var2, C, Link_Name => "var2_link_name");
7198end Exports;
7199@end example
7200
7201In this case, the link name for @code{Var1} is whatever link name the
7202C compiler would assign for the C function @code{var1_name}. This typically
7203would be either @code{var1_name} or @code{_var1_name}, depending on operating
7204system conventions, but other possibilities exist. The link name for
7205@code{Var2} is @code{var2_link_name}, and this is not operating system
7206dependent.
7207
7208One exception occurs for library level procedures. A potential ambiguity
7209arises between the required name @code{_main} for the C main program,
7210and the name we would otherwise assign to an Ada library level procedure
7211called @code{Main} (which might well not be the main program).
7212
7213To avoid this ambiguity, we attach the prefix @code{_ada_} to such
7214names. So if we have a library level procedure such as:
7215
7216@example
7217procedure Hello (S : String);
7218@end example
7219
7220the external name of this procedure will be @code{_ada_hello}.
7221
7222@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
7223
7224@node Building Executable Programs with GNAT,GNAT Utility Programs,The GNAT Compilation Model,Top
7225@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}
7226@chapter Building Executable Programs with GNAT
7227
7228
7229This chapter describes first the gnatmake tool
7230(@ref{1b,,Building with gnatmake}),
7231which automatically determines the set of sources
7232needed by an Ada compilation unit and executes the necessary
7233(re)compilations, binding and linking.
7234It also explains how to use each tool individually: the
7235compiler (gcc, see @ref{1c,,Compiling with gcc}),
7236binder (gnatbind, see @ref{1d,,Binding with gnatbind}),
7237and linker (gnatlink, see @ref{1e,,Linking with gnatlink})
7238to build executable programs.
7239Finally, this chapter provides examples of
7240how to make use of the general GNU make mechanism
7241in a GNAT context (see @ref{1f,,Using the GNU make Utility}).
7242
7243
7244@menu
7245* Building with gnatmake::
7246* Compiling with gcc::
7247* Compiler Switches::
7248* Linker Switches::
7249* Binding with gnatbind::
7250* Linking with gnatlink::
7251* Using the GNU make Utility::
7252
7253@end menu
7254
7255@node Building with gnatmake,Compiling with gcc,,Building Executable Programs with GNAT
7256@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}
7257@section Building with @code{gnatmake}
7258
7259
7260@geindex gnatmake
7261
7262A typical development cycle when working on an Ada program consists of
7263the following steps:
7264
7265
7266@enumerate
7267
7268@item
7269Edit some sources to fix bugs;
7270
7271@item
7272Add enhancements;
7273
7274@item
7275Compile all sources affected;
7276
7277@item
7278Rebind and relink; and
7279
7280@item
7281Test.
7282@end enumerate
7283
7284@geindex Dependency rules (compilation)
7285
7286The third step in particular can be tricky, because not only do the modified
7287files have to be compiled, but any files depending on these files must also be
7288recompiled. The dependency rules in Ada can be quite complex, especially
7289in the presence of overloading, @code{use} clauses, generics and inlined
7290subprograms.
7291
7292@code{gnatmake} automatically takes care of the third and fourth steps
7293of this process. It determines which sources need to be compiled,
7294compiles them, and binds and links the resulting object files.
7295
7296Unlike some other Ada make programs, the dependencies are always
7297accurately recomputed from the new sources. The source based approach of
7298the GNAT compilation model makes this possible. This means that if
7299changes to the source program cause corresponding changes in
7300dependencies, they will always be tracked exactly correctly by
7301@code{gnatmake}.
7302
7303Note that for advanced forms of project structure, we recommend creating
7304a project file as explained in the @emph{GNAT_Project_Manager} chapter in the
7305@emph{GPRbuild User's Guide}, and using the
7306@code{gprbuild} tool which supports building with project files and works similarly
7307to @code{gnatmake}.
7308
7309@menu
7310* Running gnatmake::
7311* Switches for gnatmake::
7312* Mode Switches for gnatmake::
7313* Notes on the Command Line::
7314* How gnatmake Works::
7315* Examples of gnatmake Usage::
7316
7317@end menu
7318
7319@node Running gnatmake,Switches for gnatmake,,Building with gnatmake
7320@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatmake}@anchor{da}@anchor{gnat_ugn/building_executable_programs_with_gnat id2}@anchor{db}
7321@subsection Running @code{gnatmake}
7322
7323
7324The usual form of the @code{gnatmake} command is
7325
7326@example
7327$ gnatmake [<switches>] <file_name> [<file_names>] [<mode_switches>]
7328@end example
7329
7330The only required argument is one @code{file_name}, which specifies
7331a compilation unit that is a main program. Several @code{file_names} can be
7332specified: this will result in several executables being built.
7333If @code{switches} are present, they can be placed before the first
7334@code{file_name}, between @code{file_names} or after the last @code{file_name}.
7335If @code{mode_switches} are present, they must always be placed after
7336the last @code{file_name} and all @code{switches}.
7337
7338If you are using standard file extensions (@code{.adb} and
7339@code{.ads}), then the
7340extension may be omitted from the @code{file_name} arguments. However, if
7341you are using non-standard extensions, then it is required that the
7342extension be given. A relative or absolute directory path can be
7343specified in a @code{file_name}, in which case, the input source file will
7344be searched for in the specified directory only. Otherwise, the input
7345source file will first be searched in the directory where
7346@code{gnatmake} was invoked and if it is not found, it will be search on
7347the source path of the compiler as described in
7348@ref{89,,Search Paths and the Run-Time Library (RTL)}.
7349
7350All @code{gnatmake} output (except when you specify @code{-M}) is sent to
7351@code{stderr}. The output produced by the
7352@code{-M} switch is sent to @code{stdout}.
7353
7354@node Switches for gnatmake,Mode Switches for gnatmake,Running gnatmake,Building with gnatmake
7355@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatmake}@anchor{dc}@anchor{gnat_ugn/building_executable_programs_with_gnat id3}@anchor{dd}
7356@subsection Switches for @code{gnatmake}
7357
7358
7359You may specify any of the following switches to @code{gnatmake}:
7360
7361@geindex --version (gnatmake)
7362
7363
7364@table @asis
7365
7366@item @code{--version}
7367
7368Display Copyright and version, then exit disregarding all other options.
7369@end table
7370
7371@geindex --help (gnatmake)
7372
7373
7374@table @asis
7375
7376@item @code{--help}
7377
7378If @code{--version} was not used, display usage, then exit disregarding
7379all other options.
7380@end table
7381
7382@geindex --GCC=compiler_name (gnatmake)
7383
7384
7385@table @asis
7386
7387@item @code{--GCC=@emph{compiler_name}}
7388
7389Program used for compiling. The default is @code{gcc}. You need to use
7390quotes around @code{compiler_name} if @code{compiler_name} contains
7391spaces or other separator characters.
7392As an example @code{--GCC="foo -x  -y"}
7393will instruct @code{gnatmake} to use @code{foo -x -y} as your
7394compiler. A limitation of this syntax is that the name and path name of
7395the executable itself must not include any embedded spaces. Note that
7396switch @code{-c} is always inserted after your command name. Thus in the
7397above example the compiler command that will be used by @code{gnatmake}
7398will be @code{foo -c -x -y}. If several @code{--GCC=compiler_name} are
7399used, only the last @code{compiler_name} is taken into account. However,
7400all the additional switches are also taken into account. Thus,
7401@code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
7402@code{--GCC="bar -x -y -z -t"}.
7403@end table
7404
7405@geindex --GNATBIND=binder_name (gnatmake)
7406
7407
7408@table @asis
7409
7410@item @code{--GNATBIND=@emph{binder_name}}
7411
7412Program used for binding. The default is @code{gnatbind}. You need to
7413use quotes around @code{binder_name} if @code{binder_name} contains spaces
7414or other separator characters.
7415As an example @code{--GNATBIND="bar -x  -y"}
7416will instruct @code{gnatmake} to use @code{bar -x -y} as your
7417binder. Binder switches that are normally appended by @code{gnatmake}
7418to @code{gnatbind} are now appended to the end of @code{bar -x -y}.
7419A limitation of this syntax is that the name and path name of the executable
7420itself must not include any embedded spaces.
7421@end table
7422
7423@geindex --GNATLINK=linker_name (gnatmake)
7424
7425
7426@table @asis
7427
7428@item @code{--GNATLINK=@emph{linker_name}}
7429
7430Program used for linking. The default is @code{gnatlink}. You need to
7431use quotes around @code{linker_name} if @code{linker_name} contains spaces
7432or other separator characters.
7433As an example @code{--GNATLINK="lan -x  -y"}
7434will instruct @code{gnatmake} to use @code{lan -x -y} as your
7435linker. Linker switches that are normally appended by @code{gnatmake} to
7436@code{gnatlink} are now appended to the end of @code{lan -x -y}.
7437A limitation of this syntax is that the name and path name of the executable
7438itself must not include any embedded spaces.
7439
7440@item @code{--create-map-file}
7441
7442When linking an executable, create a map file. The name of the map file
7443has the same name as the executable with extension ".map".
7444
7445@item @code{--create-map-file=@emph{mapfile}}
7446
7447When linking an executable, create a map file with the specified name.
7448@end table
7449
7450@geindex --create-missing-dirs (gnatmake)
7451
7452
7453@table @asis
7454
7455@item @code{--create-missing-dirs}
7456
7457When using project files (@code{-P@emph{project}}), automatically create
7458missing object directories, library directories and exec
7459directories.
7460
7461@item @code{--single-compile-per-obj-dir}
7462
7463Disallow simultaneous compilations in the same object directory when
7464project files are used.
7465
7466@item @code{--subdirs=@emph{subdir}}
7467
7468Actual object directory of each project file is the subdirectory subdir of the
7469object directory specified or defaulted in the project file.
7470
7471@item @code{--unchecked-shared-lib-imports}
7472
7473By default, shared library projects are not allowed to import static library
7474projects. When this switch is used on the command line, this restriction is
7475relaxed.
7476
7477@item @code{--source-info=@emph{source info file}}
7478
7479Specify a source info file. This switch is active only when project files
7480are used. If the source info file is specified as a relative path, then it is
7481relative to the object directory of the main project. If the source info file
7482does not exist, then after the Project Manager has successfully parsed and
7483processed the project files and found the sources, it creates the source info
7484file. If the source info file already exists and can be read successfully,
7485then the Project Manager will get all the needed information about the sources
7486from the source info file and will not look for them. This reduces the time
7487to process the project files, especially when looking for sources that take a
7488long time. If the source info file exists but cannot be parsed successfully,
7489the Project Manager will attempt to recreate it. If the Project Manager fails
7490to create the source info file, a message is issued, but gnatmake does not
7491fail. @code{gnatmake} "trusts" the source info file. This means that
7492if the source files have changed (addition, deletion, moving to a different
7493source directory), then the source info file need to be deleted and recreated.
7494@end table
7495
7496@geindex -a (gnatmake)
7497
7498
7499@table @asis
7500
7501@item @code{-a}
7502
7503Consider all files in the make process, even the GNAT internal system
7504files (for example, the predefined Ada library files), as well as any
7505locked files. Locked files are files whose ALI file is write-protected.
7506By default,
7507@code{gnatmake} does not check these files,
7508because the assumption is that the GNAT internal files are properly up
7509to date, and also that any write protected ALI files have been properly
7510installed. Note that if there is an installation problem, such that one
7511of these files is not up to date, it will be properly caught by the
7512binder.
7513You may have to specify this switch if you are working on GNAT
7514itself. The switch @code{-a} is also useful
7515in conjunction with @code{-f}
7516if you need to recompile an entire application,
7517including run-time files, using special configuration pragmas,
7518such as a @code{Normalize_Scalars} pragma.
7519
7520By default
7521@code{gnatmake -a} compiles all GNAT
7522internal files with
7523@code{gcc -c -gnatpg} rather than @code{gcc -c}.
7524@end table
7525
7526@geindex -b (gnatmake)
7527
7528
7529@table @asis
7530
7531@item @code{-b}
7532
7533Bind only. Can be combined with @code{-c} to do
7534compilation and binding, but no link.
7535Can be combined with @code{-l}
7536to do binding and linking. When not combined with
7537@code{-c}
7538all the units in the closure of the main program must have been previously
7539compiled and must be up to date. The root unit specified by @code{file_name}
7540may be given without extension, with the source extension or, if no GNAT
7541Project File is specified, with the ALI file extension.
7542@end table
7543
7544@geindex -c (gnatmake)
7545
7546
7547@table @asis
7548
7549@item @code{-c}
7550
7551Compile only. Do not perform binding, except when @code{-b}
7552is also specified. Do not perform linking, except if both
7553@code{-b} and
7554@code{-l} are also specified.
7555If the root unit specified by @code{file_name} is not a main unit, this is the
7556default. Otherwise @code{gnatmake} will attempt binding and linking
7557unless all objects are up to date and the executable is more recent than
7558the objects.
7559@end table
7560
7561@geindex -C (gnatmake)
7562
7563
7564@table @asis
7565
7566@item @code{-C}
7567
7568Use a temporary mapping file. A mapping file is a way to communicate
7569to the compiler two mappings: from unit names to file names (without
7570any directory information) and from file names to path names (with
7571full directory information). A mapping file can make the compiler's
7572file searches faster, especially if there are many source directories,
7573or the sources are read over a slow network connection. If
7574@code{-P} is used, a mapping file is always used, so
7575@code{-C} is unnecessary; in this case the mapping file
7576is initially populated based on the project file. If
7577@code{-C} is used without
7578@code{-P},
7579the mapping file is initially empty. Each invocation of the compiler
7580will add any newly accessed sources to the mapping file.
7581@end table
7582
7583@geindex -C= (gnatmake)
7584
7585
7586@table @asis
7587
7588@item @code{-C=@emph{file}}
7589
7590Use a specific mapping file. The file, specified as a path name (absolute or
7591relative) by this switch, should already exist, otherwise the switch is
7592ineffective. The specified mapping file will be communicated to the compiler.
7593This switch is not compatible with a project file
7594(-P`file`) or with multiple compiling processes
7595(-jnnn, when nnn is greater than 1).
7596@end table
7597
7598@geindex -d (gnatmake)
7599
7600
7601@table @asis
7602
7603@item @code{-d}
7604
7605Display progress for each source, up to date or not, as a single line:
7606
7607@example
7608completed x out of y (zz%)
7609@end example
7610
7611If the file needs to be compiled this is displayed after the invocation of
7612the compiler. These lines are displayed even in quiet output mode.
7613@end table
7614
7615@geindex -D (gnatmake)
7616
7617
7618@table @asis
7619
7620@item @code{-D @emph{dir}}
7621
7622Put all object files and ALI file in directory @code{dir}.
7623If the @code{-D} switch is not used, all object files
7624and ALI files go in the current working directory.
7625
7626This switch cannot be used when using a project file.
7627@end table
7628
7629@geindex -eI (gnatmake)
7630
7631
7632@table @asis
7633
7634@item @code{-eI@emph{nnn}}
7635
7636Indicates that the main source is a multi-unit source and the rank of the unit
7637in the source file is nnn. nnn needs to be a positive number and a valid
7638index in the source. This switch cannot be used when @code{gnatmake} is
7639invoked for several mains.
7640@end table
7641
7642@geindex -eL (gnatmake)
7643
7644@geindex symbolic links
7645
7646
7647@table @asis
7648
7649@item @code{-eL}
7650
7651Follow all symbolic links when processing project files.
7652This should be used if your project uses symbolic links for files or
7653directories, but is not needed in other cases.
7654
7655@geindex naming scheme
7656
7657This also assumes that no directory matches the naming scheme for files (for
7658instance that you do not have a directory called "sources.ads" when using the
7659default GNAT naming scheme).
7660
7661When you do not have to use this switch (i.e., by default), gnatmake is able to
7662save a lot of system calls (several per source file and object file), which
7663can result in a significant speed up to load and manipulate a project file,
7664especially when using source files from a remote system.
7665@end table
7666
7667@geindex -eS (gnatmake)
7668
7669
7670@table @asis
7671
7672@item @code{-eS}
7673
7674Output the commands for the compiler, the binder and the linker
7675on standard output,
7676instead of standard error.
7677@end table
7678
7679@geindex -f (gnatmake)
7680
7681
7682@table @asis
7683
7684@item @code{-f}
7685
7686Force recompilations. Recompile all sources, even though some object
7687files may be up to date, but don't recompile predefined or GNAT internal
7688files or locked files (files with a write-protected ALI file),
7689unless the @code{-a} switch is also specified.
7690@end table
7691
7692@geindex -F (gnatmake)
7693
7694
7695@table @asis
7696
7697@item @code{-F}
7698
7699When using project files, if some errors or warnings are detected during
7700parsing and verbose mode is not in effect (no use of switch
7701-v), then error lines start with the full path name of the project
7702file, rather than its simple file name.
7703@end table
7704
7705@geindex -g (gnatmake)
7706
7707
7708@table @asis
7709
7710@item @code{-g}
7711
7712Enable debugging. This switch is simply passed to the compiler and to the
7713linker.
7714@end table
7715
7716@geindex -i (gnatmake)
7717
7718
7719@table @asis
7720
7721@item @code{-i}
7722
7723In normal mode, @code{gnatmake} compiles all object files and ALI files
7724into the current directory. If the @code{-i} switch is used,
7725then instead object files and ALI files that already exist are overwritten
7726in place. This means that once a large project is organized into separate
7727directories in the desired manner, then @code{gnatmake} will automatically
7728maintain and update this organization. If no ALI files are found on the
7729Ada object path (see @ref{89,,Search Paths and the Run-Time Library (RTL)}),
7730the new object and ALI files are created in the
7731directory containing the source being compiled. If another organization
7732is desired, where objects and sources are kept in different directories,
7733a useful technique is to create dummy ALI files in the desired directories.
7734When detecting such a dummy file, @code{gnatmake} will be forced to
7735recompile the corresponding source file, and it will be put the resulting
7736object and ALI files in the directory where it found the dummy file.
7737@end table
7738
7739@geindex -j (gnatmake)
7740
7741@geindex Parallel make
7742
7743
7744@table @asis
7745
7746@item @code{-j@emph{n}}
7747
7748Use @code{n} processes to carry out the (re)compilations. On a multiprocessor
7749machine compilations will occur in parallel. If @code{n} is 0, then the
7750maximum number of parallel compilations is the number of core processors
7751on the platform. In the event of compilation errors, messages from various
7752compilations might get interspersed (but @code{gnatmake} will give you the
7753full ordered list of failing compiles at the end). If this is problematic,
7754rerun the make process with n set to 1 to get a clean list of messages.
7755@end table
7756
7757@geindex -k (gnatmake)
7758
7759
7760@table @asis
7761
7762@item @code{-k}
7763
7764Keep going. Continue as much as possible after a compilation error. To
7765ease the programmer's task in case of compilation errors, the list of
7766sources for which the compile fails is given when @code{gnatmake}
7767terminates.
7768
7769If @code{gnatmake} is invoked with several @code{file_names} and with this
7770switch, if there are compilation errors when building an executable,
7771@code{gnatmake} will not attempt to build the following executables.
7772@end table
7773
7774@geindex -l (gnatmake)
7775
7776
7777@table @asis
7778
7779@item @code{-l}
7780
7781Link only. Can be combined with @code{-b} to binding
7782and linking. Linking will not be performed if combined with
7783@code{-c}
7784but not with @code{-b}.
7785When not combined with @code{-b}
7786all the units in the closure of the main program must have been previously
7787compiled and must be up to date, and the main program needs to have been bound.
7788The root unit specified by @code{file_name}
7789may be given without extension, with the source extension or, if no GNAT
7790Project File is specified, with the ALI file extension.
7791@end table
7792
7793@geindex -m (gnatmake)
7794
7795
7796@table @asis
7797
7798@item @code{-m}
7799
7800Specify that the minimum necessary amount of recompilations
7801be performed. In this mode @code{gnatmake} ignores time
7802stamp differences when the only
7803modifications to a source file consist in adding/removing comments,
7804empty lines, spaces or tabs. This means that if you have changed the
7805comments in a source file or have simply reformatted it, using this
7806switch will tell @code{gnatmake} not to recompile files that depend on it
7807(provided other sources on which these files depend have undergone no
7808semantic modifications). Note that the debugging information may be
7809out of date with respect to the sources if the @code{-m} switch causes
7810a compilation to be switched, so the use of this switch represents a
7811trade-off between compilation time and accurate debugging information.
7812@end table
7813
7814@geindex Dependencies
7815@geindex producing list
7816
7817@geindex -M (gnatmake)
7818
7819
7820@table @asis
7821
7822@item @code{-M}
7823
7824Check if all objects are up to date. If they are, output the object
7825dependences to @code{stdout} in a form that can be directly exploited in
7826a @code{Makefile}. By default, each source file is prefixed with its
7827(relative or absolute) directory name. This name is whatever you
7828specified in the various @code{-aI}
7829and @code{-I} switches. If you use
7830@code{gnatmake -M}  @code{-q}
7831(see below), only the source file names,
7832without relative paths, are output. If you just specify the  @code{-M}
7833switch, dependencies of the GNAT internal system files are omitted. This
7834is typically what you want. If you also specify
7835the @code{-a} switch,
7836dependencies of the GNAT internal files are also listed. Note that
7837dependencies of the objects in external Ada libraries (see
7838switch  @code{-aL@emph{dir}} in the following list)
7839are never reported.
7840@end table
7841
7842@geindex -n (gnatmake)
7843
7844
7845@table @asis
7846
7847@item @code{-n}
7848
7849Don't compile, bind, or link. Checks if all objects are up to date.
7850If they are not, the full name of the first file that needs to be
7851recompiled is printed.
7852Repeated use of this option, followed by compiling the indicated source
7853file, will eventually result in recompiling all required units.
7854@end table
7855
7856@geindex -o (gnatmake)
7857
7858
7859@table @asis
7860
7861@item @code{-o @emph{exec_name}}
7862
7863Output executable name. The name of the final executable program will be
7864@code{exec_name}. If the @code{-o} switch is omitted the default
7865name for the executable will be the name of the input file in appropriate form
7866for an executable file on the host system.
7867
7868This switch cannot be used when invoking @code{gnatmake} with several
7869@code{file_names}.
7870@end table
7871
7872@geindex -p (gnatmake)
7873
7874
7875@table @asis
7876
7877@item @code{-p}
7878
7879Same as @code{--create-missing-dirs}
7880@end table
7881
7882@geindex -P (gnatmake)
7883
7884
7885@table @asis
7886
7887@item @code{-P@emph{project}}
7888
7889Use project file @code{project}. Only one such switch can be used.
7890@end table
7891
7892@c -- Comment:
7893@c :ref:`gnatmake_and_Project_Files`.
7894
7895@geindex -q (gnatmake)
7896
7897
7898@table @asis
7899
7900@item @code{-q}
7901
7902Quiet. When this flag is not set, the commands carried out by
7903@code{gnatmake} are displayed.
7904@end table
7905
7906@geindex -s (gnatmake)
7907
7908
7909@table @asis
7910
7911@item @code{-s}
7912
7913Recompile if compiler switches have changed since last compilation.
7914All compiler switches but -I and -o are taken into account in the
7915following way:
7916orders between different 'first letter' switches are ignored, but
7917orders between same switches are taken into account. For example,
7918@code{-O -O2} is different than @code{-O2 -O}, but @code{-g -O}
7919is equivalent to @code{-O -g}.
7920
7921This switch is recommended when Integrated Preprocessing is used.
7922@end table
7923
7924@geindex -u (gnatmake)
7925
7926
7927@table @asis
7928
7929@item @code{-u}
7930
7931Unique. Recompile at most the main files. It implies -c. Combined with
7932-f, it is equivalent to calling the compiler directly. Note that using
7933-u with a project file and no main has a special meaning.
7934@end table
7935
7936@c --Comment
7937@c (See :ref:`Project_Files_and_Main_Subprograms`.)
7938
7939@geindex -U (gnatmake)
7940
7941
7942@table @asis
7943
7944@item @code{-U}
7945
7946When used without a project file or with one or several mains on the command
7947line, is equivalent to -u. When used with a project file and no main
7948on the command line, all sources of all project files are checked and compiled
7949if not up to date, and libraries are rebuilt, if necessary.
7950@end table
7951
7952@geindex -v (gnatmake)
7953
7954
7955@table @asis
7956
7957@item @code{-v}
7958
7959Verbose. Display the reason for all recompilations @code{gnatmake}
7960decides are necessary, with the highest verbosity level.
7961@end table
7962
7963@geindex -vl (gnatmake)
7964
7965
7966@table @asis
7967
7968@item @code{-vl}
7969
7970Verbosity level Low. Display fewer lines than in verbosity Medium.
7971@end table
7972
7973@geindex -vm (gnatmake)
7974
7975
7976@table @asis
7977
7978@item @code{-vm}
7979
7980Verbosity level Medium. Potentially display fewer lines than in verbosity High.
7981@end table
7982
7983@geindex -vm (gnatmake)
7984
7985
7986@table @asis
7987
7988@item @code{-vh}
7989
7990Verbosity level High. Equivalent to -v.
7991
7992@item @code{-vP@emph{x}}
7993
7994Indicate the verbosity of the parsing of GNAT project files.
7995See @ref{de,,Switches Related to Project Files}.
7996@end table
7997
7998@geindex -x (gnatmake)
7999
8000
8001@table @asis
8002
8003@item @code{-x}
8004
8005Indicate that sources that are not part of any Project File may be compiled.
8006Normally, when using Project Files, only sources that are part of a Project
8007File may be compile. When this switch is used, a source outside of all Project
8008Files may be compiled. The ALI file and the object file will be put in the
8009object directory of the main Project. The compilation switches used will only
8010be those specified on the command line. Even when
8011@code{-x} is used, mains specified on the
8012command line need to be sources of a project file.
8013
8014@item @code{-X@emph{name}=@emph{value}}
8015
8016Indicate that external variable @code{name} has the value @code{value}.
8017The Project Manager will use this value for occurrences of
8018@code{external(name)} when parsing the project file.
8019@ref{de,,Switches Related to Project Files}.
8020@end table
8021
8022@geindex -z (gnatmake)
8023
8024
8025@table @asis
8026
8027@item @code{-z}
8028
8029No main subprogram. Bind and link the program even if the unit name
8030given on the command line is a package name. The resulting executable
8031will execute the elaboration routines of the package and its closure,
8032then the finalization routines.
8033@end table
8034
8035@subsubheading GCC switches
8036
8037
8038Any uppercase or multi-character switch that is not a @code{gnatmake} switch
8039is passed to @code{gcc} (e.g., @code{-O}, @code{-gnato,} etc.)
8040
8041@subsubheading Source and library search path switches
8042
8043
8044@geindex -aI (gnatmake)
8045
8046
8047@table @asis
8048
8049@item @code{-aI@emph{dir}}
8050
8051When looking for source files also look in directory @code{dir}.
8052The order in which source files search is undertaken is
8053described in @ref{89,,Search Paths and the Run-Time Library (RTL)}.
8054@end table
8055
8056@geindex -aL (gnatmake)
8057
8058
8059@table @asis
8060
8061@item @code{-aL@emph{dir}}
8062
8063Consider @code{dir} as being an externally provided Ada library.
8064Instructs @code{gnatmake} to skip compilation units whose @code{.ALI}
8065files have been located in directory @code{dir}. This allows you to have
8066missing bodies for the units in @code{dir} and to ignore out of date bodies
8067for the same units. You still need to specify
8068the location of the specs for these units by using the switches
8069@code{-aI@emph{dir}}  or @code{-I@emph{dir}}.
8070Note: this switch is provided for compatibility with previous versions
8071of @code{gnatmake}. The easier method of causing standard libraries
8072to be excluded from consideration is to write-protect the corresponding
8073ALI files.
8074@end table
8075
8076@geindex -aO (gnatmake)
8077
8078
8079@table @asis
8080
8081@item @code{-aO@emph{dir}}
8082
8083When searching for library and object files, look in directory
8084@code{dir}. The order in which library files are searched is described in
8085@ref{8c,,Search Paths for gnatbind}.
8086@end table
8087
8088@geindex Search paths
8089@geindex for gnatmake
8090
8091@geindex -A (gnatmake)
8092
8093
8094@table @asis
8095
8096@item @code{-A@emph{dir}}
8097
8098Equivalent to @code{-aL@emph{dir}} @code{-aI@emph{dir}}.
8099
8100@geindex -I (gnatmake)
8101
8102@item @code{-I@emph{dir}}
8103
8104Equivalent to @code{-aO@emph{dir} -aI@emph{dir}}.
8105@end table
8106
8107@geindex -I- (gnatmake)
8108
8109@geindex Source files
8110@geindex suppressing search
8111
8112
8113@table @asis
8114
8115@item @code{-I-}
8116
8117Do not look for source files in the directory containing the source
8118file named in the command line.
8119Do not look for ALI or object files in the directory
8120where @code{gnatmake} was invoked.
8121@end table
8122
8123@geindex -L (gnatmake)
8124
8125@geindex Linker libraries
8126
8127
8128@table @asis
8129
8130@item @code{-L@emph{dir}}
8131
8132Add directory @code{dir} to the list of directories in which the linker
8133will search for libraries. This is equivalent to
8134@code{-largs} @code{-L@emph{dir}}.
8135Furthermore, under Windows, the sources pointed to by the libraries path
8136set in the registry are not searched for.
8137@end table
8138
8139@geindex -nostdinc (gnatmake)
8140
8141
8142@table @asis
8143
8144@item @code{-nostdinc}
8145
8146Do not look for source files in the system default directory.
8147@end table
8148
8149@geindex -nostdlib (gnatmake)
8150
8151
8152@table @asis
8153
8154@item @code{-nostdlib}
8155
8156Do not look for library files in the system default directory.
8157@end table
8158
8159@geindex --RTS (gnatmake)
8160
8161
8162@table @asis
8163
8164@item @code{--RTS=@emph{rts-path}}
8165
8166Specifies the default location of the runtime library. GNAT looks for the
8167runtime
8168in the following directories, and stops as soon as a valid runtime is found
8169(@code{adainclude} or @code{ada_source_path}, and @code{adalib} or
8170@code{ada_object_path} present):
8171
8172
8173@itemize *
8174
8175@item
8176@emph{<current directory>/$rts_path}
8177
8178@item
8179@emph{<default-search-dir>/$rts_path}
8180
8181@item
8182@emph{<default-search-dir>/rts-$rts_path}
8183
8184@item
8185The selected path is handled like a normal RTS path.
8186@end itemize
8187@end table
8188
8189@node Mode Switches for gnatmake,Notes on the Command Line,Switches for gnatmake,Building with gnatmake
8190@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}
8191@subsection Mode Switches for @code{gnatmake}
8192
8193
8194The mode switches (referred to as @code{mode_switches}) allow the
8195inclusion of switches that are to be passed to the compiler itself, the
8196binder or the linker. The effect of a mode switch is to cause all
8197subsequent switches up to the end of the switch list, or up to the next
8198mode switch, to be interpreted as switches to be passed on to the
8199designated component of GNAT.
8200
8201@geindex -cargs (gnatmake)
8202
8203
8204@table @asis
8205
8206@item @code{-cargs @emph{switches}}
8207
8208Compiler switches. Here @code{switches} is a list of switches
8209that are valid switches for @code{gcc}. They will be passed on to
8210all compile steps performed by @code{gnatmake}.
8211@end table
8212
8213@geindex -bargs (gnatmake)
8214
8215
8216@table @asis
8217
8218@item @code{-bargs @emph{switches}}
8219
8220Binder switches. Here @code{switches} is a list of switches
8221that are valid switches for @code{gnatbind}. They will be passed on to
8222all bind steps performed by @code{gnatmake}.
8223@end table
8224
8225@geindex -largs (gnatmake)
8226
8227
8228@table @asis
8229
8230@item @code{-largs @emph{switches}}
8231
8232Linker switches. Here @code{switches} is a list of switches
8233that are valid switches for @code{gnatlink}. They will be passed on to
8234all link steps performed by @code{gnatmake}.
8235@end table
8236
8237@geindex -margs (gnatmake)
8238
8239
8240@table @asis
8241
8242@item @code{-margs @emph{switches}}
8243
8244Make switches. The switches are directly interpreted by @code{gnatmake},
8245regardless of any previous occurrence of @code{-cargs}, @code{-bargs}
8246or @code{-largs}.
8247@end table
8248
8249@node Notes on the Command Line,How gnatmake Works,Mode Switches for gnatmake,Building with gnatmake
8250@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}
8251@subsection Notes on the Command Line
8252
8253
8254This section contains some additional useful notes on the operation
8255of the @code{gnatmake} command.
8256
8257@geindex Recompilation (by gnatmake)
8258
8259
8260@itemize *
8261
8262@item
8263If @code{gnatmake} finds no ALI files, it recompiles the main program
8264and all other units required by the main program.
8265This means that @code{gnatmake}
8266can be used for the initial compile, as well as during subsequent steps of
8267the development cycle.
8268
8269@item
8270If you enter @code{gnatmake foo.adb}, where @code{foo}
8271is a subunit or body of a generic unit, @code{gnatmake} recompiles
8272@code{foo.adb} (because it finds no ALI) and stops, issuing a
8273warning.
8274
8275@item
8276In @code{gnatmake} the switch @code{-I}
8277is used to specify both source and
8278library file paths. Use @code{-aI}
8279instead if you just want to specify
8280source paths only and @code{-aO}
8281if you want to specify library paths
8282only.
8283
8284@item
8285@code{gnatmake} will ignore any files whose ALI file is write-protected.
8286This may conveniently be used to exclude standard libraries from
8287consideration and in particular it means that the use of the
8288@code{-f} switch will not recompile these files
8289unless @code{-a} is also specified.
8290
8291@item
8292@code{gnatmake} has been designed to make the use of Ada libraries
8293particularly convenient. Assume you have an Ada library organized
8294as follows: @emph{obj-dir} contains the objects and ALI files for
8295of your Ada compilation units,
8296whereas @emph{include-dir} contains the
8297specs of these units, but no bodies. Then to compile a unit
8298stored in @code{main.adb}, which uses this Ada library you would just type:
8299
8300@example
8301$ gnatmake -aI`include-dir`  -aL`obj-dir`  main
8302@end example
8303
8304@item
8305Using @code{gnatmake} along with the @code{-m (minimal recompilation)}
8306switch provides a mechanism for avoiding unnecessary recompilations. Using
8307this switch,
8308you can update the comments/format of your
8309source files without having to recompile everything. Note, however, that
8310adding or deleting lines in a source files may render its debugging
8311info obsolete. If the file in question is a spec, the impact is rather
8312limited, as that debugging info will only be useful during the
8313elaboration phase of your program. For bodies the impact can be more
8314significant. In all events, your debugger will warn you if a source file
8315is more recent than the corresponding object, and alert you to the fact
8316that the debugging information may be out of date.
8317@end itemize
8318
8319@node How gnatmake Works,Examples of gnatmake Usage,Notes on the Command Line,Building with gnatmake
8320@anchor{gnat_ugn/building_executable_programs_with_gnat id6}@anchor{e3}@anchor{gnat_ugn/building_executable_programs_with_gnat how-gnatmake-works}@anchor{e4}
8321@subsection How @code{gnatmake} Works
8322
8323
8324Generally @code{gnatmake} automatically performs all necessary
8325recompilations and you don't need to worry about how it works. However,
8326it may be useful to have some basic understanding of the @code{gnatmake}
8327approach and in particular to understand how it uses the results of
8328previous compilations without incorrectly depending on them.
8329
8330First a definition: an object file is considered @emph{up to date} if the
8331corresponding ALI file exists and if all the source files listed in the
8332dependency section of this ALI file have time stamps matching those in
8333the ALI file. This means that neither the source file itself nor any
8334files that it depends on have been modified, and hence there is no need
8335to recompile this file.
8336
8337@code{gnatmake} works by first checking if the specified main unit is up
8338to date. If so, no compilations are required for the main unit. If not,
8339@code{gnatmake} compiles the main program to build a new ALI file that
8340reflects the latest sources. Then the ALI file of the main unit is
8341examined to find all the source files on which the main program depends,
8342and @code{gnatmake} recursively applies the above procedure on all these
8343files.
8344
8345This process ensures that @code{gnatmake} only trusts the dependencies
8346in an existing ALI file if they are known to be correct. Otherwise it
8347always recompiles to determine a new, guaranteed accurate set of
8348dependencies. As a result the program is compiled 'upside down' from what may
8349be more familiar as the required order of compilation in some other Ada
8350systems. In particular, clients are compiled before the units on which
8351they depend. The ability of GNAT to compile in any order is critical in
8352allowing an order of compilation to be chosen that guarantees that
8353@code{gnatmake} will recompute a correct set of new dependencies if
8354necessary.
8355
8356When invoking @code{gnatmake} with several @code{file_names}, if a unit is
8357imported by several of the executables, it will be recompiled at most once.
8358
8359Note: when using non-standard naming conventions
8360(@ref{35,,Using Other File Names}), changing through a configuration pragmas
8361file the version of a source and invoking @code{gnatmake} to recompile may
8362have no effect, if the previous version of the source is still accessible
8363by @code{gnatmake}. It may be necessary to use the switch
8364-f.
8365
8366@node Examples of gnatmake Usage,,How gnatmake Works,Building with gnatmake
8367@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}
8368@subsection Examples of @code{gnatmake} Usage
8369
8370
8371
8372@table @asis
8373
8374@item @emph{gnatmake hello.adb}
8375
8376Compile all files necessary to bind and link the main program
8377@code{hello.adb} (containing unit @code{Hello}) and bind and link the
8378resulting object files to generate an executable file @code{hello}.
8379
8380@item @emph{gnatmake main1 main2 main3}
8381
8382Compile all files necessary to bind and link the main programs
8383@code{main1.adb} (containing unit @code{Main1}), @code{main2.adb}
8384(containing unit @code{Main2}) and @code{main3.adb}
8385(containing unit @code{Main3}) and bind and link the resulting object files
8386to generate three executable files @code{main1},
8387@code{main2}  and @code{main3}.
8388
8389@item @emph{gnatmake -q Main_Unit -cargs -O2 -bargs -l}
8390
8391Compile all files necessary to bind and link the main program unit
8392@code{Main_Unit} (from file @code{main_unit.adb}). All compilations will
8393be done with optimization level 2 and the order of elaboration will be
8394listed by the binder. @code{gnatmake} will operate in quiet mode, not
8395displaying commands it is executing.
8396@end table
8397
8398@node Compiling with gcc,Compiler Switches,Building with gnatmake,Building Executable Programs with GNAT
8399@anchor{gnat_ugn/building_executable_programs_with_gnat compiling-with-gcc}@anchor{1c}@anchor{gnat_ugn/building_executable_programs_with_gnat id8}@anchor{e7}
8400@section Compiling with @code{gcc}
8401
8402
8403This section discusses how to compile Ada programs using the @code{gcc}
8404command. It also describes the set of switches
8405that can be used to control the behavior of the compiler.
8406
8407@menu
8408* Compiling Programs::
8409* Search Paths and the Run-Time Library (RTL): Search Paths and the Run-Time Library RTL.
8410* Order of Compilation Issues::
8411* Examples::
8412
8413@end menu
8414
8415@node Compiling Programs,Search Paths and the Run-Time Library RTL,,Compiling with gcc
8416@anchor{gnat_ugn/building_executable_programs_with_gnat compiling-programs}@anchor{e8}@anchor{gnat_ugn/building_executable_programs_with_gnat id9}@anchor{e9}
8417@subsection Compiling Programs
8418
8419
8420The first step in creating an executable program is to compile the units
8421of the program using the @code{gcc} command. You must compile the
8422following files:
8423
8424
8425@itemize *
8426
8427@item
8428the body file (@code{.adb}) for a library level subprogram or generic
8429subprogram
8430
8431@item
8432the spec file (@code{.ads}) for a library level package or generic
8433package that has no body
8434
8435@item
8436the body file (@code{.adb}) for a library level package
8437or generic package that has a body
8438@end itemize
8439
8440You need @emph{not} compile the following files
8441
8442
8443@itemize *
8444
8445@item
8446the spec of a library unit which has a body
8447
8448@item
8449subunits
8450@end itemize
8451
8452because they are compiled as part of compiling related units. GNAT
8453package specs
8454when the corresponding body is compiled, and subunits when the parent is
8455compiled.
8456
8457@geindex cannot generate code
8458
8459If you attempt to compile any of these files, you will get one of the
8460following error messages (where @code{fff} is the name of the file you
8461compiled):
8462
8463@quotation
8464
8465@example
8466cannot generate code for file `@w{`}fff`@w{`} (package spec)
8467to check package spec, use -gnatc
8468
8469cannot generate code for file `@w{`}fff`@w{`} (missing subunits)
8470to check parent unit, use -gnatc
8471
8472cannot generate code for file `@w{`}fff`@w{`} (subprogram spec)
8473to check subprogram spec, use -gnatc
8474
8475cannot generate code for file `@w{`}fff`@w{`} (subunit)
8476to check subunit, use -gnatc
8477@end example
8478@end quotation
8479
8480As indicated by the above error messages, if you want to submit
8481one of these files to the compiler to check for correct semantics
8482without generating code, then use the @code{-gnatc} switch.
8483
8484The basic command for compiling a file containing an Ada unit is:
8485
8486@example
8487$ gcc -c [switches] <file name>
8488@end example
8489
8490where @code{file name} is the name of the Ada file (usually
8491having an extension @code{.ads} for a spec or @code{.adb} for a body).
8492You specify the
8493@code{-c} switch to tell @code{gcc} to compile, but not link, the file.
8494The result of a successful compilation is an object file, which has the
8495same name as the source file but an extension of @code{.o} and an Ada
8496Library Information (ALI) file, which also has the same name as the
8497source file, but with @code{.ali} as the extension. GNAT creates these
8498two output files in the current directory, but you may specify a source
8499file in any directory using an absolute or relative path specification
8500containing the directory information.
8501
8502TESTING: the @code{--foobar@emph{NN}} switch
8503
8504@geindex gnat1
8505
8506@code{gcc} is actually a driver program that looks at the extensions of
8507the file arguments and loads the appropriate compiler. For example, the
8508GNU C compiler is @code{cc1}, and the Ada compiler is @code{gnat1}.
8509These programs are in directories known to the driver program (in some
8510configurations via environment variables you set), but need not be in
8511your path. The @code{gcc} driver also calls the assembler and any other
8512utilities needed to complete the generation of the required object
8513files.
8514
8515It is possible to supply several file names on the same @code{gcc}
8516command. This causes @code{gcc} to call the appropriate compiler for
8517each file. For example, the following command lists two separate
8518files to be compiled:
8519
8520@example
8521$ gcc -c x.adb y.adb
8522@end example
8523
8524calls @code{gnat1} (the Ada compiler) twice to compile @code{x.adb} and
8525@code{y.adb}.
8526The compiler generates two object files @code{x.o} and @code{y.o}
8527and the two ALI files @code{x.ali} and @code{y.ali}.
8528
8529Any switches apply to all the files listed, see @ref{ea,,Compiler Switches} for a
8530list of available @code{gcc} switches.
8531
8532@node Search Paths and the Run-Time Library RTL,Order of Compilation Issues,Compiling Programs,Compiling with gcc
8533@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}
8534@subsection Search Paths and the Run-Time Library (RTL)
8535
8536
8537With the GNAT source-based library system, the compiler must be able to
8538find source files for units that are needed by the unit being compiled.
8539Search paths are used to guide this process.
8540
8541The compiler compiles one source file whose name must be given
8542explicitly on the command line. In other words, no searching is done
8543for this file. To find all other source files that are needed (the most
8544common being the specs of units), the compiler examines the following
8545directories, in the following order:
8546
8547
8548@itemize *
8549
8550@item
8551The directory containing the source file of the main unit being compiled
8552(the file name on the command line).
8553
8554@item
8555Each directory named by an @code{-I} switch given on the @code{gcc}
8556command line, in the order given.
8557
8558@geindex ADA_PRJ_INCLUDE_FILE
8559
8560@item
8561Each of the directories listed in the text file whose name is given
8562by the
8563@geindex ADA_PRJ_INCLUDE_FILE
8564@geindex environment variable; ADA_PRJ_INCLUDE_FILE
8565@code{ADA_PRJ_INCLUDE_FILE} environment variable.
8566@geindex ADA_PRJ_INCLUDE_FILE
8567@geindex environment variable; ADA_PRJ_INCLUDE_FILE
8568@code{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the gnat
8569driver when project files are used. It should not normally be set
8570by other means.
8571
8572@geindex ADA_INCLUDE_PATH
8573
8574@item
8575Each of the directories listed in the value of the
8576@geindex ADA_INCLUDE_PATH
8577@geindex environment variable; ADA_INCLUDE_PATH
8578@code{ADA_INCLUDE_PATH} environment variable.
8579Construct this value
8580exactly as the
8581@geindex PATH
8582@geindex environment variable; PATH
8583@code{PATH} environment variable: a list of directory
8584names separated by colons (semicolons when working with the NT version).
8585
8586@item
8587The content of the @code{ada_source_path} file which is part of the GNAT
8588installation tree and is used to store standard libraries such as the
8589GNAT Run Time Library (RTL) source files.
8590@ref{87,,Installing a library}
8591@end itemize
8592
8593Specifying the switch @code{-I-}
8594inhibits the use of the directory
8595containing the source file named in the command line. You can still
8596have this directory on your search path, but in this case it must be
8597explicitly requested with a @code{-I} switch.
8598
8599Specifying the switch @code{-nostdinc}
8600inhibits the search of the default location for the GNAT Run Time
8601Library (RTL) source files.
8602
8603The compiler outputs its object files and ALI files in the current
8604working directory.
8605Caution: The object file can be redirected with the @code{-o} switch;
8606however, @code{gcc} and @code{gnat1} have not been coordinated on this
8607so the @code{ALI} file will not go to the right place. Therefore, you should
8608avoid using the @code{-o} switch.
8609
8610@geindex System.IO
8611
8612The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8613children make up the GNAT RTL, together with the simple @code{System.IO}
8614package used in the @code{"Hello World"} example. The sources for these units
8615are needed by the compiler and are kept together in one directory. Not
8616all of the bodies are needed, but all of the sources are kept together
8617anyway. In a normal installation, you need not specify these directory
8618names when compiling or binding. Either the environment variables or
8619the built-in defaults cause these files to be found.
8620
8621In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8622@code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8623consisting of child units of @code{GNAT}. This is a collection of generally
8624useful types, subprograms, etc. See the @cite{GNAT_Reference_Manual}
8625for further details.
8626
8627Besides simplifying access to the RTL, a major use of search paths is
8628in compiling sources from multiple directories. This can make
8629development environments much more flexible.
8630
8631@node Order of Compilation Issues,Examples,Search Paths and the Run-Time Library RTL,Compiling with gcc
8632@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}
8633@subsection Order of Compilation Issues
8634
8635
8636If, in our earlier example, there was a spec for the @code{hello}
8637procedure, it would be contained in the file @code{hello.ads}; yet this
8638file would not have to be explicitly compiled. This is the result of the
8639model we chose to implement library management. Some of the consequences
8640of this model are as follows:
8641
8642
8643@itemize *
8644
8645@item
8646There is no point in compiling specs (except for package
8647specs with no bodies) because these are compiled as needed by clients. If
8648you attempt a useless compilation, you will receive an error message.
8649It is also useless to compile subunits because they are compiled as needed
8650by the parent.
8651
8652@item
8653There are no order of compilation requirements: performing a
8654compilation never obsoletes anything. The only way you can obsolete
8655something and require recompilations is to modify one of the
8656source files on which it depends.
8657
8658@item
8659There is no library as such, apart from the ALI files
8660(@ref{42,,The Ada Library Information Files}, for information on the format
8661of these files). For now we find it convenient to create separate ALI files,
8662but eventually the information therein may be incorporated into the object
8663file directly.
8664
8665@item
8666When you compile a unit, the source files for the specs of all units
8667that it @emph{with}s, all its subunits, and the bodies of any generics it
8668instantiates must be available (reachable by the search-paths mechanism
8669described above), or you will receive a fatal error message.
8670@end itemize
8671
8672@node Examples,,Order of Compilation Issues,Compiling with gcc
8673@anchor{gnat_ugn/building_executable_programs_with_gnat id12}@anchor{ee}@anchor{gnat_ugn/building_executable_programs_with_gnat examples}@anchor{ef}
8674@subsection Examples
8675
8676
8677The following are some typical Ada compilation command line examples:
8678
8679@example
8680$ gcc -c xyz.adb
8681@end example
8682
8683Compile body in file @code{xyz.adb} with all default options.
8684
8685@example
8686$ gcc -c -O2 -gnata xyz-def.adb
8687@end example
8688
8689Compile the child unit package in file @code{xyz-def.adb} with extensive
8690optimizations, and pragma @code{Assert}/@cite{Debug} statements
8691enabled.
8692
8693@example
8694$ gcc -c -gnatc abc-def.adb
8695@end example
8696
8697Compile the subunit in file @code{abc-def.adb} in semantic-checking-only
8698mode.
8699
8700@node Compiler Switches,Linker Switches,Compiling with gcc,Building Executable Programs with GNAT
8701@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}
8702@section Compiler Switches
8703
8704
8705The @code{gcc} command accepts switches that control the
8706compilation process. These switches are fully described in this section:
8707first an alphabetical listing of all switches with a brief description,
8708and then functionally grouped sets of switches with more detailed
8709information.
8710
8711More switches exist for GCC than those documented here, especially
8712for specific targets. However, their use is not recommended as
8713they may change code generation in ways that are incompatible with
8714the Ada run-time library, or can cause inconsistencies between
8715compilation units.
8716
8717@menu
8718* Alphabetical List of All Switches::
8719* Output and Error Message Control::
8720* Warning Message Control::
8721* Debugging and Assertion Control::
8722* Validity Checking::
8723* Style Checking::
8724* Run-Time Checks::
8725* Using gcc for Syntax Checking::
8726* Using gcc for Semantic Checking::
8727* Compiling Different Versions of Ada::
8728* Character Set Control::
8729* File Naming Control::
8730* Subprogram Inlining Control::
8731* Auxiliary Output Control::
8732* Debugging Control::
8733* Exception Handling Control::
8734* Units to Sources Mapping Files::
8735* Code Generation Control::
8736
8737@end menu
8738
8739@node Alphabetical List of All Switches,Output and Error Message Control,,Compiler Switches
8740@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}
8741@subsection Alphabetical List of All Switches
8742
8743
8744@geindex -b (gcc)
8745
8746
8747@table @asis
8748
8749@item @code{-b @emph{target}}
8750
8751Compile your program to run on @code{target}, which is the name of a
8752system configuration. You must have a GNAT cross-compiler built if
8753@code{target} is not the same as your host system.
8754@end table
8755
8756@geindex -B (gcc)
8757
8758
8759@table @asis
8760
8761@item @code{-B@emph{dir}}
8762
8763Load compiler executables (for example, @code{gnat1}, the Ada compiler)
8764from @code{dir} instead of the default location. Only use this switch
8765when multiple versions of the GNAT compiler are available.
8766See the "Options for Directory Search" section in the
8767@cite{Using the GNU Compiler Collection (GCC)} manual for further details.
8768You would normally use the @code{-b} or @code{-V} switch instead.
8769@end table
8770
8771@geindex -c (gcc)
8772
8773
8774@table @asis
8775
8776@item @code{-c}
8777
8778Compile. Always use this switch when compiling Ada programs.
8779
8780Note: for some other languages when using @code{gcc}, notably in
8781the case of C and C++, it is possible to use
8782use @code{gcc} without a @code{-c} switch to
8783compile and link in one step. In the case of GNAT, you
8784cannot use this approach, because the binder must be run
8785and @code{gcc} cannot be used to run the GNAT binder.
8786@end table
8787
8788@geindex -fcallgraph-info (gcc)
8789
8790
8791@table @asis
8792
8793@item @code{-fcallgraph-info[=su,da]}
8794
8795Makes the compiler output callgraph information for the program, on a
8796per-file basis. The information is generated in the VCG format.  It can
8797be decorated with additional, per-node and/or per-edge information, if a
8798list of comma-separated markers is additionally specified. When the
8799@code{su} marker is specified, the callgraph is decorated with stack usage
8800information; it is equivalent to @code{-fstack-usage}. When the @code{da}
8801marker is specified, the callgraph is decorated with information about
8802dynamically allocated objects.
8803@end table
8804
8805@geindex -fdump-scos (gcc)
8806
8807
8808@table @asis
8809
8810@item @code{-fdump-scos}
8811
8812Generates SCO (Source Coverage Obligation) information in the ALI file.
8813This information is used by advanced coverage tools. See unit @code{SCOs}
8814in the compiler sources for details in files @code{scos.ads} and
8815@code{scos.adb}.
8816@end table
8817
8818@geindex -flto (gcc)
8819
8820
8821@table @asis
8822
8823@item @code{-flto[=@emph{n}]}
8824
8825Enables Link Time Optimization. This switch must be used in conjunction
8826with the @code{-Ox} switches (but not with the @code{-gnatn} switch
8827since it is a full replacement for the latter) and instructs the compiler
8828to defer most optimizations until the link stage. The advantage of this
8829approach is that the compiler can do a whole-program analysis and choose
8830the best interprocedural optimization strategy based on a complete view
8831of the program, instead of a fragmentary view with the usual approach.
8832This can also speed up the compilation of big programs and reduce the
8833size of the executable, compared with a traditional per-unit compilation
8834with inlining across modules enabled by the @code{-gnatn} switch.
8835The drawback of this approach is that it may require more memory and that
8836the debugging information generated by -g with it might be hardly usable.
8837The switch, as well as the accompanying @code{-Ox} switches, must be
8838specified both for the compilation and the link phases.
8839If the @code{n} parameter is specified, the optimization and final code
8840generation at link time are executed using @code{n} parallel jobs by
8841means of an installed @code{make} program.
8842@end table
8843
8844@geindex -fno-inline (gcc)
8845
8846
8847@table @asis
8848
8849@item @code{-fno-inline}
8850
8851Suppresses all inlining, unless requested with pragma @code{Inline_Always}. The
8852effect is enforced regardless of other optimization or inlining switches.
8853Note that inlining can also be suppressed on a finer-grained basis with
8854pragma @code{No_Inline}.
8855@end table
8856
8857@geindex -fno-inline-functions (gcc)
8858
8859
8860@table @asis
8861
8862@item @code{-fno-inline-functions}
8863
8864Suppresses automatic inlining of subprograms, which is enabled
8865if @code{-O3} is used.
8866@end table
8867
8868@geindex -fno-inline-small-functions (gcc)
8869
8870
8871@table @asis
8872
8873@item @code{-fno-inline-small-functions}
8874
8875Suppresses automatic inlining of small subprograms, which is enabled
8876if @code{-O2} is used.
8877@end table
8878
8879@geindex -fno-inline-functions-called-once (gcc)
8880
8881
8882@table @asis
8883
8884@item @code{-fno-inline-functions-called-once}
8885
8886Suppresses inlining of subprograms local to the unit and called once
8887from within it, which is enabled if @code{-O1} is used.
8888@end table
8889
8890@geindex -fno-ivopts (gcc)
8891
8892
8893@table @asis
8894
8895@item @code{-fno-ivopts}
8896
8897Suppresses high-level loop induction variable optimizations, which are
8898enabled if @code{-O1} is used. These optimizations are generally
8899profitable but, for some specific cases of loops with numerous uses
8900of the iteration variable that follow a common pattern, they may end
8901up destroying the regularity that could be exploited at a lower level
8902and thus producing inferior code.
8903@end table
8904
8905@geindex -fno-strict-aliasing (gcc)
8906
8907
8908@table @asis
8909
8910@item @code{-fno-strict-aliasing}
8911
8912Causes the compiler to avoid assumptions regarding non-aliasing
8913of objects of different types. See
8914@ref{f3,,Optimization and Strict Aliasing} for details.
8915@end table
8916
8917@geindex -fno-strict-overflow (gcc)
8918
8919
8920@table @asis
8921
8922@item @code{-fno-strict-overflow}
8923
8924Causes the compiler to avoid assumptions regarding the rules of signed
8925integer overflow. These rules specify that signed integer overflow will
8926result in a Constraint_Error exception at run time and are enforced in
8927default mode by the compiler, so this switch should not be necessary in
8928normal operating mode. It might be useful in conjunction with @code{-gnato0}
8929for very peculiar cases of low-level programming.
8930@end table
8931
8932@geindex -fstack-check (gcc)
8933
8934
8935@table @asis
8936
8937@item @code{-fstack-check}
8938
8939Activates stack checking.
8940See @ref{f4,,Stack Overflow Checking} for details.
8941@end table
8942
8943@geindex -fstack-usage (gcc)
8944
8945
8946@table @asis
8947
8948@item @code{-fstack-usage}
8949
8950Makes the compiler output stack usage information for the program, on a
8951per-subprogram basis. See @ref{f5,,Static Stack Usage Analysis} for details.
8952@end table
8953
8954@geindex -g (gcc)
8955
8956
8957@table @asis
8958
8959@item @code{-g}
8960
8961Generate debugging information. This information is stored in the object
8962file and copied from there to the final executable file by the linker,
8963where it can be read by the debugger. You must use the
8964@code{-g} switch if you plan on using the debugger.
8965@end table
8966
8967@geindex -gnat05 (gcc)
8968
8969
8970@table @asis
8971
8972@item @code{-gnat05}
8973
8974Allow full Ada 2005 features.
8975@end table
8976
8977@geindex -gnat12 (gcc)
8978
8979
8980@table @asis
8981
8982@item @code{-gnat12}
8983
8984Allow full Ada 2012 features.
8985@end table
8986
8987@geindex -gnat83 (gcc)
8988
8989@geindex -gnat2005 (gcc)
8990
8991
8992@table @asis
8993
8994@item @code{-gnat2005}
8995
8996Allow full Ada 2005 features (same as @code{-gnat05})
8997@end table
8998
8999@geindex -gnat2012 (gcc)
9000
9001
9002@table @asis
9003
9004@item @code{-gnat2012}
9005
9006Allow full Ada 2012 features (same as @code{-gnat12})
9007
9008@item @code{-gnat83}
9009
9010Enforce Ada 83 restrictions.
9011@end table
9012
9013@geindex -gnat95 (gcc)
9014
9015
9016@table @asis
9017
9018@item @code{-gnat95}
9019
9020Enforce Ada 95 restrictions.
9021
9022Note: for compatibility with some Ada 95 compilers which support only
9023the @code{overriding} keyword of Ada 2005, the @code{-gnatd.D} switch can
9024be used along with @code{-gnat95} to achieve a similar effect with GNAT.
9025
9026@code{-gnatd.D} instructs GNAT to consider @code{overriding} as a keyword
9027and handle its associated semantic checks, even in Ada 95 mode.
9028@end table
9029
9030@geindex -gnata (gcc)
9031
9032
9033@table @asis
9034
9035@item @code{-gnata}
9036
9037Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
9038activated. Note that these pragmas can also be controlled using the
9039configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
9040It also activates pragmas @code{Check}, @code{Precondition}, and
9041@code{Postcondition}. Note that these pragmas can also be controlled
9042using the configuration pragma @code{Check_Policy}. In Ada 2012, it
9043also activates all assertions defined in the RM as aspects: preconditions,
9044postconditions, type invariants and (sub)type predicates. In all Ada modes,
9045corresponding pragmas for type invariants and (sub)type predicates are
9046also activated. The default is that all these assertions are disabled,
9047and have no effect, other than being checked for syntactic validity, and
9048in the case of subtype predicates, constructions such as membership tests
9049still test predicates even if assertions are turned off.
9050@end table
9051
9052@geindex -gnatA (gcc)
9053
9054
9055@table @asis
9056
9057@item @code{-gnatA}
9058
9059Avoid processing @code{gnat.adc}. If a @code{gnat.adc} file is present,
9060it will be ignored.
9061@end table
9062
9063@geindex -gnatb (gcc)
9064
9065
9066@table @asis
9067
9068@item @code{-gnatb}
9069
9070Generate brief messages to @code{stderr} even if verbose mode set.
9071@end table
9072
9073@geindex -gnatB (gcc)
9074
9075
9076@table @asis
9077
9078@item @code{-gnatB}
9079
9080Assume no invalid (bad) values except for 'Valid attribute use
9081(@ref{f6,,Validity Checking}).
9082@end table
9083
9084@geindex -gnatc (gcc)
9085
9086
9087@table @asis
9088
9089@item @code{-gnatc}
9090
9091Check syntax and semantics only (no code generation attempted). When the
9092compiler is invoked by @code{gnatmake}, if the switch @code{-gnatc} is
9093only given to the compiler (after @code{-cargs} or in package Compiler of
9094the project file, @code{gnatmake} will fail because it will not find the
9095object file after compilation. If @code{gnatmake} is called with
9096@code{-gnatc} as a builder switch (before @code{-cargs} or in package
9097Builder of the project file) then @code{gnatmake} will not fail because
9098it will not look for the object files after compilation, and it will not try
9099to build and link.
9100@end table
9101
9102@geindex -gnatC (gcc)
9103
9104
9105@table @asis
9106
9107@item @code{-gnatC}
9108
9109Generate CodePeer intermediate format (no code generation attempted).
9110This switch will generate an intermediate representation suitable for
9111use by CodePeer (@code{.scil} files). This switch is not compatible with
9112code generation (it will, among other things, disable some switches such
9113as -gnatn, and enable others such as -gnata).
9114@end table
9115
9116@geindex -gnatd (gcc)
9117
9118
9119@table @asis
9120
9121@item @code{-gnatd}
9122
9123Specify debug options for the compiler. The string of characters after
9124the @code{-gnatd} specify the specific debug options. The possible
9125characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
9126compiler source file @code{debug.adb} for details of the implemented
9127debug options. Certain debug options are relevant to applications
9128programmers, and these are documented at appropriate points in this
9129users guide.
9130@end table
9131
9132@geindex -gnatD[nn] (gcc)
9133
9134
9135@table @asis
9136
9137@item @code{-gnatD}
9138
9139Create expanded source files for source level debugging. This switch
9140also suppresses generation of cross-reference information
9141(see @code{-gnatx}). Note that this switch is not allowed if a previous
9142-gnatR switch has been given, since these two switches are not compatible.
9143@end table
9144
9145@geindex -gnateA (gcc)
9146
9147
9148@table @asis
9149
9150@item @code{-gnateA}
9151
9152Check that the actual parameters of a subprogram call are not aliases of one
9153another. To qualify as aliasing, the actuals must denote objects of a composite
9154type, their memory locations must be identical or overlapping, and at least one
9155of the corresponding formal parameters must be of mode OUT or IN OUT.
9156
9157@example
9158type Rec_Typ is record
9159   Data : Integer := 0;
9160end record;
9161
9162function Self (Val : Rec_Typ) return Rec_Typ is
9163begin
9164   return Val;
9165end Self;
9166
9167procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
9168begin
9169   null;
9170end Detect_Aliasing;
9171
9172Obj : Rec_Typ;
9173
9174Detect_Aliasing (Obj, Obj);
9175Detect_Aliasing (Obj, Self (Obj));
9176@end example
9177
9178In the example above, the first call to @code{Detect_Aliasing} fails with a
9179@code{Program_Error} at runtime because the actuals for @code{Val_1} and
9180@code{Val_2} denote the same object. The second call executes without raising
9181an exception because @code{Self(Obj)} produces an anonymous object which does
9182not share the memory location of @code{Obj}.
9183@end table
9184
9185@geindex -gnatec (gcc)
9186
9187
9188@table @asis
9189
9190@item @code{-gnatec=@emph{path}}
9191
9192Specify a configuration pragma file
9193(the equal sign is optional)
9194(@ref{79,,The Configuration Pragmas Files}).
9195@end table
9196
9197@geindex -gnateC (gcc)
9198
9199
9200@table @asis
9201
9202@item @code{-gnateC}
9203
9204Generate CodePeer messages in a compiler-like format. This switch is only
9205effective if @code{-gnatcC} is also specified and requires an installation
9206of CodePeer.
9207@end table
9208
9209@geindex -gnated (gcc)
9210
9211
9212@table @asis
9213
9214@item @code{-gnated}
9215
9216Disable atomic synchronization
9217@end table
9218
9219@geindex -gnateD (gcc)
9220
9221
9222@table @asis
9223
9224@item @code{-gnateDsymbol[=@emph{value}]}
9225
9226Defines a symbol, associated with @code{value}, for preprocessing.
9227(@ref{18,,Integrated Preprocessing}).
9228@end table
9229
9230@geindex -gnateE (gcc)
9231
9232
9233@table @asis
9234
9235@item @code{-gnateE}
9236
9237Generate extra information in exception messages. In particular, display
9238extra column information and the value and range associated with index and
9239range check failures, and extra column information for access checks.
9240In cases where the compiler is able to determine at compile time that
9241a check will fail, it gives a warning, and the extra information is not
9242produced at run time.
9243@end table
9244
9245@geindex -gnatef (gcc)
9246
9247
9248@table @asis
9249
9250@item @code{-gnatef}
9251
9252Display full source path name in brief error messages.
9253@end table
9254
9255@geindex -gnateF (gcc)
9256
9257
9258@table @asis
9259
9260@item @code{-gnateF}
9261
9262Check for overflow on all floating-point operations, including those
9263for unconstrained predefined types. See description of pragma
9264@code{Check_Float_Overflow} in GNAT RM.
9265@end table
9266
9267@geindex -gnateg (gcc)
9268
9269@code{-gnateg}
9270@code{-gnatceg}
9271
9272@quotation
9273
9274The @code{-gnatc} switch must always be specified before this switch, e.g.
9275@code{-gnatceg}. Generate a C header from the Ada input file. See
9276@ref{ca,,Generating C Headers for Ada Specifications} for more
9277information.
9278@end quotation
9279
9280@geindex -gnateG (gcc)
9281
9282
9283@table @asis
9284
9285@item @code{-gnateG}
9286
9287Save result of preprocessing in a text file.
9288@end table
9289
9290@geindex -gnatei (gcc)
9291
9292
9293@table @asis
9294
9295@item @code{-gnatei@emph{nnn}}
9296
9297Set maximum number of instantiations during compilation of a single unit to
9298@code{nnn}. This may be useful in increasing the default maximum of 8000 for
9299the rare case when a single unit legitimately exceeds this limit.
9300@end table
9301
9302@geindex -gnateI (gcc)
9303
9304
9305@table @asis
9306
9307@item @code{-gnateI@emph{nnn}}
9308
9309Indicates that the source is a multi-unit source and that the index of the
9310unit to compile is @code{nnn}. @code{nnn} needs to be a positive number and need
9311to be a valid index in the multi-unit source.
9312@end table
9313
9314@geindex -gnatel (gcc)
9315
9316
9317@table @asis
9318
9319@item @code{-gnatel}
9320
9321This switch can be used with the static elaboration model to issue info
9322messages showing
9323where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
9324are generated. This is useful in diagnosing elaboration circularities
9325caused by these implicit pragmas when using the static elaboration
9326model. See See the section in this guide on elaboration checking for
9327further details. These messages are not generated by default, and are
9328intended only for temporary use when debugging circularity problems.
9329@end table
9330
9331@geindex -gnatel (gcc)
9332
9333
9334@table @asis
9335
9336@item @code{-gnateL}
9337
9338This switch turns off the info messages about implicit elaboration pragmas.
9339@end table
9340
9341@geindex -gnatem (gcc)
9342
9343
9344@table @asis
9345
9346@item @code{-gnatem=@emph{path}}
9347
9348Specify a mapping file
9349(the equal sign is optional)
9350(@ref{f7,,Units to Sources Mapping Files}).
9351@end table
9352
9353@geindex -gnatep (gcc)
9354
9355
9356@table @asis
9357
9358@item @code{-gnatep=@emph{file}}
9359
9360Specify a preprocessing data file
9361(the equal sign is optional)
9362(@ref{18,,Integrated Preprocessing}).
9363@end table
9364
9365@geindex -gnateP (gcc)
9366
9367
9368@table @asis
9369
9370@item @code{-gnateP}
9371
9372Turn categorization dependency errors into warnings.
9373Ada requires that units that WITH one another have compatible categories, for
9374example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
9375these errors become warnings (which can be ignored, or suppressed in the usual
9376manner). This can be useful in some specialized circumstances such as the
9377temporary use of special test software.
9378@end table
9379
9380@geindex -gnateS (gcc)
9381
9382
9383@table @asis
9384
9385@item @code{-gnateS}
9386
9387Synonym of @code{-fdump-scos}, kept for backwards compatibility.
9388@end table
9389
9390@geindex -gnatet=file (gcc)
9391
9392
9393@table @asis
9394
9395@item @code{-gnatet=@emph{path}}
9396
9397Generate target dependent information. The format of the output file is
9398described in the section about switch @code{-gnateT}.
9399@end table
9400
9401@geindex -gnateT (gcc)
9402
9403
9404@table @asis
9405
9406@item @code{-gnateT=@emph{path}}
9407
9408Read target dependent information, such as endianness or sizes and alignments
9409of base type. If this switch is passed, the default target dependent
9410information of the compiler is replaced by the one read from the input file.
9411This is used by tools other than the compiler, e.g. to do
9412semantic analysis of programs that will run on some other target than
9413the machine on which the tool is run.
9414
9415The following target dependent values should be defined,
9416where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
9417positive integer value, and fields marked with a question mark are
9418boolean fields, where a value of 0 is False, and a value of 1 is True:
9419
9420@example
9421Bits_BE                    : Nat; -- Bits stored big-endian?
9422Bits_Per_Unit              : Pos; -- Bits in a storage unit
9423Bits_Per_Word              : Pos; -- Bits in a word
9424Bytes_BE                   : Nat; -- Bytes stored big-endian?
9425Char_Size                  : Pos; -- Standard.Character'Size
9426Double_Float_Alignment     : Nat; -- Alignment of double float
9427Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
9428Double_Size                : Pos; -- Standard.Long_Float'Size
9429Float_Size                 : Pos; -- Standard.Float'Size
9430Float_Words_BE             : Nat; -- Float words stored big-endian?
9431Int_Size                   : Pos; -- Standard.Integer'Size
9432Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
9433Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
9434Long_Size                  : Pos; -- Standard.Long_Integer'Size
9435Maximum_Alignment          : Pos; -- Maximum permitted alignment
9436Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
9437Pointer_Size               : Pos; -- System.Address'Size
9438Short_Enums                : Nat; -- Short foreign convention enums?
9439Short_Size                 : Pos; -- Standard.Short_Integer'Size
9440Strict_Alignment           : Nat; -- Strict alignment?
9441System_Allocator_Alignment : Nat; -- Alignment for malloc calls
9442Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
9443Words_BE                   : Nat; -- Words stored big-endian?
9444@end example
9445
9446The format of the input file is as follows. First come the values of
9447the variables defined above, with one line per value:
9448
9449@example
9450name  value
9451@end example
9452
9453where @code{name} is the name of the parameter, spelled out in full,
9454and cased as in the above list, and @code{value} is an unsigned decimal
9455integer. Two or more blanks separates the name from the value.
9456
9457All the variables must be present, in alphabetical order (i.e. the
9458same order as the list above).
9459
9460Then there is a blank line to separate the two parts of the file. Then
9461come the lines showing the floating-point types to be registered, with
9462one line per registered mode:
9463
9464@example
9465name  digs float_rep size alignment
9466@end example
9467
9468where @code{name} is the string name of the type (which can have
9469single spaces embedded in the name (e.g. long double), @code{digs} is
9470the number of digits for the floating-point type, @code{float_rep} is
9471the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
9472AAMP), @code{size} is the size in bits, @code{alignment} is the
9473alignment in bits. The name is followed by at least two blanks, fields
9474are separated by at least one blank, and a LF character immediately
9475follows the alignment field.
9476
9477Here is an example of a target parameterization file:
9478
9479@example
9480Bits_BE                       0
9481Bits_Per_Unit                 8
9482Bits_Per_Word                64
9483Bytes_BE                      0
9484Char_Size                     8
9485Double_Float_Alignment        0
9486Double_Scalar_Alignment       0
9487Double_Size                  64
9488Float_Size                   32
9489Float_Words_BE                0
9490Int_Size                     64
9491Long_Double_Size            128
9492Long_Long_Size               64
9493Long_Size                    64
9494Maximum_Alignment            16
9495Max_Unaligned_Field          64
9496Pointer_Size                 64
9497Short_Size                   16
9498Strict_Alignment              0
9499System_Allocator_Alignment   16
9500Wchar_T_Size                 32
9501Words_BE                      0
9502
9503float         15  I  64  64
9504double        15  I  64  64
9505long double   18  I  80 128
9506TF            33  I 128 128
9507@end example
9508@end table
9509
9510@geindex -gnateu (gcc)
9511
9512
9513@table @asis
9514
9515@item @code{-gnateu}
9516
9517Ignore unrecognized validity, warning, and style switches that
9518appear after this switch is given. This may be useful when
9519compiling sources developed on a later version of the compiler
9520with an earlier version. Of course the earlier version must
9521support this switch.
9522@end table
9523
9524@geindex -gnateV (gcc)
9525
9526
9527@table @asis
9528
9529@item @code{-gnateV}
9530
9531Check that all actual parameters of a subprogram call are valid according to
9532the rules of validity checking (@ref{f6,,Validity Checking}).
9533@end table
9534
9535@geindex -gnateY (gcc)
9536
9537
9538@table @asis
9539
9540@item @code{-gnateY}
9541
9542Ignore all STYLE_CHECKS pragmas. Full legality checks
9543are still carried out, but the pragmas have no effect
9544on what style checks are active. This allows all style
9545checking options to be controlled from the command line.
9546@end table
9547
9548@geindex -gnatE (gcc)
9549
9550
9551@table @asis
9552
9553@item @code{-gnatE}
9554
9555Full dynamic elaboration checks.
9556@end table
9557
9558@geindex -gnatf (gcc)
9559
9560
9561@table @asis
9562
9563@item @code{-gnatf}
9564
9565Full errors. Multiple errors per line, all undefined references, do not
9566attempt to suppress cascaded errors.
9567@end table
9568
9569@geindex -gnatF (gcc)
9570
9571
9572@table @asis
9573
9574@item @code{-gnatF}
9575
9576Externals names are folded to all uppercase.
9577@end table
9578
9579@geindex -gnatg (gcc)
9580
9581
9582@table @asis
9583
9584@item @code{-gnatg}
9585
9586Internal GNAT implementation mode. This should not be used for
9587applications programs, it is intended only for use by the compiler
9588and its run-time library. For documentation, see the GNAT sources.
9589Note that @code{-gnatg} implies
9590@code{-gnatw.ge} and
9591@code{-gnatyg}
9592so that all standard warnings and all standard style options are turned on.
9593All warnings and style messages are treated as errors.
9594@end table
9595
9596@geindex -gnatG[nn] (gcc)
9597
9598
9599@table @asis
9600
9601@item @code{-gnatG=nn}
9602
9603List generated expanded code in source form.
9604@end table
9605
9606@geindex -gnath (gcc)
9607
9608
9609@table @asis
9610
9611@item @code{-gnath}
9612
9613Output usage information. The output is written to @code{stdout}.
9614@end table
9615
9616@geindex -gnati (gcc)
9617
9618
9619@table @asis
9620
9621@item @code{-gnati@emph{c}}
9622
9623Identifier character set (@code{c} = 1/2/3/4/8/9/p/f/n/w).
9624For details of the possible selections for @code{c},
9625see @ref{48,,Character Set Control}.
9626@end table
9627
9628@geindex -gnatI (gcc)
9629
9630
9631@table @asis
9632
9633@item @code{-gnatI}
9634
9635Ignore representation clauses. When this switch is used,
9636representation clauses are treated as comments. This is useful
9637when initially porting code where you want to ignore rep clause
9638problems, and also for compiling foreign code (particularly
9639for use with ASIS). The representation clauses that are ignored
9640are: enumeration_representation_clause, record_representation_clause,
9641and attribute_definition_clause for the following attributes:
9642Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
9643Object_Size, Scalar_Storage_Order, Size, Small, Stream_Size,
9644and Value_Size. Pragma Default_Scalar_Storage_Order is also ignored.
9645Note that this option should be used only for compiling -- the
9646code is likely to malfunction at run time.
9647
9648Note that when @code{-gnatct} is used to generate trees for input
9649into ASIS tools, these representation clauses are removed
9650from the tree and ignored. This means that the tool will not see them.
9651@end table
9652
9653@geindex -gnatjnn (gcc)
9654
9655
9656@table @asis
9657
9658@item @code{-gnatj@emph{nn}}
9659
9660Reformat error messages to fit on @code{nn} character lines
9661@end table
9662
9663@geindex -gnatk (gcc)
9664
9665
9666@table @asis
9667
9668@item @code{-gnatk=@emph{n}}
9669
9670Limit file names to @code{n} (1-999) characters (@code{k} = krunch).
9671@end table
9672
9673@geindex -gnatl (gcc)
9674
9675
9676@table @asis
9677
9678@item @code{-gnatl}
9679
9680Output full source listing with embedded error messages.
9681@end table
9682
9683@geindex -gnatL (gcc)
9684
9685
9686@table @asis
9687
9688@item @code{-gnatL}
9689
9690Used in conjunction with -gnatG or -gnatD to intersperse original
9691source lines (as comment lines with line numbers) in the expanded
9692source output.
9693@end table
9694
9695@geindex -gnatm (gcc)
9696
9697
9698@table @asis
9699
9700@item @code{-gnatm=@emph{n}}
9701
9702Limit number of detected error or warning messages to @code{n}
9703where @code{n} is in the range 1..999999. The default setting if
9704no switch is given is 9999. If the number of warnings reaches this
9705limit, then a message is output and further warnings are suppressed,
9706but the compilation is continued. If the number of error messages
9707reaches this limit, then a message is output and the compilation
9708is abandoned. The equal sign here is optional. A value of zero
9709means that no limit applies.
9710@end table
9711
9712@geindex -gnatn (gcc)
9713
9714
9715@table @asis
9716
9717@item @code{-gnatn[12]}
9718
9719Activate inlining across modules for subprograms for which pragma @code{Inline}
9720is specified. This inlining is performed by the GCC back-end. An optional
9721digit sets the inlining level: 1 for moderate inlining across modules
9722or 2 for full inlining across modules. If no inlining level is specified,
9723the compiler will pick it based on the optimization level.
9724@end table
9725
9726@geindex -gnatN (gcc)
9727
9728
9729@table @asis
9730
9731@item @code{-gnatN}
9732
9733Activate front end inlining for subprograms for which
9734pragma @code{Inline} is specified. This inlining is performed
9735by the front end and will be visible in the
9736@code{-gnatG} output.
9737
9738When using a gcc-based back end (in practice this means using any version
9739of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
9740@code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
9741Historically front end inlining was more extensive than the gcc back end
9742inlining, but that is no longer the case.
9743@end table
9744
9745@geindex -gnato0 (gcc)
9746
9747
9748@table @asis
9749
9750@item @code{-gnato0}
9751
9752Suppresses overflow checking. This causes the behavior of the compiler to
9753match the default for older versions where overflow checking was suppressed
9754by default. This is equivalent to having
9755@code{pragma Suppress (Overflow_Check)} in a configuration pragma file.
9756@end table
9757
9758@geindex -gnato?? (gcc)
9759
9760
9761@table @asis
9762
9763@item @code{-gnato??}
9764
9765Set default mode for handling generation of code to avoid intermediate
9766arithmetic overflow. Here @code{??} is two digits, a
9767single digit, or nothing. Each digit is one of the digits @code{1}
9768through @code{3}:
9769
9770
9771@multitable {xxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
9772@item
9773
9774Digit
9775
9776@tab
9777
9778Interpretation
9779
9780@item
9781
9782@emph{1}
9783
9784@tab
9785
9786All intermediate overflows checked against base type (@code{STRICT})
9787
9788@item
9789
9790@emph{2}
9791
9792@tab
9793
9794Minimize intermediate overflows (@code{MINIMIZED})
9795
9796@item
9797
9798@emph{3}
9799
9800@tab
9801
9802Eliminate intermediate overflows (@code{ELIMINATED})
9803
9804@end multitable
9805
9806
9807If only one digit appears, then it applies to all
9808cases; if two digits are given, then the first applies outside
9809assertions, pre/postconditions, and type invariants, and the second
9810applies within assertions, pre/postconditions, and type invariants.
9811
9812If no digits follow the @code{-gnato}, then it is equivalent to
9813@code{-gnato11},
9814causing all intermediate overflows to be handled in strict
9815mode.
9816
9817This switch also causes arithmetic overflow checking to be performed
9818(as though @code{pragma Unsuppress (Overflow_Check)} had been specified).
9819
9820The default if no option @code{-gnato} is given is that overflow handling
9821is in @code{STRICT} mode (computations done using the base type), and that
9822overflow checking is enabled.
9823
9824Note that division by zero is a separate check that is not
9825controlled by this switch (divide-by-zero checking is on by default).
9826
9827See also @ref{f8,,Specifying the Desired Mode}.
9828@end table
9829
9830@geindex -gnatp (gcc)
9831
9832
9833@table @asis
9834
9835@item @code{-gnatp}
9836
9837Suppress all checks. See @ref{f9,,Run-Time Checks} for details. This switch
9838has no effect if cancelled by a subsequent @code{-gnat-p} switch.
9839@end table
9840
9841@geindex -gnat-p (gcc)
9842
9843
9844@table @asis
9845
9846@item @code{-gnat-p}
9847
9848Cancel effect of previous @code{-gnatp} switch.
9849@end table
9850
9851@geindex -gnatP (gcc)
9852
9853
9854@table @asis
9855
9856@item @code{-gnatP}
9857
9858Enable polling. This is required on some systems (notably Windows NT) to
9859obtain asynchronous abort and asynchronous transfer of control capability.
9860See @code{Pragma_Polling} in the @cite{GNAT_Reference_Manual} for full
9861details.
9862@end table
9863
9864@geindex -gnatq (gcc)
9865
9866
9867@table @asis
9868
9869@item @code{-gnatq}
9870
9871Don't quit. Try semantics, even if parse errors.
9872@end table
9873
9874@geindex -gnatQ (gcc)
9875
9876
9877@table @asis
9878
9879@item @code{-gnatQ}
9880
9881Don't quit. Generate @code{ALI} and tree files even if illegalities.
9882Note that code generation is still suppressed in the presence of any
9883errors, so even with @code{-gnatQ} no object file is generated.
9884@end table
9885
9886@geindex -gnatr (gcc)
9887
9888
9889@table @asis
9890
9891@item @code{-gnatr}
9892
9893Treat pragma Restrictions as Restriction_Warnings.
9894@end table
9895
9896@geindex -gnatR (gcc)
9897
9898
9899@table @asis
9900
9901@item @code{-gnatR[0/1/2/3][e][m][s]}
9902
9903Output representation information for declared types, objects and
9904subprograms. Note that this switch is not allowed if a previous
9905@code{-gnatD} switch has been given, since these two switches
9906are not compatible.
9907@end table
9908
9909@geindex -gnats (gcc)
9910
9911
9912@table @asis
9913
9914@item @code{-gnats}
9915
9916Syntax check only.
9917@end table
9918
9919@geindex -gnatS (gcc)
9920
9921
9922@table @asis
9923
9924@item @code{-gnatS}
9925
9926Print package Standard.
9927@end table
9928
9929@geindex -gnatt (gcc)
9930
9931
9932@table @asis
9933
9934@item @code{-gnatt}
9935
9936Generate tree output file.
9937@end table
9938
9939@geindex -gnatT (gcc)
9940
9941
9942@table @asis
9943
9944@item @code{-gnatT@emph{nnn}}
9945
9946All compiler tables start at @code{nnn} times usual starting size.
9947@end table
9948
9949@geindex -gnatu (gcc)
9950
9951
9952@table @asis
9953
9954@item @code{-gnatu}
9955
9956List units for this compilation.
9957@end table
9958
9959@geindex -gnatU (gcc)
9960
9961
9962@table @asis
9963
9964@item @code{-gnatU}
9965
9966Tag all error messages with the unique string 'error:'
9967@end table
9968
9969@geindex -gnatv (gcc)
9970
9971
9972@table @asis
9973
9974@item @code{-gnatv}
9975
9976Verbose mode. Full error output with source lines to @code{stdout}.
9977@end table
9978
9979@geindex -gnatV (gcc)
9980
9981
9982@table @asis
9983
9984@item @code{-gnatV}
9985
9986Control level of validity checking (@ref{f6,,Validity Checking}).
9987@end table
9988
9989@geindex -gnatw (gcc)
9990
9991
9992@table @asis
9993
9994@item @code{-gnatw@emph{xxx}}
9995
9996Warning mode where
9997@code{xxx} is a string of option letters that denotes
9998the exact warnings that
9999are enabled or disabled (@ref{fa,,Warning Message Control}).
10000@end table
10001
10002@geindex -gnatW (gcc)
10003
10004
10005@table @asis
10006
10007@item @code{-gnatW@emph{e}}
10008
10009Wide character encoding method
10010(@code{e}=n/h/u/s/e/8).
10011@end table
10012
10013@geindex -gnatx (gcc)
10014
10015
10016@table @asis
10017
10018@item @code{-gnatx}
10019
10020Suppress generation of cross-reference information.
10021@end table
10022
10023@geindex -gnatX (gcc)
10024
10025
10026@table @asis
10027
10028@item @code{-gnatX}
10029
10030Enable GNAT implementation extensions and latest Ada version.
10031@end table
10032
10033@geindex -gnaty (gcc)
10034
10035
10036@table @asis
10037
10038@item @code{-gnaty}
10039
10040Enable built-in style checks (@ref{fb,,Style Checking}).
10041@end table
10042
10043@geindex -gnatz (gcc)
10044
10045
10046@table @asis
10047
10048@item @code{-gnatz@emph{m}}
10049
10050Distribution stub generation and compilation
10051(@code{m}=r/c for receiver/caller stubs).
10052@end table
10053
10054@geindex -I (gcc)
10055
10056
10057@table @asis
10058
10059@item @code{-I@emph{dir}}
10060
10061@geindex RTL
10062
10063Direct GNAT to search the @code{dir} directory for source files needed by
10064the current compilation
10065(see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
10066@end table
10067
10068@geindex -I- (gcc)
10069
10070
10071@table @asis
10072
10073@item @code{-I-}
10074
10075@geindex RTL
10076
10077Except for the source file named in the command line, do not look for source
10078files in the directory containing the source file named in the command line
10079(see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
10080@end table
10081
10082@geindex -o (gcc)
10083
10084
10085@table @asis
10086
10087@item @code{-o @emph{file}}
10088
10089This switch is used in @code{gcc} to redirect the generated object file
10090and its associated ALI file. Beware of this switch with GNAT, because it may
10091cause the object file and ALI file to have different names which in turn
10092may confuse the binder and the linker.
10093@end table
10094
10095@geindex -nostdinc (gcc)
10096
10097
10098@table @asis
10099
10100@item @code{-nostdinc}
10101
10102Inhibit the search of the default location for the GNAT Run Time
10103Library (RTL) source files.
10104@end table
10105
10106@geindex -nostdlib (gcc)
10107
10108
10109@table @asis
10110
10111@item @code{-nostdlib}
10112
10113Inhibit the search of the default location for the GNAT Run Time
10114Library (RTL) ALI files.
10115@end table
10116
10117@geindex -O (gcc)
10118
10119
10120@table @asis
10121
10122@item @code{-O[@emph{n}]}
10123
10124@code{n} controls the optimization level:
10125
10126
10127@multitable {xxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
10128@item
10129
10130@emph{n}
10131
10132@tab
10133
10134Effect
10135
10136@item
10137
10138@emph{0}
10139
10140@tab
10141
10142No optimization, the default setting if no @code{-O} appears
10143
10144@item
10145
10146@emph{1}
10147
10148@tab
10149
10150Normal optimization, the default if you specify @code{-O} without an
10151operand. A good compromise between code quality and compilation
10152time.
10153
10154@item
10155
10156@emph{2}
10157
10158@tab
10159
10160Extensive optimization, may improve execution time, possibly at
10161the cost of substantially increased compilation time.
10162
10163@item
10164
10165@emph{3}
10166
10167@tab
10168
10169Same as @code{-O2}, and also includes inline expansion for small
10170subprograms in the same unit.
10171
10172@item
10173
10174@emph{s}
10175
10176@tab
10177
10178Optimize space usage
10179
10180@end multitable
10181
10182
10183See also @ref{fc,,Optimization Levels}.
10184@end table
10185
10186@geindex -pass-exit-codes (gcc)
10187
10188
10189@table @asis
10190
10191@item @code{-pass-exit-codes}
10192
10193Catch exit codes from the compiler and use the most meaningful as
10194exit status.
10195@end table
10196
10197@geindex --RTS (gcc)
10198
10199
10200@table @asis
10201
10202@item @code{--RTS=@emph{rts-path}}
10203
10204Specifies the default location of the runtime library. Same meaning as the
10205equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
10206@end table
10207
10208@geindex -S (gcc)
10209
10210
10211@table @asis
10212
10213@item @code{-S}
10214
10215Used in place of @code{-c} to
10216cause the assembler source file to be
10217generated, using @code{.s} as the extension,
10218instead of the object file.
10219This may be useful if you need to examine the generated assembly code.
10220@end table
10221
10222@geindex -fverbose-asm (gcc)
10223
10224
10225@table @asis
10226
10227@item @code{-fverbose-asm}
10228
10229Used in conjunction with @code{-S}
10230to cause the generated assembly code file to be annotated with variable
10231names, making it significantly easier to follow.
10232@end table
10233
10234@geindex -v (gcc)
10235
10236
10237@table @asis
10238
10239@item @code{-v}
10240
10241Show commands generated by the @code{gcc} driver. Normally used only for
10242debugging purposes or if you need to be sure what version of the
10243compiler you are executing.
10244@end table
10245
10246@geindex -V (gcc)
10247
10248
10249@table @asis
10250
10251@item @code{-V @emph{ver}}
10252
10253Execute @code{ver} version of the compiler. This is the @code{gcc}
10254version, not the GNAT version.
10255@end table
10256
10257@geindex -w (gcc)
10258
10259
10260@table @asis
10261
10262@item @code{-w}
10263
10264Turn off warnings generated by the back end of the compiler. Use of
10265this switch also causes the default for front end warnings to be set
10266to suppress (as though @code{-gnatws} had appeared at the start of
10267the options).
10268@end table
10269
10270@geindex Combining GNAT switches
10271
10272You may combine a sequence of GNAT switches into a single switch. For
10273example, the combined switch
10274
10275@quotation
10276
10277@example
10278-gnatofi3
10279@end example
10280@end quotation
10281
10282is equivalent to specifying the following sequence of switches:
10283
10284@quotation
10285
10286@example
10287-gnato -gnatf -gnati3
10288@end example
10289@end quotation
10290
10291The following restrictions apply to the combination of switches
10292in this manner:
10293
10294
10295@itemize *
10296
10297@item
10298The switch @code{-gnatc} if combined with other switches must come
10299first in the string.
10300
10301@item
10302The switch @code{-gnats} if combined with other switches must come
10303first in the string.
10304
10305@item
10306The switches
10307@code{-gnatzc} and @code{-gnatzr} may not be combined with any other
10308switches, and only one of them may appear in the command line.
10309
10310@item
10311The switch @code{-gnat-p} may not be combined with any other switch.
10312
10313@item
10314Once a 'y' appears in the string (that is a use of the @code{-gnaty}
10315switch), then all further characters in the switch are interpreted
10316as style modifiers (see description of @code{-gnaty}).
10317
10318@item
10319Once a 'd' appears in the string (that is a use of the @code{-gnatd}
10320switch), then all further characters in the switch are interpreted
10321as debug flags (see description of @code{-gnatd}).
10322
10323@item
10324Once a 'w' appears in the string (that is a use of the @code{-gnatw}
10325switch), then all further characters in the switch are interpreted
10326as warning mode modifiers (see description of @code{-gnatw}).
10327
10328@item
10329Once a 'V' appears in the string (that is a use of the @code{-gnatV}
10330switch), then all further characters in the switch are interpreted
10331as validity checking options (@ref{f6,,Validity Checking}).
10332
10333@item
10334Option 'em', 'ec', 'ep', 'l=' and 'R' must be the last options in
10335a combined list of options.
10336@end itemize
10337
10338@node Output and Error Message Control,Warning Message Control,Alphabetical List of All Switches,Compiler Switches
10339@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}
10340@subsection Output and Error Message Control
10341
10342
10343@geindex stderr
10344
10345The standard default format for error messages is called 'brief format'.
10346Brief format messages are written to @code{stderr} (the standard error
10347file) and have the following form:
10348
10349@example
10350e.adb:3:04: Incorrect spelling of keyword "function"
10351e.adb:4:20: ";" should be "is"
10352@end example
10353
10354The first integer after the file name is the line number in the file,
10355and the second integer is the column number within the line.
10356@code{GPS} can parse the error messages
10357and point to the referenced character.
10358The following switches provide control over the error message
10359format:
10360
10361@geindex -gnatv (gcc)
10362
10363
10364@table @asis
10365
10366@item @code{-gnatv}
10367
10368The @code{v} stands for verbose.
10369The effect of this setting is to write long-format error
10370messages to @code{stdout} (the standard output file.
10371The same program compiled with the
10372@code{-gnatv} switch would generate:
10373
10374@example
103753. funcion X (Q : Integer)
10376   |
10377>>> Incorrect spelling of keyword "function"
103784. return Integer;
10379                 |
10380>>> ";" should be "is"
10381@end example
10382
10383The vertical bar indicates the location of the error, and the @code{>>>}
10384prefix can be used to search for error messages. When this switch is
10385used the only source lines output are those with errors.
10386@end table
10387
10388@geindex -gnatl (gcc)
10389
10390
10391@table @asis
10392
10393@item @code{-gnatl}
10394
10395The @code{l} stands for list.
10396This switch causes a full listing of
10397the file to be generated. In the case where a body is
10398compiled, the corresponding spec is also listed, along
10399with any subunits. Typical output from compiling a package
10400body @code{p.adb} might look like:
10401
10402@example
10403Compiling: p.adb
10404
10405     1. package body p is
10406     2.    procedure a;
10407     3.    procedure a is separate;
10408     4. begin
10409     5.    null
10410               |
10411        >>> missing ";"
10412
10413     6. end;
10414
10415Compiling: p.ads
10416
10417     1. package p is
10418     2.    pragma Elaborate_Body
10419                                |
10420        >>> missing ";"
10421
10422     3. end p;
10423
10424Compiling: p-a.adb
10425
10426     1. separate p
10427                |
10428        >>> missing "("
10429
10430     2. procedure a is
10431     3. begin
10432     4.    null
10433               |
10434        >>> missing ";"
10435
10436     5. end;
10437@end example
10438
10439When you specify the @code{-gnatv} or @code{-gnatl} switches and
10440standard output is redirected, a brief summary is written to
10441@code{stderr} (standard error) giving the number of error messages and
10442warning messages generated.
10443@end table
10444
10445@geindex -gnatl=fname (gcc)
10446
10447
10448@table @asis
10449
10450@item @code{-gnatl=@emph{fname}}
10451
10452This has the same effect as @code{-gnatl} except that the output is
10453written to a file instead of to standard output. If the given name
10454@code{fname} does not start with a period, then it is the full name
10455of the file to be written. If @code{fname} is an extension, it is
10456appended to the name of the file being compiled. For example, if
10457file @code{xyz.adb} is compiled with @code{-gnatl=.lst},
10458then the output is written to file xyz.adb.lst.
10459@end table
10460
10461@geindex -gnatU (gcc)
10462
10463
10464@table @asis
10465
10466@item @code{-gnatU}
10467
10468This switch forces all error messages to be preceded by the unique
10469string 'error:'. This means that error messages take a few more
10470characters in space, but allows easy searching for and identification
10471of error messages.
10472@end table
10473
10474@geindex -gnatb (gcc)
10475
10476
10477@table @asis
10478
10479@item @code{-gnatb}
10480
10481The @code{b} stands for brief.
10482This switch causes GNAT to generate the
10483brief format error messages to @code{stderr} (the standard error
10484file) as well as the verbose
10485format message or full listing (which as usual is written to
10486@code{stdout} (the standard output file).
10487@end table
10488
10489@geindex -gnatm (gcc)
10490
10491
10492@table @asis
10493
10494@item @code{-gnatm=@emph{n}}
10495
10496The @code{m} stands for maximum.
10497@code{n} is a decimal integer in the
10498range of 1 to 999999 and limits the number of error or warning
10499messages to be generated. For example, using
10500@code{-gnatm2} might yield
10501
10502@example
10503e.adb:3:04: Incorrect spelling of keyword "function"
10504e.adb:5:35: missing ".."
10505fatal error: maximum number of errors detected
10506compilation abandoned
10507@end example
10508
10509The default setting if
10510no switch is given is 9999. If the number of warnings reaches this
10511limit, then a message is output and further warnings are suppressed,
10512but the compilation is continued. If the number of error messages
10513reaches this limit, then a message is output and the compilation
10514is abandoned. A value of zero means that no limit applies.
10515
10516Note that the equal sign is optional, so the switches
10517@code{-gnatm2} and @code{-gnatm=2} are equivalent.
10518@end table
10519
10520@geindex -gnatf (gcc)
10521
10522
10523@table @asis
10524
10525@item @code{-gnatf}
10526
10527@geindex Error messages
10528@geindex suppressing
10529
10530The @code{f} stands for full.
10531Normally, the compiler suppresses error messages that are likely to be
10532redundant. This switch causes all error
10533messages to be generated. In particular, in the case of
10534references to undefined variables. If a given variable is referenced
10535several times, the normal format of messages is
10536
10537@example
10538e.adb:7:07: "V" is undefined (more references follow)
10539@end example
10540
10541where the parenthetical comment warns that there are additional
10542references to the variable @code{V}. Compiling the same program with the
10543@code{-gnatf} switch yields
10544
10545@example
10546e.adb:7:07: "V" is undefined
10547e.adb:8:07: "V" is undefined
10548e.adb:8:12: "V" is undefined
10549e.adb:8:16: "V" is undefined
10550e.adb:9:07: "V" is undefined
10551e.adb:9:12: "V" is undefined
10552@end example
10553
10554The @code{-gnatf} switch also generates additional information for
10555some error messages.  Some examples are:
10556
10557
10558@itemize *
10559
10560@item
10561Details on possibly non-portable unchecked conversion
10562
10563@item
10564List possible interpretations for ambiguous calls
10565
10566@item
10567Additional details on incorrect parameters
10568@end itemize
10569@end table
10570
10571@geindex -gnatjnn (gcc)
10572
10573
10574@table @asis
10575
10576@item @code{-gnatjnn}
10577
10578In normal operation mode (or if @code{-gnatj0} is used), then error messages
10579with continuation lines are treated as though the continuation lines were
10580separate messages (and so a warning with two continuation lines counts as
10581three warnings, and is listed as three separate messages).
10582
10583If the @code{-gnatjnn} switch is used with a positive value for nn, then
10584messages are output in a different manner. A message and all its continuation
10585lines are treated as a unit, and count as only one warning or message in the
10586statistics totals. Furthermore, the message is reformatted so that no line
10587is longer than nn characters.
10588@end table
10589
10590@geindex -gnatq (gcc)
10591
10592
10593@table @asis
10594
10595@item @code{-gnatq}
10596
10597The @code{q} stands for quit (really 'don't quit').
10598In normal operation mode, the compiler first parses the program and
10599determines if there are any syntax errors. If there are, appropriate
10600error messages are generated and compilation is immediately terminated.
10601This switch tells
10602GNAT to continue with semantic analysis even if syntax errors have been
10603found. This may enable the detection of more errors in a single run. On
10604the other hand, the semantic analyzer is more likely to encounter some
10605internal fatal error when given a syntactically invalid tree.
10606@end table
10607
10608@geindex -gnatQ (gcc)
10609
10610
10611@table @asis
10612
10613@item @code{-gnatQ}
10614
10615In normal operation mode, the @code{ALI} file is not generated if any
10616illegalities are detected in the program. The use of @code{-gnatQ} forces
10617generation of the @code{ALI} file. This file is marked as being in
10618error, so it cannot be used for binding purposes, but it does contain
10619reasonably complete cross-reference information, and thus may be useful
10620for use by tools (e.g., semantic browsing tools or integrated development
10621environments) that are driven from the @code{ALI} file. This switch
10622implies @code{-gnatq}, since the semantic phase must be run to get a
10623meaningful ALI file.
10624
10625In addition, if @code{-gnatt} is also specified, then the tree file is
10626generated even if there are illegalities. It may be useful in this case
10627to also specify @code{-gnatq} to ensure that full semantic processing
10628occurs. The resulting tree file can be processed by ASIS, for the purpose
10629of providing partial information about illegal units, but if the error
10630causes the tree to be badly malformed, then ASIS may crash during the
10631analysis.
10632
10633When @code{-gnatQ} is used and the generated @code{ALI} file is marked as
10634being in error, @code{gnatmake} will attempt to recompile the source when it
10635finds such an @code{ALI} file, including with switch @code{-gnatc}.
10636
10637Note that @code{-gnatQ} has no effect if @code{-gnats} is specified,
10638since ALI files are never generated if @code{-gnats} is set.
10639@end table
10640
10641@node Warning Message Control,Debugging and Assertion Control,Output and Error Message Control,Compiler Switches
10642@anchor{gnat_ugn/building_executable_programs_with_gnat warning-message-control}@anchor{fa}@anchor{gnat_ugn/building_executable_programs_with_gnat id15}@anchor{ff}
10643@subsection Warning Message Control
10644
10645
10646@geindex Warning messages
10647
10648In addition to error messages, which correspond to illegalities as defined
10649in the Ada Reference Manual, the compiler detects two kinds of warning
10650situations.
10651
10652First, the compiler considers some constructs suspicious and generates a
10653warning message to alert you to a possible error. Second, if the
10654compiler detects a situation that is sure to raise an exception at
10655run time, it generates a warning message. The following shows an example
10656of warning messages:
10657
10658@example
10659e.adb:4:24: warning: creation of object may raise Storage_Error
10660e.adb:10:17: warning: static value out of range
10661e.adb:10:17: warning: "Constraint_Error" will be raised at run time
10662@end example
10663
10664GNAT considers a large number of situations as appropriate
10665for the generation of warning messages. As always, warnings are not
10666definite indications of errors. For example, if you do an out-of-range
10667assignment with the deliberate intention of raising a
10668@code{Constraint_Error} exception, then the warning that may be
10669issued does not indicate an error. Some of the situations for which GNAT
10670issues warnings (at least some of the time) are given in the following
10671list. This list is not complete, and new warnings are often added to
10672subsequent versions of GNAT. The list is intended to give a general idea
10673of the kinds of warnings that are generated.
10674
10675
10676@itemize *
10677
10678@item
10679Possible infinitely recursive calls
10680
10681@item
10682Out-of-range values being assigned
10683
10684@item
10685Possible order of elaboration problems
10686
10687@item
10688Size not a multiple of alignment for a record type
10689
10690@item
10691Assertions (pragma Assert) that are sure to fail
10692
10693@item
10694Unreachable code
10695
10696@item
10697Address clauses with possibly unaligned values, or where an attempt is
10698made to overlay a smaller variable with a larger one.
10699
10700@item
10701Fixed-point type declarations with a null range
10702
10703@item
10704Direct_IO or Sequential_IO instantiated with a type that has access values
10705
10706@item
10707Variables that are never assigned a value
10708
10709@item
10710Variables that are referenced before being initialized
10711
10712@item
10713Task entries with no corresponding @code{accept} statement
10714
10715@item
10716Duplicate accepts for the same task entry in a @code{select}
10717
10718@item
10719Objects that take too much storage
10720
10721@item
10722Unchecked conversion between types of differing sizes
10723
10724@item
10725Missing @code{return} statement along some execution path in a function
10726
10727@item
10728Incorrect (unrecognized) pragmas
10729
10730@item
10731Incorrect external names
10732
10733@item
10734Allocation from empty storage pool
10735
10736@item
10737Potentially blocking operation in protected type
10738
10739@item
10740Suspicious parenthesization of expressions
10741
10742@item
10743Mismatching bounds in an aggregate
10744
10745@item
10746Attempt to return local value by reference
10747
10748@item
10749Premature instantiation of a generic body
10750
10751@item
10752Attempt to pack aliased components
10753
10754@item
10755Out of bounds array subscripts
10756
10757@item
10758Wrong length on string assignment
10759
10760@item
10761Violations of style rules if style checking is enabled
10762
10763@item
10764Unused @emph{with} clauses
10765
10766@item
10767@code{Bit_Order} usage that does not have any effect
10768
10769@item
10770@code{Standard.Duration} used to resolve universal fixed expression
10771
10772@item
10773Dereference of possibly null value
10774
10775@item
10776Declaration that is likely to cause storage error
10777
10778@item
10779Internal GNAT unit @emph{with}ed by application unit
10780
10781@item
10782Values known to be out of range at compile time
10783
10784@item
10785Unreferenced or unmodified variables. Note that a special
10786exemption applies to variables which contain any of the substrings
10787@code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
10788are considered likely to be intentionally used in a situation where
10789otherwise a warning would be given, so warnings of this kind are
10790always suppressed for such variables.
10791
10792@item
10793Address overlays that could clobber memory
10794
10795@item
10796Unexpected initialization when address clause present
10797
10798@item
10799Bad alignment for address clause
10800
10801@item
10802Useless type conversions
10803
10804@item
10805Redundant assignment statements and other redundant constructs
10806
10807@item
10808Useless exception handlers
10809
10810@item
10811Accidental hiding of name by child unit
10812
10813@item
10814Access before elaboration detected at compile time
10815
10816@item
10817A range in a @code{for} loop that is known to be null or might be null
10818@end itemize
10819
10820The following section lists compiler switches that are available
10821to control the handling of warning messages. It is also possible
10822to exercise much finer control over what warnings are issued and
10823suppressed using the GNAT pragma Warnings (see the description
10824of the pragma in the @cite{GNAT_Reference_manual}).
10825
10826@geindex -gnatwa (gcc)
10827
10828
10829@table @asis
10830
10831@item @code{-gnatwa}
10832
10833@emph{Activate most optional warnings.}
10834
10835This switch activates most optional warning messages.  See the remaining list
10836in this section for details on optional warning messages that can be
10837individually controlled.  The warnings that are not turned on by this
10838switch are:
10839
10840
10841@itemize *
10842
10843@item
10844@code{-gnatwd} (implicit dereferencing)
10845
10846@item
10847@code{-gnatw.d} (tag warnings with -gnatw switch)
10848
10849@item
10850@code{-gnatwh} (hiding)
10851
10852@item
10853@code{-gnatw.h} (holes in record layouts)
10854
10855@item
10856@code{-gnatw.j} (late primitives of tagged types)
10857
10858@item
10859@code{-gnatw.k} (redefinition of names in standard)
10860
10861@item
10862@code{-gnatwl} (elaboration warnings)
10863
10864@item
10865@code{-gnatw.l} (inherited aspects)
10866
10867@item
10868@code{-gnatw.n} (atomic synchronization)
10869
10870@item
10871@code{-gnatwo} (address clause overlay)
10872
10873@item
10874@code{-gnatw.o} (values set by out parameters ignored)
10875
10876@item
10877@code{-gnatw.q} (questionable layout of record types)
10878
10879@item
10880@code{-gnatw.s} (overridden size clause)
10881
10882@item
10883@code{-gnatwt} (tracking of deleted conditional code)
10884
10885@item
10886@code{-gnatw.u} (unordered enumeration)
10887
10888@item
10889@code{-gnatw.w} (use of Warnings Off)
10890
10891@item
10892@code{-gnatw.y} (reasons for package needing body)
10893@end itemize
10894
10895All other optional warnings are turned on.
10896@end table
10897
10898@geindex -gnatwA (gcc)
10899
10900
10901@table @asis
10902
10903@item @code{-gnatwA}
10904
10905@emph{Suppress all optional errors.}
10906
10907This switch suppresses all optional warning messages, see remaining list
10908in this section for details on optional warning messages that can be
10909individually controlled. Note that unlike switch @code{-gnatws}, the
10910use of switch @code{-gnatwA} does not suppress warnings that are
10911normally given unconditionally and cannot be individually controlled
10912(for example, the warning about a missing exit path in a function).
10913Also, again unlike switch @code{-gnatws}, warnings suppressed by
10914the use of switch @code{-gnatwA} can be individually turned back
10915on. For example the use of switch @code{-gnatwA} followed by
10916switch @code{-gnatwd} will suppress all optional warnings except
10917the warnings for implicit dereferencing.
10918@end table
10919
10920@geindex -gnatw.a (gcc)
10921
10922
10923@table @asis
10924
10925@item @code{-gnatw.a}
10926
10927@emph{Activate warnings on failing assertions.}
10928
10929@geindex Assert failures
10930
10931This switch activates warnings for assertions where the compiler can tell at
10932compile time that the assertion will fail. Note that this warning is given
10933even if assertions are disabled. The default is that such warnings are
10934generated.
10935@end table
10936
10937@geindex -gnatw.A (gcc)
10938
10939
10940@table @asis
10941
10942@item @code{-gnatw.A}
10943
10944@emph{Suppress warnings on failing assertions.}
10945
10946@geindex Assert failures
10947
10948This switch suppresses warnings for assertions where the compiler can tell at
10949compile time that the assertion will fail.
10950@end table
10951
10952@geindex -gnatwb (gcc)
10953
10954
10955@table @asis
10956
10957@item @code{-gnatwb}
10958
10959@emph{Activate warnings on bad fixed values.}
10960
10961@geindex Bad fixed values
10962
10963@geindex Fixed-point Small value
10964
10965@geindex Small value
10966
10967This switch activates warnings for static fixed-point expressions whose
10968value is not an exact multiple of Small. Such values are implementation
10969dependent, since an implementation is free to choose either of the multiples
10970that surround the value. GNAT always chooses the closer one, but this is not
10971required behavior, and it is better to specify a value that is an exact
10972multiple, ensuring predictable execution. The default is that such warnings
10973are not generated.
10974@end table
10975
10976@geindex -gnatwB (gcc)
10977
10978
10979@table @asis
10980
10981@item @code{-gnatwB}
10982
10983@emph{Suppress warnings on bad fixed values.}
10984
10985This switch suppresses warnings for static fixed-point expressions whose
10986value is not an exact multiple of Small.
10987@end table
10988
10989@geindex -gnatw.b (gcc)
10990
10991
10992@table @asis
10993
10994@item @code{-gnatw.b}
10995
10996@emph{Activate warnings on biased representation.}
10997
10998@geindex Biased representation
10999
11000This switch activates warnings when a size clause, value size clause, component
11001clause, or component size clause forces the use of biased representation for an
11002integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
11003to represent 10/11). The default is that such warnings are generated.
11004@end table
11005
11006@geindex -gnatwB (gcc)
11007
11008
11009@table @asis
11010
11011@item @code{-gnatw.B}
11012
11013@emph{Suppress warnings on biased representation.}
11014
11015This switch suppresses warnings for representation clauses that force the use
11016of biased representation.
11017@end table
11018
11019@geindex -gnatwc (gcc)
11020
11021
11022@table @asis
11023
11024@item @code{-gnatwc}
11025
11026@emph{Activate warnings on conditionals.}
11027
11028@geindex Conditionals
11029@geindex constant
11030
11031This switch activates warnings for conditional expressions used in
11032tests that are known to be True or False at compile time. The default
11033is that such warnings are not generated.
11034Note that this warning does
11035not get issued for the use of boolean variables or constants whose
11036values are known at compile time, since this is a standard technique
11037for conditional compilation in Ada, and this would generate too many
11038false positive warnings.
11039
11040This warning option also activates a special test for comparisons using
11041the operators '>=' and' <='.
11042If the compiler can tell that only the equality condition is possible,
11043then it will warn that the '>' or '<' part of the test
11044is useless and that the operator could be replaced by '='.
11045An example would be comparing a @code{Natural} variable <= 0.
11046
11047This warning option also generates warnings if
11048one or both tests is optimized away in a membership test for integer
11049values if the result can be determined at compile time. Range tests on
11050enumeration types are not included, since it is common for such tests
11051to include an end point.
11052
11053This warning can also be turned on using @code{-gnatwa}.
11054@end table
11055
11056@geindex -gnatwC (gcc)
11057
11058
11059@table @asis
11060
11061@item @code{-gnatwC}
11062
11063@emph{Suppress warnings on conditionals.}
11064
11065This switch suppresses warnings for conditional expressions used in
11066tests that are known to be True or False at compile time.
11067@end table
11068
11069@geindex -gnatw.c (gcc)
11070
11071
11072@table @asis
11073
11074@item @code{-gnatw.c}
11075
11076@emph{Activate warnings on missing component clauses.}
11077
11078@geindex Component clause
11079@geindex missing
11080
11081This switch activates warnings for record components where a record
11082representation clause is present and has component clauses for the
11083majority, but not all, of the components. A warning is given for each
11084component for which no component clause is present.
11085@end table
11086
11087@geindex -gnatwC (gcc)
11088
11089
11090@table @asis
11091
11092@item @code{-gnatw.C}
11093
11094@emph{Suppress warnings on missing component clauses.}
11095
11096This switch suppresses warnings for record components that are
11097missing a component clause in the situation described above.
11098@end table
11099
11100@geindex -gnatwd (gcc)
11101
11102
11103@table @asis
11104
11105@item @code{-gnatwd}
11106
11107@emph{Activate warnings on implicit dereferencing.}
11108
11109If this switch is set, then the use of a prefix of an access type
11110in an indexed component, slice, or selected component without an
11111explicit @code{.all} will generate a warning. With this warning
11112enabled, access checks occur only at points where an explicit
11113@code{.all} appears in the source code (assuming no warnings are
11114generated as a result of this switch). The default is that such
11115warnings are not generated.
11116@end table
11117
11118@geindex -gnatwD (gcc)
11119
11120
11121@table @asis
11122
11123@item @code{-gnatwD}
11124
11125@emph{Suppress warnings on implicit dereferencing.}
11126
11127@geindex Implicit dereferencing
11128
11129@geindex Dereferencing
11130@geindex implicit
11131
11132This switch suppresses warnings for implicit dereferences in
11133indexed components, slices, and selected components.
11134@end table
11135
11136@geindex -gnatw.d (gcc)
11137
11138
11139@table @asis
11140
11141@item @code{-gnatw.d}
11142
11143@emph{Activate tagging of warning and info messages.}
11144
11145If this switch is set, then warning messages are tagged, with one of the
11146following strings:
11147
11148@quotation
11149
11150
11151@itemize -
11152
11153@item
11154@emph{[-gnatw?]}
11155Used to tag warnings controlled by the switch @code{-gnatwx} where x
11156is a letter a-z.
11157
11158@item
11159@emph{[-gnatw.?]}
11160Used to tag warnings controlled by the switch @code{-gnatw.x} where x
11161is a letter a-z.
11162
11163@item
11164@emph{[-gnatel]}
11165Used to tag elaboration information (info) messages generated when the
11166static model of elaboration is used and the @code{-gnatel} switch is set.
11167
11168@item
11169@emph{[restriction warning]}
11170Used to tag warning messages for restriction violations, activated by use
11171of the pragma @code{Restriction_Warnings}.
11172
11173@item
11174@emph{[warning-as-error]}
11175Used to tag warning messages that have been converted to error messages by
11176use of the pragma Warning_As_Error. Note that such warnings are prefixed by
11177the string "error: " rather than "warning: ".
11178
11179@item
11180@emph{[enabled by default]}
11181Used to tag all other warnings that are always given by default, unless
11182warnings are completely suppressed using pragma @emph{Warnings(Off)} or
11183the switch @code{-gnatws}.
11184@end itemize
11185@end quotation
11186@end table
11187
11188@geindex -gnatw.d (gcc)
11189
11190
11191@table @asis
11192
11193@item @code{-gnatw.D}
11194
11195@emph{Deactivate tagging of warning and info messages messages.}
11196
11197If this switch is set, then warning messages return to the default
11198mode in which warnings and info messages are not tagged as described above for
11199@code{-gnatw.d}.
11200@end table
11201
11202@geindex -gnatwe (gcc)
11203
11204@geindex Warnings
11205@geindex treat as error
11206
11207
11208@table @asis
11209
11210@item @code{-gnatwe}
11211
11212@emph{Treat warnings and style checks as errors.}
11213
11214This switch causes warning messages and style check messages to be
11215treated as errors.
11216The warning string still appears, but the warning messages are counted
11217as errors, and prevent the generation of an object file. Note that this
11218is the only -gnatw switch that affects the handling of style check messages.
11219Note also that this switch has no effect on info (information) messages, which
11220are not treated as errors if this switch is present.
11221@end table
11222
11223@geindex -gnatw.e (gcc)
11224
11225
11226@table @asis
11227
11228@item @code{-gnatw.e}
11229
11230@emph{Activate every optional warning.}
11231
11232@geindex Warnings
11233@geindex activate every optional warning
11234
11235This switch activates all optional warnings, including those which
11236are not activated by @code{-gnatwa}. The use of this switch is not
11237recommended for normal use. If you turn this switch on, it is almost
11238certain that you will get large numbers of useless warnings. The
11239warnings that are excluded from @code{-gnatwa} are typically highly
11240specialized warnings that are suitable for use only in code that has
11241been specifically designed according to specialized coding rules.
11242@end table
11243
11244@geindex -gnatwE (gcc)
11245
11246@geindex Warnings
11247@geindex treat as error
11248
11249
11250@table @asis
11251
11252@item @code{-gnatwE}
11253
11254@emph{Treat all run-time exception warnings as errors.}
11255
11256This switch causes warning messages regarding errors that will be raised
11257during run-time execution to be treated as errors.
11258@end table
11259
11260@geindex -gnatwf (gcc)
11261
11262
11263@table @asis
11264
11265@item @code{-gnatwf}
11266
11267@emph{Activate warnings on unreferenced formals.}
11268
11269@geindex Formals
11270@geindex unreferenced
11271
11272This switch causes a warning to be generated if a formal parameter
11273is not referenced in the body of the subprogram. This warning can
11274also be turned on using @code{-gnatwu}. The
11275default is that these warnings are not generated.
11276@end table
11277
11278@geindex -gnatwF (gcc)
11279
11280
11281@table @asis
11282
11283@item @code{-gnatwF}
11284
11285@emph{Suppress warnings on unreferenced formals.}
11286
11287This switch suppresses warnings for unreferenced formal
11288parameters. Note that the
11289combination @code{-gnatwu} followed by @code{-gnatwF} has the
11290effect of warning on unreferenced entities other than subprogram
11291formals.
11292@end table
11293
11294@geindex -gnatwg (gcc)
11295
11296
11297@table @asis
11298
11299@item @code{-gnatwg}
11300
11301@emph{Activate warnings on unrecognized pragmas.}
11302
11303@geindex Pragmas
11304@geindex unrecognized
11305
11306This switch causes a warning to be generated if an unrecognized
11307pragma is encountered. Apart from issuing this warning, the
11308pragma is ignored and has no effect. The default
11309is that such warnings are issued (satisfying the Ada Reference
11310Manual requirement that such warnings appear).
11311@end table
11312
11313@geindex -gnatwG (gcc)
11314
11315
11316@table @asis
11317
11318@item @code{-gnatwG}
11319
11320@emph{Suppress warnings on unrecognized pragmas.}
11321
11322This switch suppresses warnings for unrecognized pragmas.
11323@end table
11324
11325@geindex -gnatw.g (gcc)
11326
11327
11328@table @asis
11329
11330@item @code{-gnatw.g}
11331
11332@emph{Warnings used for GNAT sources.}
11333
11334This switch sets the warning categories that are used by the standard
11335GNAT style. Currently this is equivalent to
11336@code{-gnatwAao.q.s.CI.V.X.Z}
11337but more warnings may be added in the future without advanced notice.
11338@end table
11339
11340@geindex -gnatwh (gcc)
11341
11342
11343@table @asis
11344
11345@item @code{-gnatwh}
11346
11347@emph{Activate warnings on hiding.}
11348
11349@geindex Hiding of Declarations
11350
11351This switch activates warnings on hiding declarations that are considered
11352potentially confusing. Not all cases of hiding cause warnings; for example an
11353overriding declaration hides an implicit declaration, which is just normal
11354code. The default is that warnings on hiding are not generated.
11355@end table
11356
11357@geindex -gnatwH (gcc)
11358
11359
11360@table @asis
11361
11362@item @code{-gnatwH}
11363
11364@emph{Suppress warnings on hiding.}
11365
11366This switch suppresses warnings on hiding declarations.
11367@end table
11368
11369@geindex -gnatw.h (gcc)
11370
11371
11372@table @asis
11373
11374@item @code{-gnatw.h}
11375
11376@emph{Activate warnings on holes/gaps in records.}
11377
11378@geindex Record Representation (gaps)
11379
11380This switch activates warnings on component clauses in record
11381representation clauses that leave holes (gaps) in the record layout.
11382If this warning option is active, then record representation clauses
11383should specify a contiguous layout, adding unused fill fields if needed.
11384@end table
11385
11386@geindex -gnatw.H (gcc)
11387
11388
11389@table @asis
11390
11391@item @code{-gnatw.H}
11392
11393@emph{Suppress warnings on holes/gaps in records.}
11394
11395This switch suppresses warnings on component clauses in record
11396representation clauses that leave holes (haps) in the record layout.
11397@end table
11398
11399@geindex -gnatwi (gcc)
11400
11401
11402@table @asis
11403
11404@item @code{-gnatwi}
11405
11406@emph{Activate warnings on implementation units.}
11407
11408This switch activates warnings for a @emph{with} of an internal GNAT
11409implementation unit, defined as any unit from the @code{Ada},
11410@code{Interfaces}, @code{GNAT},
11411or @code{System}
11412hierarchies that is not
11413documented in either the Ada Reference Manual or the GNAT
11414Programmer's Reference Manual. Such units are intended only
11415for internal implementation purposes and should not be @emph{with}ed
11416by user programs. The default is that such warnings are generated
11417@end table
11418
11419@geindex -gnatwI (gcc)
11420
11421
11422@table @asis
11423
11424@item @code{-gnatwI}
11425
11426@emph{Disable warnings on implementation units.}
11427
11428This switch disables warnings for a @emph{with} of an internal GNAT
11429implementation unit.
11430@end table
11431
11432@geindex -gnatw.i (gcc)
11433
11434
11435@table @asis
11436
11437@item @code{-gnatw.i}
11438
11439@emph{Activate warnings on overlapping actuals.}
11440
11441This switch enables a warning on statically detectable overlapping actuals in
11442a subprogram call, when one of the actuals is an in-out parameter, and the
11443types of the actuals are not by-copy types. This warning is off by default.
11444@end table
11445
11446@geindex -gnatw.I (gcc)
11447
11448
11449@table @asis
11450
11451@item @code{-gnatw.I}
11452
11453@emph{Disable warnings on overlapping actuals.}
11454
11455This switch disables warnings on overlapping actuals in a call..
11456@end table
11457
11458@geindex -gnatwj (gcc)
11459
11460
11461@table @asis
11462
11463@item @code{-gnatwj}
11464
11465@emph{Activate warnings on obsolescent features (Annex J).}
11466
11467@geindex Features
11468@geindex obsolescent
11469
11470@geindex Obsolescent features
11471
11472If this warning option is activated, then warnings are generated for
11473calls to subprograms marked with @code{pragma Obsolescent} and
11474for use of features in Annex J of the Ada Reference Manual. In the
11475case of Annex J, not all features are flagged. In particular use
11476of the renamed packages (like @code{Text_IO}) and use of package
11477@code{ASCII} are not flagged, since these are very common and
11478would generate many annoying positive warnings. The default is that
11479such warnings are not generated.
11480
11481In addition to the above cases, warnings are also generated for
11482GNAT features that have been provided in past versions but which
11483have been superseded (typically by features in the new Ada standard).
11484For example, @code{pragma Ravenscar} will be flagged since its
11485function is replaced by @code{pragma Profile(Ravenscar)}, and
11486@code{pragma Interface_Name} will be flagged since its function
11487is replaced by @code{pragma Import}.
11488
11489Note that this warning option functions differently from the
11490restriction @code{No_Obsolescent_Features} in two respects.
11491First, the restriction applies only to annex J features.
11492Second, the restriction does flag uses of package @code{ASCII}.
11493@end table
11494
11495@geindex -gnatwJ (gcc)
11496
11497
11498@table @asis
11499
11500@item @code{-gnatwJ}
11501
11502@emph{Suppress warnings on obsolescent features (Annex J).}
11503
11504This switch disables warnings on use of obsolescent features.
11505@end table
11506
11507@geindex -gnatw.j (gcc)
11508
11509
11510@table @asis
11511
11512@item @code{-gnatw.j}
11513
11514@emph{Activate warnings on late declarations of tagged type primitives.}
11515
11516This switch activates warnings on visible primitives added to a
11517tagged type after deriving a private extension from it.
11518@end table
11519
11520@geindex -gnatw.J (gcc)
11521
11522
11523@table @asis
11524
11525@item @code{-gnatw.J}
11526
11527@emph{Suppress warnings on late declarations of tagged type primitives.}
11528
11529This switch suppresses warnings on visible primitives added to a
11530tagged type after deriving a private extension from it.
11531@end table
11532
11533@geindex -gnatwk (gcc)
11534
11535
11536@table @asis
11537
11538@item @code{-gnatwk}
11539
11540@emph{Activate warnings on variables that could be constants.}
11541
11542This switch activates warnings for variables that are initialized but
11543never modified, and then could be declared constants. The default is that
11544such warnings are not given.
11545@end table
11546
11547@geindex -gnatwK (gcc)
11548
11549
11550@table @asis
11551
11552@item @code{-gnatwK}
11553
11554@emph{Suppress warnings on variables that could be constants.}
11555
11556This switch disables warnings on variables that could be declared constants.
11557@end table
11558
11559@geindex -gnatw.k (gcc)
11560
11561
11562@table @asis
11563
11564@item @code{-gnatw.k}
11565
11566@emph{Activate warnings on redefinition of names in standard.}
11567
11568This switch activates warnings for declarations that declare a name that
11569is defined in package Standard. Such declarations can be confusing,
11570especially since the names in package Standard continue to be directly
11571visible, meaning that use visibiliy on such redeclared names does not
11572work as expected. Names of discriminants and components in records are
11573not included in this check.
11574@end table
11575
11576@geindex -gnatwK (gcc)
11577
11578
11579@table @asis
11580
11581@item @code{-gnatw.K}
11582
11583@emph{Suppress warnings on redefinition of names in standard.}
11584
11585This switch activates warnings for declarations that declare a name that
11586is defined in package Standard.
11587@end table
11588
11589@geindex -gnatwl (gcc)
11590
11591
11592@table @asis
11593
11594@item @code{-gnatwl}
11595
11596@emph{Activate warnings for elaboration pragmas.}
11597
11598@geindex Elaboration
11599@geindex warnings
11600
11601This switch activates warnings for possible elaboration problems,
11602including suspicious use
11603of @code{Elaborate} pragmas, when using the static elaboration model, and
11604possible situations that may raise @code{Program_Error} when using the
11605dynamic elaboration model.
11606See the section in this guide on elaboration checking for further details.
11607The default is that such warnings
11608are not generated.
11609@end table
11610
11611@geindex -gnatwL (gcc)
11612
11613
11614@table @asis
11615
11616@item @code{-gnatwL}
11617
11618@emph{Suppress warnings for elaboration pragmas.}
11619
11620This switch suppresses warnings for possible elaboration problems.
11621@end table
11622
11623@geindex -gnatw.l (gcc)
11624
11625
11626@table @asis
11627
11628@item @code{-gnatw.l}
11629
11630@emph{List inherited aspects.}
11631
11632This switch causes the compiler to list inherited invariants,
11633preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
11634Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
11635@end table
11636
11637@geindex -gnatw.L (gcc)
11638
11639
11640@table @asis
11641
11642@item @code{-gnatw.L}
11643
11644@emph{Suppress listing of inherited aspects.}
11645
11646This switch suppresses listing of inherited aspects.
11647@end table
11648
11649@geindex -gnatwm (gcc)
11650
11651
11652@table @asis
11653
11654@item @code{-gnatwm}
11655
11656@emph{Activate warnings on modified but unreferenced variables.}
11657
11658This switch activates warnings for variables that are assigned (using
11659an initialization value or with one or more assignment statements) but
11660whose value is never read. The warning is suppressed for volatile
11661variables and also for variables that are renamings of other variables
11662or for which an address clause is given.
11663The default is that these warnings are not given.
11664@end table
11665
11666@geindex -gnatwM (gcc)
11667
11668
11669@table @asis
11670
11671@item @code{-gnatwM}
11672
11673@emph{Disable warnings on modified but unreferenced variables.}
11674
11675This switch disables warnings for variables that are assigned or
11676initialized, but never read.
11677@end table
11678
11679@geindex -gnatw.m (gcc)
11680
11681
11682@table @asis
11683
11684@item @code{-gnatw.m}
11685
11686@emph{Activate warnings on suspicious modulus values.}
11687
11688This switch activates warnings for modulus values that seem suspicious.
11689The cases caught are where the size is the same as the modulus (e.g.
11690a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
11691with no size clause. The guess in both cases is that 2**x was intended
11692rather than x. In addition expressions of the form 2*x for small x
11693generate a warning (the almost certainly accurate guess being that
116942**x was intended). The default is that these warnings are given.
11695@end table
11696
11697@geindex -gnatw.M (gcc)
11698
11699
11700@table @asis
11701
11702@item @code{-gnatw.M}
11703
11704@emph{Disable warnings on suspicious modulus values.}
11705
11706This switch disables warnings for suspicious modulus values.
11707@end table
11708
11709@geindex -gnatwn (gcc)
11710
11711
11712@table @asis
11713
11714@item @code{-gnatwn}
11715
11716@emph{Set normal warnings mode.}
11717
11718This switch sets normal warning mode, in which enabled warnings are
11719issued and treated as warnings rather than errors. This is the default
11720mode. the switch @code{-gnatwn} can be used to cancel the effect of
11721an explicit @code{-gnatws} or
11722@code{-gnatwe}. It also cancels the effect of the
11723implicit @code{-gnatwe} that is activated by the
11724use of @code{-gnatg}.
11725@end table
11726
11727@geindex -gnatw.n (gcc)
11728
11729@geindex Atomic Synchronization
11730@geindex warnings
11731
11732
11733@table @asis
11734
11735@item @code{-gnatw.n}
11736
11737@emph{Activate warnings on atomic synchronization.}
11738
11739This switch actives warnings when an access to an atomic variable
11740requires the generation of atomic synchronization code. These
11741warnings are off by default.
11742@end table
11743
11744@geindex -gnatw.N (gcc)
11745
11746
11747@table @asis
11748
11749@item @code{-gnatw.N}
11750
11751@emph{Suppress warnings on atomic synchronization.}
11752
11753@geindex Atomic Synchronization
11754@geindex warnings
11755
11756This switch suppresses warnings when an access to an atomic variable
11757requires the generation of atomic synchronization code.
11758@end table
11759
11760@geindex -gnatwo (gcc)
11761
11762@geindex Address Clauses
11763@geindex warnings
11764
11765
11766@table @asis
11767
11768@item @code{-gnatwo}
11769
11770@emph{Activate warnings on address clause overlays.}
11771
11772This switch activates warnings for possibly unintended initialization
11773effects of defining address clauses that cause one variable to overlap
11774another. The default is that such warnings are generated.
11775@end table
11776
11777@geindex -gnatwO (gcc)
11778
11779
11780@table @asis
11781
11782@item @code{-gnatwO}
11783
11784@emph{Suppress warnings on address clause overlays.}
11785
11786This switch suppresses warnings on possibly unintended initialization
11787effects of defining address clauses that cause one variable to overlap
11788another.
11789@end table
11790
11791@geindex -gnatw.o (gcc)
11792
11793
11794@table @asis
11795
11796@item @code{-gnatw.o}
11797
11798@emph{Activate warnings on modified but unreferenced out parameters.}
11799
11800This switch activates warnings for variables that are modified by using
11801them as actuals for a call to a procedure with an out mode formal, where
11802the resulting assigned value is never read. It is applicable in the case
11803where there is more than one out mode formal. If there is only one out
11804mode formal, the warning is issued by default (controlled by -gnatwu).
11805The warning is suppressed for volatile
11806variables and also for variables that are renamings of other variables
11807or for which an address clause is given.
11808The default is that these warnings are not given.
11809@end table
11810
11811@geindex -gnatw.O (gcc)
11812
11813
11814@table @asis
11815
11816@item @code{-gnatw.O}
11817
11818@emph{Disable warnings on modified but unreferenced out parameters.}
11819
11820This switch suppresses warnings for variables that are modified by using
11821them as actuals for a call to a procedure with an out mode formal, where
11822the resulting assigned value is never read.
11823@end table
11824
11825@geindex -gnatwp (gcc)
11826
11827@geindex Inlining
11828@geindex warnings
11829
11830
11831@table @asis
11832
11833@item @code{-gnatwp}
11834
11835@emph{Activate warnings on ineffective pragma Inlines.}
11836
11837This switch activates warnings for failure of front end inlining
11838(activated by @code{-gnatN}) to inline a particular call. There are
11839many reasons for not being able to inline a call, including most
11840commonly that the call is too complex to inline. The default is
11841that such warnings are not given.
11842Warnings on ineffective inlining by the gcc back-end can be activated
11843separately, using the gcc switch -Winline.
11844@end table
11845
11846@geindex -gnatwP (gcc)
11847
11848
11849@table @asis
11850
11851@item @code{-gnatwP}
11852
11853@emph{Suppress warnings on ineffective pragma Inlines.}
11854
11855This switch suppresses warnings on ineffective pragma Inlines. If the
11856inlining mechanism cannot inline a call, it will simply ignore the
11857request silently.
11858@end table
11859
11860@geindex -gnatw.p (gcc)
11861
11862@geindex Parameter order
11863@geindex warnings
11864
11865
11866@table @asis
11867
11868@item @code{-gnatw.p}
11869
11870@emph{Activate warnings on parameter ordering.}
11871
11872This switch activates warnings for cases of suspicious parameter
11873ordering when the list of arguments are all simple identifiers that
11874match the names of the formals, but are in a different order. The
11875warning is suppressed if any use of named parameter notation is used,
11876so this is the appropriate way to suppress a false positive (and
11877serves to emphasize that the "misordering" is deliberate). The
11878default is that such warnings are not given.
11879@end table
11880
11881@geindex -gnatw.P (gcc)
11882
11883
11884@table @asis
11885
11886@item @code{-gnatw.P}
11887
11888@emph{Suppress warnings on parameter ordering.}
11889
11890This switch suppresses warnings on cases of suspicious parameter
11891ordering.
11892@end table
11893
11894@geindex -gnatwq (gcc)
11895
11896@geindex Parentheses
11897@geindex warnings
11898
11899
11900@table @asis
11901
11902@item @code{-gnatwq}
11903
11904@emph{Activate warnings on questionable missing parentheses.}
11905
11906This switch activates warnings for cases where parentheses are not used and
11907the result is potential ambiguity from a readers point of view. For example
11908(not a > b) when a and b are modular means ((not a) > b) and very likely the
11909programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
11910quite likely ((-x) mod 5) was intended. In such situations it seems best to
11911follow the rule of always parenthesizing to make the association clear, and
11912this warning switch warns if such parentheses are not present. The default
11913is that these warnings are given.
11914@end table
11915
11916@geindex -gnatwQ (gcc)
11917
11918
11919@table @asis
11920
11921@item @code{-gnatwQ}
11922
11923@emph{Suppress warnings on questionable missing parentheses.}
11924
11925This switch suppresses warnings for cases where the association is not
11926clear and the use of parentheses is preferred.
11927@end table
11928
11929@geindex -gnatw.q (gcc)
11930
11931@geindex Layout
11932@geindex warnings
11933
11934
11935@table @asis
11936
11937@item @code{-gnatw.q}
11938
11939@emph{Activate warnings on questionable layout of record types.}
11940
11941This switch activates warnings for cases where the default layout of
11942a record type, that is to say the layout of its components in textual
11943order of the source code, would very likely cause inefficiencies in
11944the code generated by the compiler, both in terms of space and speed
11945during execution. One warning is issued for each problematic component
11946without representation clause in the nonvariant part and then in each
11947variant recursively, if any.
11948
11949The purpose of these warnings is neither to prescribe an optimal layout
11950nor to force the use of representation clauses, but rather to get rid of
11951the most blatant inefficiencies in the layout. Therefore, the default
11952layout is matched against the following synthetic ordered layout and
11953the deviations are flagged on a component-by-component basis:
11954
11955
11956@itemize *
11957
11958@item
11959first all components or groups of components whose length is fixed
11960and a multiple of the storage unit,
11961
11962@item
11963then the remaining components whose length is fixed and not a multiple
11964of the storage unit,
11965
11966@item
11967then the remaining components whose length doesn't depend on discriminants
11968(that is to say, with variable but uniform length for all objects),
11969
11970@item
11971then all components whose length depends on discriminants,
11972
11973@item
11974finally the variant part (if any),
11975@end itemize
11976
11977for the nonvariant part and for each variant recursively, if any.
11978
11979The exact wording of the warning depends on whether the compiler is allowed
11980to reorder the components in the record type or precluded from doing it by
11981means of pragma @code{No_Component_Reordering}.
11982
11983The default is that these warnings are not given.
11984@end table
11985
11986@geindex -gnatw.Q (gcc)
11987
11988
11989@table @asis
11990
11991@item @code{-gnatw.Q}
11992
11993@emph{Suppress warnings on questionable layout of record types.}
11994
11995This switch suppresses warnings for cases where the default layout of
11996a record type would very likely cause inefficiencies.
11997@end table
11998
11999@geindex -gnatwr (gcc)
12000
12001
12002@table @asis
12003
12004@item @code{-gnatwr}
12005
12006@emph{Activate warnings on redundant constructs.}
12007
12008This switch activates warnings for redundant constructs. The following
12009is the current list of constructs regarded as redundant:
12010
12011
12012@itemize *
12013
12014@item
12015Assignment of an item to itself.
12016
12017@item
12018Type conversion that converts an expression to its own type.
12019
12020@item
12021Use of the attribute @code{Base} where @code{typ'Base} is the same
12022as @code{typ}.
12023
12024@item
12025Use of pragma @code{Pack} when all components are placed by a record
12026representation clause.
12027
12028@item
12029Exception handler containing only a reraise statement (raise with no
12030operand) which has no effect.
12031
12032@item
12033Use of the operator abs on an operand that is known at compile time
12034to be non-negative
12035
12036@item
12037Comparison of an object or (unary or binary) operation of boolean type to
12038an explicit True value.
12039@end itemize
12040
12041The default is that warnings for redundant constructs are not given.
12042@end table
12043
12044@geindex -gnatwR (gcc)
12045
12046
12047@table @asis
12048
12049@item @code{-gnatwR}
12050
12051@emph{Suppress warnings on redundant constructs.}
12052
12053This switch suppresses warnings for redundant constructs.
12054@end table
12055
12056@geindex -gnatw.r (gcc)
12057
12058
12059@table @asis
12060
12061@item @code{-gnatw.r}
12062
12063@emph{Activate warnings for object renaming function.}
12064
12065This switch activates warnings for an object renaming that renames a
12066function call, which is equivalent to a constant declaration (as
12067opposed to renaming the function itself).  The default is that these
12068warnings are given.
12069@end table
12070
12071@geindex -gnatwT (gcc)
12072
12073
12074@table @asis
12075
12076@item @code{-gnatw.R}
12077
12078@emph{Suppress warnings for object renaming function.}
12079
12080This switch suppresses warnings for object renaming function.
12081@end table
12082
12083@geindex -gnatws (gcc)
12084
12085
12086@table @asis
12087
12088@item @code{-gnatws}
12089
12090@emph{Suppress all warnings.}
12091
12092This switch completely suppresses the
12093output of all warning messages from the GNAT front end, including
12094both warnings that can be controlled by switches described in this
12095section, and those that are normally given unconditionally. The
12096effect of this suppress action can only be cancelled by a subsequent
12097use of the switch @code{-gnatwn}.
12098
12099Note that switch @code{-gnatws} does not suppress
12100warnings from the @code{gcc} back end.
12101To suppress these back end warnings as well, use the switch @code{-w}
12102in addition to @code{-gnatws}. Also this switch has no effect on the
12103handling of style check messages.
12104@end table
12105
12106@geindex -gnatw.s (gcc)
12107
12108@geindex Record Representation (component sizes)
12109
12110
12111@table @asis
12112
12113@item @code{-gnatw.s}
12114
12115@emph{Activate warnings on overridden size clauses.}
12116
12117This switch activates warnings on component clauses in record
12118representation clauses where the length given overrides that
12119specified by an explicit size clause for the component type. A
12120warning is similarly given in the array case if a specified
12121component size overrides an explicit size clause for the array
12122component type.
12123@end table
12124
12125@geindex -gnatw.S (gcc)
12126
12127
12128@table @asis
12129
12130@item @code{-gnatw.S}
12131
12132@emph{Suppress warnings on overridden size clauses.}
12133
12134This switch suppresses warnings on component clauses in record
12135representation clauses that override size clauses, and similar
12136warnings when an array component size overrides a size clause.
12137@end table
12138
12139@geindex -gnatwt (gcc)
12140
12141@geindex Deactivated code
12142@geindex warnings
12143
12144@geindex Deleted code
12145@geindex warnings
12146
12147
12148@table @asis
12149
12150@item @code{-gnatwt}
12151
12152@emph{Activate warnings for tracking of deleted conditional code.}
12153
12154This switch activates warnings for tracking of code in conditionals (IF and
12155CASE statements) that is detected to be dead code which cannot be executed, and
12156which is removed by the front end. This warning is off by default. This may be
12157useful for detecting deactivated code in certified applications.
12158@end table
12159
12160@geindex -gnatwT (gcc)
12161
12162
12163@table @asis
12164
12165@item @code{-gnatwT}
12166
12167@emph{Suppress warnings for tracking of deleted conditional code.}
12168
12169This switch suppresses warnings for tracking of deleted conditional code.
12170@end table
12171
12172@geindex -gnatw.t (gcc)
12173
12174
12175@table @asis
12176
12177@item @code{-gnatw.t}
12178
12179@emph{Activate warnings on suspicious contracts.}
12180
12181This switch activates warnings on suspicious contracts. This includes
12182warnings on suspicious postconditions (whether a pragma @code{Postcondition} or a
12183@code{Post} aspect in Ada 2012) and suspicious contract cases (pragma or aspect
12184@code{Contract_Cases}). A function postcondition or contract case is suspicious
12185when no postcondition or contract case for this function mentions the result
12186of the function.  A procedure postcondition or contract case is suspicious
12187when it only refers to the pre-state of the procedure, because in that case
12188it should rather be expressed as a precondition. This switch also controls
12189warnings on suspicious cases of expressions typically found in contracts like
12190quantified expressions and uses of Update attribute. The default is that such
12191warnings are generated.
12192@end table
12193
12194@geindex -gnatw.T (gcc)
12195
12196
12197@table @asis
12198
12199@item @code{-gnatw.T}
12200
12201@emph{Suppress warnings on suspicious contracts.}
12202
12203This switch suppresses warnings on suspicious contracts.
12204@end table
12205
12206@geindex -gnatwu (gcc)
12207
12208
12209@table @asis
12210
12211@item @code{-gnatwu}
12212
12213@emph{Activate warnings on unused entities.}
12214
12215This switch activates warnings to be generated for entities that
12216are declared but not referenced, and for units that are @emph{with}ed
12217and not
12218referenced. In the case of packages, a warning is also generated if
12219no entities in the package are referenced. This means that if a with'ed
12220package is referenced but the only references are in @code{use}
12221clauses or @code{renames}
12222declarations, a warning is still generated. A warning is also generated
12223for a generic package that is @emph{with}ed but never instantiated.
12224In the case where a package or subprogram body is compiled, and there
12225is a @emph{with} on the corresponding spec
12226that is only referenced in the body,
12227a warning is also generated, noting that the
12228@emph{with} can be moved to the body. The default is that
12229such warnings are not generated.
12230This switch also activates warnings on unreferenced formals
12231(it includes the effect of @code{-gnatwf}).
12232@end table
12233
12234@geindex -gnatwU (gcc)
12235
12236
12237@table @asis
12238
12239@item @code{-gnatwU}
12240
12241@emph{Suppress warnings on unused entities.}
12242
12243This switch suppresses warnings for unused entities and packages.
12244It also turns off warnings on unreferenced formals (and thus includes
12245the effect of @code{-gnatwF}).
12246@end table
12247
12248@geindex -gnatw.u (gcc)
12249
12250
12251@table @asis
12252
12253@item @code{-gnatw.u}
12254
12255@emph{Activate warnings on unordered enumeration types.}
12256
12257This switch causes enumeration types to be considered as conceptually
12258unordered, unless an explicit pragma @code{Ordered} is given for the type.
12259The effect is to generate warnings in clients that use explicit comparisons
12260or subranges, since these constructs both treat objects of the type as
12261ordered. (A @emph{client} is defined as a unit that is other than the unit in
12262which the type is declared, or its body or subunits.) Please refer to
12263the description of pragma @code{Ordered} in the
12264@cite{GNAT Reference Manual} for further details.
12265The default is that such warnings are not generated.
12266@end table
12267
12268@geindex -gnatw.U (gcc)
12269
12270
12271@table @asis
12272
12273@item @code{-gnatw.U}
12274
12275@emph{Deactivate warnings on unordered enumeration types.}
12276
12277This switch causes all enumeration types to be considered as ordered, so
12278that no warnings are given for comparisons or subranges for any type.
12279@end table
12280
12281@geindex -gnatwv (gcc)
12282
12283@geindex Unassigned variable warnings
12284
12285
12286@table @asis
12287
12288@item @code{-gnatwv}
12289
12290@emph{Activate warnings on unassigned variables.}
12291
12292This switch activates warnings for access to variables which
12293may not be properly initialized. The default is that
12294such warnings are generated.
12295@end table
12296
12297@geindex -gnatwV (gcc)
12298
12299
12300@table @asis
12301
12302@item @code{-gnatwV}
12303
12304@emph{Suppress warnings on unassigned variables.}
12305
12306This switch suppresses warnings for access to variables which
12307may not be properly initialized.
12308For variables of a composite type, the warning can also be suppressed in
12309Ada 2005 by using a default initialization with a box. For example, if
12310Table is an array of records whose components are only partially uninitialized,
12311then the following code:
12312
12313@example
12314Tab : Table := (others => <>);
12315@end example
12316
12317will suppress warnings on subsequent statements that access components
12318of variable Tab.
12319@end table
12320
12321@geindex -gnatw.v (gcc)
12322
12323@geindex bit order warnings
12324
12325
12326@table @asis
12327
12328@item @code{-gnatw.v}
12329
12330@emph{Activate info messages for non-default bit order.}
12331
12332This switch activates messages (labeled "info", they are not warnings,
12333just informational messages) about the effects of non-default bit-order
12334on records to which a component clause is applied. The effect of specifying
12335non-default bit ordering is a bit subtle (and changed with Ada 2005), so
12336these messages, which are given by default, are useful in understanding the
12337exact consequences of using this feature.
12338@end table
12339
12340@geindex -gnatw.V (gcc)
12341
12342
12343@table @asis
12344
12345@item @code{-gnatw.V}
12346
12347@emph{Suppress info messages for non-default bit order.}
12348
12349This switch suppresses information messages for the effects of specifying
12350non-default bit order on record components with component clauses.
12351@end table
12352
12353@geindex -gnatww (gcc)
12354
12355@geindex String indexing warnings
12356
12357
12358@table @asis
12359
12360@item @code{-gnatww}
12361
12362@emph{Activate warnings on wrong low bound assumption.}
12363
12364This switch activates warnings for indexing an unconstrained string parameter
12365with a literal or S'Length. This is a case where the code is assuming that the
12366low bound is one, which is in general not true (for example when a slice is
12367passed). The default is that such warnings are generated.
12368@end table
12369
12370@geindex -gnatwW (gcc)
12371
12372
12373@table @asis
12374
12375@item @code{-gnatwW}
12376
12377@emph{Suppress warnings on wrong low bound assumption.}
12378
12379This switch suppresses warnings for indexing an unconstrained string parameter
12380with a literal or S'Length. Note that this warning can also be suppressed
12381in a particular case by adding an assertion that the lower bound is 1,
12382as shown in the following example:
12383
12384@example
12385procedure K (S : String) is
12386   pragma Assert (S'First = 1);
12387   ...
12388@end example
12389@end table
12390
12391@geindex -gnatw.w (gcc)
12392
12393@geindex Warnings Off control
12394
12395
12396@table @asis
12397
12398@item @code{-gnatw.w}
12399
12400@emph{Activate warnings on Warnings Off pragmas.}
12401
12402This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
12403where either the pragma is entirely useless (because it suppresses no
12404warnings), or it could be replaced by @code{pragma Unreferenced} or
12405@code{pragma Unmodified}.
12406Also activates warnings for the case of
12407Warnings (Off, String), where either there is no matching
12408Warnings (On, String), or the Warnings (Off) did not suppress any warning.
12409The default is that these warnings are not given.
12410@end table
12411
12412@geindex -gnatw.W (gcc)
12413
12414
12415@table @asis
12416
12417@item @code{-gnatw.W}
12418
12419@emph{Suppress warnings on unnecessary Warnings Off pragmas.}
12420
12421This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
12422@end table
12423
12424@geindex -gnatwx (gcc)
12425
12426@geindex Export/Import pragma warnings
12427
12428
12429@table @asis
12430
12431@item @code{-gnatwx}
12432
12433@emph{Activate warnings on Export/Import pragmas.}
12434
12435This switch activates warnings on Export/Import pragmas when
12436the compiler detects a possible conflict between the Ada and
12437foreign language calling sequences. For example, the use of
12438default parameters in a convention C procedure is dubious
12439because the C compiler cannot supply the proper default, so
12440a warning is issued. The default is that such warnings are
12441generated.
12442@end table
12443
12444@geindex -gnatwX (gcc)
12445
12446
12447@table @asis
12448
12449@item @code{-gnatwX}
12450
12451@emph{Suppress warnings on Export/Import pragmas.}
12452
12453This switch suppresses warnings on Export/Import pragmas.
12454The sense of this is that you are telling the compiler that
12455you know what you are doing in writing the pragma, and it
12456should not complain at you.
12457@end table
12458
12459@geindex -gnatwm (gcc)
12460
12461
12462@table @asis
12463
12464@item @code{-gnatw.x}
12465
12466@emph{Activate warnings for No_Exception_Propagation mode.}
12467
12468This switch activates warnings for exception usage when pragma Restrictions
12469(No_Exception_Propagation) is in effect. Warnings are given for implicit or
12470explicit exception raises which are not covered by a local handler, and for
12471exception handlers which do not cover a local raise. The default is that
12472these warnings are given for units that contain exception handlers.
12473
12474@item @code{-gnatw.X}
12475
12476@emph{Disable warnings for No_Exception_Propagation mode.}
12477
12478This switch disables warnings for exception usage when pragma Restrictions
12479(No_Exception_Propagation) is in effect.
12480@end table
12481
12482@geindex -gnatwy (gcc)
12483
12484@geindex Ada compatibility issues warnings
12485
12486
12487@table @asis
12488
12489@item @code{-gnatwy}
12490
12491@emph{Activate warnings for Ada compatibility issues.}
12492
12493For the most part, newer versions of Ada are upwards compatible
12494with older versions. For example, Ada 2005 programs will almost
12495always work when compiled as Ada 2012.
12496However there are some exceptions (for example the fact that
12497@code{some} is now a reserved word in Ada 2012). This
12498switch activates several warnings to help in identifying
12499and correcting such incompatibilities. The default is that
12500these warnings are generated. Note that at one point Ada 2005
12501was called Ada 0Y, hence the choice of character.
12502@end table
12503
12504@geindex -gnatwY (gcc)
12505
12506@geindex Ada compatibility issues warnings
12507
12508
12509@table @asis
12510
12511@item @code{-gnatwY}
12512
12513@emph{Disable warnings for Ada compatibility issues.}
12514
12515This switch suppresses the warnings intended to help in identifying
12516incompatibilities between Ada language versions.
12517@end table
12518
12519@geindex -gnatw.y (gcc)
12520
12521@geindex Package spec needing body
12522
12523
12524@table @asis
12525
12526@item @code{-gnatw.y}
12527
12528@emph{Activate information messages for why package spec needs body.}
12529
12530There are a number of cases in which a package spec needs a body.
12531For example, the use of pragma Elaborate_Body, or the declaration
12532of a procedure specification requiring a completion. This switch
12533causes information messages to be output showing why a package
12534specification requires a body. This can be useful in the case of
12535a large package specification which is unexpectedly requiring a
12536body. The default is that such information messages are not output.
12537@end table
12538
12539@geindex -gnatw.Y (gcc)
12540
12541@geindex No information messages for why package spec needs body
12542
12543
12544@table @asis
12545
12546@item @code{-gnatw.Y}
12547
12548@emph{Disable information messages for why package spec needs body.}
12549
12550This switch suppresses the output of information messages showing why
12551a package specification needs a body.
12552@end table
12553
12554@geindex -gnatwz (gcc)
12555
12556@geindex Unchecked_Conversion warnings
12557
12558
12559@table @asis
12560
12561@item @code{-gnatwz}
12562
12563@emph{Activate warnings on unchecked conversions.}
12564
12565This switch activates warnings for unchecked conversions
12566where the types are known at compile time to have different
12567sizes. The default is that such warnings are generated. Warnings are also
12568generated for subprogram pointers with different conventions.
12569@end table
12570
12571@geindex -gnatwZ (gcc)
12572
12573
12574@table @asis
12575
12576@item @code{-gnatwZ}
12577
12578@emph{Suppress warnings on unchecked conversions.}
12579
12580This switch suppresses warnings for unchecked conversions
12581where the types are known at compile time to have different
12582sizes or conventions.
12583@end table
12584
12585@geindex -gnatw.z (gcc)
12586
12587@geindex Size/Alignment warnings
12588
12589
12590@table @asis
12591
12592@item @code{-gnatw.z}
12593
12594@emph{Activate warnings for size not a multiple of alignment.}
12595
12596This switch activates warnings for cases of record types with
12597specified @code{Size} and @code{Alignment} attributes where the
12598size is not a multiple of the alignment, resulting in an object
12599size that is greater than the specified size. The default
12600is that such warnings are generated.
12601@end table
12602
12603@geindex -gnatw.Z (gcc)
12604
12605@geindex Size/Alignment warnings
12606
12607
12608@table @asis
12609
12610@item @code{-gnatw.Z}
12611
12612@emph{Suppress warnings for size not a multiple of alignment.}
12613
12614This switch suppresses warnings for cases of record types with
12615specified @code{Size} and @code{Alignment} attributes where the
12616size is not a multiple of the alignment, resulting in an object
12617size that is greater than the specified size.
12618The warning can also be
12619suppressed by giving an explicit @code{Object_Size} value.
12620@end table
12621
12622@geindex -Wunused (gcc)
12623
12624
12625@table @asis
12626
12627@item @code{-Wunused}
12628
12629The warnings controlled by the @code{-gnatw} switch are generated by
12630the front end of the compiler. The GCC back end can provide
12631additional warnings and they are controlled by the @code{-W} switch.
12632For example, @code{-Wunused} activates back end
12633warnings for entities that are declared but not referenced.
12634@end table
12635
12636@geindex -Wuninitialized (gcc)
12637
12638
12639@table @asis
12640
12641@item @code{-Wuninitialized}
12642
12643Similarly, @code{-Wuninitialized} activates
12644the back end warning for uninitialized variables. This switch must be
12645used in conjunction with an optimization level greater than zero.
12646@end table
12647
12648@geindex -Wstack-usage (gcc)
12649
12650
12651@table @asis
12652
12653@item @code{-Wstack-usage=@emph{len}}
12654
12655Warn if the stack usage of a subprogram might be larger than @code{len} bytes.
12656See @ref{f5,,Static Stack Usage Analysis} for details.
12657@end table
12658
12659@geindex -Wall (gcc)
12660
12661
12662@table @asis
12663
12664@item @code{-Wall}
12665
12666This switch enables most warnings from the GCC back end.
12667The code generator detects a number of warning situations that are missed
12668by the GNAT front end, and this switch can be used to activate them.
12669The use of this switch also sets the default front end warning mode to
12670@code{-gnatwa}, that is, most front end warnings activated as well.
12671@end table
12672
12673@geindex -w (gcc)
12674
12675
12676@table @asis
12677
12678@item @code{-w}
12679
12680Conversely, this switch suppresses warnings from the GCC back end.
12681The use of this switch also sets the default front end warning mode to
12682@code{-gnatws}, that is, front end warnings suppressed as well.
12683@end table
12684
12685@geindex -Werror (gcc)
12686
12687
12688@table @asis
12689
12690@item @code{-Werror}
12691
12692This switch causes warnings from the GCC back end to be treated as
12693errors.  The warning string still appears, but the warning messages are
12694counted as errors, and prevent the generation of an object file.
12695@end table
12696
12697A string of warning parameters can be used in the same parameter. For example:
12698
12699@example
12700-gnatwaGe
12701@end example
12702
12703will turn on all optional warnings except for unrecognized pragma warnings,
12704and also specify that warnings should be treated as errors.
12705
12706When no switch @code{-gnatw} is used, this is equivalent to:
12707
12708@quotation
12709
12710
12711@itemize *
12712
12713@item
12714@code{-gnatw.a}
12715
12716@item
12717@code{-gnatwB}
12718
12719@item
12720@code{-gnatw.b}
12721
12722@item
12723@code{-gnatwC}
12724
12725@item
12726@code{-gnatw.C}
12727
12728@item
12729@code{-gnatwD}
12730
12731@item
12732@code{-gnatw.D}
12733
12734@item
12735@code{-gnatwF}
12736
12737@item
12738@code{-gnatw.F}
12739
12740@item
12741@code{-gnatwg}
12742
12743@item
12744@code{-gnatwH}
12745
12746@item
12747@code{-gnatw.H}
12748
12749@item
12750@code{-gnatwi}
12751
12752@item
12753@code{-gnatwJ}
12754
12755@item
12756@code{-gnatw.J}
12757
12758@item
12759@code{-gnatwK}
12760
12761@item
12762@code{-gnatw.K}
12763
12764@item
12765@code{-gnatwL}
12766
12767@item
12768@code{-gnatw.L}
12769
12770@item
12771@code{-gnatwM}
12772
12773@item
12774@code{-gnatw.m}
12775
12776@item
12777@code{-gnatwn}
12778
12779@item
12780@code{-gnatw.N}
12781
12782@item
12783@code{-gnatwo}
12784
12785@item
12786@code{-gnatw.O}
12787
12788@item
12789@code{-gnatwP}
12790
12791@item
12792@code{-gnatw.P}
12793
12794@item
12795@code{-gnatwq}
12796
12797@item
12798@code{-gnatw.Q}
12799
12800@item
12801@code{-gnatwR}
12802
12803@item
12804@code{-gnatw.R}
12805
12806@item
12807@code{-gnatw.S}
12808
12809@item
12810@code{-gnatwT}
12811
12812@item
12813@code{-gnatw.t}
12814
12815@item
12816@code{-gnatwU}
12817
12818@item
12819@code{-gnatw.U}
12820
12821@item
12822@code{-gnatwv}
12823
12824@item
12825@code{-gnatw.v}
12826
12827@item
12828@code{-gnatww}
12829
12830@item
12831@code{-gnatw.W}
12832
12833@item
12834@code{-gnatwx}
12835
12836@item
12837@code{-gnatw.X}
12838
12839@item
12840@code{-gnatwy}
12841
12842@item
12843@code{-gnatw.Y}
12844
12845@item
12846@code{-gnatwz}
12847
12848@item
12849@code{-gnatw.z}
12850@end itemize
12851@end quotation
12852
12853@node Debugging and Assertion Control,Validity Checking,Warning Message Control,Compiler Switches
12854@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}
12855@subsection Debugging and Assertion Control
12856
12857
12858@geindex -gnata (gcc)
12859
12860
12861@table @asis
12862
12863@item @code{-gnata}
12864
12865@geindex Assert
12866
12867@geindex Debug
12868
12869@geindex Assertions
12870
12871@geindex Precondition
12872
12873@geindex Postcondition
12874
12875@geindex Type invariants
12876
12877@geindex Subtype predicates
12878
12879The @code{-gnata} option is equivalent to the following @code{Assertion_Policy} pragma:
12880
12881@example
12882pragma Assertion_Policy (Check);
12883@end example
12884
12885Which is a shorthand for:
12886
12887@example
12888pragma Assertion_Policy
12889  (Assert               => Check,
12890   Static_Predicate     => Check,
12891   Dynamic_Predicate    => Check,
12892   Pre                  => Check,
12893   Pre'Class            => Check,
12894   Post                 => Check,
12895   Post'Class           => Check,
12896   Type_Invariant       => Check,
12897   Type_Invariant'Class => Check);
12898@end example
12899
12900The pragmas @code{Assert} and @code{Debug} normally have no effect and
12901are ignored. This switch, where @code{a} stands for 'assert', causes
12902pragmas @code{Assert} and @code{Debug} to be activated. This switch also
12903causes preconditions, postconditions, subtype predicates, and
12904type invariants to be activated.
12905
12906The pragmas have the form:
12907
12908@example
12909pragma Assert (<Boolean-expression> [, <static-string-expression>])
12910pragma Debug (<procedure call>)
12911pragma Type_Invariant (<type-local-name>, <Boolean-expression>)
12912pragma Predicate (<type-local-name>, <Boolean-expression>)
12913pragma Precondition (<Boolean-expression>, <string-expression>)
12914pragma Postcondition (<Boolean-expression>, <string-expression>)
12915@end example
12916
12917The aspects have the form:
12918
12919@example
12920with [Pre|Post|Type_Invariant|Dynamic_Predicate|Static_Predicate]
12921  => <Boolean-expression>;
12922@end example
12923
12924The @code{Assert} pragma causes @code{Boolean-expression} to be tested.
12925If the result is @code{True}, the pragma has no effect (other than
12926possible side effects from evaluating the expression). If the result is
12927@code{False}, the exception @code{Assert_Failure} declared in the package
12928@code{System.Assertions} is raised (passing @code{static-string-expression}, if
12929present, as the message associated with the exception). If no string
12930expression is given, the default is a string containing the file name and
12931line number of the pragma.
12932
12933The @code{Debug} pragma causes @code{procedure} to be called. Note that
12934@code{pragma Debug} may appear within a declaration sequence, allowing
12935debugging procedures to be called between declarations.
12936
12937For the aspect specification, the @code{Boolean-expression} is evaluated.
12938If the result is @code{True}, the aspect has no effect. If the result
12939is @code{False}, the exception @code{Assert_Failure} is raised.
12940@end table
12941
12942@node Validity Checking,Style Checking,Debugging and Assertion Control,Compiler Switches
12943@anchor{gnat_ugn/building_executable_programs_with_gnat validity-checking}@anchor{f6}@anchor{gnat_ugn/building_executable_programs_with_gnat id17}@anchor{102}
12944@subsection Validity Checking
12945
12946
12947@geindex Validity Checking
12948
12949The Ada Reference Manual defines the concept of invalid values (see
12950RM 13.9.1). The primary source of invalid values is uninitialized
12951variables. A scalar variable that is left uninitialized may contain
12952an invalid value; the concept of invalid does not apply to access or
12953composite types.
12954
12955It is an error to read an invalid value, but the RM does not require
12956run-time checks to detect such errors, except for some minimal
12957checking to prevent erroneous execution (i.e. unpredictable
12958behavior). This corresponds to the @code{-gnatVd} switch below,
12959which is the default. For example, by default, if the expression of a
12960case statement is invalid, it will raise Constraint_Error rather than
12961causing a wild jump, and if an array index on the left-hand side of an
12962assignment is invalid, it will raise Constraint_Error rather than
12963overwriting an arbitrary memory location.
12964
12965The @code{-gnatVa} may be used to enable additional validity checks,
12966which are not required by the RM. These checks are often very
12967expensive (which is why the RM does not require them). These checks
12968are useful in tracking down uninitialized variables, but they are
12969not usually recommended for production builds, and in particular
12970we do not recommend using these extra validity checking options in
12971combination with optimization, since this can confuse the optimizer.
12972If performance is a consideration, leading to the need to optimize,
12973then the validity checking options should not be used.
12974
12975The other @code{-gnatV@emph{x}} switches below allow finer-grained
12976control; you can enable whichever validity checks you desire. However,
12977for most debugging purposes, @code{-gnatVa} is sufficient, and the
12978default @code{-gnatVd} (i.e. standard Ada behavior) is usually
12979sufficient for non-debugging use.
12980
12981The @code{-gnatB} switch tells the compiler to assume that all
12982values are valid (that is, within their declared subtype range)
12983except in the context of a use of the Valid attribute. This means
12984the compiler can generate more efficient code, since the range
12985of values is better known at compile time. However, an uninitialized
12986variable can cause wild jumps and memory corruption in this mode.
12987
12988The @code{-gnatV@emph{x}} switch allows control over the validity
12989checking mode as described below.
12990The @code{x} argument is a string of letters that
12991indicate validity checks that are performed or not performed in addition
12992to the default checks required by Ada as described above.
12993
12994@geindex -gnatVa (gcc)
12995
12996
12997@table @asis
12998
12999@item @code{-gnatVa}
13000
13001@emph{All validity checks.}
13002
13003All validity checks are turned on.
13004That is, @code{-gnatVa} is
13005equivalent to @code{gnatVcdfimorst}.
13006@end table
13007
13008@geindex -gnatVc (gcc)
13009
13010
13011@table @asis
13012
13013@item @code{-gnatVc}
13014
13015@emph{Validity checks for copies.}
13016
13017The right hand side of assignments, and the initializing values of
13018object declarations are validity checked.
13019@end table
13020
13021@geindex -gnatVd (gcc)
13022
13023
13024@table @asis
13025
13026@item @code{-gnatVd}
13027
13028@emph{Default (RM) validity checks.}
13029
13030Some validity checks are done by default following normal Ada semantics
13031(RM 13.9.1 (9-11)).
13032A check is done in case statements that the expression is within the range
13033of the subtype. If it is not, Constraint_Error is raised.
13034For assignments to array components, a check is done that the expression used
13035as index is within the range. If it is not, Constraint_Error is raised.
13036Both these validity checks may be turned off using switch @code{-gnatVD}.
13037They are turned on by default. If @code{-gnatVD} is specified, a subsequent
13038switch @code{-gnatVd} will leave the checks turned on.
13039Switch @code{-gnatVD} should be used only if you are sure that all such
13040expressions have valid values. If you use this switch and invalid values
13041are present, then the program is erroneous, and wild jumps or memory
13042overwriting may occur.
13043@end table
13044
13045@geindex -gnatVe (gcc)
13046
13047
13048@table @asis
13049
13050@item @code{-gnatVe}
13051
13052@emph{Validity checks for elementary components.}
13053
13054In the absence of this switch, assignments to record or array components are
13055not validity checked, even if validity checks for assignments generally
13056(@code{-gnatVc}) are turned on. In Ada, assignment of composite values do not
13057require valid data, but assignment of individual components does. So for
13058example, there is a difference between copying the elements of an array with a
13059slice assignment, compared to assigning element by element in a loop. This
13060switch allows you to turn off validity checking for components, even when they
13061are assigned component by component.
13062@end table
13063
13064@geindex -gnatVf (gcc)
13065
13066
13067@table @asis
13068
13069@item @code{-gnatVf}
13070
13071@emph{Validity checks for floating-point values.}
13072
13073In the absence of this switch, validity checking occurs only for discrete
13074values. If @code{-gnatVf} is specified, then validity checking also applies
13075for floating-point values, and NaNs and infinities are considered invalid,
13076as well as out of range values for constrained types. Note that this means
13077that standard IEEE infinity mode is not allowed. The exact contexts
13078in which floating-point values are checked depends on the setting of other
13079options. For example, @code{-gnatVif} or @code{-gnatVfi}
13080(the order does not matter) specifies that floating-point parameters of mode
13081@code{in} should be validity checked.
13082@end table
13083
13084@geindex -gnatVi (gcc)
13085
13086
13087@table @asis
13088
13089@item @code{-gnatVi}
13090
13091@emph{Validity checks for `@w{`}in`@w{`} mode parameters.}
13092
13093Arguments for parameters of mode @code{in} are validity checked in function
13094and procedure calls at the point of call.
13095@end table
13096
13097@geindex -gnatVm (gcc)
13098
13099
13100@table @asis
13101
13102@item @code{-gnatVm}
13103
13104@emph{Validity checks for `@w{`}in out`@w{`} mode parameters.}
13105
13106Arguments for parameters of mode @code{in out} are validity checked in
13107procedure calls at the point of call. The @code{'m'} here stands for
13108modify, since this concerns parameters that can be modified by the call.
13109Note that there is no specific option to test @code{out} parameters,
13110but any reference within the subprogram will be tested in the usual
13111manner, and if an invalid value is copied back, any reference to it
13112will be subject to validity checking.
13113@end table
13114
13115@geindex -gnatVn (gcc)
13116
13117
13118@table @asis
13119
13120@item @code{-gnatVn}
13121
13122@emph{No validity checks.}
13123
13124This switch turns off all validity checking, including the default checking
13125for case statements and left hand side subscripts. Note that the use of
13126the switch @code{-gnatp} suppresses all run-time checks, including
13127validity checks, and thus implies @code{-gnatVn}. When this switch
13128is used, it cancels any other @code{-gnatV} previously issued.
13129@end table
13130
13131@geindex -gnatVo (gcc)
13132
13133
13134@table @asis
13135
13136@item @code{-gnatVo}
13137
13138@emph{Validity checks for operator and attribute operands.}
13139
13140Arguments for predefined operators and attributes are validity checked.
13141This includes all operators in package @code{Standard},
13142the shift operators defined as intrinsic in package @code{Interfaces}
13143and operands for attributes such as @code{Pos}. Checks are also made
13144on individual component values for composite comparisons, and on the
13145expressions in type conversions and qualified expressions. Checks are
13146also made on explicit ranges using @code{..} (e.g., slices, loops etc).
13147@end table
13148
13149@geindex -gnatVp (gcc)
13150
13151
13152@table @asis
13153
13154@item @code{-gnatVp}
13155
13156@emph{Validity checks for parameters.}
13157
13158This controls the treatment of parameters within a subprogram (as opposed
13159to @code{-gnatVi} and @code{-gnatVm} which control validity testing
13160of parameters on a call. If either of these call options is used, then
13161normally an assumption is made within a subprogram that the input arguments
13162have been validity checking at the point of call, and do not need checking
13163again within a subprogram). If @code{-gnatVp} is set, then this assumption
13164is not made, and parameters are not assumed to be valid, so their validity
13165will be checked (or rechecked) within the subprogram.
13166@end table
13167
13168@geindex -gnatVr (gcc)
13169
13170
13171@table @asis
13172
13173@item @code{-gnatVr}
13174
13175@emph{Validity checks for function returns.}
13176
13177The expression in @code{return} statements in functions is validity
13178checked.
13179@end table
13180
13181@geindex -gnatVs (gcc)
13182
13183
13184@table @asis
13185
13186@item @code{-gnatVs}
13187
13188@emph{Validity checks for subscripts.}
13189
13190All subscripts expressions are checked for validity, whether they appear
13191on the right side or left side (in default mode only left side subscripts
13192are validity checked).
13193@end table
13194
13195@geindex -gnatVt (gcc)
13196
13197
13198@table @asis
13199
13200@item @code{-gnatVt}
13201
13202@emph{Validity checks for tests.}
13203
13204Expressions used as conditions in @code{if}, @code{while} or @code{exit}
13205statements are checked, as well as guard expressions in entry calls.
13206@end table
13207
13208The @code{-gnatV} switch may be followed by a string of letters
13209to turn on a series of validity checking options.
13210For example, @code{-gnatVcr}
13211specifies that in addition to the default validity checking, copies and
13212function return expressions are to be validity checked.
13213In order to make it easier to specify the desired combination of effects,
13214the upper case letters @code{CDFIMORST} may
13215be used to turn off the corresponding lower case option.
13216Thus @code{-gnatVaM} turns on all validity checking options except for
13217checking of @code{in out} parameters.
13218
13219The specification of additional validity checking generates extra code (and
13220in the case of @code{-gnatVa} the code expansion can be substantial).
13221However, these additional checks can be very useful in detecting
13222uninitialized variables, incorrect use of unchecked conversion, and other
13223errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
13224is useful in conjunction with the extra validity checking, since this
13225ensures that wherever possible uninitialized variables have invalid values.
13226
13227See also the pragma @code{Validity_Checks} which allows modification of
13228the validity checking mode at the program source level, and also allows for
13229temporary disabling of validity checks.
13230
13231@node Style Checking,Run-Time Checks,Validity Checking,Compiler Switches
13232@anchor{gnat_ugn/building_executable_programs_with_gnat id18}@anchor{103}@anchor{gnat_ugn/building_executable_programs_with_gnat style-checking}@anchor{fb}
13233@subsection Style Checking
13234
13235
13236@geindex Style checking
13237
13238@geindex -gnaty (gcc)
13239
13240The @code{-gnatyx} switch causes the compiler to
13241enforce specified style rules. A limited set of style rules has been used
13242in writing the GNAT sources themselves. This switch allows user programs
13243to activate all or some of these checks. If the source program fails a
13244specified style check, an appropriate message is given, preceded by
13245the character sequence '(style)'. This message does not prevent
13246successful compilation (unless the @code{-gnatwe} switch is used).
13247
13248Note that this is by no means intended to be a general facility for
13249checking arbitrary coding standards. It is simply an embedding of the
13250style rules we have chosen for the GNAT sources. If you are starting
13251a project which does not have established style standards, you may
13252find it useful to adopt the entire set of GNAT coding standards, or
13253some subset of them.
13254
13255
13256The string @code{x} is a sequence of letters or digits
13257indicating the particular style
13258checks to be performed. The following checks are defined:
13259
13260@geindex -gnaty[0-9] (gcc)
13261
13262
13263@table @asis
13264
13265@item @code{-gnaty0}
13266
13267@emph{Specify indentation level.}
13268
13269If a digit from 1-9 appears
13270in the string after @code{-gnaty}
13271then proper indentation is checked, with the digit indicating the
13272indentation level required. A value of zero turns off this style check.
13273The general style of required indentation is as specified by
13274the examples in the Ada Reference Manual. Full line comments must be
13275aligned with the @code{--} starting on a column that is a multiple of
13276the alignment level, or they may be aligned the same way as the following
13277non-blank line (this is useful when full line comments appear in the middle
13278of a statement, or they may be aligned with the source line on the previous
13279non-blank line.
13280@end table
13281
13282@geindex -gnatya (gcc)
13283
13284
13285@table @asis
13286
13287@item @code{-gnatya}
13288
13289@emph{Check attribute casing.}
13290
13291Attribute names, including the case of keywords such as @code{digits}
13292used as attributes names, must be written in mixed case, that is, the
13293initial letter and any letter following an underscore must be uppercase.
13294All other letters must be lowercase.
13295@end table
13296
13297@geindex -gnatyA (gcc)
13298
13299
13300@table @asis
13301
13302@item @code{-gnatyA}
13303
13304@emph{Use of array index numbers in array attributes.}
13305
13306When using the array attributes First, Last, Range,
13307or Length, the index number must be omitted for one-dimensional arrays
13308and is required for multi-dimensional arrays.
13309@end table
13310
13311@geindex -gnatyb (gcc)
13312
13313
13314@table @asis
13315
13316@item @code{-gnatyb}
13317
13318@emph{Blanks not allowed at statement end.}
13319
13320Trailing blanks are not allowed at the end of statements. The purpose of this
13321rule, together with h (no horizontal tabs), is to enforce a canonical format
13322for the use of blanks to separate source tokens.
13323@end table
13324
13325@geindex -gnatyB (gcc)
13326
13327
13328@table @asis
13329
13330@item @code{-gnatyB}
13331
13332@emph{Check Boolean operators.}
13333
13334The use of AND/OR operators is not permitted except in the cases of modular
13335operands, array operands, and simple stand-alone boolean variables or
13336boolean constants. In all other cases @code{and then}/@cite{or else} are
13337required.
13338@end table
13339
13340@geindex -gnatyc (gcc)
13341
13342
13343@table @asis
13344
13345@item @code{-gnatyc}
13346
13347@emph{Check comments, double space.}
13348
13349Comments must meet the following set of rules:
13350
13351
13352@itemize *
13353
13354@item
13355The @code{--} that starts the column must either start in column one,
13356or else at least one blank must precede this sequence.
13357
13358@item
13359Comments that follow other tokens on a line must have at least one blank
13360following the @code{--} at the start of the comment.
13361
13362@item
13363Full line comments must have at least two blanks following the
13364@code{--} that starts the comment, with the following exceptions.
13365
13366@item
13367A line consisting only of the @code{--} characters, possibly preceded
13368by blanks is permitted.
13369
13370@item
13371A comment starting with @code{--x} where @code{x} is a special character
13372is permitted.
13373This allows proper processing of the output from specialized tools
13374such as @code{gnatprep} (where @code{--!} is used) and in earlier versions of the SPARK
13375annotation
13376language (where @code{--#} is used). For the purposes of this rule, a
13377special character is defined as being in one of the ASCII ranges
13378@code{16#21#...16#2F#} or @code{16#3A#...16#3F#}.
13379Note that this usage is not permitted
13380in GNAT implementation units (i.e., when @code{-gnatg} is used).
13381
13382@item
13383A line consisting entirely of minus signs, possibly preceded by blanks, is
13384permitted. This allows the construction of box comments where lines of minus
13385signs are used to form the top and bottom of the box.
13386
13387@item
13388A comment that starts and ends with @code{--} is permitted as long as at
13389least one blank follows the initial @code{--}. Together with the preceding
13390rule, this allows the construction of box comments, as shown in the following
13391example:
13392
13393@example
13394---------------------------
13395-- This is a box comment --
13396-- with two text lines.  --
13397---------------------------
13398@end example
13399@end itemize
13400@end table
13401
13402@geindex -gnatyC (gcc)
13403
13404
13405@table @asis
13406
13407@item @code{-gnatyC}
13408
13409@emph{Check comments, single space.}
13410
13411This is identical to @code{c} except that only one space
13412is required following the @code{--} of a comment instead of two.
13413@end table
13414
13415@geindex -gnatyd (gcc)
13416
13417
13418@table @asis
13419
13420@item @code{-gnatyd}
13421
13422@emph{Check no DOS line terminators present.}
13423
13424All lines must be terminated by a single ASCII.LF
13425character (in particular the DOS line terminator sequence CR/LF is not
13426allowed).
13427@end table
13428
13429@geindex -gnatye (gcc)
13430
13431
13432@table @asis
13433
13434@item @code{-gnatye}
13435
13436@emph{Check end/exit labels.}
13437
13438Optional labels on @code{end} statements ending subprograms and on
13439@code{exit} statements exiting named loops, are required to be present.
13440@end table
13441
13442@geindex -gnatyf (gcc)
13443
13444
13445@table @asis
13446
13447@item @code{-gnatyf}
13448
13449@emph{No form feeds or vertical tabs.}
13450
13451Neither form feeds nor vertical tab characters are permitted
13452in the source text.
13453@end table
13454
13455@geindex -gnatyg (gcc)
13456
13457
13458@table @asis
13459
13460@item @code{-gnatyg}
13461
13462@emph{GNAT style mode.}
13463
13464The set of style check switches is set to match that used by the GNAT sources.
13465This may be useful when developing code that is eventually intended to be
13466incorporated into GNAT. Currently this is equivalent to @code{-gnatwydISux})
13467but additional style switches may be added to this set in the future without
13468advance notice.
13469@end table
13470
13471@geindex -gnatyh (gcc)
13472
13473
13474@table @asis
13475
13476@item @code{-gnatyh}
13477
13478@emph{No horizontal tabs.}
13479
13480Horizontal tab characters are not permitted in the source text.
13481Together with the b (no blanks at end of line) check, this
13482enforces a canonical form for the use of blanks to separate
13483source tokens.
13484@end table
13485
13486@geindex -gnatyi (gcc)
13487
13488
13489@table @asis
13490
13491@item @code{-gnatyi}
13492
13493@emph{Check if-then layout.}
13494
13495The keyword @code{then} must appear either on the same
13496line as corresponding @code{if}, or on a line on its own, lined
13497up under the @code{if}.
13498@end table
13499
13500@geindex -gnatyI (gcc)
13501
13502
13503@table @asis
13504
13505@item @code{-gnatyI}
13506
13507@emph{check mode IN keywords.}
13508
13509Mode @code{in} (the default mode) is not
13510allowed to be given explicitly. @code{in out} is fine,
13511but not @code{in} on its own.
13512@end table
13513
13514@geindex -gnatyk (gcc)
13515
13516
13517@table @asis
13518
13519@item @code{-gnatyk}
13520
13521@emph{Check keyword casing.}
13522
13523All keywords must be in lower case (with the exception of keywords
13524such as @code{digits} used as attribute names to which this check
13525does not apply).
13526@end table
13527
13528@geindex -gnatyl (gcc)
13529
13530
13531@table @asis
13532
13533@item @code{-gnatyl}
13534
13535@emph{Check layout.}
13536
13537Layout of statement and declaration constructs must follow the
13538recommendations in the Ada Reference Manual, as indicated by the
13539form of the syntax rules. For example an @code{else} keyword must
13540be lined up with the corresponding @code{if} keyword.
13541
13542There are two respects in which the style rule enforced by this check
13543option are more liberal than those in the Ada Reference Manual. First
13544in the case of record declarations, it is permissible to put the
13545@code{record} keyword on the same line as the @code{type} keyword, and
13546then the @code{end} in @code{end record} must line up under @code{type}.
13547This is also permitted when the type declaration is split on two lines.
13548For example, any of the following three layouts is acceptable:
13549
13550@example
13551type q is record
13552   a : integer;
13553   b : integer;
13554end record;
13555
13556type q is
13557   record
13558      a : integer;
13559      b : integer;
13560   end record;
13561
13562type q is
13563   record
13564      a : integer;
13565      b : integer;
13566end record;
13567@end example
13568
13569Second, in the case of a block statement, a permitted alternative
13570is to put the block label on the same line as the @code{declare} or
13571@code{begin} keyword, and then line the @code{end} keyword up under
13572the block label. For example both the following are permitted:
13573
13574@example
13575Block : declare
13576   A : Integer := 3;
13577begin
13578   Proc (A, A);
13579end Block;
13580
13581Block :
13582   declare
13583      A : Integer := 3;
13584   begin
13585      Proc (A, A);
13586   end Block;
13587@end example
13588
13589The same alternative format is allowed for loops. For example, both of
13590the following are permitted:
13591
13592@example
13593Clear : while J < 10 loop
13594   A (J) := 0;
13595end loop Clear;
13596
13597Clear :
13598   while J < 10 loop
13599      A (J) := 0;
13600   end loop Clear;
13601@end example
13602@end table
13603
13604@geindex -gnatyLnnn (gcc)
13605
13606
13607@table @asis
13608
13609@item @code{-gnatyL}
13610
13611@emph{Set maximum nesting level.}
13612
13613The maximum level of nesting of constructs (including subprograms, loops,
13614blocks, packages, and conditionals) may not exceed the given value
13615@emph{nnn}. A value of zero disconnects this style check.
13616@end table
13617
13618@geindex -gnatym (gcc)
13619
13620
13621@table @asis
13622
13623@item @code{-gnatym}
13624
13625@emph{Check maximum line length.}
13626
13627The length of source lines must not exceed 79 characters, including
13628any trailing blanks. The value of 79 allows convenient display on an
1362980 character wide device or window, allowing for possible special
13630treatment of 80 character lines. Note that this count is of
13631characters in the source text. This means that a tab character counts
13632as one character in this count and a wide character sequence counts as
13633a single character (however many bytes are needed in the encoding).
13634@end table
13635
13636@geindex -gnatyMnnn (gcc)
13637
13638
13639@table @asis
13640
13641@item @code{-gnatyM}
13642
13643@emph{Set maximum line length.}
13644
13645The length of lines must not exceed the
13646given value @emph{nnn}. The maximum value that can be specified is 32767.
13647If neither style option for setting the line length is used, then the
13648default is 255. This also controls the maximum length of lexical elements,
13649where the only restriction is that they must fit on a single line.
13650@end table
13651
13652@geindex -gnatyn (gcc)
13653
13654
13655@table @asis
13656
13657@item @code{-gnatyn}
13658
13659@emph{Check casing of entities in Standard.}
13660
13661Any identifier from Standard must be cased
13662to match the presentation in the Ada Reference Manual (for example,
13663@code{Integer} and @code{ASCII.NUL}).
13664@end table
13665
13666@geindex -gnatyN (gcc)
13667
13668
13669@table @asis
13670
13671@item @code{-gnatyN}
13672
13673@emph{Turn off all style checks.}
13674
13675All style check options are turned off.
13676@end table
13677
13678@geindex -gnatyo (gcc)
13679
13680
13681@table @asis
13682
13683@item @code{-gnatyo}
13684
13685@emph{Check order of subprogram bodies.}
13686
13687All subprogram bodies in a given scope
13688(e.g., a package body) must be in alphabetical order. The ordering
13689rule uses normal Ada rules for comparing strings, ignoring casing
13690of letters, except that if there is a trailing numeric suffix, then
13691the value of this suffix is used in the ordering (e.g., Junk2 comes
13692before Junk10).
13693@end table
13694
13695@geindex -gnatyO (gcc)
13696
13697
13698@table @asis
13699
13700@item @code{-gnatyO}
13701
13702@emph{Check that overriding subprograms are explicitly marked as such.}
13703
13704This applies to all subprograms of a derived type that override a primitive
13705operation of the type, for both tagged and untagged types. In particular,
13706the declaration of a primitive operation of a type extension that overrides
13707an inherited operation must carry an overriding indicator. Another case is
13708the declaration of a function that overrides a predefined operator (such
13709as an equality operator).
13710@end table
13711
13712@geindex -gnatyp (gcc)
13713
13714
13715@table @asis
13716
13717@item @code{-gnatyp}
13718
13719@emph{Check pragma casing.}
13720
13721Pragma names must be written in mixed case, that is, the
13722initial letter and any letter following an underscore must be uppercase.
13723All other letters must be lowercase. An exception is that SPARK_Mode is
13724allowed as an alternative for Spark_Mode.
13725@end table
13726
13727@geindex -gnatyr (gcc)
13728
13729
13730@table @asis
13731
13732@item @code{-gnatyr}
13733
13734@emph{Check references.}
13735
13736All identifier references must be cased in the same way as the
13737corresponding declaration. No specific casing style is imposed on
13738identifiers. The only requirement is for consistency of references
13739with declarations.
13740@end table
13741
13742@geindex -gnatys (gcc)
13743
13744
13745@table @asis
13746
13747@item @code{-gnatys}
13748
13749@emph{Check separate specs.}
13750
13751Separate declarations ('specs') are required for subprograms (a
13752body is not allowed to serve as its own declaration). The only
13753exception is that parameterless library level procedures are
13754not required to have a separate declaration. This exception covers
13755the most frequent form of main program procedures.
13756@end table
13757
13758@geindex -gnatyS (gcc)
13759
13760
13761@table @asis
13762
13763@item @code{-gnatyS}
13764
13765@emph{Check no statements after then/else.}
13766
13767No statements are allowed
13768on the same line as a @code{then} or @code{else} keyword following the
13769keyword in an @code{if} statement. @code{or else} and @code{and then} are not
13770affected, and a special exception allows a pragma to appear after @code{else}.
13771@end table
13772
13773@geindex -gnatyt (gcc)
13774
13775
13776@table @asis
13777
13778@item @code{-gnatyt}
13779
13780@emph{Check token spacing.}
13781
13782The following token spacing rules are enforced:
13783
13784
13785@itemize *
13786
13787@item
13788The keywords @code{abs} and @code{not} must be followed by a space.
13789
13790@item
13791The token @code{=>} must be surrounded by spaces.
13792
13793@item
13794The token @code{<>} must be preceded by a space or a left parenthesis.
13795
13796@item
13797Binary operators other than @code{**} must be surrounded by spaces.
13798There is no restriction on the layout of the @code{**} binary operator.
13799
13800@item
13801Colon must be surrounded by spaces.
13802
13803@item
13804Colon-equal (assignment, initialization) must be surrounded by spaces.
13805
13806@item
13807Comma must be the first non-blank character on the line, or be
13808immediately preceded by a non-blank character, and must be followed
13809by a space.
13810
13811@item
13812If the token preceding a left parenthesis ends with a letter or digit, then
13813a space must separate the two tokens.
13814
13815@item
13816If the token following a right parenthesis starts with a letter or digit, then
13817a space must separate the two tokens.
13818
13819@item
13820A right parenthesis must either be the first non-blank character on
13821a line, or it must be preceded by a non-blank character.
13822
13823@item
13824A semicolon must not be preceded by a space, and must not be followed by
13825a non-blank character.
13826
13827@item
13828A unary plus or minus may not be followed by a space.
13829
13830@item
13831A vertical bar must be surrounded by spaces.
13832@end itemize
13833
13834Exactly one blank (and no other white space) must appear between
13835a @code{not} token and a following @code{in} token.
13836@end table
13837
13838@geindex -gnatyu (gcc)
13839
13840
13841@table @asis
13842
13843@item @code{-gnatyu}
13844
13845@emph{Check unnecessary blank lines.}
13846
13847Unnecessary blank lines are not allowed. A blank line is considered
13848unnecessary if it appears at the end of the file, or if more than
13849one blank line occurs in sequence.
13850@end table
13851
13852@geindex -gnatyx (gcc)
13853
13854
13855@table @asis
13856
13857@item @code{-gnatyx}
13858
13859@emph{Check extra parentheses.}
13860
13861Unnecessary extra level of parentheses (C-style) are not allowed
13862around conditions in @code{if} statements, @code{while} statements and
13863@code{exit} statements.
13864@end table
13865
13866@geindex -gnatyy (gcc)
13867
13868
13869@table @asis
13870
13871@item @code{-gnatyy}
13872
13873@emph{Set all standard style check options.}
13874
13875This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
13876options enabled with the exception of @code{-gnatyB}, @code{-gnatyd},
13877@code{-gnatyI}, @code{-gnatyLnnn}, @code{-gnatyo}, @code{-gnatyO},
13878@code{-gnatyS}, @code{-gnatyu}, and @code{-gnatyx}.
13879@end table
13880
13881@geindex -gnaty- (gcc)
13882
13883
13884@table @asis
13885
13886@item @code{-gnaty-}
13887
13888@emph{Remove style check options.}
13889
13890This causes any subsequent options in the string to act as canceling the
13891corresponding style check option. To cancel maximum nesting level control,
13892use the @code{L} parameter without any integer value after that, because any
13893digit following @emph{-} in the parameter string of the @code{-gnaty}
13894option will be treated as canceling the indentation check. The same is true
13895for the @code{M} parameter. @code{y} and @code{N} parameters are not
13896allowed after @emph{-}.
13897@end table
13898
13899@geindex -gnaty+ (gcc)
13900
13901
13902@table @asis
13903
13904@item @code{-gnaty+}
13905
13906@emph{Enable style check options.}
13907
13908This causes any subsequent options in the string to enable the corresponding
13909style check option. That is, it cancels the effect of a previous -,
13910if any.
13911@end table
13912
13913@c end of switch description (leave this comment to ease automatic parsing for
13914
13915@c GPS
13916
13917In the above rules, appearing in column one is always permitted, that is,
13918counts as meeting either a requirement for a required preceding space,
13919or as meeting a requirement for no preceding space.
13920
13921Appearing at the end of a line is also always permitted, that is, counts
13922as meeting either a requirement for a following space, or as meeting
13923a requirement for no following space.
13924
13925If any of these style rules is violated, a message is generated giving
13926details on the violation. The initial characters of such messages are
13927always '@cite{(style)}'. Note that these messages are treated as warning
13928messages, so they normally do not prevent the generation of an object
13929file. The @code{-gnatwe} switch can be used to treat warning messages,
13930including style messages, as fatal errors.
13931
13932The switch @code{-gnaty} on its own (that is not
13933followed by any letters or digits) is equivalent
13934to the use of @code{-gnatyy} as described above, that is all
13935built-in standard style check options are enabled.
13936
13937The switch @code{-gnatyN} clears any previously set style checks.
13938
13939@node Run-Time Checks,Using gcc for Syntax Checking,Style Checking,Compiler Switches
13940@anchor{gnat_ugn/building_executable_programs_with_gnat run-time-checks}@anchor{f9}@anchor{gnat_ugn/building_executable_programs_with_gnat id19}@anchor{104}
13941@subsection Run-Time Checks
13942
13943
13944@geindex Division by zero
13945
13946@geindex Access before elaboration
13947
13948@geindex Checks
13949@geindex division by zero
13950
13951@geindex Checks
13952@geindex access before elaboration
13953
13954@geindex Checks
13955@geindex stack overflow checking
13956
13957By default, the following checks are suppressed: stack overflow
13958checks, and checks for access before elaboration on subprogram
13959calls. All other checks, including overflow checks, range checks and
13960array bounds checks, are turned on by default. The following @code{gcc}
13961switches refine this default behavior.
13962
13963@geindex -gnatp (gcc)
13964
13965
13966@table @asis
13967
13968@item @code{-gnatp}
13969
13970@geindex Suppressing checks
13971
13972@geindex Checks
13973@geindex suppressing
13974
13975This switch causes the unit to be compiled
13976as though @code{pragma Suppress (All_checks)}
13977had been present in the source. Validity checks are also eliminated (in
13978other words @code{-gnatp} also implies @code{-gnatVn}.
13979Use this switch to improve the performance
13980of the code at the expense of safety in the presence of invalid data or
13981program bugs.
13982
13983Note that when checks are suppressed, the compiler is allowed, but not
13984required, to omit the checking code. If the run-time cost of the
13985checking code is zero or near-zero, the compiler will generate it even
13986if checks are suppressed. In particular, if the compiler can prove
13987that a certain check will necessarily fail, it will generate code to
13988do an unconditional 'raise', even if checks are suppressed. The
13989compiler warns in this case. Another case in which checks may not be
13990eliminated is when they are embedded in certain run time routines such
13991as math library routines.
13992
13993Of course, run-time checks are omitted whenever the compiler can prove
13994that they will not fail, whether or not checks are suppressed.
13995
13996Note that if you suppress a check that would have failed, program
13997execution is erroneous, which means the behavior is totally
13998unpredictable. The program might crash, or print wrong answers, or
13999do anything else. It might even do exactly what you wanted it to do
14000(and then it might start failing mysteriously next week or next
14001year). The compiler will generate code based on the assumption that
14002the condition being checked is true, which can result in erroneous
14003execution if that assumption is wrong.
14004
14005The checks subject to suppression include all the checks defined by the Ada
14006standard, the additional implementation defined checks @code{Alignment_Check},
14007@code{Duplicated_Tag_Check}, @code{Predicate_Check}, @code{Container_Checks}, @code{Tampering_Check},
14008and @code{Validity_Check}, as well as any checks introduced using @code{pragma Check_Name}.
14009Note that @code{Atomic_Synchronization} is not automatically suppressed by use of this option.
14010
14011If the code depends on certain checks being active, you can use
14012pragma @code{Unsuppress} either as a configuration pragma or as
14013a local pragma to make sure that a specified check is performed
14014even if @code{gnatp} is specified.
14015
14016The @code{-gnatp} switch has no effect if a subsequent
14017@code{-gnat-p} switch appears.
14018@end table
14019
14020@geindex -gnat-p (gcc)
14021
14022@geindex Suppressing checks
14023
14024@geindex Checks
14025@geindex suppressing
14026
14027@geindex Suppress
14028
14029
14030@table @asis
14031
14032@item @code{-gnat-p}
14033
14034This switch cancels the effect of a previous @code{gnatp} switch.
14035@end table
14036
14037@geindex -gnato?? (gcc)
14038
14039@geindex Overflow checks
14040
14041@geindex Overflow mode
14042
14043@geindex Check
14044@geindex overflow
14045
14046
14047@table @asis
14048
14049@item @code{-gnato??}
14050
14051This switch controls the mode used for computing intermediate
14052arithmetic integer operations, and also enables overflow checking.
14053For a full description of overflow mode and checking control, see
14054the 'Overflow Check Handling in GNAT' appendix in this
14055User's Guide.
14056
14057Overflow checks are always enabled by this switch. The argument
14058controls the mode, using the codes
14059
14060
14061@table @asis
14062
14063@item @emph{1 = STRICT}
14064
14065In STRICT mode, intermediate operations are always done using the
14066base type, and overflow checking ensures that the result is within
14067the base type range.
14068
14069@item @emph{2 = MINIMIZED}
14070
14071In MINIMIZED mode, overflows in intermediate operations are avoided
14072where possible by using a larger integer type for the computation
14073(typically @code{Long_Long_Integer}). Overflow checking ensures that
14074the result fits in this larger integer type.
14075
14076@item @emph{3 = ELIMINATED}
14077
14078In ELIMINATED mode, overflows in intermediate operations are avoided
14079by using multi-precision arithmetic. In this case, overflow checking
14080has no effect on intermediate operations (since overflow is impossible).
14081@end table
14082
14083If two digits are present after @code{-gnato} then the first digit
14084sets the mode for expressions outside assertions, and the second digit
14085sets the mode for expressions within assertions. Here assertions is used
14086in the technical sense (which includes for example precondition and
14087postcondition expressions).
14088
14089If one digit is present, the corresponding mode is applicable to both
14090expressions within and outside assertion expressions.
14091
14092If no digits are present, the default is to enable overflow checks
14093and set STRICT mode for both kinds of expressions. This is compatible
14094with the use of @code{-gnato} in previous versions of GNAT.
14095
14096@geindex Machine_Overflows
14097
14098Note that the @code{-gnato??} switch does not affect the code generated
14099for any floating-point operations; it applies only to integer semantics.
14100For floating-point, GNAT has the @code{Machine_Overflows}
14101attribute set to @code{False} and the normal mode of operation is to
14102generate IEEE NaN and infinite values on overflow or invalid operations
14103(such as dividing 0.0 by 0.0).
14104
14105The reason that we distinguish overflow checking from other kinds of
14106range constraint checking is that a failure of an overflow check, unlike
14107for example the failure of a range check, can result in an incorrect
14108value, but cannot cause random memory destruction (like an out of range
14109subscript), or a wild jump (from an out of range case value). Overflow
14110checking is also quite expensive in time and space, since in general it
14111requires the use of double length arithmetic.
14112
14113Note again that the default is @code{-gnato11} (equivalent to @code{-gnato1}),
14114so overflow checking is performed in STRICT mode by default.
14115@end table
14116
14117@geindex -gnatE (gcc)
14118
14119@geindex Elaboration checks
14120
14121@geindex Check
14122@geindex elaboration
14123
14124
14125@table @asis
14126
14127@item @code{-gnatE}
14128
14129Enables dynamic checks for access-before-elaboration
14130on subprogram calls and generic instantiations.
14131Note that @code{-gnatE} is not necessary for safety, because in the
14132default mode, GNAT ensures statically that the checks would not fail.
14133For full details of the effect and use of this switch,
14134@ref{1c,,Compiling with gcc}.
14135@end table
14136
14137@geindex -fstack-check (gcc)
14138
14139@geindex Stack Overflow Checking
14140
14141@geindex Checks
14142@geindex stack overflow checking
14143
14144
14145@table @asis
14146
14147@item @code{-fstack-check}
14148
14149Activates stack overflow checking. For full details of the effect and use of
14150this switch see @ref{f4,,Stack Overflow Checking}.
14151@end table
14152
14153@geindex Unsuppress
14154
14155The setting of these switches only controls the default setting of the
14156checks. You may modify them using either @code{Suppress} (to remove
14157checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
14158the program source.
14159
14160@node Using gcc for Syntax Checking,Using gcc for Semantic Checking,Run-Time Checks,Compiler Switches
14161@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}
14162@subsection Using @code{gcc} for Syntax Checking
14163
14164
14165@geindex -gnats (gcc)
14166
14167
14168@table @asis
14169
14170@item @code{-gnats}
14171
14172The @code{s} stands for 'syntax'.
14173
14174Run GNAT in syntax checking only mode. For
14175example, the command
14176
14177@example
14178$ gcc -c -gnats x.adb
14179@end example
14180
14181compiles file @code{x.adb} in syntax-check-only mode. You can check a
14182series of files in a single command
14183, and can use wild cards to specify such a group of files.
14184Note that you must specify the @code{-c} (compile
14185only) flag in addition to the @code{-gnats} flag.
14186
14187You may use other switches in conjunction with @code{-gnats}. In
14188particular, @code{-gnatl} and @code{-gnatv} are useful to control the
14189format of any generated error messages.
14190
14191When the source file is empty or contains only empty lines and/or comments,
14192the output is a warning:
14193
14194@example
14195$ gcc -c -gnats -x ada toto.txt
14196toto.txt:1:01: warning: empty file, contains no compilation units
14197$
14198@end example
14199
14200Otherwise, the output is simply the error messages, if any. No object file or
14201ALI file is generated by a syntax-only compilation. Also, no units other
14202than the one specified are accessed. For example, if a unit @code{X}
14203@emph{with}s a unit @code{Y}, compiling unit @code{X} in syntax
14204check only mode does not access the source file containing unit
14205@code{Y}.
14206
14207@geindex Multiple units
14208@geindex syntax checking
14209
14210Normally, GNAT allows only a single unit in a source file. However, this
14211restriction does not apply in syntax-check-only mode, and it is possible
14212to check a file containing multiple compilation units concatenated
14213together. This is primarily used by the @code{gnatchop} utility
14214(@ref{36,,Renaming Files with gnatchop}).
14215@end table
14216
14217@node Using gcc for Semantic Checking,Compiling Different Versions of Ada,Using gcc for Syntax Checking,Compiler Switches
14218@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}
14219@subsection Using @code{gcc} for Semantic Checking
14220
14221
14222@geindex -gnatc (gcc)
14223
14224
14225@table @asis
14226
14227@item @code{-gnatc}
14228
14229The @code{c} stands for 'check'.
14230Causes the compiler to operate in semantic check mode,
14231with full checking for all illegalities specified in the
14232Ada Reference Manual, but without generation of any object code
14233(no object file is generated).
14234
14235Because dependent files must be accessed, you must follow the GNAT
14236semantic restrictions on file structuring to operate in this mode:
14237
14238
14239@itemize *
14240
14241@item
14242The needed source files must be accessible
14243(see @ref{89,,Search Paths and the Run-Time Library (RTL)}).
14244
14245@item
14246Each file must contain only one compilation unit.
14247
14248@item
14249The file name and unit name must match (@ref{52,,File Naming Rules}).
14250@end itemize
14251
14252The output consists of error messages as appropriate. No object file is
14253generated. An @code{ALI} file is generated for use in the context of
14254cross-reference tools, but this file is marked as not being suitable
14255for binding (since no object file is generated).
14256The checking corresponds exactly to the notion of
14257legality in the Ada Reference Manual.
14258
14259Any unit can be compiled in semantics-checking-only mode, including
14260units that would not normally be compiled (subunits,
14261and specifications where a separate body is present).
14262@end table
14263
14264@node Compiling Different Versions of Ada,Character Set Control,Using gcc for Semantic Checking,Compiler Switches
14265@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}
14266@subsection Compiling Different Versions of Ada
14267
14268
14269The switches described in this section allow you to explicitly specify
14270the version of the Ada language that your programs are written in.
14271The default mode is Ada 2012,
14272but you can also specify Ada 95, Ada 2005 mode, or
14273indicate Ada 83 compatibility mode.
14274
14275@geindex Compatibility with Ada 83
14276
14277@geindex -gnat83 (gcc)
14278
14279@geindex ACVC
14280@geindex Ada 83 tests
14281
14282@geindex Ada 83 mode
14283
14284
14285@table @asis
14286
14287@item @code{-gnat83} (Ada 83 Compatibility Mode)
14288
14289Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
14290specifies that the program is to be compiled in Ada 83 mode. With
14291@code{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
14292semantics where this can be done easily.
14293It is not possible to guarantee this switch does a perfect
14294job; some subtle tests, such as are
14295found in earlier ACVC tests (and that have been removed from the ACATS suite
14296for Ada 95), might not compile correctly.
14297Nevertheless, this switch may be useful in some circumstances, for example
14298where, due to contractual reasons, existing code needs to be maintained
14299using only Ada 83 features.
14300
14301With few exceptions (most notably the need to use @code{<>} on
14302unconstrained
14303@geindex Generic formal parameters
14304generic formal parameters,
14305the use of the new Ada 95 / Ada 2005
14306reserved words, and the use of packages
14307with optional bodies), it is not necessary to specify the
14308@code{-gnat83} switch when compiling Ada 83 programs, because, with rare
14309exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
14310a correct Ada 83 program is usually also a correct program
14311in these later versions of the language standard. For further information
14312please refer to the @emph{Compatibility and Porting Guide} chapter in the
14313@cite{GNAT Reference Manual}.
14314@end table
14315
14316@geindex -gnat95 (gcc)
14317
14318@geindex Ada 95 mode
14319
14320
14321@table @asis
14322
14323@item @code{-gnat95} (Ada 95 mode)
14324
14325This switch directs the compiler to implement the Ada 95 version of the
14326language.
14327Since Ada 95 is almost completely upwards
14328compatible with Ada 83, Ada 83 programs may generally be compiled using
14329this switch (see the description of the @code{-gnat83} switch for further
14330information about Ada 83 mode).
14331If an Ada 2005 program is compiled in Ada 95 mode,
14332uses of the new Ada 2005 features will cause error
14333messages or warnings.
14334
14335This switch also can be used to cancel the effect of a previous
14336@code{-gnat83}, @code{-gnat05/2005}, or @code{-gnat12/2012}
14337switch earlier in the command line.
14338@end table
14339
14340@geindex -gnat05 (gcc)
14341
14342@geindex -gnat2005 (gcc)
14343
14344@geindex Ada 2005 mode
14345
14346
14347@table @asis
14348
14349@item @code{-gnat05} or @code{-gnat2005} (Ada 2005 mode)
14350
14351This switch directs the compiler to implement the Ada 2005 version of the
14352language, as documented in the official Ada standards document.
14353Since Ada 2005 is almost completely upwards
14354compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
14355may generally be compiled using this switch (see the description of the
14356@code{-gnat83} and @code{-gnat95} switches for further
14357information).
14358@end table
14359
14360@geindex -gnat12 (gcc)
14361
14362@geindex -gnat2012 (gcc)
14363
14364@geindex Ada 2012 mode
14365
14366
14367@table @asis
14368
14369@item @code{-gnat12} or @code{-gnat2012} (Ada 2012 mode)
14370
14371This switch directs the compiler to implement the Ada 2012 version of the
14372language (also the default).
14373Since Ada 2012 is almost completely upwards
14374compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
14375Ada 83 and Ada 95 programs
14376may generally be compiled using this switch (see the description of the
14377@code{-gnat83}, @code{-gnat95}, and @code{-gnat05/2005} switches
14378for further information).
14379@end table
14380
14381@geindex -gnatX (gcc)
14382
14383@geindex Ada language extensions
14384
14385@geindex GNAT extensions
14386
14387
14388@table @asis
14389
14390@item @code{-gnatX} (Enable GNAT Extensions)
14391
14392This switch directs the compiler to implement the latest version of the
14393language (currently Ada 2012) and also to enable certain GNAT implementation
14394extensions that are not part of any Ada standard. For a full list of these
14395extensions, see the GNAT reference manual.
14396@end table
14397
14398@node Character Set Control,File Naming Control,Compiling Different Versions of Ada,Compiler Switches
14399@anchor{gnat_ugn/building_executable_programs_with_gnat id23}@anchor{10a}@anchor{gnat_ugn/building_executable_programs_with_gnat character-set-control}@anchor{48}
14400@subsection Character Set Control
14401
14402
14403@geindex -gnati (gcc)
14404
14405
14406@table @asis
14407
14408@item @code{-gnati@emph{c}}
14409
14410Normally GNAT recognizes the Latin-1 character set in source program
14411identifiers, as described in the Ada Reference Manual.
14412This switch causes
14413GNAT to recognize alternate character sets in identifiers. @code{c} is a
14414single character  indicating the character set, as follows:
14415
14416
14417@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14418@item
14419
14420@emph{1}
14421
14422@tab
14423
14424ISO 8859-1 (Latin-1) identifiers
14425
14426@item
14427
14428@emph{2}
14429
14430@tab
14431
14432ISO 8859-2 (Latin-2) letters allowed in identifiers
14433
14434@item
14435
14436@emph{3}
14437
14438@tab
14439
14440ISO 8859-3 (Latin-3) letters allowed in identifiers
14441
14442@item
14443
14444@emph{4}
14445
14446@tab
14447
14448ISO 8859-4 (Latin-4) letters allowed in identifiers
14449
14450@item
14451
14452@emph{5}
14453
14454@tab
14455
14456ISO 8859-5 (Cyrillic) letters allowed in identifiers
14457
14458@item
14459
14460@emph{9}
14461
14462@tab
14463
14464ISO 8859-15 (Latin-9) letters allowed in identifiers
14465
14466@item
14467
14468@emph{p}
14469
14470@tab
14471
14472IBM PC letters (code page 437) allowed in identifiers
14473
14474@item
14475
14476@emph{8}
14477
14478@tab
14479
14480IBM PC letters (code page 850) allowed in identifiers
14481
14482@item
14483
14484@emph{f}
14485
14486@tab
14487
14488Full upper-half codes allowed in identifiers
14489
14490@item
14491
14492@emph{n}
14493
14494@tab
14495
14496No upper-half codes allowed in identifiers
14497
14498@item
14499
14500@emph{w}
14501
14502@tab
14503
14504Wide-character codes (that is, codes greater than 255)
14505allowed in identifiers
14506
14507@end multitable
14508
14509
14510See @ref{3e,,Foreign Language Representation} for full details on the
14511implementation of these character sets.
14512@end table
14513
14514@geindex -gnatW (gcc)
14515
14516
14517@table @asis
14518
14519@item @code{-gnatW@emph{e}}
14520
14521Specify the method of encoding for wide characters.
14522@code{e} is one of the following:
14523
14524
14525@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14526@item
14527
14528@emph{h}
14529
14530@tab
14531
14532Hex encoding (brackets coding also recognized)
14533
14534@item
14535
14536@emph{u}
14537
14538@tab
14539
14540Upper half encoding (brackets encoding also recognized)
14541
14542@item
14543
14544@emph{s}
14545
14546@tab
14547
14548Shift/JIS encoding (brackets encoding also recognized)
14549
14550@item
14551
14552@emph{e}
14553
14554@tab
14555
14556EUC encoding (brackets encoding also recognized)
14557
14558@item
14559
14560@emph{8}
14561
14562@tab
14563
14564UTF-8 encoding (brackets encoding also recognized)
14565
14566@item
14567
14568@emph{b}
14569
14570@tab
14571
14572Brackets encoding only (default value)
14573
14574@end multitable
14575
14576
14577For full details on these encoding
14578methods see @ref{4e,,Wide_Character Encodings}.
14579Note that brackets coding is always accepted, even if one of the other
14580options is specified, so for example @code{-gnatW8} specifies that both
14581brackets and UTF-8 encodings will be recognized. The units that are
14582with'ed directly or indirectly will be scanned using the specified
14583representation scheme, and so if one of the non-brackets scheme is
14584used, it must be used consistently throughout the program. However,
14585since brackets encoding is always recognized, it may be conveniently
14586used in standard libraries, allowing these libraries to be used with
14587any of the available coding schemes.
14588
14589Note that brackets encoding only applies to program text. Within comments,
14590brackets are considered to be normal graphic characters, and bracket sequences
14591are never recognized as wide characters.
14592
14593If no @code{-gnatW?} parameter is present, then the default
14594representation is normally Brackets encoding only. However, if the
14595first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
14596byte order mark or BOM for UTF-8), then these three characters are
14597skipped and the default representation for the file is set to UTF-8.
14598
14599Note that the wide character representation that is specified (explicitly
14600or by default) for the main program also acts as the default encoding used
14601for Wide_Text_IO files if not specifically overridden by a WCEM form
14602parameter.
14603@end table
14604
14605When no @code{-gnatW?} is specified, then characters (other than wide
14606characters represented using brackets notation) are treated as 8-bit
14607Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
14608and ASCII format effectors (CR, LF, HT, VT). Other lower half control
14609characters in the range 16#00#..16#1F# are not accepted in program text
14610or in comments. Upper half control characters (16#80#..16#9F#) are rejected
14611in program text, but allowed and ignored in comments. Note in particular
14612that the Next Line (NEL) character whose encoding is 16#85# is not recognized
14613as an end of line in this default mode. If your source program contains
14614instances of the NEL character used as a line terminator,
14615you must use UTF-8 encoding for the whole
14616source program. In default mode, all lines must be ended by a standard
14617end of line sequence (CR, CR/LF, or LF).
14618
14619Note that the convention of simply accepting all upper half characters in
14620comments means that programs that use standard ASCII for program text, but
14621UTF-8 encoding for comments are accepted in default mode, providing that the
14622comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
14623This is a common mode for many programs with foreign language comments.
14624
14625@node File Naming Control,Subprogram Inlining Control,Character Set Control,Compiler Switches
14626@anchor{gnat_ugn/building_executable_programs_with_gnat file-naming-control}@anchor{10b}@anchor{gnat_ugn/building_executable_programs_with_gnat id24}@anchor{10c}
14627@subsection File Naming Control
14628
14629
14630@geindex -gnatk (gcc)
14631
14632
14633@table @asis
14634
14635@item @code{-gnatk@emph{n}}
14636
14637Activates file name 'krunching'. @code{n}, a decimal integer in the range
146381-999, indicates the maximum allowable length of a file name (not
14639including the @code{.ads} or @code{.adb} extension). The default is not
14640to enable file name krunching.
14641
14642For the source file naming rules, @ref{52,,File Naming Rules}.
14643@end table
14644
14645@node Subprogram Inlining Control,Auxiliary Output Control,File Naming Control,Compiler Switches
14646@anchor{gnat_ugn/building_executable_programs_with_gnat subprogram-inlining-control}@anchor{10d}@anchor{gnat_ugn/building_executable_programs_with_gnat id25}@anchor{10e}
14647@subsection Subprogram Inlining Control
14648
14649
14650@geindex -gnatn (gcc)
14651
14652
14653@table @asis
14654
14655@item @code{-gnatn[12]}
14656
14657The @code{n} here is intended to suggest the first syllable of the word 'inline'.
14658GNAT recognizes and processes @code{Inline} pragmas. However, for inlining to
14659actually occur, optimization must be enabled and, by default, inlining of
14660subprograms across modules is not performed. If you want to additionally
14661enable inlining of subprograms specified by pragma @code{Inline} across modules,
14662you must also specify this switch.
14663
14664In the absence of this switch, GNAT does not attempt inlining across modules
14665and does not access the bodies of subprograms for which @code{pragma Inline} is
14666specified if they are not in the current unit.
14667
14668You can optionally specify the inlining level: 1 for moderate inlining across
14669modules, which is a good compromise between compilation times and performances
14670at run time, or 2 for full inlining across modules, which may bring about
14671longer compilation times. If no inlining level is specified, the compiler will
14672pick it based on the optimization level: 1 for @code{-O1}, @code{-O2} or
14673@code{-Os} and 2 for @code{-O3}.
14674
14675If you specify this switch the compiler will access these bodies,
14676creating an extra source dependency for the resulting object file, and
14677where possible, the call will be inlined.
14678For further details on when inlining is possible
14679see @ref{10f,,Inlining of Subprograms}.
14680@end table
14681
14682@geindex -gnatN (gcc)
14683
14684
14685@table @asis
14686
14687@item @code{-gnatN}
14688
14689This switch activates front-end inlining which also
14690generates additional dependencies.
14691
14692When using a gcc-based back end (in practice this means using any version
14693of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
14694@code{-gnatN} is deprecated, and the use of @code{-gnatn} is preferred.
14695Historically front end inlining was more extensive than the gcc back end
14696inlining, but that is no longer the case.
14697@end table
14698
14699@node Auxiliary Output Control,Debugging Control,Subprogram Inlining Control,Compiler Switches
14700@anchor{gnat_ugn/building_executable_programs_with_gnat auxiliary-output-control}@anchor{110}@anchor{gnat_ugn/building_executable_programs_with_gnat id26}@anchor{111}
14701@subsection Auxiliary Output Control
14702
14703
14704@geindex -gnatt (gcc)
14705
14706@geindex Writing internal trees
14707
14708@geindex Internal trees
14709@geindex writing to file
14710
14711
14712@table @asis
14713
14714@item @code{-gnatt}
14715
14716Causes GNAT to write the internal tree for a unit to a file (with the
14717extension @code{.adt}.
14718This not normally required, but is used by separate analysis tools.
14719Typically
14720these tools do the necessary compilations automatically, so you should
14721not have to specify this switch in normal operation.
14722Note that the combination of switches @code{-gnatct}
14723generates a tree in the form required by ASIS applications.
14724@end table
14725
14726@geindex -gnatu (gcc)
14727
14728
14729@table @asis
14730
14731@item @code{-gnatu}
14732
14733Print a list of units required by this compilation on @code{stdout}.
14734The listing includes all units on which the unit being compiled depends
14735either directly or indirectly.
14736@end table
14737
14738@geindex -pass-exit-codes (gcc)
14739
14740
14741@table @asis
14742
14743@item @code{-pass-exit-codes}
14744
14745If this switch is not used, the exit code returned by @code{gcc} when
14746compiling multiple files indicates whether all source files have
14747been successfully used to generate object files or not.
14748
14749When @code{-pass-exit-codes} is used, @code{gcc} exits with an extended
14750exit status and allows an integrated development environment to better
14751react to a compilation failure. Those exit status are:
14752
14753
14754@multitable {xxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
14755@item
14756
14757@emph{5}
14758
14759@tab
14760
14761There was an error in at least one source file.
14762
14763@item
14764
14765@emph{3}
14766
14767@tab
14768
14769At least one source file did not generate an object file.
14770
14771@item
14772
14773@emph{2}
14774
14775@tab
14776
14777The compiler died unexpectedly (internal error for example).
14778
14779@item
14780
14781@emph{0}
14782
14783@tab
14784
14785An object file has been generated for every source file.
14786
14787@end multitable
14788
14789@end table
14790
14791@node Debugging Control,Exception Handling Control,Auxiliary Output Control,Compiler Switches
14792@anchor{gnat_ugn/building_executable_programs_with_gnat debugging-control}@anchor{112}@anchor{gnat_ugn/building_executable_programs_with_gnat id27}@anchor{113}
14793@subsection Debugging Control
14794
14795
14796@quotation
14797
14798@geindex Debugging options
14799@end quotation
14800
14801@geindex -gnatd (gcc)
14802
14803
14804@table @asis
14805
14806@item @code{-gnatd@emph{x}}
14807
14808Activate internal debugging switches. @code{x} is a letter or digit, or
14809string of letters or digits, which specifies the type of debugging
14810outputs desired. Normally these are used only for internal development
14811or system debugging purposes. You can find full documentation for these
14812switches in the body of the @code{Debug} unit in the compiler source
14813file @code{debug.adb}.
14814@end table
14815
14816@geindex -gnatG (gcc)
14817
14818
14819@table @asis
14820
14821@item @code{-gnatG[=@emph{nn}]}
14822
14823This switch causes the compiler to generate auxiliary output containing
14824a pseudo-source listing of the generated expanded code. Like most Ada
14825compilers, GNAT works by first transforming the high level Ada code into
14826lower level constructs. For example, tasking operations are transformed
14827into calls to the tasking run-time routines. A unique capability of GNAT
14828is to list this expanded code in a form very close to normal Ada source.
14829This is very useful in understanding the implications of various Ada
14830usage on the efficiency of the generated code. There are many cases in
14831Ada (e.g., the use of controlled types), where simple Ada statements can
14832generate a lot of run-time code. By using @code{-gnatG} you can identify
14833these cases, and consider whether it may be desirable to modify the coding
14834approach to improve efficiency.
14835
14836The optional parameter @code{nn} if present after -gnatG specifies an
14837alternative maximum line length that overrides the normal default of 72.
14838This value is in the range 40-999999, values less than 40 being silently
14839reset to 40. The equal sign is optional.
14840
14841The format of the output is very similar to standard Ada source, and is
14842easily understood by an Ada programmer. The following special syntactic
14843additions correspond to low level features used in the generated code that
14844do not have any exact analogies in pure Ada source form. The following
14845is a partial list of these special constructions. See the spec
14846of package @code{Sprint} in file @code{sprint.ads} for a full list.
14847
14848@geindex -gnatL (gcc)
14849
14850If the switch @code{-gnatL} is used in conjunction with
14851@code{-gnatG}, then the original source lines are interspersed
14852in the expanded source (as comment lines with the original line number).
14853
14854
14855@table @asis
14856
14857@item @code{new @emph{xxx} [storage_pool = @emph{yyy}]}
14858
14859Shows the storage pool being used for an allocator.
14860
14861@item @code{at end @emph{procedure-name};}
14862
14863Shows the finalization (cleanup) procedure for a scope.
14864
14865@item @code{(if @emph{expr} then @emph{expr} else @emph{expr})}
14866
14867Conditional expression equivalent to the @code{x?y:z} construction in C.
14868
14869@item @code{@emph{target}^(@emph{source})}
14870
14871A conversion with floating-point truncation instead of rounding.
14872
14873@item @code{@emph{target}?(@emph{source})}
14874
14875A conversion that bypasses normal Ada semantic checking. In particular
14876enumeration types and fixed-point types are treated simply as integers.
14877
14878@item @code{@emph{target}?^(@emph{source})}
14879
14880Combines the above two cases.
14881@end table
14882
14883@code{@emph{x} #/ @emph{y}}
14884
14885@code{@emph{x} #mod @emph{y}}
14886
14887@code{@emph{x} # @emph{y}}
14888
14889
14890@table @asis
14891
14892@item @code{@emph{x} #rem @emph{y}}
14893
14894A division or multiplication of fixed-point values which are treated as
14895integers without any kind of scaling.
14896
14897@item @code{free @emph{expr} [storage_pool = @emph{xxx}]}
14898
14899Shows the storage pool associated with a @code{free} statement.
14900
14901@item @code{[subtype or type declaration]}
14902
14903Used to list an equivalent declaration for an internally generated
14904type that is referenced elsewhere in the listing.
14905
14906@item @code{freeze @emph{type-name} [@emph{actions}]}
14907
14908Shows the point at which @code{type-name} is frozen, with possible
14909associated actions to be performed at the freeze point.
14910
14911@item @code{reference @emph{itype}}
14912
14913Reference (and hence definition) to internal type @code{itype}.
14914
14915@item @code{@emph{function-name}! (@emph{arg}, @emph{arg}, @emph{arg})}
14916
14917Intrinsic function call.
14918
14919@item @code{@emph{label-name} : label}
14920
14921Declaration of label @code{labelname}.
14922
14923@item @code{#$ @emph{subprogram-name}}
14924
14925An implicit call to a run-time support routine
14926(to meet the requirement of H.3.1(9) in a
14927convenient manner).
14928
14929@item @code{@emph{expr} && @emph{expr} && @emph{expr} ... && @emph{expr}}
14930
14931A multiple concatenation (same effect as @code{expr} & @code{expr} &
14932@code{expr}, but handled more efficiently).
14933
14934@item @code{[constraint_error]}
14935
14936Raise the @code{Constraint_Error} exception.
14937
14938@item @code{@emph{expression}'reference}
14939
14940A pointer to the result of evaluating @{expression@}.
14941
14942@item @code{@emph{target-type}!(@emph{source-expression})}
14943
14944An unchecked conversion of @code{source-expression} to @code{target-type}.
14945
14946@item @code{[@emph{numerator}/@emph{denominator}]}
14947
14948Used to represent internal real literals (that) have no exact
14949representation in base 2-16 (for example, the result of compile time
14950evaluation of the expression 1.0/27.0).
14951@end table
14952@end table
14953
14954@geindex -gnatD (gcc)
14955
14956
14957@table @asis
14958
14959@item @code{-gnatD[=nn]}
14960
14961When used in conjunction with @code{-gnatG}, this switch causes
14962the expanded source, as described above for
14963@code{-gnatG} to be written to files with names
14964@code{xxx.dg}, where @code{xxx} is the normal file name,
14965instead of to the standard output file. For
14966example, if the source file name is @code{hello.adb}, then a file
14967@code{hello.adb.dg} will be written.  The debugging
14968information generated by the @code{gcc} @code{-g} switch
14969will refer to the generated @code{xxx.dg} file. This allows
14970you to do source level debugging using the generated code which is
14971sometimes useful for complex code, for example to find out exactly
14972which part of a complex construction raised an exception. This switch
14973also suppresses generation of cross-reference information (see
14974@code{-gnatx}) since otherwise the cross-reference information
14975would refer to the @code{.dg} file, which would cause
14976confusion since this is not the original source file.
14977
14978Note that @code{-gnatD} actually implies @code{-gnatG}
14979automatically, so it is not necessary to give both options.
14980In other words @code{-gnatD} is equivalent to @code{-gnatDG}).
14981
14982@geindex -gnatL (gcc)
14983
14984If the switch @code{-gnatL} is used in conjunction with
14985@code{-gnatDG}, then the original source lines are interspersed
14986in the expanded source (as comment lines with the original line number).
14987
14988The optional parameter @code{nn} if present after -gnatD specifies an
14989alternative maximum line length that overrides the normal default of 72.
14990This value is in the range 40-999999, values less than 40 being silently
14991reset to 40. The equal sign is optional.
14992@end table
14993
14994@geindex -gnatr (gcc)
14995
14996@geindex pragma Restrictions
14997
14998
14999@table @asis
15000
15001@item @code{-gnatr}
15002
15003This switch causes pragma Restrictions to be treated as Restriction_Warnings
15004so that violation of restrictions causes warnings rather than illegalities.
15005This is useful during the development process when new restrictions are added
15006or investigated. The switch also causes pragma Profile to be treated as
15007Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
15008restriction warnings rather than restrictions.
15009@end table
15010
15011@geindex -gnatR (gcc)
15012
15013
15014@table @asis
15015
15016@item @code{-gnatR[0|1|2|3][e][m][s]}
15017
15018This switch controls output from the compiler of a listing showing
15019representation information for declared types, objects and subprograms.
15020For @code{-gnatR0}, no information is output (equivalent to omitting
15021the @code{-gnatR} switch). For @code{-gnatR1} (which is the default,
15022so @code{-gnatR} with no parameter has the same effect), size and
15023alignment information is listed for declared array and record types.
15024For @code{-gnatR2}, size and alignment information is listed for all
15025declared types and objects. The @code{Linker_Section} is also listed for any
15026entity for which the @code{Linker_Section} is set explicitly or implicitly (the
15027latter case occurs for objects of a type for which a @code{Linker_Section}
15028is set).
15029
15030For @code{-gnatR3}, symbolic expressions for values that are computed
15031at run time for records are included. These symbolic expressions have
15032a mostly obvious format with #n being used to represent the value of the
15033n'th discriminant. See source files @code{repinfo.ads/adb} in the
15034GNAT sources for full details on the format of @code{-gnatR3} output.
15035
15036If the switch is followed by an @code{e} (e.g. @code{-gnatR2e}), then
15037extended representation information for record sub-components of records
15038are included.
15039
15040If the switch is followed by an @code{m} (e.g. @code{-gnatRm}), then
15041subprogram conventions and parameter passing mechanisms for all the
15042subprograms are included.
15043
15044If the switch is followed by an @code{s} (e.g., @code{-gnatR3s}), then
15045the output is to a file with the name @code{file.rep} where file is
15046the name of the corresponding source file.
15047
15048Note that it is possible for record components to have zero size. In
15049this case, the component clause uses an obvious extension of permitted
15050Ada syntax, for example @code{at 0 range 0 .. -1}.
15051@end table
15052
15053@geindex -gnatS (gcc)
15054
15055
15056@table @asis
15057
15058@item @code{-gnatS}
15059
15060The use of the switch @code{-gnatS} for an
15061Ada compilation will cause the compiler to output a
15062representation of package Standard in a form very
15063close to standard Ada. It is not quite possible to
15064do this entirely in standard Ada (since new
15065numeric base types cannot be created in standard
15066Ada), but the output is easily
15067readable to any Ada programmer, and is useful to
15068determine the characteristics of target dependent
15069types in package Standard.
15070@end table
15071
15072@geindex -gnatx (gcc)
15073
15074
15075@table @asis
15076
15077@item @code{-gnatx}
15078
15079Normally the compiler generates full cross-referencing information in
15080the @code{ALI} file. This information is used by a number of tools,
15081including @code{gnatfind} and @code{gnatxref}. The @code{-gnatx} switch
15082suppresses this information. This saves some space and may slightly
15083speed up compilation, but means that these tools cannot be used.
15084@end table
15085
15086@node Exception Handling Control,Units to Sources Mapping Files,Debugging Control,Compiler Switches
15087@anchor{gnat_ugn/building_executable_programs_with_gnat id28}@anchor{114}@anchor{gnat_ugn/building_executable_programs_with_gnat exception-handling-control}@anchor{115}
15088@subsection Exception Handling Control
15089
15090
15091GNAT uses two methods for handling exceptions at run-time. The
15092@code{setjmp/longjmp} method saves the context when entering
15093a frame with an exception handler. Then when an exception is
15094raised, the context can be restored immediately, without the
15095need for tracing stack frames. This method provides very fast
15096exception propagation, but introduces significant overhead for
15097the use of exception handlers, even if no exception is raised.
15098
15099The other approach is called 'zero cost' exception handling.
15100With this method, the compiler builds static tables to describe
15101the exception ranges. No dynamic code is required when entering
15102a frame containing an exception handler. When an exception is
15103raised, the tables are used to control a back trace of the
15104subprogram invocation stack to locate the required exception
15105handler. This method has considerably poorer performance for
15106the propagation of exceptions, but there is no overhead for
15107exception handlers if no exception is raised. Note that in this
15108mode and in the context of mixed Ada and C/C++ programming,
15109to propagate an exception through a C/C++ code, the C/C++ code
15110must be compiled with the @code{-funwind-tables} GCC's
15111option.
15112
15113The following switches may be used to control which of the
15114two exception handling methods is used.
15115
15116@geindex --RTS=sjlj (gnatmake)
15117
15118
15119@table @asis
15120
15121@item @code{--RTS=sjlj}
15122
15123This switch causes the setjmp/longjmp run-time (when available) to be used
15124for exception handling. If the default
15125mechanism for the target is zero cost exceptions, then
15126this switch can be used to modify this default, and must be
15127used for all units in the partition.
15128This option is rarely used. One case in which it may be
15129advantageous is if you have an application where exception
15130raising is common and the overall performance of the
15131application is improved by favoring exception propagation.
15132@end table
15133
15134@geindex --RTS=zcx (gnatmake)
15135
15136@geindex Zero Cost Exceptions
15137
15138
15139@table @asis
15140
15141@item @code{--RTS=zcx}
15142
15143This switch causes the zero cost approach to be used
15144for exception handling. If this is the default mechanism for the
15145target (see below), then this switch is unneeded. If the default
15146mechanism for the target is setjmp/longjmp exceptions, then
15147this switch can be used to modify this default, and must be
15148used for all units in the partition.
15149This option can only be used if the zero cost approach
15150is available for the target in use, otherwise it will generate an error.
15151@end table
15152
15153The same option @code{--RTS} must be used both for @code{gcc}
15154and @code{gnatbind}. Passing this option to @code{gnatmake}
15155(@ref{dc,,Switches for gnatmake}) will ensure the required consistency
15156through the compilation and binding steps.
15157
15158@node Units to Sources Mapping Files,Code Generation Control,Exception Handling Control,Compiler Switches
15159@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}
15160@subsection Units to Sources Mapping Files
15161
15162
15163@geindex -gnatem (gcc)
15164
15165
15166@table @asis
15167
15168@item @code{-gnatem=@emph{path}}
15169
15170A mapping file is a way to communicate to the compiler two mappings:
15171from unit names to file names (without any directory information) and from
15172file names to path names (with full directory information). These mappings
15173are used by the compiler to short-circuit the path search.
15174
15175The use of mapping files is not required for correct operation of the
15176compiler, but mapping files can improve efficiency, particularly when
15177sources are read over a slow network connection. In normal operation,
15178you need not be concerned with the format or use of mapping files,
15179and the @code{-gnatem} switch is not a switch that you would use
15180explicitly. It is intended primarily for use by automatic tools such as
15181@code{gnatmake} running under the project file facility. The
15182description here of the format of mapping files is provided
15183for completeness and for possible use by other tools.
15184
15185A mapping file is a sequence of sets of three lines. In each set, the
15186first line is the unit name, in lower case, with @code{%s} appended
15187for specs and @code{%b} appended for bodies; the second line is the
15188file name; and the third line is the path name.
15189
15190Example:
15191
15192@example
15193main%b
15194main.2.ada
15195/gnat/project1/sources/main.2.ada
15196@end example
15197
15198When the switch @code{-gnatem} is specified, the compiler will
15199create in memory the two mappings from the specified file. If there is
15200any problem (nonexistent file, truncated file or duplicate entries),
15201no mapping will be created.
15202
15203Several @code{-gnatem} switches may be specified; however, only the
15204last one on the command line will be taken into account.
15205
15206When using a project file, @code{gnatmake} creates a temporary
15207mapping file and communicates it to the compiler using this switch.
15208@end table
15209
15210@node Code Generation Control,,Units to Sources Mapping Files,Compiler Switches
15211@anchor{gnat_ugn/building_executable_programs_with_gnat code-generation-control}@anchor{117}@anchor{gnat_ugn/building_executable_programs_with_gnat id30}@anchor{118}
15212@subsection Code Generation Control
15213
15214
15215The GCC technology provides a wide range of target dependent
15216@code{-m} switches for controlling
15217details of code generation with respect to different versions of
15218architectures. This includes variations in instruction sets (e.g.,
15219different members of the power pc family), and different requirements
15220for optimal arrangement of instructions (e.g., different members of
15221the x86 family). The list of available @code{-m} switches may be
15222found in the GCC documentation.
15223
15224Use of these @code{-m} switches may in some cases result in improved
15225code performance.
15226
15227The GNAT technology is tested and qualified without any
15228@code{-m} switches,
15229so generally the most reliable approach is to avoid the use of these
15230switches. However, we generally expect most of these switches to work
15231successfully with GNAT, and many customers have reported successful
15232use of these options.
15233
15234Our general advice is to avoid the use of @code{-m} switches unless
15235special needs lead to requirements in this area. In particular,
15236there is no point in using @code{-m} switches to improve performance
15237unless you actually see a performance improvement.
15238
15239@node Linker Switches,Binding with gnatbind,Compiler Switches,Building Executable Programs with GNAT
15240@anchor{gnat_ugn/building_executable_programs_with_gnat linker-switches}@anchor{119}@anchor{gnat_ugn/building_executable_programs_with_gnat id31}@anchor{11a}
15241@section Linker Switches
15242
15243
15244Linker switches can be specified after @code{-largs} builder switch.
15245
15246@geindex -fuse-ld=name
15247
15248
15249@table @asis
15250
15251@item @code{-fuse-ld=@emph{name}}
15252
15253Linker to be used. The default is @code{bfd} for @code{ld.bfd},
15254the alternative being @code{gold} for @code{ld.gold}. The later is
15255a more recent and faster linker, but only available on GNU/Linux
15256platforms.
15257@end table
15258
15259@node Binding with gnatbind,Linking with gnatlink,Linker Switches,Building Executable Programs with GNAT
15260@anchor{gnat_ugn/building_executable_programs_with_gnat binding-with-gnatbind}@anchor{1d}@anchor{gnat_ugn/building_executable_programs_with_gnat id32}@anchor{11b}
15261@section Binding with @code{gnatbind}
15262
15263
15264@geindex gnatbind
15265
15266This chapter describes the GNAT binder, @code{gnatbind}, which is used
15267to bind compiled GNAT objects.
15268
15269The @code{gnatbind} program performs four separate functions:
15270
15271
15272@itemize *
15273
15274@item
15275Checks that a program is consistent, in accordance with the rules in
15276Chapter 10 of the Ada Reference Manual. In particular, error
15277messages are generated if a program uses inconsistent versions of a
15278given unit.
15279
15280@item
15281Checks that an acceptable order of elaboration exists for the program
15282and issues an error message if it cannot find an order of elaboration
15283that satisfies the rules in Chapter 10 of the Ada Language Manual.
15284
15285@item
15286Generates a main program incorporating the given elaboration order.
15287This program is a small Ada package (body and spec) that
15288must be subsequently compiled
15289using the GNAT compiler. The necessary compilation step is usually
15290performed automatically by @code{gnatlink}. The two most important
15291functions of this program
15292are to call the elaboration routines of units in an appropriate order
15293and to call the main program.
15294
15295@item
15296Determines the set of object files required by the given main program.
15297This information is output in the forms of comments in the generated program,
15298to be read by the @code{gnatlink} utility used to link the Ada application.
15299@end itemize
15300
15301@menu
15302* Running gnatbind::
15303* Switches for gnatbind::
15304* Command-Line Access::
15305* Search Paths for gnatbind::
15306* Examples of gnatbind Usage::
15307
15308@end menu
15309
15310@node Running gnatbind,Switches for gnatbind,,Binding with gnatbind
15311@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatbind}@anchor{11c}@anchor{gnat_ugn/building_executable_programs_with_gnat id33}@anchor{11d}
15312@subsection Running @code{gnatbind}
15313
15314
15315The form of the @code{gnatbind} command is
15316
15317@example
15318$ gnatbind [ switches ] mainprog[.ali] [ switches ]
15319@end example
15320
15321where @code{mainprog.adb} is the Ada file containing the main program
15322unit body. @code{gnatbind} constructs an Ada
15323package in two files whose names are
15324@code{b~mainprog.ads}, and @code{b~mainprog.adb}.
15325For example, if given the
15326parameter @code{hello.ali}, for a main program contained in file
15327@code{hello.adb}, the binder output files would be @code{b~hello.ads}
15328and @code{b~hello.adb}.
15329
15330When doing consistency checking, the binder takes into consideration
15331any source files it can locate. For example, if the binder determines
15332that the given main program requires the package @code{Pack}, whose
15333@code{.ALI}
15334file is @code{pack.ali} and whose corresponding source spec file is
15335@code{pack.ads}, it attempts to locate the source file @code{pack.ads}
15336(using the same search path conventions as previously described for the
15337@code{gcc} command). If it can locate this source file, it checks that
15338the time stamps
15339or source checksums of the source and its references to in @code{ALI} files
15340match. In other words, any @code{ALI} files that mentions this spec must have
15341resulted from compiling this version of the source file (or in the case
15342where the source checksums match, a version close enough that the
15343difference does not matter).
15344
15345@geindex Source files
15346@geindex use by binder
15347
15348The effect of this consistency checking, which includes source files, is
15349that the binder ensures that the program is consistent with the latest
15350version of the source files that can be located at bind time. Editing a
15351source file without compiling files that depend on the source file cause
15352error messages to be generated by the binder.
15353
15354For example, suppose you have a main program @code{hello.adb} and a
15355package @code{P}, from file @code{p.ads} and you perform the following
15356steps:
15357
15358
15359@itemize *
15360
15361@item
15362Enter @code{gcc -c hello.adb} to compile the main program.
15363
15364@item
15365Enter @code{gcc -c p.ads} to compile package @code{P}.
15366
15367@item
15368Edit file @code{p.ads}.
15369
15370@item
15371Enter @code{gnatbind hello}.
15372@end itemize
15373
15374At this point, the file @code{p.ali} contains an out-of-date time stamp
15375because the file @code{p.ads} has been edited. The attempt at binding
15376fails, and the binder generates the following error messages:
15377
15378@example
15379error: "hello.adb" must be recompiled ("p.ads" has been modified)
15380error: "p.ads" has been modified and must be recompiled
15381@end example
15382
15383Now both files must be recompiled as indicated, and then the bind can
15384succeed, generating a main program. You need not normally be concerned
15385with the contents of this file, but for reference purposes a sample
15386binder output file is given in @ref{e,,Example of Binder Output File}.
15387
15388In most normal usage, the default mode of @code{gnatbind} which is to
15389generate the main package in Ada, as described in the previous section.
15390In particular, this means that any Ada programmer can read and understand
15391the generated main program. It can also be debugged just like any other
15392Ada code provided the @code{-g} switch is used for
15393@code{gnatbind} and @code{gnatlink}.
15394
15395@node Switches for gnatbind,Command-Line Access,Running gnatbind,Binding with gnatbind
15396@anchor{gnat_ugn/building_executable_programs_with_gnat id34}@anchor{11e}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatbind}@anchor{11f}
15397@subsection Switches for @code{gnatbind}
15398
15399
15400The following switches are available with @code{gnatbind}; details will
15401be presented in subsequent sections.
15402
15403@geindex --version (gnatbind)
15404
15405
15406@table @asis
15407
15408@item @code{--version}
15409
15410Display Copyright and version, then exit disregarding all other options.
15411@end table
15412
15413@geindex --help (gnatbind)
15414
15415
15416@table @asis
15417
15418@item @code{--help}
15419
15420If @code{--version} was not used, display usage, then exit disregarding
15421all other options.
15422@end table
15423
15424@geindex -a (gnatbind)
15425
15426
15427@table @asis
15428
15429@item @code{-a}
15430
15431Indicates that, if supported by the platform, the adainit procedure should
15432be treated as an initialisation routine by the linker (a constructor). This
15433is intended to be used by the Project Manager to automatically initialize
15434shared Stand-Alone Libraries.
15435@end table
15436
15437@geindex -aO (gnatbind)
15438
15439
15440@table @asis
15441
15442@item @code{-aO}
15443
15444Specify directory to be searched for ALI files.
15445@end table
15446
15447@geindex -aI (gnatbind)
15448
15449
15450@table @asis
15451
15452@item @code{-aI}
15453
15454Specify directory to be searched for source file.
15455@end table
15456
15457@geindex -A (gnatbind)
15458
15459
15460@table @asis
15461
15462@item @code{-A[=@emph{filename}]}
15463
15464Output ALI list (to standard output or to the named file).
15465@end table
15466
15467@geindex -b (gnatbind)
15468
15469
15470@table @asis
15471
15472@item @code{-b}
15473
15474Generate brief messages to @code{stderr} even if verbose mode set.
15475@end table
15476
15477@geindex -c (gnatbind)
15478
15479
15480@table @asis
15481
15482@item @code{-c}
15483
15484Check only, no generation of binder output file.
15485@end table
15486
15487@geindex -dnn[k|m] (gnatbind)
15488
15489
15490@table @asis
15491
15492@item @code{-d@emph{nn}[k|m]}
15493
15494This switch can be used to change the default task stack size value
15495to a specified size @code{nn}, which is expressed in bytes by default, or
15496in kilobytes when suffixed with @code{k} or in megabytes when suffixed
15497with @code{m}.
15498In the absence of a @code{[k|m]} suffix, this switch is equivalent,
15499in effect, to completing all task specs with
15500
15501@example
15502pragma Storage_Size (nn);
15503@end example
15504
15505When they do not already have such a pragma.
15506@end table
15507
15508@geindex -D (gnatbind)
15509
15510
15511@table @asis
15512
15513@item @code{-D@emph{nn}[k|m]}
15514
15515This switch can be used to change the default secondary stack size value
15516to a specified size @code{nn}, which is expressed in bytes by default, or
15517in kilobytes when suffixed with @code{k} or in megabytes when suffixed
15518with @code{m}.
15519
15520The secondary stack is used to deal with functions that return a variable
15521sized result, for example a function returning an unconstrained
15522String. There are two ways in which this secondary stack is allocated.
15523
15524For most targets, the secondary stack grows on demand and is allocated
15525as a chain of blocks in the heap. The -D option is not very
15526relevant. It only give some control over the size of the allocated
15527blocks (whose size is the minimum of the default secondary stack size value,
15528and the actual size needed for the current allocation request).
15529
15530For certain targets, notably VxWorks 653 and bare board targets,
15531the secondary stack is allocated by carving off a chunk of the primary task
15532stack. By default this is a fixed percentage of the primary task stack as
15533defined by System.Parameter.Sec_Stack_Percentage. This can be overridden per
15534task using the Secondary_Stack_Size pragma/aspect. The -D option is used to
15535define the size of the environment task's secondary stack.
15536@end table
15537
15538@geindex -e (gnatbind)
15539
15540
15541@table @asis
15542
15543@item @code{-e}
15544
15545Output complete list of elaboration-order dependencies.
15546@end table
15547
15548@geindex -Ea (gnatbind)
15549
15550
15551@table @asis
15552
15553@item @code{-Ea}
15554
15555Store tracebacks in exception occurrences when the target supports it.
15556The "a" is for "address"; tracebacks will contain hexadecimal addresses,
15557unless symbolic tracebacks are enabled.
15558
15559See also the packages @code{GNAT.Traceback} and
15560@code{GNAT.Traceback.Symbolic} for more information.
15561Note that on x86 ports, you must not use @code{-fomit-frame-pointer}
15562@code{gcc} option.
15563@end table
15564
15565@geindex -Es (gnatbind)
15566
15567
15568@table @asis
15569
15570@item @code{-Es}
15571
15572Store tracebacks in exception occurrences when the target supports it.
15573The "s" is for "symbolic"; symbolic tracebacks are enabled.
15574@end table
15575
15576@geindex -E (gnatbind)
15577
15578
15579@table @asis
15580
15581@item @code{-E}
15582
15583Currently the same as @code{-Ea}.
15584@end table
15585
15586@geindex -f (gnatbind)
15587
15588
15589@table @asis
15590
15591@item @code{-f@emph{elab-order}}
15592
15593Force elaboration order.
15594@end table
15595
15596@geindex -F (gnatbind)
15597
15598
15599@table @asis
15600
15601@item @code{-F}
15602
15603Force the checks of elaboration flags. @code{gnatbind} does not normally
15604generate checks of elaboration flags for the main executable, except when
15605a Stand-Alone Library is used. However, there are cases when this cannot be
15606detected by gnatbind. An example is importing an interface of a Stand-Alone
15607Library through a pragma Import and only specifying through a linker switch
15608this Stand-Alone Library. This switch is used to guarantee that elaboration
15609flag checks are generated.
15610@end table
15611
15612@geindex -h (gnatbind)
15613
15614
15615@table @asis
15616
15617@item @code{-h}
15618
15619Output usage (help) information.
15620
15621@geindex -H32 (gnatbind)
15622
15623@item @code{-H32}
15624
15625Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
15626For further details see @ref{120,,Dynamic Allocation Control}.
15627
15628@geindex -H64 (gnatbind)
15629
15630@geindex __gnat_malloc
15631
15632@item @code{-H64}
15633
15634Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
15635For further details see @ref{120,,Dynamic Allocation Control}.
15636
15637@geindex -I (gnatbind)
15638
15639@item @code{-I}
15640
15641Specify directory to be searched for source and ALI files.
15642
15643@geindex -I- (gnatbind)
15644
15645@item @code{-I-}
15646
15647Do not look for sources in the current directory where @code{gnatbind} was
15648invoked, and do not look for ALI files in the directory containing the
15649ALI file named in the @code{gnatbind} command line.
15650
15651@geindex -l (gnatbind)
15652
15653@item @code{-l}
15654
15655Output chosen elaboration order.
15656
15657@geindex -L (gnatbind)
15658
15659@item @code{-L@emph{xxx}}
15660
15661Bind the units for library building. In this case the @code{adainit} and
15662@code{adafinal} procedures (@ref{b4,,Binding with Non-Ada Main Programs})
15663are renamed to @code{@emph{xxx}init} and
15664@code{@emph{xxx}final}.
15665Implies -n.
15666(@ref{15,,GNAT and Libraries}, for more details.)
15667
15668@geindex -M (gnatbind)
15669
15670@item @code{-M@emph{xyz}}
15671
15672Rename generated main program from main to xyz. This option is
15673supported on cross environments only.
15674
15675@geindex -m (gnatbind)
15676
15677@item @code{-m@emph{n}}
15678
15679Limit number of detected errors or warnings to @code{n}, where @code{n} is
15680in the range 1..999999. The default value if no switch is
15681given is 9999. If the number of warnings reaches this limit, then a
15682message is output and further warnings are suppressed, the bind
15683continues in this case. If the number of errors reaches this
15684limit, then a message is output and the bind is abandoned.
15685A value of zero means that no limit is enforced. The equal
15686sign is optional.
15687
15688@geindex -n (gnatbind)
15689
15690@item @code{-n}
15691
15692No main program.
15693
15694@geindex -nostdinc (gnatbind)
15695
15696@item @code{-nostdinc}
15697
15698Do not look for sources in the system default directory.
15699
15700@geindex -nostdlib (gnatbind)
15701
15702@item @code{-nostdlib}
15703
15704Do not look for library files in the system default directory.
15705
15706@geindex --RTS (gnatbind)
15707
15708@item @code{--RTS=@emph{rts-path}}
15709
15710Specifies the default location of the runtime library. Same meaning as the
15711equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
15712
15713@geindex -o (gnatbind)
15714
15715@item @code{-o @emph{file}}
15716
15717Name the output file @code{file} (default is @code{b~`xxx}.adb`).
15718Note that if this option is used, then linking must be done manually,
15719gnatlink cannot be used.
15720
15721@geindex -O (gnatbind)
15722
15723@item @code{-O[=@emph{filename}]}
15724
15725Output object list (to standard output or to the named file).
15726
15727@geindex -p (gnatbind)
15728
15729@item @code{-p}
15730
15731Pessimistic (worst-case) elaboration order.
15732
15733@geindex -P (gnatbind)
15734
15735@item @code{-P}
15736
15737Generate binder file suitable for CodePeer.
15738
15739@geindex -R (gnatbind)
15740
15741@item @code{-R}
15742
15743Output closure source list, which includes all non-run-time units that are
15744included in the bind.
15745
15746@geindex -Ra (gnatbind)
15747
15748@item @code{-Ra}
15749
15750Like @code{-R} but the list includes run-time units.
15751
15752@geindex -s (gnatbind)
15753
15754@item @code{-s}
15755
15756Require all source files to be present.
15757
15758@geindex -S (gnatbind)
15759
15760@item @code{-S@emph{xxx}}
15761
15762Specifies the value to be used when detecting uninitialized scalar
15763objects with pragma Initialize_Scalars.
15764The @code{xxx} string specified with the switch is one of:
15765
15766
15767@itemize *
15768
15769@item
15770@code{in} for an invalid value.
15771
15772If zero is invalid for the discrete type in question,
15773then the scalar value is set to all zero bits.
15774For signed discrete types, the largest possible negative value of
15775the underlying scalar is set (i.e. a one bit followed by all zero bits).
15776For unsigned discrete types, the underlying scalar value is set to all
15777one bits. For floating-point types, a NaN value is set
15778(see body of package System.Scalar_Values for exact values).
15779
15780@item
15781@code{lo} for low value.
15782
15783If zero is invalid for the discrete type in question,
15784then the scalar value is set to all zero bits.
15785For signed discrete types, the largest possible negative value of
15786the underlying scalar is set (i.e. a one bit followed by all zero bits).
15787For unsigned discrete types, the underlying scalar value is set to all
15788zero bits. For floating-point, a small value is set
15789(see body of package System.Scalar_Values for exact values).
15790
15791@item
15792@code{hi} for high value.
15793
15794If zero is invalid for the discrete type in question,
15795then the scalar value is set to all one bits.
15796For signed discrete types, the largest possible positive value of
15797the underlying scalar is set (i.e. a zero bit followed by all one bits).
15798For unsigned discrete types, the underlying scalar value is set to all
15799one bits. For floating-point, a large value is set
15800(see body of package System.Scalar_Values for exact values).
15801
15802@item
15803@code{xx} for hex value (two hex digits).
15804
15805The underlying scalar is set to a value consisting of repeated bytes, whose
15806value corresponds to the given value. For example if @code{BF} is given,
15807then a 32-bit scalar value will be set to the bit patterm @code{16#BFBFBFBF#}.
15808@end itemize
15809
15810@geindex GNAT_INIT_SCALARS
15811
15812In addition, you can specify @code{-Sev} to indicate that the value is
15813to be set at run time. In this case, the program will look for an environment
15814variable of the form @code{GNAT_INIT_SCALARS=@emph{yy}}, where @code{yy} is one
15815of @code{in/lo/hi/@emph{xx}} with the same meanings as above.
15816If no environment variable is found, or if it does not have a valid value,
15817then the default is @code{in} (invalid values).
15818@end table
15819
15820@geindex -static (gnatbind)
15821
15822
15823@table @asis
15824
15825@item @code{-static}
15826
15827Link against a static GNAT run time.
15828
15829@geindex -shared (gnatbind)
15830
15831@item @code{-shared}
15832
15833Link against a shared GNAT run time when available.
15834
15835@geindex -t (gnatbind)
15836
15837@item @code{-t}
15838
15839Tolerate time stamp and other consistency errors.
15840
15841@geindex -T (gnatbind)
15842
15843@item @code{-T@emph{n}}
15844
15845Set the time slice value to @code{n} milliseconds. If the system supports
15846the specification of a specific time slice value, then the indicated value
15847is used. If the system does not support specific time slice values, but
15848does support some general notion of round-robin scheduling, then any
15849nonzero value will activate round-robin scheduling.
15850
15851A value of zero is treated specially. It turns off time
15852slicing, and in addition, indicates to the tasking run time that the
15853semantics should match as closely as possible the Annex D
15854requirements of the Ada RM, and in particular sets the default
15855scheduling policy to @code{FIFO_Within_Priorities}.
15856
15857@geindex -u (gnatbind)
15858
15859@item @code{-u@emph{n}}
15860
15861Enable dynamic stack usage, with @code{n} results stored and displayed
15862at program termination. A result is generated when a task
15863terminates. Results that can't be stored are displayed on the fly, at
15864task termination. This option is currently not supported on Itanium
15865platforms. (See @ref{121,,Dynamic Stack Usage Analysis} for details.)
15866
15867@geindex -v (gnatbind)
15868
15869@item @code{-v}
15870
15871Verbose mode. Write error messages, header, summary output to
15872@code{stdout}.
15873
15874@geindex -V (gnatbind)
15875
15876@item @code{-V@emph{key}=@emph{value}}
15877
15878Store the given association of @code{key} to @code{value} in the bind environment.
15879Values stored this way can be retrieved at run time using
15880@code{GNAT.Bind_Environment}.
15881
15882@geindex -w (gnatbind)
15883
15884@item @code{-w@emph{x}}
15885
15886Warning mode; @code{x} = s/e for suppress/treat as error.
15887
15888@geindex -Wx (gnatbind)
15889
15890@item @code{-Wx@emph{e}}
15891
15892Override default wide character encoding for standard Text_IO files.
15893
15894@geindex -x (gnatbind)
15895
15896@item @code{-x}
15897
15898Exclude source files (check object consistency only).
15899
15900@geindex -Xnnn (gnatbind)
15901
15902@item @code{-X@emph{nnn}}
15903
15904Set default exit status value, normally 0 for POSIX compliance.
15905
15906@geindex -y (gnatbind)
15907
15908@item @code{-y}
15909
15910Enable leap seconds support in @code{Ada.Calendar} and its children.
15911
15912@geindex -z (gnatbind)
15913
15914@item @code{-z}
15915
15916No main subprogram.
15917@end table
15918
15919You may obtain this listing of switches by running @code{gnatbind} with
15920no arguments.
15921
15922@menu
15923* Consistency-Checking Modes::
15924* Binder Error Message Control::
15925* Elaboration Control::
15926* Output Control::
15927* Dynamic Allocation Control::
15928* Binding with Non-Ada Main Programs::
15929* Binding Programs with No Main Subprogram::
15930
15931@end menu
15932
15933@node Consistency-Checking Modes,Binder Error Message Control,,Switches for gnatbind
15934@anchor{gnat_ugn/building_executable_programs_with_gnat consistency-checking-modes}@anchor{122}@anchor{gnat_ugn/building_executable_programs_with_gnat id35}@anchor{123}
15935@subsubsection Consistency-Checking Modes
15936
15937
15938As described earlier, by default @code{gnatbind} checks
15939that object files are consistent with one another and are consistent
15940with any source files it can locate. The following switches control binder
15941access to sources.
15942
15943@quotation
15944
15945@geindex -s (gnatbind)
15946@end quotation
15947
15948
15949@table @asis
15950
15951@item @code{-s}
15952
15953Require source files to be present. In this mode, the binder must be
15954able to locate all source files that are referenced, in order to check
15955their consistency. In normal mode, if a source file cannot be located it
15956is simply ignored. If you specify this switch, a missing source
15957file is an error.
15958
15959@geindex -Wx (gnatbind)
15960
15961@item @code{-Wx@emph{e}}
15962
15963Override default wide character encoding for standard Text_IO files.
15964Normally the default wide character encoding method used for standard
15965[Wide_[Wide_]]Text_IO files is taken from the encoding specified for
15966the main source input (see description of switch
15967@code{-gnatWx} for the compiler). The
15968use of this switch for the binder (which has the same set of
15969possible arguments) overrides this default as specified.
15970
15971@geindex -x (gnatbind)
15972
15973@item @code{-x}
15974
15975Exclude source files. In this mode, the binder only checks that ALI
15976files are consistent with one another. Source files are not accessed.
15977The binder runs faster in this mode, and there is still a guarantee that
15978the resulting program is self-consistent.
15979If a source file has been edited since it was last compiled, and you
15980specify this switch, the binder will not detect that the object
15981file is out of date with respect to the source file. Note that this is the
15982mode that is automatically used by @code{gnatmake} because in this
15983case the checking against sources has already been performed by
15984@code{gnatmake} in the course of compilation (i.e., before binding).
15985@end table
15986
15987@node Binder Error Message Control,Elaboration Control,Consistency-Checking Modes,Switches for gnatbind
15988@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}
15989@subsubsection Binder Error Message Control
15990
15991
15992The following switches provide control over the generation of error
15993messages from the binder:
15994
15995@quotation
15996
15997@geindex -v (gnatbind)
15998@end quotation
15999
16000
16001@table @asis
16002
16003@item @code{-v}
16004
16005Verbose mode. In the normal mode, brief error messages are generated to
16006@code{stderr}. If this switch is present, a header is written
16007to @code{stdout} and any error messages are directed to @code{stdout}.
16008All that is written to @code{stderr} is a brief summary message.
16009
16010@geindex -b (gnatbind)
16011
16012@item @code{-b}
16013
16014Generate brief error messages to @code{stderr} even if verbose mode is
16015specified. This is relevant only when used with the
16016@code{-v} switch.
16017
16018@geindex -m (gnatbind)
16019
16020@item @code{-m@emph{n}}
16021
16022Limits the number of error messages to @code{n}, a decimal integer in the
16023range 1-999. The binder terminates immediately if this limit is reached.
16024
16025@geindex -M (gnatbind)
16026
16027@item @code{-M@emph{xxx}}
16028
16029Renames the generated main program from @code{main} to @code{xxx}.
16030This is useful in the case of some cross-building environments, where
16031the actual main program is separate from the one generated
16032by @code{gnatbind}.
16033
16034@geindex -ws (gnatbind)
16035
16036@geindex Warnings
16037
16038@item @code{-ws}
16039
16040Suppress all warning messages.
16041
16042@geindex -we (gnatbind)
16043
16044@item @code{-we}
16045
16046Treat any warning messages as fatal errors.
16047
16048@geindex -t (gnatbind)
16049
16050@geindex Time stamp checks
16051@geindex in binder
16052
16053@geindex Binder consistency checks
16054
16055@geindex Consistency checks
16056@geindex in binder
16057
16058@item @code{-t}
16059
16060The binder performs a number of consistency checks including:
16061
16062
16063@itemize *
16064
16065@item
16066Check that time stamps of a given source unit are consistent
16067
16068@item
16069Check that checksums of a given source unit are consistent
16070
16071@item
16072Check that consistent versions of @code{GNAT} were used for compilation
16073
16074@item
16075Check consistency of configuration pragmas as required
16076@end itemize
16077
16078Normally failure of such checks, in accordance with the consistency
16079requirements of the Ada Reference Manual, causes error messages to be
16080generated which abort the binder and prevent the output of a binder
16081file and subsequent link to obtain an executable.
16082
16083The @code{-t} switch converts these error messages
16084into warnings, so that
16085binding and linking can continue to completion even in the presence of such
16086errors. The result may be a failed link (due to missing symbols), or a
16087non-functional executable which has undefined semantics.
16088
16089@cartouche
16090@quotation Note
16091This means that @code{-t} should be used only in unusual situations,
16092with extreme care.
16093@end quotation
16094@end cartouche
16095@end table
16096
16097@node Elaboration Control,Output Control,Binder Error Message Control,Switches for gnatbind
16098@anchor{gnat_ugn/building_executable_programs_with_gnat id37}@anchor{126}@anchor{gnat_ugn/building_executable_programs_with_gnat elaboration-control}@anchor{127}
16099@subsubsection Elaboration Control
16100
16101
16102The following switches provide additional control over the elaboration
16103order. For full details see @ref{f,,Elaboration Order Handling in GNAT}.
16104
16105@geindex -f (gnatbind)
16106
16107
16108@table @asis
16109
16110@item @code{-f@emph{elab-order}}
16111
16112Force elaboration order.
16113
16114@code{elab-order} should be the name of a "forced elaboration order file", that
16115is, a text file containing library item names, one per line. A name of the
16116form "some.unit%s" or "some.unit (spec)" denotes the spec of Some.Unit. A
16117name of the form "some.unit%b" or "some.unit (body)" denotes the body of
16118Some.Unit. Each pair of lines is taken to mean that there is an elaboration
16119dependence of the second line on the first. For example, if the file
16120contains:
16121
16122@example
16123this (spec)
16124this (body)
16125that (spec)
16126that (body)
16127@end example
16128
16129then the spec of This will be elaborated before the body of This, and the
16130body of This will be elaborated before the spec of That, and the spec of That
16131will be elaborated before the body of That. The first and last of these three
16132dependences are already required by Ada rules, so this file is really just
16133forcing the body of This to be elaborated before the spec of That.
16134
16135The given order must be consistent with Ada rules, or else @code{gnatbind} will
16136give elaboration cycle errors. For example, if you say x (body) should be
16137elaborated before x (spec), there will be a cycle, because Ada rules require
16138x (spec) to be elaborated before x (body); you can't have the spec and body
16139both elaborated before each other.
16140
16141If you later add "with That;" to the body of This, there will be a cycle, in
16142which case you should erase either "this (body)" or "that (spec)" from the
16143above forced elaboration order file.
16144
16145Blank lines and Ada-style comments are ignored. Unit names that do not exist
16146in the program are ignored. Units in the GNAT predefined library are also
16147ignored.
16148
16149@geindex -p (gnatbind)
16150
16151@item @code{-p}
16152
16153Normally the binder attempts to choose an elaboration order that is
16154likely to minimize the likelihood of an elaboration order error resulting
16155in raising a @code{Program_Error} exception. This switch reverses the
16156action of the binder, and requests that it deliberately choose an order
16157that is likely to maximize the likelihood of an elaboration error.
16158This is useful in ensuring portability and avoiding dependence on
16159accidental fortuitous elaboration ordering.
16160
16161Normally it only makes sense to use the @code{-p}
16162switch if dynamic
16163elaboration checking is used (@code{-gnatE} switch used for compilation).
16164This is because in the default static elaboration mode, all necessary
16165@code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
16166These implicit pragmas are still respected by the binder in
16167@code{-p} mode, so a
16168safe elaboration order is assured.
16169
16170Note that @code{-p} is not intended for
16171production use; it is more for debugging/experimental use.
16172@end table
16173
16174@node Output Control,Dynamic Allocation Control,Elaboration Control,Switches for gnatbind
16175@anchor{gnat_ugn/building_executable_programs_with_gnat output-control}@anchor{128}@anchor{gnat_ugn/building_executable_programs_with_gnat id38}@anchor{129}
16176@subsubsection Output Control
16177
16178
16179The following switches allow additional control over the output
16180generated by the binder.
16181
16182@quotation
16183
16184@geindex -c (gnatbind)
16185@end quotation
16186
16187
16188@table @asis
16189
16190@item @code{-c}
16191
16192Check only. Do not generate the binder output file. In this mode the
16193binder performs all error checks but does not generate an output file.
16194
16195@geindex -e (gnatbind)
16196
16197@item @code{-e}
16198
16199Output complete list of elaboration-order dependencies, showing the
16200reason for each dependency. This output can be rather extensive but may
16201be useful in diagnosing problems with elaboration order. The output is
16202written to @code{stdout}.
16203
16204@geindex -h (gnatbind)
16205
16206@item @code{-h}
16207
16208Output usage information. The output is written to @code{stdout}.
16209
16210@geindex -K (gnatbind)
16211
16212@item @code{-K}
16213
16214Output linker options to @code{stdout}. Includes library search paths,
16215contents of pragmas Ident and Linker_Options, and libraries added
16216by @code{gnatbind}.
16217
16218@geindex -l (gnatbind)
16219
16220@item @code{-l}
16221
16222Output chosen elaboration order. The output is written to @code{stdout}.
16223
16224@geindex -O (gnatbind)
16225
16226@item @code{-O}
16227
16228Output full names of all the object files that must be linked to provide
16229the Ada component of the program. The output is written to @code{stdout}.
16230This list includes the files explicitly supplied and referenced by the user
16231as well as implicitly referenced run-time unit files. The latter are
16232omitted if the corresponding units reside in shared libraries. The
16233directory names for the run-time units depend on the system configuration.
16234
16235@geindex -o (gnatbind)
16236
16237@item @code{-o @emph{file}}
16238
16239Set name of output file to @code{file} instead of the normal
16240@code{b~`mainprog}.adb` default. Note that @code{file} denote the Ada
16241binder generated body filename.
16242Note that if this option is used, then linking must be done manually.
16243It is not possible to use gnatlink in this case, since it cannot locate
16244the binder file.
16245
16246@geindex -r (gnatbind)
16247
16248@item @code{-r}
16249
16250Generate list of @code{pragma Restrictions} that could be applied to
16251the current unit. This is useful for code audit purposes, and also may
16252be used to improve code generation in some cases.
16253@end table
16254
16255@node Dynamic Allocation Control,Binding with Non-Ada Main Programs,Output Control,Switches for gnatbind
16256@anchor{gnat_ugn/building_executable_programs_with_gnat dynamic-allocation-control}@anchor{120}@anchor{gnat_ugn/building_executable_programs_with_gnat id39}@anchor{12a}
16257@subsubsection Dynamic Allocation Control
16258
16259
16260The heap control switches -- @code{-H32} and @code{-H64} --
16261determine whether dynamic allocation uses 32-bit or 64-bit memory.
16262They only affect compiler-generated allocations via @code{__gnat_malloc};
16263explicit calls to @code{malloc} and related functions from the C
16264run-time library are unaffected.
16265
16266
16267@table @asis
16268
16269@item @code{-H32}
16270
16271Allocate memory on 32-bit heap
16272
16273@item @code{-H64}
16274
16275Allocate memory on 64-bit heap.  This is the default
16276unless explicitly overridden by a @code{'Size} clause on the access type.
16277@end table
16278
16279These switches are only effective on VMS platforms.
16280
16281@node Binding with Non-Ada Main Programs,Binding Programs with No Main Subprogram,Dynamic Allocation Control,Switches for gnatbind
16282@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}
16283@subsubsection Binding with Non-Ada Main Programs
16284
16285
16286The description so far has assumed that the main
16287program is in Ada, and that the task of the binder is to generate a
16288corresponding function @code{main} that invokes this Ada main
16289program. GNAT also supports the building of executable programs where
16290the main program is not in Ada, but some of the called routines are
16291written in Ada and compiled using GNAT (@ref{44,,Mixed Language Programming}).
16292The following switch is used in this situation:
16293
16294@quotation
16295
16296@geindex -n (gnatbind)
16297@end quotation
16298
16299
16300@table @asis
16301
16302@item @code{-n}
16303
16304No main program. The main program is not in Ada.
16305@end table
16306
16307In this case, most of the functions of the binder are still required,
16308but instead of generating a main program, the binder generates a file
16309containing the following callable routines:
16310
16311@quotation
16312
16313@geindex adainit
16314
16315
16316@table @asis
16317
16318@item @code{adainit}
16319
16320You must call this routine to initialize the Ada part of the program by
16321calling the necessary elaboration routines. A call to @code{adainit} is
16322required before the first call to an Ada subprogram.
16323
16324Note that it is assumed that the basic execution environment must be setup
16325to be appropriate for Ada execution at the point where the first Ada
16326subprogram is called. In particular, if the Ada code will do any
16327floating-point operations, then the FPU must be setup in an appropriate
16328manner. For the case of the x86, for example, full precision mode is
16329required. The procedure GNAT.Float_Control.Reset may be used to ensure
16330that the FPU is in the right state.
16331@end table
16332
16333@geindex adafinal
16334
16335
16336@table @asis
16337
16338@item @code{adafinal}
16339
16340You must call this routine to perform any library-level finalization
16341required by the Ada subprograms. A call to @code{adafinal} is required
16342after the last call to an Ada subprogram, and before the program
16343terminates.
16344@end table
16345@end quotation
16346
16347@geindex -n (gnatbind)
16348
16349@geindex Binder
16350@geindex multiple input files
16351
16352If the @code{-n} switch
16353is given, more than one ALI file may appear on
16354the command line for @code{gnatbind}. The normal @code{closure}
16355calculation is performed for each of the specified units. Calculating
16356the closure means finding out the set of units involved by tracing
16357@emph{with} references. The reason it is necessary to be able to
16358specify more than one ALI file is that a given program may invoke two or
16359more quite separate groups of Ada units.
16360
16361The binder takes the name of its output file from the last specified ALI
16362file, unless overridden by the use of the @code{-o file}.
16363
16364@geindex -o (gnatbind)
16365
16366The output is an Ada unit in source form that can be compiled with GNAT.
16367This compilation occurs automatically as part of the @code{gnatlink}
16368processing.
16369
16370Currently the GNAT run time requires a FPU using 80 bits mode
16371precision. Under targets where this is not the default it is required to
16372call GNAT.Float_Control.Reset before using floating point numbers (this
16373include float computation, float input and output) in the Ada code. A
16374side effect is that this could be the wrong mode for the foreign code
16375where floating point computation could be broken after this call.
16376
16377@node Binding Programs with No Main Subprogram,,Binding with Non-Ada Main Programs,Switches for gnatbind
16378@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}
16379@subsubsection Binding Programs with No Main Subprogram
16380
16381
16382It is possible to have an Ada program which does not have a main
16383subprogram. This program will call the elaboration routines of all the
16384packages, then the finalization routines.
16385
16386The following switch is used to bind programs organized in this manner:
16387
16388@quotation
16389
16390@geindex -z (gnatbind)
16391@end quotation
16392
16393
16394@table @asis
16395
16396@item @code{-z}
16397
16398Normally the binder checks that the unit name given on the command line
16399corresponds to a suitable main subprogram. When this switch is used,
16400a list of ALI files can be given, and the execution of the program
16401consists of elaboration of these units in an appropriate order. Note
16402that the default wide character encoding method for standard Text_IO
16403files is always set to Brackets if this switch is set (you can use
16404the binder switch
16405@code{-Wx} to override this default).
16406@end table
16407
16408@node Command-Line Access,Search Paths for gnatbind,Switches for gnatbind,Binding with gnatbind
16409@anchor{gnat_ugn/building_executable_programs_with_gnat id42}@anchor{12e}@anchor{gnat_ugn/building_executable_programs_with_gnat command-line-access}@anchor{12f}
16410@subsection Command-Line Access
16411
16412
16413The package @code{Ada.Command_Line} provides access to the command-line
16414arguments and program name. In order for this interface to operate
16415correctly, the two variables
16416
16417@example
16418int gnat_argc;
16419char **gnat_argv;
16420@end example
16421
16422@geindex gnat_argv
16423
16424@geindex gnat_argc
16425
16426are declared in one of the GNAT library routines. These variables must
16427be set from the actual @code{argc} and @code{argv} values passed to the
16428main program. With no @emph{n} present, @code{gnatbind}
16429generates the C main program to automatically set these variables.
16430If the @emph{n} switch is used, there is no automatic way to
16431set these variables. If they are not set, the procedures in
16432@code{Ada.Command_Line} will not be available, and any attempt to use
16433them will raise @code{Constraint_Error}. If command line access is
16434required, your main program must set @code{gnat_argc} and
16435@code{gnat_argv} from the @code{argc} and @code{argv} values passed to
16436it.
16437
16438@node Search Paths for gnatbind,Examples of gnatbind Usage,Command-Line Access,Binding with gnatbind
16439@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}
16440@subsection Search Paths for @code{gnatbind}
16441
16442
16443The binder takes the name of an ALI file as its argument and needs to
16444locate source files as well as other ALI files to verify object consistency.
16445
16446For source files, it follows exactly the same search rules as @code{gcc}
16447(see @ref{89,,Search Paths and the Run-Time Library (RTL)}). For ALI files the
16448directories searched are:
16449
16450
16451@itemize *
16452
16453@item
16454The directory containing the ALI file named in the command line, unless
16455the switch @code{-I-} is specified.
16456
16457@item
16458All directories specified by @code{-I}
16459switches on the @code{gnatbind}
16460command line, in the order given.
16461
16462@geindex ADA_PRJ_OBJECTS_FILE
16463
16464@item
16465Each of the directories listed in the text file whose name is given
16466by the
16467@geindex ADA_PRJ_OBJECTS_FILE
16468@geindex environment variable; ADA_PRJ_OBJECTS_FILE
16469@code{ADA_PRJ_OBJECTS_FILE} environment variable.
16470
16471@geindex ADA_PRJ_OBJECTS_FILE
16472@geindex environment variable; ADA_PRJ_OBJECTS_FILE
16473@code{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the gnat
16474driver when project files are used. It should not normally be set
16475by other means.
16476
16477@geindex ADA_OBJECTS_PATH
16478
16479@item
16480Each of the directories listed in the value of the
16481@geindex ADA_OBJECTS_PATH
16482@geindex environment variable; ADA_OBJECTS_PATH
16483@code{ADA_OBJECTS_PATH} environment variable.
16484Construct this value
16485exactly as the
16486@geindex PATH
16487@geindex environment variable; PATH
16488@code{PATH} environment variable: a list of directory
16489names separated by colons (semicolons when working with the NT version
16490of GNAT).
16491
16492@item
16493The content of the @code{ada_object_path} file which is part of the GNAT
16494installation tree and is used to store standard libraries such as the
16495GNAT Run Time Library (RTL) unless the switch @code{-nostdlib} is
16496specified. See @ref{87,,Installing a library}
16497@end itemize
16498
16499@geindex -I (gnatbind)
16500
16501@geindex -aI (gnatbind)
16502
16503@geindex -aO (gnatbind)
16504
16505In the binder the switch @code{-I}
16506is used to specify both source and
16507library file paths. Use @code{-aI}
16508instead if you want to specify
16509source paths only, and @code{-aO}
16510if you want to specify library paths
16511only. This means that for the binder
16512@code{-I@emph{dir}} is equivalent to
16513@code{-aI@emph{dir}}
16514@code{-aO`@emph{dir}}.
16515The binder generates the bind file (a C language source file) in the
16516current working directory.
16517
16518@geindex Ada
16519
16520@geindex System
16521
16522@geindex Interfaces
16523
16524@geindex GNAT
16525
16526The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
16527children make up the GNAT Run-Time Library, together with the package
16528GNAT and its children, which contain a set of useful additional
16529library functions provided by GNAT. The sources for these units are
16530needed by the compiler and are kept together in one directory. The ALI
16531files and object files generated by compiling the RTL are needed by the
16532binder and the linker and are kept together in one directory, typically
16533different from the directory containing the sources. In a normal
16534installation, you need not specify these directory names when compiling
16535or binding. Either the environment variables or the built-in defaults
16536cause these files to be found.
16537
16538Besides simplifying access to the RTL, a major use of search paths is
16539in compiling sources from multiple directories. This can make
16540development environments much more flexible.
16541
16542@node Examples of gnatbind Usage,,Search Paths for gnatbind,Binding with gnatbind
16543@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}
16544@subsection Examples of @code{gnatbind} Usage
16545
16546
16547Here are some examples of @code{gnatbind} invovations:
16548
16549@quotation
16550
16551@example
16552gnatbind hello
16553@end example
16554
16555The main program @code{Hello} (source program in @code{hello.adb}) is
16556bound using the standard switch settings. The generated main program is
16557@code{b~hello.adb}. This is the normal, default use of the binder.
16558
16559@example
16560gnatbind hello -o mainprog.adb
16561@end example
16562
16563The main program @code{Hello} (source program in @code{hello.adb}) is
16564bound using the standard switch settings. The generated main program is
16565@code{mainprog.adb} with the associated spec in
16566@code{mainprog.ads}. Note that you must specify the body here not the
16567spec. Note that if this option is used, then linking must be done manually,
16568since gnatlink will not be able to find the generated file.
16569@end quotation
16570
16571@node Linking with gnatlink,Using the GNU make Utility,Binding with gnatbind,Building Executable Programs with GNAT
16572@anchor{gnat_ugn/building_executable_programs_with_gnat id45}@anchor{133}@anchor{gnat_ugn/building_executable_programs_with_gnat linking-with-gnatlink}@anchor{1e}
16573@section Linking with @code{gnatlink}
16574
16575
16576@geindex gnatlink
16577
16578This chapter discusses @code{gnatlink}, a tool that links
16579an Ada program and builds an executable file. This utility
16580invokes the system linker (via the @code{gcc} command)
16581with a correct list of object files and library references.
16582@code{gnatlink} automatically determines the list of files and
16583references for the Ada part of a program. It uses the binder file
16584generated by the @code{gnatbind} to determine this list.
16585
16586@menu
16587* Running gnatlink::
16588* Switches for gnatlink::
16589
16590@end menu
16591
16592@node Running gnatlink,Switches for gnatlink,,Linking with gnatlink
16593@anchor{gnat_ugn/building_executable_programs_with_gnat id46}@anchor{134}@anchor{gnat_ugn/building_executable_programs_with_gnat running-gnatlink}@anchor{135}
16594@subsection Running @code{gnatlink}
16595
16596
16597The form of the @code{gnatlink} command is
16598
16599@example
16600$ gnatlink [ switches ] mainprog [.ali]
16601           [ non-Ada objects ] [ linker options ]
16602@end example
16603
16604The arguments of @code{gnatlink} (switches, main @code{ALI} file,
16605non-Ada objects
16606or linker options) may be in any order, provided that no non-Ada object may
16607be mistaken for a main @code{ALI} file.
16608Any file name @code{F} without the @code{.ali}
16609extension will be taken as the main @code{ALI} file if a file exists
16610whose name is the concatenation of @code{F} and @code{.ali}.
16611
16612@code{mainprog.ali} references the ALI file of the main program.
16613The @code{.ali} extension of this file can be omitted. From this
16614reference, @code{gnatlink} locates the corresponding binder file
16615@code{b~mainprog.adb} and, using the information in this file along
16616with the list of non-Ada objects and linker options, constructs a
16617linker command file to create the executable.
16618
16619The arguments other than the @code{gnatlink} switches and the main
16620@code{ALI} file are passed to the linker uninterpreted.
16621They typically include the names of
16622object files for units written in other languages than Ada and any library
16623references required to resolve references in any of these foreign language
16624units, or in @code{Import} pragmas in any Ada units.
16625
16626@code{linker options} is an optional list of linker specific
16627switches.
16628The default linker called by gnatlink is @code{gcc} which in
16629turn calls the appropriate system linker.
16630
16631One useful option for the linker is @code{-s}: it reduces the size of the
16632executable by removing all symbol table and relocation information from the
16633executable.
16634
16635Standard options for the linker such as @code{-lmy_lib} or
16636@code{-Ldir} can be added as is.
16637For options that are not recognized by
16638@code{gcc} as linker options, use the @code{gcc} switches
16639@code{-Xlinker} or @code{-Wl,}.
16640
16641Refer to the GCC documentation for
16642details.
16643
16644Here is an example showing how to generate a linker map:
16645
16646@example
16647$ gnatlink my_prog -Wl,-Map,MAPFILE
16648@end example
16649
16650Using @code{linker options} it is possible to set the program stack and
16651heap size.
16652See @ref{136,,Setting Stack Size from gnatlink} and
16653@ref{137,,Setting Heap Size from gnatlink}.
16654
16655@code{gnatlink} determines the list of objects required by the Ada
16656program and prepends them to the list of objects passed to the linker.
16657@code{gnatlink} also gathers any arguments set by the use of
16658@code{pragma Linker_Options} and adds them to the list of arguments
16659presented to the linker.
16660
16661@node Switches for gnatlink,,Running gnatlink,Linking with gnatlink
16662@anchor{gnat_ugn/building_executable_programs_with_gnat id47}@anchor{138}@anchor{gnat_ugn/building_executable_programs_with_gnat switches-for-gnatlink}@anchor{139}
16663@subsection Switches for @code{gnatlink}
16664
16665
16666The following switches are available with the @code{gnatlink} utility:
16667
16668@geindex --version (gnatlink)
16669
16670
16671@table @asis
16672
16673@item @code{--version}
16674
16675Display Copyright and version, then exit disregarding all other options.
16676@end table
16677
16678@geindex --help (gnatlink)
16679
16680
16681@table @asis
16682
16683@item @code{--help}
16684
16685If @code{--version} was not used, display usage, then exit disregarding
16686all other options.
16687@end table
16688
16689@geindex Command line length
16690
16691@geindex -f (gnatlink)
16692
16693
16694@table @asis
16695
16696@item @code{-f}
16697
16698On some targets, the command line length is limited, and @code{gnatlink}
16699will generate a separate file for the linker if the list of object files
16700is too long.
16701The @code{-f} switch forces this file
16702to be generated even if
16703the limit is not exceeded. This is useful in some cases to deal with
16704special situations where the command line length is exceeded.
16705@end table
16706
16707@geindex Debugging information
16708@geindex including
16709
16710@geindex -g (gnatlink)
16711
16712
16713@table @asis
16714
16715@item @code{-g}
16716
16717The option to include debugging information causes the Ada bind file (in
16718other words, @code{b~mainprog.adb}) to be compiled with @code{-g}.
16719In addition, the binder does not delete the @code{b~mainprog.adb},
16720@code{b~mainprog.o} and @code{b~mainprog.ali} files.
16721Without @code{-g}, the binder removes these files by default.
16722@end table
16723
16724@geindex -n (gnatlink)
16725
16726
16727@table @asis
16728
16729@item @code{-n}
16730
16731Do not compile the file generated by the binder. This may be used when
16732a link is rerun with different options, but there is no need to recompile
16733the binder file.
16734@end table
16735
16736@geindex -v (gnatlink)
16737
16738
16739@table @asis
16740
16741@item @code{-v}
16742
16743Verbose mode. Causes additional information to be output, including a full
16744list of the included object files.
16745This switch option is most useful when you want
16746to see what set of object files are being used in the link step.
16747@end table
16748
16749@geindex -v -v (gnatlink)
16750
16751
16752@table @asis
16753
16754@item @code{-v -v}
16755
16756Very verbose mode. Requests that the compiler operate in verbose mode when
16757it compiles the binder file, and that the system linker run in verbose mode.
16758@end table
16759
16760@geindex -o (gnatlink)
16761
16762
16763@table @asis
16764
16765@item @code{-o @emph{exec-name}}
16766
16767@code{exec-name} specifies an alternate name for the generated
16768executable program. If this switch is omitted, the executable has the same
16769name as the main unit. For example, @code{gnatlink try.ali} creates
16770an executable called @code{try}.
16771@end table
16772
16773@geindex -B (gnatlink)
16774
16775
16776@table @asis
16777
16778@item @code{-B@emph{dir}}
16779
16780Load compiler executables (for example, @code{gnat1}, the Ada compiler)
16781from @code{dir} instead of the default location. Only use this switch
16782when multiple versions of the GNAT compiler are available.
16783See the @code{Directory Options} section in @cite{The_GNU_Compiler_Collection}
16784for further details. You would normally use the @code{-b} or
16785@code{-V} switch instead.
16786@end table
16787
16788@geindex -M (gnatlink)
16789
16790
16791@table @asis
16792
16793@item @code{-M}
16794
16795When linking an executable, create a map file. The name of the map file
16796has the same name as the executable with extension ".map".
16797@end table
16798
16799@geindex -M= (gnatlink)
16800
16801
16802@table @asis
16803
16804@item @code{-M=@emph{mapfile}}
16805
16806When linking an executable, create a map file. The name of the map file is
16807@code{mapfile}.
16808@end table
16809
16810@geindex --GCC=compiler_name (gnatlink)
16811
16812
16813@table @asis
16814
16815@item @code{--GCC=@emph{compiler_name}}
16816
16817Program used for compiling the binder file. The default is
16818@code{gcc}. You need to use quotes around @code{compiler_name} if
16819@code{compiler_name} contains spaces or other separator characters.
16820As an example @code{--GCC="foo -x -y"} will instruct @code{gnatlink} to
16821use @code{foo -x -y} as your compiler. Note that switch @code{-c} is always
16822inserted after your command name. Thus in the above example the compiler
16823command that will be used by @code{gnatlink} will be @code{foo -c -x -y}.
16824A limitation of this syntax is that the name and path name of the executable
16825itself must not include any embedded spaces. If the compiler executable is
16826different from the default one (gcc or <prefix>-gcc), then the back-end
16827switches in the ALI file are not used to compile the binder generated source.
16828For example, this is the case with @code{--GCC="foo -x -y"}. But the back end
16829switches will be used for @code{--GCC="gcc -gnatv"}. If several
16830@code{--GCC=compiler_name} are used, only the last @code{compiler_name}
16831is taken into account. However, all the additional switches are also taken
16832into account. Thus,
16833@code{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
16834@code{--GCC="bar -x -y -z -t"}.
16835@end table
16836
16837@geindex --LINK= (gnatlink)
16838
16839
16840@table @asis
16841
16842@item @code{--LINK=@emph{name}}
16843
16844@code{name} is the name of the linker to be invoked. This is especially
16845useful in mixed language programs since languages such as C++ require
16846their own linker to be used. When this switch is omitted, the default
16847name for the linker is @code{gcc}. When this switch is used, the
16848specified linker is called instead of @code{gcc} with exactly the same
16849parameters that would have been passed to @code{gcc} so if the desired
16850linker requires different parameters it is necessary to use a wrapper
16851script that massages the parameters before invoking the real linker. It
16852may be useful to control the exact invocation by using the verbose
16853switch.
16854@end table
16855
16856@node Using the GNU make Utility,,Linking with gnatlink,Building Executable Programs with GNAT
16857@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}
16858@section Using the GNU @code{make} Utility
16859
16860
16861@geindex make (GNU)
16862@geindex GNU make
16863
16864This chapter offers some examples of makefiles that solve specific
16865problems. It does not explain how to write a makefile, nor does it try to replace the
16866@code{gnatmake} utility (@ref{1b,,Building with gnatmake}).
16867
16868All the examples in this section are specific to the GNU version of
16869make. Although @code{make} is a standard utility, and the basic language
16870is the same, these examples use some advanced features found only in
16871@code{GNU make}.
16872
16873@menu
16874* Using gnatmake in a Makefile::
16875* Automatically Creating a List of Directories::
16876* Generating the Command Line Switches::
16877* Overcoming Command Line Length Limits::
16878
16879@end menu
16880
16881@node Using gnatmake in a Makefile,Automatically Creating a List of Directories,,Using the GNU make Utility
16882@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}
16883@subsection Using gnatmake in a Makefile
16884
16885
16886@c index makefile (GNU make)
16887
16888Complex project organizations can be handled in a very powerful way by
16889using GNU make combined with gnatmake. For instance, here is a Makefile
16890which allows you to build each subsystem of a big project into a separate
16891shared library. Such a makefile allows you to significantly reduce the link
16892time of very big applications while maintaining full coherence at
16893each step of the build process.
16894
16895The list of dependencies are handled automatically by
16896@code{gnatmake}. The Makefile is simply used to call gnatmake in each of
16897the appropriate directories.
16898
16899Note that you should also read the example on how to automatically
16900create the list of directories
16901(@ref{13d,,Automatically Creating a List of Directories})
16902which might help you in case your project has a lot of subdirectories.
16903
16904@example
16905## This Makefile is intended to be used with the following directory
16906## configuration:
16907##  - The sources are split into a series of csc (computer software components)
16908##    Each of these csc is put in its own directory.
16909##    Their name are referenced by the directory names.
16910##    They will be compiled into shared library (although this would also work
16911##    with static libraries
16912##  - The main program (and possibly other packages that do not belong to any
16913##    csc is put in the top level directory (where the Makefile is).
16914##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
16915##                    \\_ second_csc (sources) __ lib (will contain the library)
16916##                    \\_ ...
16917## Although this Makefile is build for shared library, it is easy to modify
16918## to build partial link objects instead (modify the lines with -shared and
16919## gnatlink below)
16920##
16921## With this makefile, you can change any file in the system or add any new
16922## file, and everything will be recompiled correctly (only the relevant shared
16923## objects will be recompiled, and the main program will be re-linked).
16924
16925# The list of computer software component for your project. This might be
16926# generated automatically.
16927CSC_LIST=aa bb cc
16928
16929# Name of the main program (no extension)
16930MAIN=main
16931
16932# If we need to build objects with -fPIC, uncomment the following line
16933#NEED_FPIC=-fPIC
16934
16935# The following variable should give the directory containing libgnat.so
16936# You can get this directory through 'gnatls -v'. This is usually the last
16937# directory in the Object_Path.
16938GLIB=...
16939
16940# The directories for the libraries
16941# (This macro expands the list of CSC to the list of shared libraries, you
16942# could simply use the expanded form:
16943# LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
16944LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
16945
16946$@{MAIN@}: objects $@{LIB_DIR@}
16947    gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
16948    gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
16949
16950objects::
16951    # recompile the sources
16952    gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
16953
16954# Note: In a future version of GNAT, the following commands will be simplified
16955# by a new tool, gnatmlib
16956$@{LIB_DIR@}:
16957    mkdir -p $@{dir $@@ @}
16958    cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
16959    cd $@{dir $@@ @} && cp -f ../*.ali .
16960
16961# The dependencies for the modules
16962# Note that we have to force the expansion of *.o, since in some cases
16963# make won't be able to do it itself.
16964aa/lib/libaa.so: $@{wildcard aa/*.o@}
16965bb/lib/libbb.so: $@{wildcard bb/*.o@}
16966cc/lib/libcc.so: $@{wildcard cc/*.o@}
16967
16968# Make sure all of the shared libraries are in the path before starting the
16969# program
16970run::
16971    LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
16972
16973clean::
16974    $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
16975    $@{RM@} $@{CSC_LIST:%=%/*.ali@}
16976    $@{RM@} $@{CSC_LIST:%=%/*.o@}
16977    $@{RM@} *.o *.ali $@{MAIN@}
16978@end example
16979
16980@node Automatically Creating a List of Directories,Generating the Command Line Switches,Using gnatmake in a Makefile,Using the GNU make Utility
16981@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}
16982@subsection Automatically Creating a List of Directories
16983
16984
16985In most makefiles, you will have to specify a list of directories, and
16986store it in a variable. For small projects, it is often easier to
16987specify each of them by hand, since you then have full control over what
16988is the proper order for these directories, which ones should be
16989included.
16990
16991However, in larger projects, which might involve hundreds of
16992subdirectories, it might be more convenient to generate this list
16993automatically.
16994
16995The example below presents two methods. The first one, although less
16996general, gives you more control over the list. It involves wildcard
16997characters, that are automatically expanded by @code{make}. Its
16998shortcoming is that you need to explicitly specify some of the
16999organization of your project, such as for instance the directory tree
17000depth, whether some directories are found in a separate tree, etc.
17001
17002The second method is the most general one. It requires an external
17003program, called @code{find}, which is standard on all Unix systems. All
17004the directories found under a given root directory will be added to the
17005list.
17006
17007@example
17008# The examples below are based on the following directory hierarchy:
17009# All the directories can contain any number of files
17010# ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
17011#                       ->  ab
17012#                       ->  ac
17013#                ->  b  ->  ba  ->  baa
17014#                       ->  bb
17015#                       ->  bc
17016# This Makefile creates a variable called DIRS, that can be reused any time
17017# you need this list (see the other examples in this section)
17018
17019# The root of your project's directory hierarchy
17020ROOT_DIRECTORY=.
17021
17022####
17023# First method: specify explicitly the list of directories
17024# This allows you to specify any subset of all the directories you need.
17025####
17026
17027DIRS := a/aa/ a/ab/ b/ba/
17028
17029####
17030# Second method: use wildcards
17031# Note that the argument(s) to wildcard below should end with a '/'.
17032# Since wildcards also return file names, we have to filter them out
17033# to avoid duplicate directory names.
17034# We thus use make's `@w{`}dir`@w{`} and `@w{`}sort`@w{`} functions.
17035# It sets DIRs to the following value (note that the directories aaa and baa
17036# are not given, unless you change the arguments to wildcard).
17037# DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
17038####
17039
17040DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
17041                    $@{ROOT_DIRECTORY@}/*/*/@}@}@}
17042
17043####
17044# Third method: use an external program
17045# This command is much faster if run on local disks, avoiding NFS slowdowns.
17046# This is the most complete command: it sets DIRs to the following value:
17047# DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
17048####
17049
17050DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
17051@end example
17052
17053@node Generating the Command Line Switches,Overcoming Command Line Length Limits,Automatically Creating a List of Directories,Using the GNU make Utility
17054@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}
17055@subsection Generating the Command Line Switches
17056
17057
17058Once you have created the list of directories as explained in the
17059previous section (@ref{13d,,Automatically Creating a List of Directories}),
17060you can easily generate the command line arguments to pass to gnatmake.
17061
17062For the sake of completeness, this example assumes that the source path
17063is not the same as the object path, and that you have two separate lists
17064of directories.
17065
17066@example
17067# see "Automatically creating a list of directories" to create
17068# these variables
17069SOURCE_DIRS=
17070OBJECT_DIRS=
17071
17072GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
17073GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
17074
17075all:
17076        gnatmake $@{GNATMAKE_SWITCHES@} main_unit
17077@end example
17078
17079@node Overcoming Command Line Length Limits,,Generating the Command Line Switches,Using the GNU make Utility
17080@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}
17081@subsection Overcoming Command Line Length Limits
17082
17083
17084One problem that might be encountered on big projects is that many
17085operating systems limit the length of the command line. It is thus hard to give
17086gnatmake the list of source and object directories.
17087
17088This example shows how you can set up environment variables, which will
17089make @code{gnatmake} behave exactly as if the directories had been
17090specified on the command line, but have a much higher length limit (or
17091even none on most systems).
17092
17093It assumes that you have created a list of directories in your Makefile,
17094using one of the methods presented in
17095@ref{13d,,Automatically Creating a List of Directories}.
17096For the sake of completeness, we assume that the object
17097path (where the ALI files are found) is different from the sources patch.
17098
17099Note a small trick in the Makefile below: for efficiency reasons, we
17100create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
17101expanded immediately by @code{make}. This way we overcome the standard
17102make behavior which is to expand the variables only when they are
17103actually used.
17104
17105On Windows, if you are using the standard Windows command shell, you must
17106replace colons with semicolons in the assignments to these variables.
17107
17108@example
17109# In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
17110# This is the same thing as putting the -I arguments on the command line.
17111# (the equivalent of using -aI on the command line would be to define
17112#  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
17113# You can of course have different values for these variables.
17114#
17115# Note also that we need to keep the previous values of these variables, since
17116# they might have been set before running 'make' to specify where the GNAT
17117# library is installed.
17118
17119# see "Automatically creating a list of directories" to create these
17120# variables
17121SOURCE_DIRS=
17122OBJECT_DIRS=
17123
17124empty:=
17125space:=$@{empty@} $@{empty@}
17126SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
17127OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
17128ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
17129ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
17130export ADA_INCLUDE_PATH
17131export ADA_OBJECTS_PATH
17132
17133all:
17134        gnatmake main_unit
17135@end example
17136
17137@node GNAT Utility Programs,GNAT and Program Execution,Building Executable Programs with GNAT,Top
17138@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}
17139@chapter GNAT Utility Programs
17140
17141
17142This chapter describes a number of utility programs:
17143
17144
17145
17146@itemize *
17147
17148@item
17149@ref{20,,The File Cleanup Utility gnatclean}
17150
17151@item
17152@ref{21,,The GNAT Library Browser gnatls}
17153
17154@item
17155@ref{22,,The Cross-Referencing Tools gnatxref and gnatfind}
17156
17157@item
17158@ref{23,,The Ada to HTML Converter gnathtml}
17159@end itemize
17160
17161Other GNAT utilities are described elsewhere in this manual:
17162
17163
17164@itemize *
17165
17166@item
17167@ref{59,,Handling Arbitrary File Naming Conventions with gnatname}
17168
17169@item
17170@ref{63,,File Name Krunching with gnatkr}
17171
17172@item
17173@ref{36,,Renaming Files with gnatchop}
17174
17175@item
17176@ref{17,,Preprocessing with gnatprep}
17177@end itemize
17178
17179@menu
17180* The File Cleanup Utility gnatclean::
17181* The GNAT Library Browser gnatls::
17182* The Cross-Referencing Tools gnatxref and gnatfind::
17183* The Ada to HTML Converter gnathtml::
17184
17185@end menu
17186
17187@node The File Cleanup Utility gnatclean,The GNAT Library Browser gnatls,,GNAT Utility Programs
17188@anchor{gnat_ugn/gnat_utility_programs id2}@anchor{145}@anchor{gnat_ugn/gnat_utility_programs the-file-cleanup-utility-gnatclean}@anchor{20}
17189@section The File Cleanup Utility @code{gnatclean}
17190
17191
17192@geindex File cleanup tool
17193
17194@geindex gnatclean
17195
17196@code{gnatclean} is a tool that allows the deletion of files produced by the
17197compiler, binder and linker, including ALI files, object files, tree files,
17198expanded source files, library files, interface copy source files, binder
17199generated files and executable files.
17200
17201@menu
17202* Running gnatclean::
17203* Switches for gnatclean::
17204
17205@end menu
17206
17207@node Running gnatclean,Switches for gnatclean,,The File Cleanup Utility gnatclean
17208@anchor{gnat_ugn/gnat_utility_programs running-gnatclean}@anchor{146}@anchor{gnat_ugn/gnat_utility_programs id3}@anchor{147}
17209@subsection Running @code{gnatclean}
17210
17211
17212The @code{gnatclean} command has the form:
17213
17214@quotation
17215
17216@example
17217$ gnatclean switches names
17218@end example
17219@end quotation
17220
17221where @code{names} is a list of source file names. Suffixes @code{.ads} and
17222@code{adb} may be omitted. If a project file is specified using switch
17223@code{-P}, then @code{names} may be completely omitted.
17224
17225In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17226if switch @code{-c} is not specified, by the binder and
17227the linker. In informative-only mode, specified by switch
17228@code{-n}, the list of files that would have been deleted in
17229normal mode is listed, but no file is actually deleted.
17230
17231@node Switches for gnatclean,,Running gnatclean,The File Cleanup Utility gnatclean
17232@anchor{gnat_ugn/gnat_utility_programs id4}@anchor{148}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatclean}@anchor{149}
17233@subsection Switches for @code{gnatclean}
17234
17235
17236@code{gnatclean} recognizes the following switches:
17237
17238@geindex --version (gnatclean)
17239
17240
17241@table @asis
17242
17243@item @code{--version}
17244
17245Display Copyright and version, then exit disregarding all other options.
17246@end table
17247
17248@geindex --help (gnatclean)
17249
17250
17251@table @asis
17252
17253@item @code{--help}
17254
17255If @code{--version} was not used, display usage, then exit disregarding
17256all other options.
17257
17258@item @code{--subdirs=@emph{subdir}}
17259
17260Actual object directory of each project file is the subdirectory subdir of the
17261object directory specified or defaulted in the project file.
17262
17263@item @code{--unchecked-shared-lib-imports}
17264
17265By default, shared library projects are not allowed to import static library
17266projects. When this switch is used on the command line, this restriction is
17267relaxed.
17268@end table
17269
17270@geindex -c (gnatclean)
17271
17272
17273@table @asis
17274
17275@item @code{-c}
17276
17277Only attempt to delete the files produced by the compiler, not those produced
17278by the binder or the linker. The files that are not to be deleted are library
17279files, interface copy files, binder generated files and executable files.
17280@end table
17281
17282@geindex -D (gnatclean)
17283
17284
17285@table @asis
17286
17287@item @code{-D @emph{dir}}
17288
17289Indicate that ALI and object files should normally be found in directory @code{dir}.
17290@end table
17291
17292@geindex -F (gnatclean)
17293
17294
17295@table @asis
17296
17297@item @code{-F}
17298
17299When using project files, if some errors or warnings are detected during
17300parsing and verbose mode is not in effect (no use of switch
17301-v), then error lines start with the full path name of the project
17302file, rather than its simple file name.
17303@end table
17304
17305@geindex -h (gnatclean)
17306
17307
17308@table @asis
17309
17310@item @code{-h}
17311
17312Output a message explaining the usage of @code{gnatclean}.
17313@end table
17314
17315@geindex -n (gnatclean)
17316
17317
17318@table @asis
17319
17320@item @code{-n}
17321
17322Informative-only mode. Do not delete any files. Output the list of the files
17323that would have been deleted if this switch was not specified.
17324@end table
17325
17326@geindex -P (gnatclean)
17327
17328
17329@table @asis
17330
17331@item @code{-P@emph{project}}
17332
17333Use project file @code{project}. Only one such switch can be used.
17334When cleaning a project file, the files produced by the compilation of the
17335immediate sources or inherited sources of the project files are to be
17336deleted. This is not depending on the presence or not of executable names
17337on the command line.
17338@end table
17339
17340@geindex -q (gnatclean)
17341
17342
17343@table @asis
17344
17345@item @code{-q}
17346
17347Quiet output. If there are no errors, do not output anything, except in
17348verbose mode (switch -v) or in informative-only mode
17349(switch -n).
17350@end table
17351
17352@geindex -r (gnatclean)
17353
17354
17355@table @asis
17356
17357@item @code{-r}
17358
17359When a project file is specified (using switch -P),
17360clean all imported and extended project files, recursively. If this switch
17361is not specified, only the files related to the main project file are to be
17362deleted. This switch has no effect if no project file is specified.
17363@end table
17364
17365@geindex -v (gnatclean)
17366
17367
17368@table @asis
17369
17370@item @code{-v}
17371
17372Verbose mode.
17373@end table
17374
17375@geindex -vP (gnatclean)
17376
17377
17378@table @asis
17379
17380@item @code{-vP@emph{x}}
17381
17382Indicates the verbosity of the parsing of GNAT project files.
17383@ref{de,,Switches Related to Project Files}.
17384@end table
17385
17386@geindex -X (gnatclean)
17387
17388
17389@table @asis
17390
17391@item @code{-X@emph{name}=@emph{value}}
17392
17393Indicates that external variable @code{name} has the value @code{value}.
17394The Project Manager will use this value for occurrences of
17395@code{external(name)} when parsing the project file.
17396See @ref{de,,Switches Related to Project Files}.
17397@end table
17398
17399@geindex -aO (gnatclean)
17400
17401
17402@table @asis
17403
17404@item @code{-aO@emph{dir}}
17405
17406When searching for ALI and object files, look in directory @code{dir}.
17407@end table
17408
17409@geindex -I (gnatclean)
17410
17411
17412@table @asis
17413
17414@item @code{-I@emph{dir}}
17415
17416Equivalent to @code{-aO@emph{dir}}.
17417@end table
17418
17419@geindex -I- (gnatclean)
17420
17421@geindex Source files
17422@geindex suppressing search
17423
17424
17425@table @asis
17426
17427@item @code{-I-}
17428
17429Do not look for ALI or object files in the directory
17430where @code{gnatclean} was invoked.
17431@end table
17432
17433@node The GNAT Library Browser gnatls,The Cross-Referencing Tools gnatxref and gnatfind,The File Cleanup Utility gnatclean,GNAT Utility Programs
17434@anchor{gnat_ugn/gnat_utility_programs the-gnat-library-browser-gnatls}@anchor{21}@anchor{gnat_ugn/gnat_utility_programs id5}@anchor{14a}
17435@section The GNAT Library Browser @code{gnatls}
17436
17437
17438@geindex Library browser
17439
17440@geindex gnatls
17441
17442@code{gnatls} is a tool that outputs information about compiled
17443units. It gives the relationship between objects, unit names and source
17444files. It can also be used to check the source dependencies of a unit
17445as well as various characteristics.
17446
17447@menu
17448* Running gnatls::
17449* Switches for gnatls::
17450* Example of gnatls Usage::
17451
17452@end menu
17453
17454@node Running gnatls,Switches for gnatls,,The GNAT Library Browser gnatls
17455@anchor{gnat_ugn/gnat_utility_programs id6}@anchor{14b}@anchor{gnat_ugn/gnat_utility_programs running-gnatls}@anchor{14c}
17456@subsection Running @code{gnatls}
17457
17458
17459The @code{gnatls} command has the form
17460
17461@quotation
17462
17463@example
17464$ gnatls switches object_or_ali_file
17465@end example
17466@end quotation
17467
17468The main argument is the list of object or @code{ali} files
17469(see @ref{42,,The Ada Library Information Files})
17470for which information is requested.
17471
17472In normal mode, without additional option, @code{gnatls} produces a
17473four-column listing. Each line represents information for a specific
17474object. The first column gives the full path of the object, the second
17475column gives the name of the principal unit in this object, the third
17476column gives the status of the source and the fourth column gives the
17477full path of the source representing this unit.
17478Here is a simple example of use:
17479
17480@quotation
17481
17482@example
17483$ gnatls *.o
17484./demo1.o            demo1            DIF demo1.adb
17485./demo2.o            demo2             OK demo2.adb
17486./hello.o            h1                OK hello.adb
17487./instr-child.o      instr.child      MOK instr-child.adb
17488./instr.o            instr             OK instr.adb
17489./tef.o              tef              DIF tef.adb
17490./text_io_example.o  text_io_example   OK text_io_example.adb
17491./tgef.o             tgef             DIF tgef.adb
17492@end example
17493@end quotation
17494
17495The first line can be interpreted as follows: the main unit which is
17496contained in
17497object file @code{demo1.o} is demo1, whose main source is in
17498@code{demo1.adb}. Furthermore, the version of the source used for the
17499compilation of demo1 has been modified (DIF). Each source file has a status
17500qualifier which can be:
17501
17502
17503@table @asis
17504
17505@item @emph{OK (unchanged)}
17506
17507The version of the source file used for the compilation of the
17508specified unit corresponds exactly to the actual source file.
17509
17510@item @emph{MOK (slightly modified)}
17511
17512The version of the source file used for the compilation of the
17513specified unit differs from the actual source file but not enough to
17514require recompilation. If you use gnatmake with the option
17515@code{-m} (minimal recompilation), a file marked
17516MOK will not be recompiled.
17517
17518@item @emph{DIF (modified)}
17519
17520No version of the source found on the path corresponds to the source
17521used to build this object.
17522
17523@item @emph{??? (file not found)}
17524
17525No source file was found for this unit.
17526
17527@item @emph{HID (hidden,  unchanged version not first on PATH)}
17528
17529The version of the source that corresponds exactly to the source used
17530for compilation has been found on the path but it is hidden by another
17531version of the same source that has been modified.
17532@end table
17533
17534@node Switches for gnatls,Example of gnatls Usage,Running gnatls,The GNAT Library Browser gnatls
17535@anchor{gnat_ugn/gnat_utility_programs id7}@anchor{14d}@anchor{gnat_ugn/gnat_utility_programs switches-for-gnatls}@anchor{14e}
17536@subsection Switches for @code{gnatls}
17537
17538
17539@code{gnatls} recognizes the following switches:
17540
17541@geindex --version (gnatls)
17542
17543
17544@table @asis
17545
17546@item @code{--version}
17547
17548Display Copyright and version, then exit disregarding all other options.
17549@end table
17550
17551@geindex --help (gnatls)
17552
17553
17554@table @asis
17555
17556@item @code{--help}
17557
17558If @code{--version} was not used, display usage, then exit disregarding
17559all other options.
17560@end table
17561
17562@geindex -a (gnatls)
17563
17564
17565@table @asis
17566
17567@item @code{-a}
17568
17569Consider all units, including those of the predefined Ada library.
17570Especially useful with @code{-d}.
17571@end table
17572
17573@geindex -d (gnatls)
17574
17575
17576@table @asis
17577
17578@item @code{-d}
17579
17580List sources from which specified units depend on.
17581@end table
17582
17583@geindex -h (gnatls)
17584
17585
17586@table @asis
17587
17588@item @code{-h}
17589
17590Output the list of options.
17591@end table
17592
17593@geindex -o (gnatls)
17594
17595
17596@table @asis
17597
17598@item @code{-o}
17599
17600Only output information about object files.
17601@end table
17602
17603@geindex -s (gnatls)
17604
17605
17606@table @asis
17607
17608@item @code{-s}
17609
17610Only output information about source files.
17611@end table
17612
17613@geindex -u (gnatls)
17614
17615
17616@table @asis
17617
17618@item @code{-u}
17619
17620Only output information about compilation units.
17621@end table
17622
17623@geindex -files (gnatls)
17624
17625
17626@table @asis
17627
17628@item @code{-files=@emph{file}}
17629
17630Take as arguments the files listed in text file @code{file}.
17631Text file @code{file} may contain empty lines that are ignored.
17632Each nonempty line should contain the name of an existing file.
17633Several such switches may be specified simultaneously.
17634@end table
17635
17636@geindex -aO (gnatls)
17637
17638@geindex -aI (gnatls)
17639
17640@geindex -I (gnatls)
17641
17642@geindex -I- (gnatls)
17643
17644
17645@table @asis
17646
17647@item @code{-aO@emph{dir}}, @code{-aI@emph{dir}}, @code{-I@emph{dir}}, @code{-I-}, @code{-nostdinc}
17648
17649Source path manipulation. Same meaning as the equivalent @code{gnatmake}
17650flags (@ref{dc,,Switches for gnatmake}).
17651@end table
17652
17653@geindex -aP (gnatls)
17654
17655
17656@table @asis
17657
17658@item @code{-aP@emph{dir}}
17659
17660Add @code{dir} at the beginning of the project search dir.
17661@end table
17662
17663@geindex --RTS (gnatls)
17664
17665
17666@table @asis
17667
17668@item @code{--RTS=@emph{rts-path}}
17669
17670Specifies the default location of the runtime library. Same meaning as the
17671equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17672@end table
17673
17674@geindex -v (gnatls)
17675
17676
17677@table @asis
17678
17679@item @code{-v}
17680
17681Verbose mode. Output the complete source, object and project paths. Do not use
17682the default column layout but instead use long format giving as much as
17683information possible on each requested units, including special
17684characteristics such as:
17685
17686
17687@itemize *
17688
17689@item
17690@emph{Preelaborable}: The unit is preelaborable in the Ada sense.
17691
17692@item
17693@emph{No_Elab_Code}:  No elaboration code has been produced by the compiler for this unit.
17694
17695@item
17696@emph{Pure}: The unit is pure in the Ada sense.
17697
17698@item
17699@emph{Elaborate_Body}: The unit contains a pragma Elaborate_Body.
17700
17701@item
17702@emph{Remote_Types}: The unit contains a pragma Remote_Types.
17703
17704@item
17705@emph{Shared_Passive}: The unit contains a pragma Shared_Passive.
17706
17707@item
17708@emph{Predefined}: This unit is part of the predefined environment and cannot be modified
17709by the user.
17710
17711@item
17712@emph{Remote_Call_Interface}: The unit contains a pragma Remote_Call_Interface.
17713@end itemize
17714@end table
17715
17716@node Example of gnatls Usage,,Switches for gnatls,The GNAT Library Browser gnatls
17717@anchor{gnat_ugn/gnat_utility_programs id8}@anchor{14f}@anchor{gnat_ugn/gnat_utility_programs example-of-gnatls-usage}@anchor{150}
17718@subsection Example of @code{gnatls} Usage
17719
17720
17721Example of using the verbose switch. Note how the source and
17722object paths are affected by the -I switch.
17723
17724@quotation
17725
17726@example
17727$ gnatls -v -I.. demo1.o
17728
17729GNATLS 5.03w (20041123-34)
17730Copyright 1997-2004 Free Software Foundation, Inc.
17731
17732Source Search Path:
17733   <Current_Directory>
17734   ../
17735   /home/comar/local/adainclude/
17736
17737Object Search Path:
17738   <Current_Directory>
17739   ../
17740   /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17741
17742Project Search Path:
17743   <Current_Directory>
17744   /home/comar/local/lib/gnat/
17745
17746./demo1.o
17747   Unit =>
17748     Name   => demo1
17749     Kind   => subprogram body
17750     Flags  => No_Elab_Code
17751     Source => demo1.adb    modified
17752@end example
17753@end quotation
17754
17755The following is an example of use of the dependency list.
17756Note the use of the -s switch
17757which gives a straight list of source files. This can be useful for
17758building specialized scripts.
17759
17760@quotation
17761
17762@example
17763$ gnatls -d demo2.o
17764./demo2.o   demo2        OK demo2.adb
17765                         OK gen_list.ads
17766                         OK gen_list.adb
17767                         OK instr.ads
17768                         OK instr-child.ads
17769
17770$ gnatls -d -s -a demo1.o
17771demo1.adb
17772/home/comar/local/adainclude/ada.ads
17773/home/comar/local/adainclude/a-finali.ads
17774/home/comar/local/adainclude/a-filico.ads
17775/home/comar/local/adainclude/a-stream.ads
17776/home/comar/local/adainclude/a-tags.ads
17777gen_list.ads
17778gen_list.adb
17779/home/comar/local/adainclude/gnat.ads
17780/home/comar/local/adainclude/g-io.ads
17781instr.ads
17782/home/comar/local/adainclude/system.ads
17783/home/comar/local/adainclude/s-exctab.ads
17784/home/comar/local/adainclude/s-finimp.ads
17785/home/comar/local/adainclude/s-finroo.ads
17786/home/comar/local/adainclude/s-secsta.ads
17787/home/comar/local/adainclude/s-stalib.ads
17788/home/comar/local/adainclude/s-stoele.ads
17789/home/comar/local/adainclude/s-stratt.ads
17790/home/comar/local/adainclude/s-tasoli.ads
17791/home/comar/local/adainclude/s-unstyp.ads
17792/home/comar/local/adainclude/unchconv.ads
17793@end example
17794@end quotation
17795
17796@node The Cross-Referencing Tools gnatxref and gnatfind,The Ada to HTML Converter gnathtml,The GNAT Library Browser gnatls,GNAT Utility Programs
17797@anchor{gnat_ugn/gnat_utility_programs the-cross-referencing-tools-gnatxref-and-gnatfind}@anchor{22}@anchor{gnat_ugn/gnat_utility_programs id9}@anchor{151}
17798@section The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
17799
17800
17801@geindex gnatxref
17802
17803@geindex gnatfind
17804
17805The compiler generates cross-referencing information (unless
17806you set the @code{-gnatx} switch), which are saved in the @code{.ali} files.
17807This information indicates where in the source each entity is declared and
17808referenced. Note that entities in package Standard are not included, but
17809entities in all other predefined units are included in the output.
17810
17811Before using any of these two tools, you need to compile successfully your
17812application, so that GNAT gets a chance to generate the cross-referencing
17813information.
17814
17815The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
17816information to provide the user with the capability to easily locate the
17817declaration and references to an entity. These tools are quite similar,
17818the difference being that @code{gnatfind} is intended for locating
17819definitions and/or references to a specified entity or entities, whereas
17820@code{gnatxref} is oriented to generating a full report of all
17821cross-references.
17822
17823To use these tools, you must not compile your application using the
17824@code{-gnatx} switch on the @code{gnatmake} command line
17825(see @ref{1b,,Building with gnatmake}). Otherwise, cross-referencing
17826information will not be generated.
17827
17828@menu
17829* gnatxref Switches::
17830* gnatfind Switches::
17831* Configuration Files for gnatxref and gnatfind::
17832* Regular Expressions in gnatfind and gnatxref::
17833* Examples of gnatxref Usage::
17834* Examples of gnatfind Usage::
17835
17836@end menu
17837
17838@node gnatxref Switches,gnatfind Switches,,The Cross-Referencing Tools gnatxref and gnatfind
17839@anchor{gnat_ugn/gnat_utility_programs id10}@anchor{152}@anchor{gnat_ugn/gnat_utility_programs gnatxref-switches}@anchor{153}
17840@subsection @code{gnatxref} Switches
17841
17842
17843The command invocation for @code{gnatxref} is:
17844
17845@quotation
17846
17847@example
17848$ gnatxref [ switches ] sourcefile1 [ sourcefile2 ... ]
17849@end example
17850@end quotation
17851
17852where
17853
17854
17855@table @asis
17856
17857@item @code{sourcefile1} [, @code{sourcefile2} ...]
17858
17859identify the source files for which a report is to be generated. The
17860@code{with}ed units will be processed too. You must provide at least one file.
17861
17862These file names are considered to be regular expressions, so for instance
17863specifying @code{source*.adb} is the same as giving every file in the current
17864directory whose name starts with @code{source} and whose extension is
17865@code{adb}.
17866
17867You shouldn't specify any directory name, just base names. @code{gnatxref}
17868and @code{gnatfind} will be able to locate these files by themselves using
17869the source path. If you specify directories, no result is produced.
17870@end table
17871
17872The following switches are available for @code{gnatxref}:
17873
17874@geindex --version (gnatxref)
17875
17876
17877@table @asis
17878
17879@item @code{--version}
17880
17881Display Copyright and version, then exit disregarding all other options.
17882@end table
17883
17884@geindex --help (gnatxref)
17885
17886
17887@table @asis
17888
17889@item @code{--help}
17890
17891If @code{--version} was not used, display usage, then exit disregarding
17892all other options.
17893@end table
17894
17895@geindex -a (gnatxref)
17896
17897
17898@table @asis
17899
17900@item @code{-a}
17901
17902If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
17903the read-only files found in the library search path. Otherwise, these files
17904will be ignored. This option can be used to protect Gnat sources or your own
17905libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
17906much faster, and their output much smaller. Read-only here refers to access
17907or permissions status in the file system for the current user.
17908@end table
17909
17910@geindex -aIDIR (gnatxref)
17911
17912
17913@table @asis
17914
17915@item @code{-aI@emph{DIR}}
17916
17917When looking for source files also look in directory DIR. The order in which
17918source file search is undertaken is the same as for @code{gnatmake}.
17919@end table
17920
17921@geindex -aODIR (gnatxref)
17922
17923
17924@table @asis
17925
17926@item @code{aO@emph{DIR}}
17927
17928When -searching for library and object files, look in directory
17929DIR. The order in which library files are searched is the same as for
17930@code{gnatmake}.
17931@end table
17932
17933@geindex -nostdinc (gnatxref)
17934
17935
17936@table @asis
17937
17938@item @code{-nostdinc}
17939
17940Do not look for sources in the system default directory.
17941@end table
17942
17943@geindex -nostdlib (gnatxref)
17944
17945
17946@table @asis
17947
17948@item @code{-nostdlib}
17949
17950Do not look for library files in the system default directory.
17951@end table
17952
17953@geindex --ext (gnatxref)
17954
17955
17956@table @asis
17957
17958@item @code{--ext=@emph{extension}}
17959
17960Specify an alternate ali file extension. The default is @code{ali} and other
17961extensions (e.g. @code{gli} for C/C++ sources) may be specified via this switch.
17962Note that if this switch overrides the default, only the new extension will
17963be considered.
17964@end table
17965
17966@geindex --RTS (gnatxref)
17967
17968
17969@table @asis
17970
17971@item @code{--RTS=@emph{rts-path}}
17972
17973Specifies the default location of the runtime library. Same meaning as the
17974equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
17975@end table
17976
17977@geindex -d (gnatxref)
17978
17979
17980@table @asis
17981
17982@item @code{-d}
17983
17984If this switch is set @code{gnatxref} will output the parent type
17985reference for each matching derived types.
17986@end table
17987
17988@geindex -f (gnatxref)
17989
17990
17991@table @asis
17992
17993@item @code{-f}
17994
17995If this switch is set, the output file names will be preceded by their
17996directory (if the file was found in the search path). If this switch is
17997not set, the directory will not be printed.
17998@end table
17999
18000@geindex -g (gnatxref)
18001
18002
18003@table @asis
18004
18005@item @code{-g}
18006
18007If this switch is set, information is output only for library-level
18008entities, ignoring local entities. The use of this switch may accelerate
18009@code{gnatfind} and @code{gnatxref}.
18010@end table
18011
18012@geindex -IDIR (gnatxref)
18013
18014
18015@table @asis
18016
18017@item @code{-I@emph{DIR}}
18018
18019Equivalent to @code{-aODIR -aIDIR}.
18020@end table
18021
18022@geindex -pFILE (gnatxref)
18023
18024
18025@table @asis
18026
18027@item @code{-p@emph{FILE}}
18028
18029Specify a configuration file to use to list the source and object directories.
18030
18031If a file is specified, then the content of the source directory and object
18032directory lines are added as if they had been specified respectively
18033by @code{-aI} and @code{-aO}.
18034
18035See @ref{154,,Configuration Files for gnatxref and gnatfind} for the syntax
18036of this configuration file.
18037
18038@item @code{-u}
18039
18040Output only unused symbols. This may be really useful if you give your
18041main compilation unit on the command line, as @code{gnatxref} will then
18042display every unused entity and 'with'ed package.
18043
18044@item @code{-v}
18045
18046Instead of producing the default output, @code{gnatxref} will generate a
18047@code{tags} file that can be used by vi. For examples how to use this
18048feature, see @ref{155,,Examples of gnatxref Usage}. The tags file is output
18049to the standard output, thus you will have to redirect it to a file.
18050@end table
18051
18052All these switches may be in any order on the command line, and may even
18053appear after the file names. They need not be separated by spaces, thus
18054you can say @code{gnatxref -ag} instead of @code{gnatxref -a -g}.
18055
18056@node gnatfind Switches,Configuration Files for gnatxref and gnatfind,gnatxref Switches,The Cross-Referencing Tools gnatxref and gnatfind
18057@anchor{gnat_ugn/gnat_utility_programs id11}@anchor{156}@anchor{gnat_ugn/gnat_utility_programs gnatfind-switches}@anchor{157}
18058@subsection @code{gnatfind} Switches
18059
18060
18061The command invocation for @code{gnatfind} is:
18062
18063@quotation
18064
18065@example
18066$ gnatfind [ switches ]  pattern[:sourcefile[:line[:column]]]
18067      [file1 file2 ...]
18068@end example
18069@end quotation
18070
18071with the following iterpretation of the command arguments:
18072
18073
18074@table @asis
18075
18076@item @emph{pattern}
18077
18078An entity will be output only if it matches the regular expression found
18079in @emph{pattern}, see @ref{158,,Regular Expressions in gnatfind and gnatxref}.
18080
18081Omitting the pattern is equivalent to specifying @code{*}, which
18082will match any entity. Note that if you do not provide a pattern, you
18083have to provide both a sourcefile and a line.
18084
18085Entity names are given in Latin-1, with uppercase/lowercase equivalence
18086for matching purposes. At the current time there is no support for
180878-bit codes other than Latin-1, or for wide characters in identifiers.
18088
18089@item @emph{sourcefile}
18090
18091@code{gnatfind} will look for references, bodies or declarations
18092of symbols referenced in @code{sourcefile}, at line @code{line}
18093and column @code{column}. See @ref{159,,Examples of gnatfind Usage}
18094for syntax examples.
18095
18096@item @emph{line}
18097
18098A decimal integer identifying the line number containing
18099the reference to the entity (or entities) to be located.
18100
18101@item @emph{column}
18102
18103A decimal integer identifying the exact location on the
18104line of the first character of the identifier for the
18105entity reference. Columns are numbered from 1.
18106
18107@item @emph{file1 file2 ...}
18108
18109The search will be restricted to these source files. If none are given, then
18110the search will be conducted for every library file in the search path.
18111These files must appear only after the pattern or sourcefile.
18112
18113These file names are considered to be regular expressions, so for instance
18114specifying @code{source*.adb} is the same as giving every file in the current
18115directory whose name starts with @code{source} and whose extension is
18116@code{adb}.
18117
18118The location of the spec of the entity will always be displayed, even if it
18119isn't in one of @code{file1}, @code{file2}, ... The
18120occurrences of the entity in the separate units of the ones given on the
18121command line will also be displayed.
18122
18123Note that if you specify at least one file in this part, @code{gnatfind} may
18124sometimes not be able to find the body of the subprograms.
18125@end table
18126
18127At least one of 'sourcefile' or 'pattern' has to be present on
18128the command line.
18129
18130The following switches are available:
18131
18132@geindex --version (gnatfind)
18133
18134
18135@table @asis
18136
18137@item @code{--version}
18138
18139Display Copyright and version, then exit disregarding all other options.
18140@end table
18141
18142@geindex --help (gnatfind)
18143
18144
18145@table @asis
18146
18147@item @code{--help}
18148
18149If @code{--version} was not used, display usage, then exit disregarding
18150all other options.
18151@end table
18152
18153@geindex -a (gnatfind)
18154
18155
18156@table @asis
18157
18158@item @code{-a}
18159
18160If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
18161the read-only files found in the library search path. Otherwise, these files
18162will be ignored. This option can be used to protect Gnat sources or your own
18163libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
18164much faster, and their output much smaller. Read-only here refers to access
18165or permission status in the file system for the current user.
18166@end table
18167
18168@geindex -aIDIR (gnatfind)
18169
18170
18171@table @asis
18172
18173@item @code{-aI@emph{DIR}}
18174
18175When looking for source files also look in directory DIR. The order in which
18176source file search is undertaken is the same as for @code{gnatmake}.
18177@end table
18178
18179@geindex -aODIR (gnatfind)
18180
18181
18182@table @asis
18183
18184@item @code{-aO@emph{DIR}}
18185
18186When searching for library and object files, look in directory
18187DIR. The order in which library files are searched is the same as for
18188@code{gnatmake}.
18189@end table
18190
18191@geindex -nostdinc (gnatfind)
18192
18193
18194@table @asis
18195
18196@item @code{-nostdinc}
18197
18198Do not look for sources in the system default directory.
18199@end table
18200
18201@geindex -nostdlib (gnatfind)
18202
18203
18204@table @asis
18205
18206@item @code{-nostdlib}
18207
18208Do not look for library files in the system default directory.
18209@end table
18210
18211@geindex --ext (gnatfind)
18212
18213
18214@table @asis
18215
18216@item @code{--ext=@emph{extension}}
18217
18218Specify an alternate ali file extension. The default is @code{ali} and other
18219extensions may be specified via this switch. Note that if this switch
18220overrides the default, only the new extension will be considered.
18221@end table
18222
18223@geindex --RTS (gnatfind)
18224
18225
18226@table @asis
18227
18228@item @code{--RTS=@emph{rts-path}}
18229
18230Specifies the default location of the runtime library. Same meaning as the
18231equivalent @code{gnatmake} flag (@ref{dc,,Switches for gnatmake}).
18232@end table
18233
18234@geindex -d (gnatfind)
18235
18236
18237@table @asis
18238
18239@item @code{-d}
18240
18241If this switch is set, then @code{gnatfind} will output the parent type
18242reference for each matching derived types.
18243@end table
18244
18245@geindex -e (gnatfind)
18246
18247
18248@table @asis
18249
18250@item @code{-e}
18251
18252By default, @code{gnatfind} accept the simple regular expression set for
18253@code{pattern}. If this switch is set, then the pattern will be
18254considered as full Unix-style regular expression.
18255@end table
18256
18257@geindex -f (gnatfind)
18258
18259
18260@table @asis
18261
18262@item @code{-f}
18263
18264If this switch is set, the output file names will be preceded by their
18265directory (if the file was found in the search path). If this switch is
18266not set, the directory will not be printed.
18267@end table
18268
18269@geindex -g (gnatfind)
18270
18271
18272@table @asis
18273
18274@item @code{-g}
18275
18276If this switch is set, information is output only for library-level
18277entities, ignoring local entities. The use of this switch may accelerate
18278@code{gnatfind} and @code{gnatxref}.
18279@end table
18280
18281@geindex -IDIR (gnatfind)
18282
18283
18284@table @asis
18285
18286@item @code{-I@emph{DIR}}
18287
18288Equivalent to @code{-aODIR -aIDIR}.
18289@end table
18290
18291@geindex -pFILE (gnatfind)
18292
18293
18294@table @asis
18295
18296@item @code{-p@emph{FILE}}
18297
18298Specify a configuration file to use to list the source and object directories.
18299
18300If a file is specified, then the content of the source directory and object
18301directory lines are added as if they had been specified respectively
18302by @code{-aI} and @code{-aO}.
18303
18304See @ref{154,,Configuration Files for gnatxref and gnatfind} for the syntax
18305of this configuration file.
18306@end table
18307
18308@geindex -r (gnatfind)
18309
18310
18311@table @asis
18312
18313@item @code{-r}
18314
18315By default, @code{gnatfind} will output only the information about the
18316declaration, body or type completion of the entities. If this switch is
18317set, the @code{gnatfind} will locate every reference to the entities in
18318the files specified on the command line (or in every file in the search
18319path if no file is given on the command line).
18320@end table
18321
18322@geindex -s (gnatfind)
18323
18324
18325@table @asis
18326
18327@item @code{-s}
18328
18329If this switch is set, then @code{gnatfind} will output the content
18330of the Ada source file lines were the entity was found.
18331@end table
18332
18333@geindex -t (gnatfind)
18334
18335
18336@table @asis
18337
18338@item @code{-t}
18339
18340If this switch is set, then @code{gnatfind} will output the type hierarchy for
18341the specified type. It act like -d option but recursively from parent
18342type to parent type. When this switch is set it is not possible to
18343specify more than one file.
18344@end table
18345
18346All these switches may be in any order on the command line, and may even
18347appear after the file names. They need not be separated by spaces, thus
18348you can say @code{gnatxref -ag} instead of
18349@code{gnatxref -a -g}.
18350
18351As stated previously, @code{gnatfind} will search in every directory in the
18352search path. You can force it to look only in the current directory if
18353you specify @code{*} at the end of the command line.
18354
18355@node Configuration Files for gnatxref and gnatfind,Regular Expressions in gnatfind and gnatxref,gnatfind Switches,The Cross-Referencing Tools gnatxref and gnatfind
18356@anchor{gnat_ugn/gnat_utility_programs configuration-files-for-gnatxref-and-gnatfind}@anchor{154}@anchor{gnat_ugn/gnat_utility_programs id12}@anchor{15a}
18357@subsection Configuration Files for @code{gnatxref} and @code{gnatfind}
18358
18359
18360Configuration files are used by @code{gnatxref} and @code{gnatfind} to specify
18361the list of source and object directories to consider. They can be
18362specified via the @code{-p} switch.
18363
18364The following lines can be included, in any order in the file:
18365
18366
18367@itemize *
18368
18369@item
18370
18371@table @asis
18372
18373@item @emph{src_dir=DIR}
18374
18375[default: @code{"./"}].
18376Specifies a directory where to look for source files. Multiple @code{src_dir}
18377lines can be specified and they will be searched in the order they
18378are specified.
18379@end table
18380
18381@item
18382
18383@table @asis
18384
18385@item @emph{obj_dir=DIR}
18386
18387[default: @code{"./"}].
18388Specifies a directory where to look for object and library files. Multiple
18389@code{obj_dir} lines can be specified, and they will be searched in the order
18390they are specified
18391@end table
18392@end itemize
18393
18394Any other line will be silently ignored.
18395
18396@node Regular Expressions in gnatfind and gnatxref,Examples of gnatxref Usage,Configuration Files for gnatxref and gnatfind,The Cross-Referencing Tools gnatxref and gnatfind
18397@anchor{gnat_ugn/gnat_utility_programs id13}@anchor{15b}@anchor{gnat_ugn/gnat_utility_programs regular-expressions-in-gnatfind-and-gnatxref}@anchor{158}
18398@subsection Regular Expressions in @code{gnatfind} and @code{gnatxref}
18399
18400
18401As specified in the section about @code{gnatfind}, the pattern can be a
18402regular expression. Two kinds of regular expressions
18403are recognized:
18404
18405
18406@itemize *
18407
18408@item
18409
18410@table @asis
18411
18412@item @emph{Globbing pattern}
18413
18414These are the most common regular expression. They are the same as are
18415generally used in a Unix shell command line, or in a DOS session.
18416
18417Here is a more formal grammar:
18418
18419@example
18420regexp ::= term
18421term   ::= elmt            -- matches elmt
18422term   ::= elmt elmt       -- concatenation (elmt then elmt)
18423term   ::= *               -- any string of 0 or more characters
18424term   ::= ?               -- matches any character
18425term   ::= [char @{char@}]   -- matches any character listed
18426term   ::= [char - char]   -- matches any character in range
18427@end example
18428@end table
18429
18430@item
18431
18432@table @asis
18433
18434@item @emph{Full regular expression}
18435
18436The second set of regular expressions is much more powerful. This is the
18437type of regular expressions recognized by utilities such as @code{grep}.
18438
18439The following is the form of a regular expression, expressed in same BNF
18440style as is found in the Ada Reference Manual:
18441
18442@example
18443regexp ::= term @{| term@}   -- alternation (term or term ...)
18444
18445term ::= item @{item@}       -- concatenation (item then item)
18446
18447item ::= elmt              -- match elmt
18448item ::= elmt *            -- zero or more elmt's
18449item ::= elmt +            -- one or more elmt's
18450item ::= elmt ?            -- matches elmt or nothing
18451
18452elmt ::= nschar            -- matches given character
18453elmt ::= [nschar @{nschar@}]   -- matches any character listed
18454elmt ::= [^ nschar @{nschar@}] -- matches any character not listed
18455elmt ::= [char - char]     -- matches chars in given range
18456elmt ::= \\ char            -- matches given character
18457elmt ::= .                 -- matches any single character
18458elmt ::= ( regexp )        -- parens used for grouping
18459
18460char ::= any character, including special characters
18461nschar ::= any character except ()[].*+?^
18462@end example
18463
18464Here are a few examples:
18465
18466@quotation
18467
18468
18469@table @asis
18470
18471@item @code{abcde|fghi}
18472
18473will match any of the two strings @code{abcde} and @code{fghi},
18474
18475@item @code{abc*d}
18476
18477will match any string like @code{abd}, @code{abcd}, @code{abccd},
18478@code{abcccd}, and so on,
18479
18480@item @code{[a-z]+}
18481
18482will match any string which has only lowercase characters in it (and at
18483least one character.
18484@end table
18485@end quotation
18486@end table
18487@end itemize
18488
18489@node Examples of gnatxref Usage,Examples of gnatfind Usage,Regular Expressions in gnatfind and gnatxref,The Cross-Referencing Tools gnatxref and gnatfind
18490@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatxref-usage}@anchor{155}@anchor{gnat_ugn/gnat_utility_programs id14}@anchor{15c}
18491@subsection Examples of @code{gnatxref} Usage
18492
18493
18494@menu
18495* General Usage::
18496* Using gnatxref with vi::
18497
18498@end menu
18499
18500@node General Usage,Using gnatxref with vi,,Examples of gnatxref Usage
18501@anchor{gnat_ugn/gnat_utility_programs general-usage}@anchor{15d}
18502@subsubsection General Usage
18503
18504
18505For the following examples, we will consider the following units:
18506
18507@quotation
18508
18509@example
18510main.ads:
185111: with Bar;
185122: package Main is
185133:     procedure Foo (B : in Integer);
185144:     C : Integer;
185155: private
185166:     D : Integer;
185177: end Main;
18518
18519main.adb:
185201: package body Main is
185212:     procedure Foo (B : in Integer) is
185223:     begin
185234:        C := B;
185245:        D := B;
185256:        Bar.Print (B);
185267:        Bar.Print (C);
185278:     end Foo;
185289: end Main;
18529
18530bar.ads:
185311: package Bar is
185322:     procedure Print (B : Integer);
185333: end bar;
18534@end example
18535@end quotation
18536
18537The first thing to do is to recompile your application (for instance, in
18538that case just by doing a @code{gnatmake main}, so that GNAT generates
18539the cross-referencing information.
18540You can then issue any of the following commands:
18541
18542@quotation
18543
18544
18545@itemize *
18546
18547@item
18548@code{gnatxref main.adb}
18549@code{gnatxref} generates cross-reference information for main.adb
18550and every unit 'with'ed by main.adb.
18551
18552The output would be:
18553
18554@quotation
18555
18556@example
18557B                                                      Type: Integer
18558  Decl: bar.ads           2:22
18559B                                                      Type: Integer
18560  Decl: main.ads          3:20
18561  Body: main.adb          2:20
18562  Ref:  main.adb          4:13     5:13     6:19
18563Bar                                                    Type: Unit
18564  Decl: bar.ads           1:9
18565  Ref:  main.adb          6:8      7:8
18566       main.ads           1:6
18567C                                                      Type: Integer
18568  Decl: main.ads          4:5
18569  Modi: main.adb          4:8
18570  Ref:  main.adb          7:19
18571D                                                      Type: Integer
18572  Decl: main.ads          6:5
18573  Modi: main.adb          5:8
18574Foo                                                    Type: Unit
18575  Decl: main.ads          3:15
18576  Body: main.adb          2:15
18577Main                                                    Type: Unit
18578  Decl: main.ads          2:9
18579  Body: main.adb          1:14
18580Print                                                   Type: Unit
18581  Decl: bar.ads           2:15
18582  Ref:  main.adb          6:12     7:12
18583@end example
18584@end quotation
18585
18586This shows that the entity @code{Main} is declared in main.ads, line 2, column 9,
18587its body is in main.adb, line 1, column 14 and is not referenced any where.
18588
18589The entity @code{Print} is declared in @code{bar.ads}, line 2, column 15 and it
18590is referenced in @code{main.adb}, line 6 column 12 and line 7 column 12.
18591
18592@item
18593@code{gnatxref package1.adb package2.ads}
18594@code{gnatxref} will generates cross-reference information for
18595@code{package1.adb}, @code{package2.ads} and any other package @code{with}ed by any
18596of these.
18597@end itemize
18598@end quotation
18599
18600@node Using gnatxref with vi,,General Usage,Examples of gnatxref Usage
18601@anchor{gnat_ugn/gnat_utility_programs using-gnatxref-with-vi}@anchor{15e}
18602@subsubsection Using @code{gnatxref} with @code{vi}
18603
18604
18605@code{gnatxref} can generate a tags file output, which can be used
18606directly from @code{vi}. Note that the standard version of @code{vi}
18607will not work properly with overloaded symbols. Consider using another
18608free implementation of @code{vi}, such as @code{vim}.
18609
18610@quotation
18611
18612@example
18613$ gnatxref -v gnatfind.adb > tags
18614@end example
18615@end quotation
18616
18617The following command will generate the tags file for @code{gnatfind} itself
18618(if the sources are in the search path!):
18619
18620@quotation
18621
18622@example
18623$ gnatxref -v gnatfind.adb > tags
18624@end example
18625@end quotation
18626
18627From @code{vi}, you can then use the command @code{:tag @emph{entity}}
18628(replacing @code{entity} by whatever you are looking for), and vi will
18629display a new file with the corresponding declaration of entity.
18630
18631@node Examples of gnatfind Usage,,Examples of gnatxref Usage,The Cross-Referencing Tools gnatxref and gnatfind
18632@anchor{gnat_ugn/gnat_utility_programs id15}@anchor{15f}@anchor{gnat_ugn/gnat_utility_programs examples-of-gnatfind-usage}@anchor{159}
18633@subsection Examples of @code{gnatfind} Usage
18634
18635
18636
18637@itemize *
18638
18639@item
18640@code{gnatfind -f xyz:main.adb}
18641Find declarations for all entities xyz referenced at least once in
18642main.adb. The references are search in every library file in the search
18643path.
18644
18645The directories will be printed as well (as the @code{-f}
18646switch is set)
18647
18648The output will look like:
18649
18650@quotation
18651
18652@example
18653directory/main.ads:106:14: xyz <= declaration
18654directory/main.adb:24:10: xyz <= body
18655directory/foo.ads:45:23: xyz <= declaration
18656@end example
18657@end quotation
18658
18659I.e., one of the entities xyz found in main.adb is declared at
18660line 12 of main.ads (and its body is in main.adb), and another one is
18661declared at line 45 of foo.ads
18662
18663@item
18664@code{gnatfind -fs xyz:main.adb}
18665This is the same command as the previous one, but @code{gnatfind} will
18666display the content of the Ada source file lines.
18667
18668The output will look like:
18669
18670@example
18671directory/main.ads:106:14: xyz <= declaration
18672   procedure xyz;
18673directory/main.adb:24:10: xyz <= body
18674   procedure xyz is
18675directory/foo.ads:45:23: xyz <= declaration
18676   xyz : Integer;
18677@end example
18678
18679This can make it easier to find exactly the location your are looking
18680for.
18681
18682@item
18683@code{gnatfind -r "*x*":main.ads:123 foo.adb}
18684Find references to all entities containing an x that are
18685referenced on line 123 of main.ads.
18686The references will be searched only in main.ads and foo.adb.
18687
18688@item
18689@code{gnatfind main.ads:123}
18690Find declarations and bodies for all entities that are referenced on
18691line 123 of main.ads.
18692
18693This is the same as @code{gnatfind "*":main.adb:123`}
18694
18695@item
18696@code{gnatfind mydir/main.adb:123:45}
18697Find the declaration for the entity referenced at column 45 in
18698line 123 of file main.adb in directory mydir. Note that it
18699is usual to omit the identifier name when the column is given,
18700since the column position identifies a unique reference.
18701
18702The column has to be the beginning of the identifier, and should not
18703point to any character in the middle of the identifier.
18704@end itemize
18705
18706@node The Ada to HTML Converter gnathtml,,The Cross-Referencing Tools gnatxref and gnatfind,GNAT Utility Programs
18707@anchor{gnat_ugn/gnat_utility_programs the-ada-to-html-converter-gnathtml}@anchor{23}@anchor{gnat_ugn/gnat_utility_programs id16}@anchor{160}
18708@section The Ada to HTML Converter @code{gnathtml}
18709
18710
18711@geindex gnathtml
18712
18713@code{gnathtml} is a Perl script that allows Ada source files to be browsed using
18714standard Web browsers. For installation information, see @ref{161,,Installing gnathtml}.
18715
18716Ada reserved keywords are highlighted in a bold font and Ada comments in
18717a blue font. Unless your program was compiled with the gcc @code{-gnatx}
18718switch to suppress the generation of cross-referencing information, user
18719defined variables and types will appear in a different color; you will
18720be able to click on any identifier and go to its declaration.
18721
18722@menu
18723* Invoking gnathtml::
18724* Installing gnathtml::
18725
18726@end menu
18727
18728@node Invoking gnathtml,Installing gnathtml,,The Ada to HTML Converter gnathtml
18729@anchor{gnat_ugn/gnat_utility_programs invoking-gnathtml}@anchor{162}@anchor{gnat_ugn/gnat_utility_programs id17}@anchor{163}
18730@subsection Invoking @code{gnathtml}
18731
18732
18733The command line is as follows:
18734
18735@quotation
18736
18737@example
18738$ perl gnathtml.pl [ switches ] ada-files
18739@end example
18740@end quotation
18741
18742You can specify as many Ada files as you want. @code{gnathtml} will generate
18743an html file for every ada file, and a global file called @code{index.htm}.
18744This file is an index of every identifier defined in the files.
18745
18746The following switches are available:
18747
18748@geindex -83 (gnathtml)
18749
18750
18751@table @asis
18752
18753@item @code{83}
18754
18755Only the Ada 83 subset of keywords will be highlighted.
18756@end table
18757
18758@geindex -cc (gnathtml)
18759
18760
18761@table @asis
18762
18763@item @code{cc @emph{color}}
18764
18765This option allows you to change the color used for comments. The default
18766value is green. The color argument can be any name accepted by html.
18767@end table
18768
18769@geindex -d (gnathtml)
18770
18771
18772@table @asis
18773
18774@item @code{d}
18775
18776If the Ada files depend on some other files (for instance through
18777@code{with} clauses, the latter files will also be converted to html.
18778Only the files in the user project will be converted to html, not the files
18779in the run-time library itself.
18780@end table
18781
18782@geindex -D (gnathtml)
18783
18784
18785@table @asis
18786
18787@item @code{D}
18788
18789This command is the same as @code{-d} above, but @code{gnathtml} will
18790also look for files in the run-time library, and generate html files for them.
18791@end table
18792
18793@geindex -ext (gnathtml)
18794
18795
18796@table @asis
18797
18798@item @code{ext @emph{extension}}
18799
18800This option allows you to change the extension of the generated HTML files.
18801If you do not specify an extension, it will default to @code{htm}.
18802@end table
18803
18804@geindex -f (gnathtml)
18805
18806
18807@table @asis
18808
18809@item @code{f}
18810
18811By default, gnathtml will generate html links only for global entities
18812('with'ed units, global variables and types,...).  If you specify
18813@code{-f} on the command line, then links will be generated for local
18814entities too.
18815@end table
18816
18817@geindex -l (gnathtml)
18818
18819
18820@table @asis
18821
18822@item @code{l @emph{number}}
18823
18824If this switch is provided and @code{number} is not 0, then
18825@code{gnathtml} will number the html files every @code{number} line.
18826@end table
18827
18828@geindex -I (gnathtml)
18829
18830
18831@table @asis
18832
18833@item @code{I @emph{dir}}
18834
18835Specify a directory to search for library files (@code{.ALI} files) and
18836source files. You can provide several -I switches on the command line,
18837and the directories will be parsed in the order of the command line.
18838@end table
18839
18840@geindex -o (gnathtml)
18841
18842
18843@table @asis
18844
18845@item @code{o @emph{dir}}
18846
18847Specify the output directory for html files. By default, gnathtml will
18848saved the generated html files in a subdirectory named @code{html/}.
18849@end table
18850
18851@geindex -p (gnathtml)
18852
18853
18854@table @asis
18855
18856@item @code{p @emph{file}}
18857
18858If you are using Emacs and the most recent Emacs Ada mode, which provides
18859a full Integrated Development Environment for compiling, checking,
18860running and debugging applications, you may use @code{.gpr} files
18861to give the directories where Emacs can find sources and object files.
18862
18863Using this switch, you can tell gnathtml to use these files.
18864This allows you to get an html version of your application, even if it
18865is spread over multiple directories.
18866@end table
18867
18868@geindex -sc (gnathtml)
18869
18870
18871@table @asis
18872
18873@item @code{sc @emph{color}}
18874
18875This switch allows you to change the color used for symbol
18876definitions.
18877The default value is red. The color argument can be any name accepted by html.
18878@end table
18879
18880@geindex -t (gnathtml)
18881
18882
18883@table @asis
18884
18885@item @code{t @emph{file}}
18886
18887This switch provides the name of a file. This file contains a list of
18888file names to be converted, and the effect is exactly as though they had
18889appeared explicitly on the command line. This
18890is the recommended way to work around the command line length limit on some
18891systems.
18892@end table
18893
18894@node Installing gnathtml,,Invoking gnathtml,The Ada to HTML Converter gnathtml
18895@anchor{gnat_ugn/gnat_utility_programs installing-gnathtml}@anchor{161}@anchor{gnat_ugn/gnat_utility_programs id18}@anchor{164}
18896@subsection Installing @code{gnathtml}
18897
18898
18899@code{Perl} needs to be installed on your machine to run this script.
18900@code{Perl} is freely available for almost every architecture and
18901operating system via the Internet.
18902
18903On Unix systems, you  may want to modify  the  first line of  the script
18904@code{gnathtml},  to explicitly  specify  where Perl
18905is located. The syntax of this line is:
18906
18907@quotation
18908
18909@example
18910#!full_path_name_to_perl
18911@end example
18912@end quotation
18913
18914Alternatively, you may run the script using the following command line:
18915
18916@quotation
18917
18918@example
18919$ perl gnathtml.pl [ switches ] files
18920@end example
18921@end quotation
18922
18923@c -- +---------------------------------------------------------------------+
18924
18925@c -- | The following sections are present only in the PRO and GPL editions |
18926
18927@c -- +---------------------------------------------------------------------+
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
18938
18939@node GNAT and Program Execution,Platform-Specific Information,GNAT Utility Programs,Top
18940@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}
18941@chapter GNAT and Program Execution
18942
18943
18944This chapter covers several topics:
18945
18946
18947@itemize *
18948
18949@item
18950@ref{167,,Running and Debugging Ada Programs}
18951
18952@item
18953@ref{168,,Code Coverage and Profiling}
18954
18955@item
18956@ref{169,,Improving Performance}
18957
18958@item
18959@ref{16a,,Overflow Check Handling in GNAT}
18960
18961@item
18962@ref{16b,,Performing Dimensionality Analysis in GNAT}
18963
18964@item
18965@ref{16c,,Stack Related Facilities}
18966
18967@item
18968@ref{16d,,Memory Management Issues}
18969@end itemize
18970
18971@menu
18972* Running and Debugging Ada Programs::
18973* Code Coverage and Profiling::
18974* Improving Performance::
18975* Overflow Check Handling in GNAT::
18976* Performing Dimensionality Analysis in GNAT::
18977* Stack Related Facilities::
18978* Memory Management Issues::
18979
18980@end menu
18981
18982@node Running and Debugging Ada Programs,Code Coverage and Profiling,,GNAT and Program Execution
18983@anchor{gnat_ugn/gnat_and_program_execution id2}@anchor{167}@anchor{gnat_ugn/gnat_and_program_execution running-and-debugging-ada-programs}@anchor{24}
18984@section Running and Debugging Ada Programs
18985
18986
18987@geindex Debugging
18988
18989This section discusses how to debug Ada programs.
18990
18991An incorrect Ada program may be handled in three ways by the GNAT compiler:
18992
18993
18994@itemize *
18995
18996@item
18997The illegality may be a violation of the static semantics of Ada. In
18998that case GNAT diagnoses the constructs in the program that are illegal.
18999It is then a straightforward matter for the user to modify those parts of
19000the program.
19001
19002@item
19003The illegality may be a violation of the dynamic semantics of Ada. In
19004that case the program compiles and executes, but may generate incorrect
19005results, or may terminate abnormally with some exception.
19006
19007@item
19008When presented with a program that contains convoluted errors, GNAT
19009itself may terminate abnormally without providing full diagnostics on
19010the incorrect user program.
19011@end itemize
19012
19013@geindex Debugger
19014
19015@geindex gdb
19016
19017@menu
19018* The GNAT Debugger GDB::
19019* Running GDB::
19020* Introduction to GDB Commands::
19021* Using Ada Expressions::
19022* Calling User-Defined Subprograms::
19023* Using the next Command in a Function::
19024* Stopping When Ada Exceptions Are Raised::
19025* Ada Tasks::
19026* Debugging Generic Units::
19027* Remote Debugging with gdbserver::
19028* GNAT Abnormal Termination or Failure to Terminate::
19029* Naming Conventions for GNAT Source Files::
19030* Getting Internal Debugging Information::
19031* Stack Traceback::
19032* Pretty-Printers for the GNAT runtime::
19033
19034@end menu
19035
19036@node The GNAT Debugger GDB,Running GDB,,Running and Debugging Ada Programs
19037@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debugger-gdb}@anchor{16e}@anchor{gnat_ugn/gnat_and_program_execution id3}@anchor{16f}
19038@subsection The GNAT Debugger GDB
19039
19040
19041@code{GDB} is a general purpose, platform-independent debugger that
19042can be used to debug mixed-language programs compiled with @code{gcc},
19043and in particular is capable of debugging Ada programs compiled with
19044GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
19045complex Ada data structures.
19046
19047See @cite{Debugging with GDB},
19048for full details on the usage of @code{GDB}, including a section on
19049its usage on programs. This manual should be consulted for full
19050details. The section that follows is a brief introduction to the
19051philosophy and use of @code{GDB}.
19052
19053When GNAT programs are compiled, the compiler optionally writes debugging
19054information into the generated object file, including information on
19055line numbers, and on declared types and variables. This information is
19056separate from the generated code. It makes the object files considerably
19057larger, but it does not add to the size of the actual executable that
19058will be loaded into memory, and has no impact on run-time performance. The
19059generation of debug information is triggered by the use of the
19060@code{-g} switch in the @code{gcc} or @code{gnatmake} command
19061used to carry out the compilations. It is important to emphasize that
19062the use of these options does not change the generated code.
19063
19064The debugging information is written in standard system formats that
19065are used by many tools, including debuggers and profilers. The format
19066of the information is typically designed to describe C types and
19067semantics, but GNAT implements a translation scheme which allows full
19068details about Ada types and variables to be encoded into these
19069standard C formats. Details of this encoding scheme may be found in
19070the file exp_dbug.ads in the GNAT source distribution. However, the
19071details of this encoding are, in general, of no interest to a user,
19072since @code{GDB} automatically performs the necessary decoding.
19073
19074When a program is bound and linked, the debugging information is
19075collected from the object files, and stored in the executable image of
19076the program. Again, this process significantly increases the size of
19077the generated executable file, but it does not increase the size of
19078the executable program itself. Furthermore, if this program is run in
19079the normal manner, it runs exactly as if the debug information were
19080not present, and takes no more actual memory.
19081
19082However, if the program is run under control of @code{GDB}, the
19083debugger is activated.  The image of the program is loaded, at which
19084point it is ready to run.  If a run command is given, then the program
19085will run exactly as it would have if @code{GDB} were not present. This
19086is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
19087entirely non-intrusive until a breakpoint is encountered.  If no
19088breakpoint is ever hit, the program will run exactly as it would if no
19089debugger were present. When a breakpoint is hit, @code{GDB} accesses
19090the debugging information and can respond to user commands to inspect
19091variables, and more generally to report on the state of execution.
19092
19093@node Running GDB,Introduction to GDB Commands,The GNAT Debugger GDB,Running and Debugging Ada Programs
19094@anchor{gnat_ugn/gnat_and_program_execution id4}@anchor{170}@anchor{gnat_ugn/gnat_and_program_execution running-gdb}@anchor{171}
19095@subsection Running GDB
19096
19097
19098This section describes how to initiate the debugger.
19099
19100The debugger can be launched from a @code{GPS} menu or
19101directly from the command line. The description below covers the latter use.
19102All the commands shown can be used in the @code{GPS} debug console window,
19103but there are usually more GUI-based ways to achieve the same effect.
19104
19105The command to run @code{GDB} is
19106
19107@quotation
19108
19109@example
19110$ gdb program
19111@end example
19112@end quotation
19113
19114where @code{program} is the name of the executable file. This
19115activates the debugger and results in a prompt for debugger commands.
19116The simplest command is simply @code{run}, which causes the program to run
19117exactly as if the debugger were not present. The following section
19118describes some of the additional commands that can be given to @code{GDB}.
19119
19120@node Introduction to GDB Commands,Using Ada Expressions,Running GDB,Running and Debugging Ada Programs
19121@anchor{gnat_ugn/gnat_and_program_execution introduction-to-gdb-commands}@anchor{172}@anchor{gnat_ugn/gnat_and_program_execution id5}@anchor{173}
19122@subsection Introduction to GDB Commands
19123
19124
19125@code{GDB} contains a large repertoire of commands.
19126See @cite{Debugging with GDB} for extensive documentation on the use
19127of these commands, together with examples of their use. Furthermore,
19128the command @emph{help} invoked from within GDB activates a simple help
19129facility which summarizes the available commands and their options.
19130In this section we summarize a few of the most commonly
19131used commands to give an idea of what @code{GDB} is about. You should create
19132a simple program with debugging information and experiment with the use of
19133these @code{GDB} commands on the program as you read through the
19134following section.
19135
19136
19137@itemize *
19138
19139@item
19140
19141@table @asis
19142
19143@item @code{set args @emph{arguments}}
19144
19145The @emph{arguments} list above is a list of arguments to be passed to
19146the program on a subsequent run command, just as though the arguments
19147had been entered on a normal invocation of the program. The @code{set args}
19148command is not needed if the program does not require arguments.
19149@end table
19150
19151@item
19152
19153@table @asis
19154
19155@item @code{run}
19156
19157The @code{run} command causes execution of the program to start from
19158the beginning. If the program is already running, that is to say if
19159you are currently positioned at a breakpoint, then a prompt will ask
19160for confirmation that you want to abandon the current execution and
19161restart.
19162@end table
19163
19164@item
19165
19166@table @asis
19167
19168@item @code{breakpoint @emph{location}}
19169
19170The breakpoint command sets a breakpoint, that is to say a point at which
19171execution will halt and @code{GDB} will await further
19172commands. @emph{location} is
19173either a line number within a file, given in the format @code{file:linenumber},
19174or it is the name of a subprogram. If you request that a breakpoint be set on
19175a subprogram that is overloaded, a prompt will ask you to specify on which of
19176those subprograms you want to breakpoint. You can also
19177specify that all of them should be breakpointed. If the program is run
19178and execution encounters the breakpoint, then the program
19179stops and @code{GDB} signals that the breakpoint was encountered by
19180printing the line of code before which the program is halted.
19181@end table
19182
19183@item
19184
19185@table @asis
19186
19187@item @code{catch exception @emph{name}}
19188
19189This command causes the program execution to stop whenever exception
19190@code{name} is raised.  If @code{name} is omitted, then the execution is
19191suspended when any exception is raised.
19192@end table
19193
19194@item
19195
19196@table @asis
19197
19198@item @code{print @emph{expression}}
19199
19200This will print the value of the given expression. Most simple
19201Ada expression formats are properly handled by @code{GDB}, so the expression
19202can contain function calls, variables, operators, and attribute references.
19203@end table
19204
19205@item
19206
19207@table @asis
19208
19209@item @code{continue}
19210
19211Continues execution following a breakpoint, until the next breakpoint or the
19212termination of the program.
19213@end table
19214
19215@item
19216
19217@table @asis
19218
19219@item @code{step}
19220
19221Executes a single line after a breakpoint. If the next statement
19222is a subprogram call, execution continues into (the first statement of)
19223the called subprogram.
19224@end table
19225
19226@item
19227
19228@table @asis
19229
19230@item @code{next}
19231
19232Executes a single line. If this line is a subprogram call, executes and
19233returns from the call.
19234@end table
19235
19236@item
19237
19238@table @asis
19239
19240@item @code{list}
19241
19242Lists a few lines around the current source location. In practice, it
19243is usually more convenient to have a separate edit window open with the
19244relevant source file displayed. Successive applications of this command
19245print subsequent lines. The command can be given an argument which is a
19246line number, in which case it displays a few lines around the specified one.
19247@end table
19248
19249@item
19250
19251@table @asis
19252
19253@item @code{backtrace}
19254
19255Displays a backtrace of the call chain. This command is typically
19256used after a breakpoint has occurred, to examine the sequence of calls that
19257leads to the current breakpoint. The display includes one line for each
19258activation record (frame) corresponding to an active subprogram.
19259@end table
19260
19261@item
19262
19263@table @asis
19264
19265@item @code{up}
19266
19267At a breakpoint, @code{GDB} can display the values of variables local
19268to the current frame. The command @code{up} can be used to
19269examine the contents of other active frames, by moving the focus up
19270the stack, that is to say from callee to caller, one frame at a time.
19271@end table
19272
19273@item
19274
19275@table @asis
19276
19277@item @code{down}
19278
19279Moves the focus of @code{GDB} down from the frame currently being
19280examined to the frame of its callee (the reverse of the previous command),
19281@end table
19282
19283@item
19284
19285@table @asis
19286
19287@item @code{frame @emph{n}}
19288
19289Inspect the frame with the given number. The value 0 denotes the frame
19290of the current breakpoint, that is to say the top of the call stack.
19291@end table
19292
19293@item
19294
19295@table @asis
19296
19297@item @code{kill}
19298
19299Kills the child process in which the program is running under GDB.
19300This may be useful for several purposes:
19301
19302
19303@itemize *
19304
19305@item
19306It allows you to recompile and relink your program, since on many systems
19307you cannot regenerate an executable file while it is running in a process.
19308
19309@item
19310You can run your program outside the debugger, on systems that do not
19311permit executing a program outside GDB while breakpoints are set
19312within GDB.
19313
19314@item
19315It allows you to debug a core dump rather than a running process.
19316@end itemize
19317@end table
19318@end itemize
19319
19320The above list is a very short introduction to the commands that
19321@code{GDB} provides. Important additional capabilities, including conditional
19322breakpoints, the ability to execute command sequences on a breakpoint,
19323the ability to debug at the machine instruction level and many other
19324features are described in detail in @cite{Debugging with GDB}.
19325Note that most commands can be abbreviated
19326(for example, c for continue, bt for backtrace).
19327
19328@node Using Ada Expressions,Calling User-Defined Subprograms,Introduction to GDB Commands,Running and Debugging Ada Programs
19329@anchor{gnat_ugn/gnat_and_program_execution id6}@anchor{174}@anchor{gnat_ugn/gnat_and_program_execution using-ada-expressions}@anchor{175}
19330@subsection Using Ada Expressions
19331
19332
19333@geindex Ada expressions (in gdb)
19334
19335@code{GDB} supports a fairly large subset of Ada expression syntax, with some
19336extensions. The philosophy behind the design of this subset is
19337
19338@quotation
19339
19340
19341@itemize *
19342
19343@item
19344That @code{GDB} should provide basic literals and access to operations for
19345arithmetic, dereferencing, field selection, indexing, and subprogram calls,
19346leaving more sophisticated computations to subprograms written into the
19347program (which therefore may be called from @code{GDB}).
19348
19349@item
19350That type safety and strict adherence to Ada language restrictions
19351are not particularly relevant in a debugging context.
19352
19353@item
19354That brevity is important to the @code{GDB} user.
19355@end itemize
19356@end quotation
19357
19358Thus, for brevity, the debugger acts as if there were
19359implicit @code{with} and @code{use} clauses in effect for all user-written
19360packages, thus making it unnecessary to fully qualify most names with
19361their packages, regardless of context. Where this causes ambiguity,
19362@code{GDB} asks the user's intent.
19363
19364For details on the supported Ada syntax, see @cite{Debugging with GDB}.
19365
19366@node Calling User-Defined Subprograms,Using the next Command in a Function,Using Ada Expressions,Running and Debugging Ada Programs
19367@anchor{gnat_ugn/gnat_and_program_execution id7}@anchor{176}@anchor{gnat_ugn/gnat_and_program_execution calling-user-defined-subprograms}@anchor{177}
19368@subsection Calling User-Defined Subprograms
19369
19370
19371An important capability of @code{GDB} is the ability to call user-defined
19372subprograms while debugging. This is achieved simply by entering
19373a subprogram call statement in the form:
19374
19375@quotation
19376
19377@example
19378call subprogram-name (parameters)
19379@end example
19380@end quotation
19381
19382The keyword @code{call} can be omitted in the normal case where the
19383@code{subprogram-name} does not coincide with any of the predefined
19384@code{GDB} commands.
19385
19386The effect is to invoke the given subprogram, passing it the
19387list of parameters that is supplied. The parameters can be expressions and
19388can include variables from the program being debugged. The
19389subprogram must be defined
19390at the library level within your program, and @code{GDB} will call the
19391subprogram within the environment of your program execution (which
19392means that the subprogram is free to access or even modify variables
19393within your program).
19394
19395The most important use of this facility is in allowing the inclusion of
19396debugging routines that are tailored to particular data structures
19397in your program. Such debugging routines can be written to provide a suitably
19398high-level description of an abstract type, rather than a low-level dump
19399of its physical layout. After all, the standard
19400@code{GDB print} command only knows the physical layout of your
19401types, not their abstract meaning. Debugging routines can provide information
19402at the desired semantic level and are thus enormously useful.
19403
19404For example, when debugging GNAT itself, it is crucial to have access to
19405the contents of the tree nodes used to represent the program internally.
19406But tree nodes are represented simply by an integer value (which in turn
19407is an index into a table of nodes).
19408Using the @code{print} command on a tree node would simply print this integer
19409value, which is not very useful. But the PN routine (defined in file
19410treepr.adb in the GNAT sources) takes a tree node as input, and displays
19411a useful high level representation of the tree node, which includes the
19412syntactic category of the node, its position in the source, the integers
19413that denote descendant nodes and parent node, as well as varied
19414semantic information. To study this example in more detail, you might want to
19415look at the body of the PN procedure in the stated file.
19416
19417Another useful application of this capability is to deal with situations of
19418complex data which are not handled suitably by GDB. For example, if you specify
19419Convention Fortran for a multi-dimensional array, GDB does not know that
19420the ordering of array elements has been switched and will not properly
19421address the array elements. In such a case, instead of trying to print the
19422elements directly from GDB, you can write a callable procedure that prints
19423the elements in the desired format.
19424
19425@node Using the next Command in a Function,Stopping When Ada Exceptions Are Raised,Calling User-Defined Subprograms,Running and Debugging Ada Programs
19426@anchor{gnat_ugn/gnat_and_program_execution using-the-next-command-in-a-function}@anchor{178}@anchor{gnat_ugn/gnat_and_program_execution id8}@anchor{179}
19427@subsection Using the @emph{next} Command in a Function
19428
19429
19430When you use the @code{next} command in a function, the current source
19431location will advance to the next statement as usual. A special case
19432arises in the case of a @code{return} statement.
19433
19434Part of the code for a return statement is the 'epilogue' of the function.
19435This is the code that returns to the caller. There is only one copy of
19436this epilogue code, and it is typically associated with the last return
19437statement in the function if there is more than one return. In some
19438implementations, this epilogue is associated with the first statement
19439of the function.
19440
19441The result is that if you use the @code{next} command from a return
19442statement that is not the last return statement of the function you
19443may see a strange apparent jump to the last return statement or to
19444the start of the function. You should simply ignore this odd jump.
19445The value returned is always that from the first return statement
19446that was stepped through.
19447
19448@node Stopping When Ada Exceptions Are Raised,Ada Tasks,Using the next Command in a Function,Running and Debugging Ada Programs
19449@anchor{gnat_ugn/gnat_and_program_execution stopping-when-ada-exceptions-are-raised}@anchor{17a}@anchor{gnat_ugn/gnat_and_program_execution id9}@anchor{17b}
19450@subsection Stopping When Ada Exceptions Are Raised
19451
19452
19453@geindex Exceptions (in gdb)
19454
19455You can set catchpoints that stop the program execution when your program
19456raises selected exceptions.
19457
19458
19459@itemize *
19460
19461@item
19462
19463@table @asis
19464
19465@item @code{catch exception}
19466
19467Set a catchpoint that stops execution whenever (any task in the) program
19468raises any exception.
19469@end table
19470
19471@item
19472
19473@table @asis
19474
19475@item @code{catch exception @emph{name}}
19476
19477Set a catchpoint that stops execution whenever (any task in the) program
19478raises the exception @emph{name}.
19479@end table
19480
19481@item
19482
19483@table @asis
19484
19485@item @code{catch exception unhandled}
19486
19487Set a catchpoint that stops executing whenever (any task in the) program
19488raises an exception for which there is no handler.
19489@end table
19490
19491@item
19492
19493@table @asis
19494
19495@item @code{info exceptions}, @code{info exceptions @emph{regexp}}
19496
19497The @code{info exceptions} command permits the user to examine all defined
19498exceptions within Ada programs. With a regular expression, @emph{regexp}, as
19499argument, prints out only those exceptions whose name matches @emph{regexp}.
19500@end table
19501@end itemize
19502
19503@geindex Tasks (in gdb)
19504
19505@node Ada Tasks,Debugging Generic Units,Stopping When Ada Exceptions Are Raised,Running and Debugging Ada Programs
19506@anchor{gnat_ugn/gnat_and_program_execution ada-tasks}@anchor{17c}@anchor{gnat_ugn/gnat_and_program_execution id10}@anchor{17d}
19507@subsection Ada Tasks
19508
19509
19510@code{GDB} allows the following task-related commands:
19511
19512
19513@itemize *
19514
19515@item
19516
19517@table @asis
19518
19519@item @code{info tasks}
19520
19521This command shows a list of current Ada tasks, as in the following example:
19522
19523@example
19524(gdb) info tasks
19525  ID       TID P-ID   Thread Pri State                 Name
19526   1   8088000   0   807e000  15 Child Activation Wait main_task
19527   2   80a4000   1   80ae000  15 Accept/Select Wait    b
19528   3   809a800   1   80a4800  15 Child Activation Wait a
19529*  4   80ae800   3   80b8000  15 Running               c
19530@end example
19531
19532In this listing, the asterisk before the first task indicates it to be the
19533currently running task. The first column lists the task ID that is used
19534to refer to tasks in the following commands.
19535@end table
19536@end itemize
19537
19538@geindex Breakpoints and tasks
19539
19540
19541@itemize *
19542
19543@item
19544@code{break`@w{`}*linespec* `@w{`}task} @emph{taskid}, @code{break} @emph{linespec} @code{task} @emph{taskid} @code{if} ...
19545
19546@quotation
19547
19548These commands are like the @code{break ... thread ...}.
19549@emph{linespec} specifies source lines.
19550
19551Use the qualifier @code{task @emph{taskid}} with a breakpoint command
19552to specify that you only want @code{GDB} to stop the program when a
19553particular Ada task reaches this breakpoint. @emph{taskid} is one of the
19554numeric task identifiers assigned by @code{GDB}, shown in the first
19555column of the @code{info tasks} display.
19556
19557If you do not specify @code{task @emph{taskid}} when you set a
19558breakpoint, the breakpoint applies to @emph{all} tasks of your
19559program.
19560
19561You can use the @code{task} qualifier on conditional breakpoints as
19562well; in this case, place @code{task @emph{taskid}} before the
19563breakpoint condition (before the @code{if}).
19564@end quotation
19565@end itemize
19566
19567@geindex Task switching (in gdb)
19568
19569
19570@itemize *
19571
19572@item
19573@code{task @emph{taskno}}
19574
19575@quotation
19576
19577This command allows switching to the task referred by @emph{taskno}. In
19578particular, this allows browsing of the backtrace of the specified
19579task. It is advisable to switch back to the original task before
19580continuing execution otherwise the scheduling of the program may be
19581perturbed.
19582@end quotation
19583@end itemize
19584
19585For more detailed information on the tasking support,
19586see @cite{Debugging with GDB}.
19587
19588@geindex Debugging Generic Units
19589
19590@geindex Generics
19591
19592@node Debugging Generic Units,Remote Debugging with gdbserver,Ada Tasks,Running and Debugging Ada Programs
19593@anchor{gnat_ugn/gnat_and_program_execution debugging-generic-units}@anchor{17e}@anchor{gnat_ugn/gnat_and_program_execution id11}@anchor{17f}
19594@subsection Debugging Generic Units
19595
19596
19597GNAT always uses code expansion for generic instantiation. This means that
19598each time an instantiation occurs, a complete copy of the original code is
19599made, with appropriate substitutions of formals by actuals.
19600
19601It is not possible to refer to the original generic entities in
19602@code{GDB}, but it is always possible to debug a particular instance of
19603a generic, by using the appropriate expanded names. For example, if we have
19604
19605@quotation
19606
19607@example
19608procedure g is
19609
19610   generic package k is
19611      procedure kp (v1 : in out integer);
19612   end k;
19613
19614   package body k is
19615      procedure kp (v1 : in out integer) is
19616      begin
19617         v1 := v1 + 1;
19618      end kp;
19619   end k;
19620
19621   package k1 is new k;
19622   package k2 is new k;
19623
19624   var : integer := 1;
19625
19626begin
19627   k1.kp (var);
19628   k2.kp (var);
19629   k1.kp (var);
19630   k2.kp (var);
19631end;
19632@end example
19633@end quotation
19634
19635Then to break on a call to procedure kp in the k2 instance, simply
19636use the command:
19637
19638@quotation
19639
19640@example
19641(gdb) break g.k2.kp
19642@end example
19643@end quotation
19644
19645When the breakpoint occurs, you can step through the code of the
19646instance in the normal manner and examine the values of local variables, as for
19647other units.
19648
19649@geindex Remote Debugging with gdbserver
19650
19651@node Remote Debugging with gdbserver,GNAT Abnormal Termination or Failure to Terminate,Debugging Generic Units,Running and Debugging Ada Programs
19652@anchor{gnat_ugn/gnat_and_program_execution remote-debugging-with-gdbserver}@anchor{180}@anchor{gnat_ugn/gnat_and_program_execution id12}@anchor{181}
19653@subsection Remote Debugging with gdbserver
19654
19655
19656On platforms where gdbserver is supported, it is possible to use this tool
19657to debug your application remotely.  This can be useful in situations
19658where the program needs to be run on a target host that is different
19659from the host used for development, particularly when the target has
19660a limited amount of resources (either CPU and/or memory).
19661
19662To do so, start your program using gdbserver on the target machine.
19663gdbserver then automatically suspends the execution of your program
19664at its entry point, waiting for a debugger to connect to it.  The
19665following commands starts an application and tells gdbserver to
19666wait for a connection with the debugger on localhost port 4444.
19667
19668@quotation
19669
19670@example
19671$ gdbserver localhost:4444 program
19672Process program created; pid = 5685
19673Listening on port 4444
19674@end example
19675@end quotation
19676
19677Once gdbserver has started listening, we can tell the debugger to establish
19678a connection with this gdbserver, and then start the same debugging session
19679as if the program was being debugged on the same host, directly under
19680the control of GDB.
19681
19682@quotation
19683
19684@example
19685$ gdb program
19686(gdb) target remote targethost:4444
19687Remote debugging using targethost:4444
196880x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
19689(gdb) b foo.adb:3
19690Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
19691(gdb) continue
19692Continuing.
19693
19694Breakpoint 1, foo () at foo.adb:4
196954       end foo;
19696@end example
19697@end quotation
19698
19699It is also possible to use gdbserver to attach to an already running
19700program, in which case the execution of that program is simply suspended
19701until the connection between the debugger and gdbserver is established.
19702
19703For more information on how to use gdbserver, see the @emph{Using the gdbserver Program}
19704section in @cite{Debugging with GDB}.
19705GNAT provides support for gdbserver on x86-linux, x86-windows and x86_64-linux.
19706
19707@geindex Abnormal Termination or Failure to Terminate
19708
19709@node GNAT Abnormal Termination or Failure to Terminate,Naming Conventions for GNAT Source Files,Remote Debugging with gdbserver,Running and Debugging Ada Programs
19710@anchor{gnat_ugn/gnat_and_program_execution gnat-abnormal-termination-or-failure-to-terminate}@anchor{182}@anchor{gnat_ugn/gnat_and_program_execution id13}@anchor{183}
19711@subsection GNAT Abnormal Termination or Failure to Terminate
19712
19713
19714When presented with programs that contain serious errors in syntax
19715or semantics,
19716GNAT may on rare occasions  experience problems in operation, such
19717as aborting with a
19718segmentation fault or illegal memory access, raising an internal
19719exception, terminating abnormally, or failing to terminate at all.
19720In such cases, you can activate
19721various features of GNAT that can help you pinpoint the construct in your
19722program that is the likely source of the problem.
19723
19724The following strategies are presented in increasing order of
19725difficulty, corresponding to your experience in using GNAT and your
19726familiarity with compiler internals.
19727
19728
19729@itemize *
19730
19731@item
19732Run @code{gcc} with the @code{-gnatf}. This first
19733switch causes all errors on a given line to be reported. In its absence,
19734only the first error on a line is displayed.
19735
19736The @code{-gnatdO} switch causes errors to be displayed as soon as they
19737are encountered, rather than after compilation is terminated. If GNAT
19738terminates prematurely or goes into an infinite loop, the last error
19739message displayed may help to pinpoint the culprit.
19740
19741@item
19742Run @code{gcc} with the @code{-v} (verbose) switch. In this
19743mode, @code{gcc} produces ongoing information about the progress of the
19744compilation and provides the name of each procedure as code is
19745generated. This switch allows you to find which Ada procedure was being
19746compiled when it encountered a code generation problem.
19747@end itemize
19748
19749@geindex -gnatdc switch
19750
19751
19752@itemize *
19753
19754@item
19755Run @code{gcc} with the @code{-gnatdc} switch. This is a GNAT specific
19756switch that does for the front-end what @code{-v} does
19757for the back end. The system prints the name of each unit,
19758either a compilation unit or nested unit, as it is being analyzed.
19759
19760@item
19761Finally, you can start
19762@code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
19763front-end of GNAT, and can be run independently (normally it is just
19764called from @code{gcc}). You can use @code{gdb} on @code{gnat1} as you
19765would on a C program (but @ref{16e,,The GNAT Debugger GDB} for caveats). The
19766@code{where} command is the first line of attack; the variable
19767@code{lineno} (seen by @code{print lineno}), used by the second phase of
19768@code{gnat1} and by the @code{gcc} backend, indicates the source line at
19769which the execution stopped, and @code{input_file name} indicates the name of
19770the source file.
19771@end itemize
19772
19773@node Naming Conventions for GNAT Source Files,Getting Internal Debugging Information,GNAT Abnormal Termination or Failure to Terminate,Running and Debugging Ada Programs
19774@anchor{gnat_ugn/gnat_and_program_execution naming-conventions-for-gnat-source-files}@anchor{184}@anchor{gnat_ugn/gnat_and_program_execution id14}@anchor{185}
19775@subsection Naming Conventions for GNAT Source Files
19776
19777
19778In order to examine the workings of the GNAT system, the following
19779brief description of its organization may be helpful:
19780
19781
19782@itemize *
19783
19784@item
19785Files with prefix @code{sc} contain the lexical scanner.
19786
19787@item
19788All files prefixed with @code{par} are components of the parser. The
19789numbers correspond to chapters of the Ada Reference Manual. For example,
19790parsing of select statements can be found in @code{par-ch9.adb}.
19791
19792@item
19793All files prefixed with @code{sem} perform semantic analysis. The
19794numbers correspond to chapters of the Ada standard. For example, all
19795issues involving context clauses can be found in @code{sem_ch10.adb}. In
19796addition, some features of the language require sufficient special processing
19797to justify their own semantic files: sem_aggr for aggregates, sem_disp for
19798dynamic dispatching, etc.
19799
19800@item
19801All files prefixed with @code{exp} perform normalization and
19802expansion of the intermediate representation (abstract syntax tree, or AST).
19803these files use the same numbering scheme as the parser and semantics files.
19804For example, the construction of record initialization procedures is done in
19805@code{exp_ch3.adb}.
19806
19807@item
19808The files prefixed with @code{bind} implement the binder, which
19809verifies the consistency of the compilation, determines an order of
19810elaboration, and generates the bind file.
19811
19812@item
19813The files @code{atree.ads} and @code{atree.adb} detail the low-level
19814data structures used by the front-end.
19815
19816@item
19817The files @code{sinfo.ads} and @code{sinfo.adb} detail the structure of
19818the abstract syntax tree as produced by the parser.
19819
19820@item
19821The files @code{einfo.ads} and @code{einfo.adb} detail the attributes of
19822all entities, computed during semantic analysis.
19823
19824@item
19825Library management issues are dealt with in files with prefix
19826@code{lib}.
19827
19828@geindex Annex A (in Ada Reference Manual)
19829
19830@item
19831Ada files with the prefix @code{a-} are children of @code{Ada}, as
19832defined in Annex A.
19833
19834@geindex Annex B (in Ada reference Manual)
19835
19836@item
19837Files with prefix @code{i-} are children of @code{Interfaces}, as
19838defined in Annex B.
19839
19840@geindex System (package in Ada Reference Manual)
19841
19842@item
19843Files with prefix @code{s-} are children of @code{System}. This includes
19844both language-defined children and GNAT run-time routines.
19845
19846@geindex GNAT (package)
19847
19848@item
19849Files with prefix @code{g-} are children of @code{GNAT}. These are useful
19850general-purpose packages, fully documented in their specs. All
19851the other @code{.c} files are modifications of common @code{gcc} files.
19852@end itemize
19853
19854@node Getting Internal Debugging Information,Stack Traceback,Naming Conventions for GNAT Source Files,Running and Debugging Ada Programs
19855@anchor{gnat_ugn/gnat_and_program_execution id15}@anchor{186}@anchor{gnat_ugn/gnat_and_program_execution getting-internal-debugging-information}@anchor{187}
19856@subsection Getting Internal Debugging Information
19857
19858
19859Most compilers have internal debugging switches and modes. GNAT
19860does also, except GNAT internal debugging switches and modes are not
19861secret. A summary and full description of all the compiler and binder
19862debug flags are in the file @code{debug.adb}. You must obtain the
19863sources of the compiler to see the full detailed effects of these flags.
19864
19865The switches that print the source of the program (reconstructed from
19866the internal tree) are of general interest for user programs, as are the
19867options to print
19868the full internal tree, and the entity table (the symbol table
19869information). The reconstructed source provides a readable version of the
19870program after the front-end has completed analysis and  expansion,
19871and is useful when studying the performance of specific constructs.
19872For example, constraint checks are indicated, complex aggregates
19873are replaced with loops and assignments, and tasking primitives
19874are replaced with run-time calls.
19875
19876@geindex traceback
19877
19878@geindex stack traceback
19879
19880@geindex stack unwinding
19881
19882@node Stack Traceback,Pretty-Printers for the GNAT runtime,Getting Internal Debugging Information,Running and Debugging Ada Programs
19883@anchor{gnat_ugn/gnat_and_program_execution stack-traceback}@anchor{188}@anchor{gnat_ugn/gnat_and_program_execution id16}@anchor{189}
19884@subsection Stack Traceback
19885
19886
19887Traceback is a mechanism to display the sequence of subprogram calls that
19888leads to a specified execution point in a program. Often (but not always)
19889the execution point is an instruction at which an exception has been raised.
19890This mechanism is also known as @emph{stack unwinding} because it obtains
19891its information by scanning the run-time stack and recovering the activation
19892records of all active subprograms. Stack unwinding is one of the most
19893important tools for program debugging.
19894
19895The first entry stored in traceback corresponds to the deepest calling level,
19896that is to say the subprogram currently executing the instruction
19897from which we want to obtain the traceback.
19898
19899Note that there is no runtime performance penalty when stack traceback
19900is enabled, and no exception is raised during program execution.
19901
19902@geindex traceback
19903@geindex non-symbolic
19904
19905@menu
19906* Non-Symbolic Traceback::
19907* Symbolic Traceback::
19908
19909@end menu
19910
19911@node Non-Symbolic Traceback,Symbolic Traceback,,Stack Traceback
19912@anchor{gnat_ugn/gnat_and_program_execution non-symbolic-traceback}@anchor{18a}@anchor{gnat_ugn/gnat_and_program_execution id17}@anchor{18b}
19913@subsubsection Non-Symbolic Traceback
19914
19915
19916Note: this feature is not supported on all platforms. See
19917@code{GNAT.Traceback} spec in @code{g-traceb.ads}
19918for a complete list of supported platforms.
19919
19920@subsubheading Tracebacks From an Unhandled Exception
19921
19922
19923A runtime non-symbolic traceback is a list of addresses of call instructions.
19924To enable this feature you must use the @code{-E}
19925@code{gnatbind} option. With this option a stack traceback is stored as part
19926of exception information. You can retrieve this information using the
19927@code{addr2line} tool.
19928
19929Here is a simple example:
19930
19931@quotation
19932
19933@example
19934procedure STB is
19935
19936   procedure P1 is
19937   begin
19938      raise Constraint_Error;
19939   end P1;
19940
19941   procedure P2 is
19942   begin
19943      P1;
19944   end P2;
19945
19946begin
19947   P2;
19948end STB;
19949@end example
19950
19951@example
19952$ gnatmake stb -bargs -E
19953$ stb
19954
19955Execution terminated by unhandled exception
19956Exception name: CONSTRAINT_ERROR
19957Message: stb.adb:5
19958Call stack traceback locations:
199590x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19960@end example
19961@end quotation
19962
19963As we see the traceback lists a sequence of addresses for the unhandled
19964exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
19965guess that this exception come from procedure P1. To translate these
19966addresses into the source lines where the calls appear, the
19967@code{addr2line} tool, described below, is invaluable. The use of this tool
19968requires the program to be compiled with debug information.
19969
19970@quotation
19971
19972@example
19973$ gnatmake -g stb -bargs -E
19974$ stb
19975
19976Execution terminated by unhandled exception
19977Exception name: CONSTRAINT_ERROR
19978Message: stb.adb:5
19979Call stack traceback locations:
199800x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
19981
19982$ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
19983   0x4011f1 0x77e892a4
19984
1998500401373 at d:/stb/stb.adb:5
199860040138B at d:/stb/stb.adb:10
199870040139C at d:/stb/stb.adb:14
1998800401335 at d:/stb/b~stb.adb:104
19989004011C4 at /build/.../crt1.c:200
19990004011F1 at /build/.../crt1.c:222
1999177E892A4 in ?? at ??:0
19992@end example
19993@end quotation
19994
19995The @code{addr2line} tool has several other useful options:
19996
19997@quotation
19998
19999
20000@multitable {xxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
20001@item
20002
20003@code{--functions}
20004
20005@tab
20006
20007to get the function name corresponding to any location
20008
20009@item
20010
20011@code{--demangle=gnat}
20012
20013@tab
20014
20015to use the gnat decoding mode for the function names.
20016Note that for binutils version 2.9.x the option is
20017simply @code{--demangle}.
20018
20019@end multitable
20020
20021
20022@example
20023$ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
20024   0x40139c 0x401335 0x4011c4 0x4011f1
20025
2002600401373 in stb.p1 at d:/stb/stb.adb:5
200270040138B in stb.p2 at d:/stb/stb.adb:10
200280040139C in stb at d:/stb/stb.adb:14
2002900401335 in main at d:/stb/b~stb.adb:104
20030004011C4 in <__mingw_CRTStartup> at /build/.../crt1.c:200
20031004011F1 in <mainCRTStartup> at /build/.../crt1.c:222
20032@end example
20033@end quotation
20034
20035From this traceback we can see that the exception was raised in
20036@code{stb.adb} at line 5, which was reached from a procedure call in
20037@code{stb.adb} at line 10, and so on. The @code{b~std.adb} is the binder file,
20038which contains the call to the main program.
20039@ref{11c,,Running gnatbind}. The remaining entries are assorted runtime routines,
20040and the output will vary from platform to platform.
20041
20042It is also possible to use @code{GDB} with these traceback addresses to debug
20043the program. For example, we can break at a given code location, as reported
20044in the stack traceback:
20045
20046@quotation
20047
20048@example
20049$ gdb -nw stb
20050@end example
20051@end quotation
20052
20053Furthermore, this feature is not implemented inside Windows DLL. Only
20054the non-symbolic traceback is reported in this case.
20055
20056@quotation
20057
20058@example
20059(gdb) break *0x401373
20060Breakpoint 1 at 0x401373: file stb.adb, line 5.
20061@end example
20062@end quotation
20063
20064It is important to note that the stack traceback addresses
20065do not change when debug information is included. This is particularly useful
20066because it makes it possible to release software without debug information (to
20067minimize object size), get a field report that includes a stack traceback
20068whenever an internal bug occurs, and then be able to retrieve the sequence
20069of calls with the same program compiled with debug information.
20070
20071@subsubheading Tracebacks From Exception Occurrences
20072
20073
20074Non-symbolic tracebacks are obtained by using the @code{-E} binder argument.
20075The stack traceback is attached to the exception information string, and can
20076be retrieved in an exception handler within the Ada program, by means of the
20077Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
20078
20079@quotation
20080
20081@example
20082with Ada.Text_IO;
20083with Ada.Exceptions;
20084
20085procedure STB is
20086
20087   use Ada;
20088   use Ada.Exceptions;
20089
20090   procedure P1 is
20091      K : Positive := 1;
20092   begin
20093      K := K - 1;
20094   exception
20095      when E : others =>
20096         Text_IO.Put_Line (Exception_Information (E));
20097   end P1;
20098
20099   procedure P2 is
20100   begin
20101      P1;
20102   end P2;
20103
20104begin
20105   P2;
20106end STB;
20107@end example
20108@end quotation
20109
20110This program will output:
20111
20112@quotation
20113
20114@example
20115$ stb
20116
20117Exception name: CONSTRAINT_ERROR
20118Message: stb.adb:12
20119Call stack traceback locations:
201200x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
20121@end example
20122@end quotation
20123
20124@subsubheading Tracebacks From Anywhere in a Program
20125
20126
20127It is also possible to retrieve a stack traceback from anywhere in a
20128program. For this you need to
20129use the @code{GNAT.Traceback} API. This package includes a procedure called
20130@code{Call_Chain} that computes a complete stack traceback, as well as useful
20131display procedures described below. It is not necessary to use the
20132@code{-E} @code{gnatbind} option in this case, because the stack traceback mechanism
20133is invoked explicitly.
20134
20135In the following example we compute a traceback at a specific location in
20136the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
20137convert addresses to strings:
20138
20139@quotation
20140
20141@example
20142with Ada.Text_IO;
20143with GNAT.Traceback;
20144with GNAT.Debug_Utilities;
20145
20146procedure STB is
20147
20148   use Ada;
20149   use GNAT;
20150   use GNAT.Traceback;
20151
20152   procedure P1 is
20153      TB  : Tracebacks_Array (1 .. 10);
20154      --  We are asking for a maximum of 10 stack frames.
20155      Len : Natural;
20156      --  Len will receive the actual number of stack frames returned.
20157   begin
20158      Call_Chain (TB, Len);
20159
20160      Text_IO.Put ("In STB.P1 : ");
20161
20162      for K in 1 .. Len loop
20163         Text_IO.Put (Debug_Utilities.Image (TB (K)));
20164         Text_IO.Put (' ');
20165      end loop;
20166
20167      Text_IO.New_Line;
20168   end P1;
20169
20170   procedure P2 is
20171   begin
20172      P1;
20173   end P2;
20174
20175begin
20176   P2;
20177end STB;
20178@end example
20179
20180@example
20181$ gnatmake -g stb
20182$ stb
20183
20184In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
2018516#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
20186@end example
20187@end quotation
20188
20189You can then get further information by invoking the @code{addr2line}
20190tool as described earlier (note that the hexadecimal addresses
20191need to be specified in C format, with a leading '0x').
20192
20193@geindex traceback
20194@geindex symbolic
20195
20196@node Symbolic Traceback,,Non-Symbolic Traceback,Stack Traceback
20197@anchor{gnat_ugn/gnat_and_program_execution id18}@anchor{18c}@anchor{gnat_ugn/gnat_and_program_execution symbolic-traceback}@anchor{18d}
20198@subsubsection Symbolic Traceback
20199
20200
20201A symbolic traceback is a stack traceback in which procedure names are
20202associated with each code location.
20203
20204Note that this feature is not supported on all platforms. See
20205@code{GNAT.Traceback.Symbolic} spec in @code{g-trasym.ads} for a complete
20206list of currently supported platforms.
20207
20208Note that the symbolic traceback requires that the program be compiled
20209with debug information. If it is not compiled with debug information
20210only the non-symbolic information will be valid.
20211
20212@subsubheading Tracebacks From Exception Occurrences
20213
20214
20215Here is an example:
20216
20217@quotation
20218
20219@example
20220with Ada.Text_IO;
20221with GNAT.Traceback.Symbolic;
20222
20223procedure STB is
20224
20225   procedure P1 is
20226   begin
20227      raise Constraint_Error;
20228   end P1;
20229
20230   procedure P2 is
20231   begin
20232      P1;
20233   end P2;
20234
20235   procedure P3 is
20236   begin
20237      P2;
20238   end P3;
20239
20240begin
20241   P3;
20242exception
20243   when E : others =>
20244      Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
20245end STB;
20246@end example
20247
20248@example
20249$ gnatmake -g .\stb -bargs -E
20250$ stb
20251
202520040149F in stb.p1 at stb.adb:8
20253004014B7 in stb.p2 at stb.adb:13
20254004014CF in stb.p3 at stb.adb:18
20255004015DD in ada.stb at stb.adb:22
2025600401461 in main at b~stb.adb:168
20257004011C4 in __mingw_CRTStartup at crt1.c:200
20258004011F1 in mainCRTStartup at crt1.c:222
2025977E892A4 in ?? at ??:0
20260@end example
20261@end quotation
20262
20263In the above example the @code{.\} syntax in the @code{gnatmake} command
20264is currently required by @code{addr2line} for files that are in
20265the current working directory.
20266Moreover, the exact sequence of linker options may vary from platform
20267to platform.
20268The above @code{-largs} section is for Windows platforms. By contrast,
20269under Unix there is no need for the @code{-largs} section.
20270Differences across platforms are due to details of linker implementation.
20271
20272@subsubheading Tracebacks From Anywhere in a Program
20273
20274
20275It is possible to get a symbolic stack traceback
20276from anywhere in a program, just as for non-symbolic tracebacks.
20277The first step is to obtain a non-symbolic
20278traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
20279information. Here is an example:
20280
20281@quotation
20282
20283@example
20284with Ada.Text_IO;
20285with GNAT.Traceback;
20286with GNAT.Traceback.Symbolic;
20287
20288procedure STB is
20289
20290   use Ada;
20291   use GNAT.Traceback;
20292   use GNAT.Traceback.Symbolic;
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      Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
20302   end P1;
20303
20304   procedure P2 is
20305   begin
20306      P1;
20307   end P2;
20308
20309begin
20310   P2;
20311end STB;
20312@end example
20313@end quotation
20314
20315@subsubheading Automatic Symbolic Tracebacks
20316
20317
20318Symbolic tracebacks may also be enabled by using the -Es switch to gnatbind (as
20319in @code{gprbuild -g ... -bargs -Es}).
20320This will cause the Exception_Information to contain a symbolic traceback,
20321which will also be printed if an unhandled exception terminates the
20322program.
20323
20324@node Pretty-Printers for the GNAT runtime,,Stack Traceback,Running and Debugging Ada Programs
20325@anchor{gnat_ugn/gnat_and_program_execution id19}@anchor{18e}@anchor{gnat_ugn/gnat_and_program_execution pretty-printers-for-the-gnat-runtime}@anchor{18f}
20326@subsection Pretty-Printers for the GNAT runtime
20327
20328
20329As discussed in @cite{Calling User-Defined Subprograms}, GDB's
20330@code{print} command only knows about the physical layout of program data
20331structures and therefore normally displays only low-level dumps, which
20332are often hard to understand.
20333
20334An example of this is when trying to display the contents of an Ada
20335standard container, such as @code{Ada.Containers.Ordered_Maps.Map}:
20336
20337@quotation
20338
20339@example
20340with Ada.Containers.Ordered_Maps;
20341
20342procedure PP is
20343   package Int_To_Nat is
20344      new Ada.Containers.Ordered_Maps (Integer, Natural);
20345
20346   Map : Int_To_Nat.Map;
20347begin
20348   Map.Insert (1, 10);
20349   Map.Insert (2, 20);
20350   Map.Insert (3, 30);
20351
20352   Map.Clear; --  BREAK HERE
20353end PP;
20354@end example
20355@end quotation
20356
20357When this program is built with debugging information and run under
20358GDB up to the @code{Map.Clear} statement, trying to print @code{Map} will
20359yield information that is only relevant to the developers of our standard
20360containers:
20361
20362@quotation
20363
20364@example
20365(gdb) print map
20366$1 = (
20367  tree => (
20368    first => 0x64e010,
20369    last => 0x64e070,
20370    root => 0x64e040,
20371    length => 3,
20372    tc => (
20373      busy => 0,
20374      lock => 0
20375    )
20376  )
20377)
20378@end example
20379@end quotation
20380
20381Fortunately, GDB has a feature called pretty-printers@footnote{http://docs.adacore.com/gdb-docs/html/gdb.html#Pretty_002dPrinter-Introduction},
20382which allows customizing how GDB displays data structures. The GDB
20383shipped with GNAT embeds such pretty-printers for the most common
20384containers in the standard library.  To enable them, either run the
20385following command manually under GDB or add it to your @code{.gdbinit} file:
20386
20387@quotation
20388
20389@example
20390python import gnatdbg; gnatdbg.setup()
20391@end example
20392@end quotation
20393
20394Once this is done, GDB's @code{print} command will automatically use
20395these pretty-printers when appropriate. Using the previous example:
20396
20397@quotation
20398
20399@example
20400(gdb) print map
20401$1 = pp.int_to_nat.map of length 3 = @{
20402  [1] = 10,
20403  [2] = 20,
20404  [3] = 30
20405@}
20406@end example
20407@end quotation
20408
20409Pretty-printers are invoked each time GDB tries to display a value,
20410including when displaying the arguments of a called subprogram (in
20411GDB's @code{backtrace} command) or when printing the value returned by a
20412function (in GDB's @code{finish} command).
20413
20414To display a value without involving pretty-printers, @code{print} can be
20415invoked with its @code{/r} option:
20416
20417@quotation
20418
20419@example
20420(gdb) print/r map
20421$1 = (
20422  tree => (...
20423@end example
20424@end quotation
20425
20426Finer 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}
20427for more information.
20428
20429@geindex Code Coverage
20430
20431@geindex Profiling
20432
20433@node Code Coverage and Profiling,Improving Performance,Running and Debugging Ada Programs,GNAT and Program Execution
20434@anchor{gnat_ugn/gnat_and_program_execution id20}@anchor{168}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-and-profiling}@anchor{25}
20435@section Code Coverage and Profiling
20436
20437
20438This section describes how to use the @code{gcov} coverage testing tool and
20439the @code{gprof} profiler tool on Ada programs.
20440
20441@geindex gcov
20442
20443@menu
20444* Code Coverage of Ada Programs with gcov::
20445* Profiling an Ada Program with gprof::
20446
20447@end menu
20448
20449@node Code Coverage of Ada Programs with gcov,Profiling an Ada Program with gprof,,Code Coverage and Profiling
20450@anchor{gnat_ugn/gnat_and_program_execution id21}@anchor{190}@anchor{gnat_ugn/gnat_and_program_execution code-coverage-of-ada-programs-with-gcov}@anchor{191}
20451@subsection Code Coverage of Ada Programs with gcov
20452
20453
20454@code{gcov} is a test coverage program: it analyzes the execution of a given
20455program on selected tests, to help you determine the portions of the program
20456that are still untested.
20457
20458@code{gcov} is part of the GCC suite, and is described in detail in the GCC
20459User's Guide. You can refer to this documentation for a more complete
20460description.
20461
20462This chapter provides a quick startup guide, and
20463details some GNAT-specific features.
20464
20465@menu
20466* Quick startup guide::
20467* GNAT specifics::
20468
20469@end menu
20470
20471@node Quick startup guide,GNAT specifics,,Code Coverage of Ada Programs with gcov
20472@anchor{gnat_ugn/gnat_and_program_execution id22}@anchor{192}@anchor{gnat_ugn/gnat_and_program_execution quick-startup-guide}@anchor{193}
20473@subsubsection Quick startup guide
20474
20475
20476In order to perform coverage analysis of a program using @code{gcov}, several
20477steps are needed:
20478
20479
20480@enumerate
20481
20482@item
20483Instrument the code during the compilation process,
20484
20485@item
20486Execute the instrumented program, and
20487
20488@item
20489Invoke the @code{gcov} tool to generate the coverage results.
20490@end enumerate
20491
20492@geindex -fprofile-arcs (gcc)
20493
20494@geindex -ftest-coverage (gcc
20495
20496@geindex -fprofile-arcs (gnatbind)
20497
20498The code instrumentation needed by gcov is created at the object level.
20499The source code is not modified in any way, because the instrumentation code is
20500inserted by gcc during the compilation process. To compile your code with code
20501coverage activated, you need to recompile your whole project using the
20502switches
20503@code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20504@code{-fprofile-arcs}.
20505
20506@quotation
20507
20508@example
20509$ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \\
20510   -largs -fprofile-arcs
20511@end example
20512@end quotation
20513
20514This compilation process will create @code{.gcno} files together with
20515the usual object files.
20516
20517Once the program is compiled with coverage instrumentation, you can
20518run it as many times as needed -- on portions of a test suite for
20519example. The first execution will produce @code{.gcda} files at the
20520same location as the @code{.gcno} files.  Subsequent executions
20521will update those files, so that a cumulative result of the covered
20522portions of the program is generated.
20523
20524Finally, you need to call the @code{gcov} tool. The different options of
20525@code{gcov} are described in the GCC User's Guide, section @emph{Invoking gcov}.
20526
20527This will create annotated source files with a @code{.gcov} extension:
20528@code{my_main.adb} file will be analyzed in @code{my_main.adb.gcov}.
20529
20530@node GNAT specifics,,Quick startup guide,Code Coverage of Ada Programs with gcov
20531@anchor{gnat_ugn/gnat_and_program_execution gnat-specifics}@anchor{194}@anchor{gnat_ugn/gnat_and_program_execution id23}@anchor{195}
20532@subsubsection GNAT specifics
20533
20534
20535Because of Ada semantics, portions of the source code may be shared among
20536several object files. This is the case for example when generics are
20537involved, when inlining is active  or when declarations generate  initialisation
20538calls. In order to take
20539into account this shared code, you need to call @code{gcov} on all
20540source files of the tested program at once.
20541
20542The list of source files might exceed the system's maximum command line
20543length. In order to bypass this limitation, a new mechanism has been
20544implemented in @code{gcov}: you can now list all your project's files into a
20545text file, and provide this file to gcov as a parameter,  preceded by a @code{@@}
20546(e.g. @code{gcov @@mysrclist.txt}).
20547
20548Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20549not supported as there can be unresolved symbols during the final link.
20550
20551@geindex gprof
20552
20553@geindex Profiling
20554
20555@node Profiling an Ada Program with gprof,,Code Coverage of Ada Programs with gcov,Code Coverage and Profiling
20556@anchor{gnat_ugn/gnat_and_program_execution profiling-an-ada-program-with-gprof}@anchor{196}@anchor{gnat_ugn/gnat_and_program_execution id24}@anchor{197}
20557@subsection Profiling an Ada Program with gprof
20558
20559
20560This section is not meant to be an exhaustive documentation of @code{gprof}.
20561Full documentation for it can be found in the @cite{GNU Profiler User's Guide}
20562documentation that is part of this GNAT distribution.
20563
20564Profiling a program helps determine the parts of a program that are executed
20565most often, and are therefore the most time-consuming.
20566
20567@code{gprof} is the standard GNU profiling tool; it has been enhanced to
20568better handle Ada programs and multitasking.
20569It is currently supported on the following platforms
20570
20571
20572@itemize *
20573
20574@item
20575linux x86/x86_64
20576
20577@item
20578solaris sparc/sparc64/x86
20579
20580@item
20581windows x86
20582@end itemize
20583
20584In order to profile a program using @code{gprof}, several steps are needed:
20585
20586
20587@enumerate
20588
20589@item
20590Instrument the code, which requires a full recompilation of the project with the
20591proper switches.
20592
20593@item
20594Execute the program under the analysis conditions, i.e. with the desired
20595input.
20596
20597@item
20598Analyze the results using the @code{gprof} tool.
20599@end enumerate
20600
20601The following sections detail the different steps, and indicate how
20602to interpret the results.
20603
20604@menu
20605* Compilation for profiling::
20606* Program execution::
20607* Running gprof::
20608* Interpretation of profiling results::
20609
20610@end menu
20611
20612@node Compilation for profiling,Program execution,,Profiling an Ada Program with gprof
20613@anchor{gnat_ugn/gnat_and_program_execution id25}@anchor{198}@anchor{gnat_ugn/gnat_and_program_execution compilation-for-profiling}@anchor{199}
20614@subsubsection Compilation for profiling
20615
20616
20617@geindex -pg (gcc)
20618@geindex for profiling
20619
20620@geindex -pg (gnatlink)
20621@geindex for profiling
20622
20623In order to profile a program the first step is to tell the compiler
20624to generate the necessary profiling information. The compiler switch to be used
20625is @code{-pg}, which must be added to other compilation switches. This
20626switch needs to be specified both during compilation and link stages, and can
20627be specified once when using gnatmake:
20628
20629@quotation
20630
20631@example
20632$ gnatmake -f -pg -P my_project
20633@end example
20634@end quotation
20635
20636Note that only the objects that were compiled with the @code{-pg} switch will
20637be profiled; if you need to profile your whole project, use the @code{-f}
20638gnatmake switch to force full recompilation.
20639
20640@node Program execution,Running gprof,Compilation for profiling,Profiling an Ada Program with gprof
20641@anchor{gnat_ugn/gnat_and_program_execution program-execution}@anchor{19a}@anchor{gnat_ugn/gnat_and_program_execution id26}@anchor{19b}
20642@subsubsection Program execution
20643
20644
20645Once the program has been compiled for profiling, you can run it as usual.
20646
20647The only constraint imposed by profiling is that the program must terminate
20648normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20649properly analyzed.
20650
20651Once the program completes execution, a data file called @code{gmon.out} is
20652generated in the directory where the program was launched from. If this file
20653already exists, it will be overwritten.
20654
20655@node Running gprof,Interpretation of profiling results,Program execution,Profiling an Ada Program with gprof
20656@anchor{gnat_ugn/gnat_and_program_execution running-gprof}@anchor{19c}@anchor{gnat_ugn/gnat_and_program_execution id27}@anchor{19d}
20657@subsubsection Running gprof
20658
20659
20660The @code{gprof} tool is called as follow:
20661
20662@quotation
20663
20664@example
20665$ gprof my_prog gmon.out
20666@end example
20667@end quotation
20668
20669or simply:
20670
20671@quotation
20672
20673@example
20674$  gprof my_prog
20675@end example
20676@end quotation
20677
20678The complete form of the gprof command line is the following:
20679
20680@quotation
20681
20682@example
20683$ gprof [switches] [executable [data-file]]
20684@end example
20685@end quotation
20686
20687@code{gprof} supports numerous switches. The order of these
20688switch does not matter. The full list of options can be found in
20689the GNU Profiler User's Guide documentation that comes with this documentation.
20690
20691The following is the subset of those switches that is most relevant:
20692
20693@geindex --demangle (gprof)
20694
20695
20696@table @asis
20697
20698@item @code{--demangle[=@emph{style}]}, @code{--no-demangle}
20699
20700These options control whether symbol names should be demangled when
20701printing output.  The default is to demangle C++ symbols.  The
20702@code{--no-demangle} option may be used to turn off demangling. Different
20703compilers have different mangling styles.  The optional demangling style
20704argument can be used to choose an appropriate demangling style for your
20705compiler, in particular Ada symbols generated by GNAT can be demangled using
20706@code{--demangle=gnat}.
20707@end table
20708
20709@geindex -e (gprof)
20710
20711
20712@table @asis
20713
20714@item @code{-e @emph{function_name}}
20715
20716The @code{-e @emph{function}} option tells @code{gprof} not to print
20717information about the function @code{function_name} (and its
20718children...) in the call graph.  The function will still be listed
20719as a child of any functions that call it, but its index number will be
20720shown as @code{[not printed]}.  More than one @code{-e} option may be
20721given; only one @code{function_name} may be indicated with each @code{-e}
20722option.
20723@end table
20724
20725@geindex -E (gprof)
20726
20727
20728@table @asis
20729
20730@item @code{-E @emph{function_name}}
20731
20732The @code{-E @emph{function}} option works like the @code{-e} option, but
20733execution time spent in the function (and children who were not called from
20734anywhere else), will not be used to compute the percentages-of-time for
20735the call graph.  More than one @code{-E} option may be given; only one
20736@code{function_name} may be indicated with each @code{-E`} option.
20737@end table
20738
20739@geindex -f (gprof)
20740
20741
20742@table @asis
20743
20744@item @code{-f @emph{function_name}}
20745
20746The @code{-f @emph{function}} option causes @code{gprof} to limit the
20747call graph to the function @code{function_name} and its children (and
20748their children...).  More than one @code{-f} option may be given;
20749only one @code{function_name} may be indicated with each @code{-f}
20750option.
20751@end table
20752
20753@geindex -F (gprof)
20754
20755
20756@table @asis
20757
20758@item @code{-F @emph{function_name}}
20759
20760The @code{-F @emph{function}} option works like the @code{-f} option, but
20761only time spent in the function and its children (and their
20762children...) will be used to determine total-time and
20763percentages-of-time for the call graph.  More than one @code{-F} option
20764may be given; only one @code{function_name} may be indicated with each
20765@code{-F} option.  The @code{-F} option overrides the @code{-E} option.
20766@end table
20767
20768@node Interpretation of profiling results,,Running gprof,Profiling an Ada Program with gprof
20769@anchor{gnat_ugn/gnat_and_program_execution id28}@anchor{19e}@anchor{gnat_ugn/gnat_and_program_execution interpretation-of-profiling-results}@anchor{19f}
20770@subsubsection Interpretation of profiling results
20771
20772
20773The results of the profiling analysis are represented by two arrays: the
20774'flat profile' and the 'call graph'. Full documentation of those outputs
20775can be found in the GNU Profiler User's Guide.
20776
20777The flat profile shows the time spent in each function of the program, and how
20778many time it has been called. This allows you to locate easily the most
20779time-consuming functions.
20780
20781The call graph shows, for each subprogram, the subprograms that call it,
20782and the subprograms that it calls. It also provides an estimate of the time
20783spent in each of those callers/called subprograms.
20784
20785@node Improving Performance,Overflow Check Handling in GNAT,Code Coverage and Profiling,GNAT and Program Execution
20786@anchor{gnat_ugn/gnat_and_program_execution id29}@anchor{169}@anchor{gnat_ugn/gnat_and_program_execution improving-performance}@anchor{26}
20787@section Improving Performance
20788
20789
20790@geindex Improving performance
20791
20792This section presents several topics related to program performance.
20793It first describes some of the tradeoffs that need to be considered
20794and some of the techniques for making your program run faster.
20795
20796
20797It then documents the unused subprogram/data elimination feature,
20798which can reduce the size of program executables.
20799
20800@menu
20801* Performance Considerations::
20802* Text_IO Suggestions::
20803* Reducing Size of Executables with Unused Subprogram/Data Elimination::
20804
20805@end menu
20806
20807@node Performance Considerations,Text_IO Suggestions,,Improving Performance
20808@anchor{gnat_ugn/gnat_and_program_execution performance-considerations}@anchor{1a0}@anchor{gnat_ugn/gnat_and_program_execution id30}@anchor{1a1}
20809@subsection Performance Considerations
20810
20811
20812The GNAT system provides a number of options that allow a trade-off
20813between
20814
20815
20816@itemize *
20817
20818@item
20819performance of the generated code
20820
20821@item
20822speed of compilation
20823
20824@item
20825minimization of dependences and recompilation
20826
20827@item
20828the degree of run-time checking.
20829@end itemize
20830
20831The defaults (if no options are selected) aim at improving the speed
20832of compilation and minimizing dependences, at the expense of performance
20833of the generated code:
20834
20835
20836@itemize *
20837
20838@item
20839no optimization
20840
20841@item
20842no inlining of subprogram calls
20843
20844@item
20845all run-time checks enabled except overflow and elaboration checks
20846@end itemize
20847
20848These options are suitable for most program development purposes. This
20849section describes how you can modify these choices, and also provides
20850some guidelines on debugging optimized code.
20851
20852@menu
20853* Controlling Run-Time Checks::
20854* Use of Restrictions::
20855* Optimization Levels::
20856* Debugging Optimized Code::
20857* Inlining of Subprograms::
20858* Floating_Point_Operations::
20859* Vectorization of loops::
20860* Other Optimization Switches::
20861* Optimization and Strict Aliasing::
20862* Aliased Variables and Optimization::
20863* Atomic Variables and Optimization::
20864* Passive Task Optimization::
20865
20866@end menu
20867
20868@node Controlling Run-Time Checks,Use of Restrictions,,Performance Considerations
20869@anchor{gnat_ugn/gnat_and_program_execution controlling-run-time-checks}@anchor{1a2}@anchor{gnat_ugn/gnat_and_program_execution id31}@anchor{1a3}
20870@subsubsection Controlling Run-Time Checks
20871
20872
20873By default, GNAT generates all run-time checks, except stack overflow
20874checks, and checks for access before elaboration on subprogram
20875calls. The latter are not required in default mode, because all
20876necessary checking is done at compile time.
20877
20878@geindex -gnatp (gcc)
20879
20880@geindex -gnato (gcc)
20881
20882The gnat switch, @code{-gnatp} allows this default to be modified. See
20883@ref{f9,,Run-Time Checks}.
20884
20885Our experience is that the default is suitable for most development
20886purposes.
20887
20888Elaboration checks are off by default, and also not needed by default, since
20889GNAT uses a static elaboration analysis approach that avoids the need for
20890run-time checking. This manual contains a full chapter discussing the issue
20891of elaboration checks, and if the default is not satisfactory for your use,
20892you should read this chapter.
20893
20894For validity checks, the minimal checks required by the Ada Reference
20895Manual (for case statements and assignments to array elements) are on
20896by default. These can be suppressed by use of the @code{-gnatVn} switch.
20897Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
20898is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
20899it may be reasonable to routinely use @code{-gnatVn}. Validity checks
20900are also suppressed entirely if @code{-gnatp} is used.
20901
20902@geindex Overflow checks
20903
20904@geindex Checks
20905@geindex overflow
20906
20907@geindex Suppress
20908
20909@geindex Unsuppress
20910
20911@geindex pragma Suppress
20912
20913@geindex pragma Unsuppress
20914
20915Note that the setting of the switches controls the default setting of
20916the checks. They may be modified using either @code{pragma Suppress} (to
20917remove checks) or @code{pragma Unsuppress} (to add back suppressed
20918checks) in the program source.
20919
20920@node Use of Restrictions,Optimization Levels,Controlling Run-Time Checks,Performance Considerations
20921@anchor{gnat_ugn/gnat_and_program_execution id32}@anchor{1a4}@anchor{gnat_ugn/gnat_and_program_execution use-of-restrictions}@anchor{1a5}
20922@subsubsection Use of Restrictions
20923
20924
20925The use of pragma Restrictions allows you to control which features are
20926permitted in your program. Apart from the obvious point that if you avoid
20927relatively expensive features like finalization (enforceable by the use
20928of pragma Restrictions (No_Finalization), the use of this pragma does not
20929affect the generated code in most cases.
20930
20931One notable exception to this rule is that the possibility of task abort
20932results in some distributed overhead, particularly if finalization or
20933exception handlers are used. The reason is that certain sections of code
20934have to be marked as non-abortable.
20935
20936If you use neither the @code{abort} statement, nor asynchronous transfer
20937of control (@code{select ... then abort}), then this distributed overhead
20938is removed, which may have a general positive effect in improving
20939overall performance.  Especially code involving frequent use of tasking
20940constructs and controlled types will show much improved performance.
20941The relevant restrictions pragmas are
20942
20943@quotation
20944
20945@example
20946pragma Restrictions (No_Abort_Statements);
20947pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
20948@end example
20949@end quotation
20950
20951It is recommended that these restriction pragmas be used if possible. Note
20952that this also means that you can write code without worrying about the
20953possibility of an immediate abort at any point.
20954
20955@node Optimization Levels,Debugging Optimized Code,Use of Restrictions,Performance Considerations
20956@anchor{gnat_ugn/gnat_and_program_execution id33}@anchor{1a6}@anchor{gnat_ugn/gnat_and_program_execution optimization-levels}@anchor{fc}
20957@subsubsection Optimization Levels
20958
20959
20960@geindex -O (gcc)
20961
20962Without any optimization option,
20963the compiler's goal is to reduce the cost of
20964compilation and to make debugging produce the expected results.
20965Statements are independent: if you stop the program with a breakpoint between
20966statements, you can then assign a new value to any variable or change
20967the program counter to any other statement in the subprogram and get exactly
20968the results you would expect from the source code.
20969
20970Turning on optimization makes the compiler attempt to improve the
20971performance and/or code size at the expense of compilation time and
20972possibly the ability to debug the program.
20973
20974If you use multiple
20975-O options, with or without level numbers,
20976the last such option is the one that is effective.
20977
20978The default is optimization off. This results in the fastest compile
20979times, but GNAT makes absolutely no attempt to optimize, and the
20980generated programs are considerably larger and slower than when
20981optimization is enabled. You can use the
20982@code{-O} switch (the permitted forms are @code{-O0}, @code{-O1}
20983@code{-O2}, @code{-O3}, and @code{-Os})
20984to @code{gcc} to control the optimization level:
20985
20986
20987@itemize *
20988
20989@item
20990
20991@table @asis
20992
20993@item @code{-O0}
20994
20995No optimization (the default);
20996generates unoptimized code but has
20997the fastest compilation time.
20998
20999Note that many other compilers do substantial optimization even
21000if 'no optimization' is specified. With gcc, it is very unusual
21001to use @code{-O0} for production if execution time is of any concern,
21002since @code{-O0} means (almost) no optimization. This difference
21003between gcc and other compilers should be kept in mind when
21004doing performance comparisons.
21005@end table
21006
21007@item
21008
21009@table @asis
21010
21011@item @code{-O1}
21012
21013Moderate optimization;
21014optimizes reasonably well but does not
21015degrade compilation time significantly.
21016@end table
21017
21018@item
21019
21020@table @asis
21021
21022@item @code{-O2}
21023
21024Full optimization;
21025generates highly optimized code and has
21026the slowest compilation time.
21027@end table
21028
21029@item
21030
21031@table @asis
21032
21033@item @code{-O3}
21034
21035Full optimization as in @code{-O2};
21036also uses more aggressive automatic inlining of subprograms within a unit
21037(@ref{10f,,Inlining of Subprograms}) and attempts to vectorize loops.
21038@end table
21039
21040@item
21041
21042@table @asis
21043
21044@item @code{-Os}
21045
21046Optimize space usage (code and data) of resulting program.
21047@end table
21048@end itemize
21049
21050Higher optimization levels perform more global transformations on the
21051program and apply more expensive analysis algorithms in order to generate
21052faster and more compact code. The price in compilation time, and the
21053resulting improvement in execution time,
21054both depend on the particular application and the hardware environment.
21055You should experiment to find the best level for your application.
21056
21057Since the precise set of optimizations done at each level will vary from
21058release to release (and sometime from target to target), it is best to think
21059of the optimization settings in general terms.
21060See the @emph{Options That Control Optimization} section in
21061@cite{Using the GNU Compiler Collection (GCC)}
21062for details about
21063the @code{-O} settings and a number of @code{-f} options that
21064individually enable or disable specific optimizations.
21065
21066Unlike some other compilation systems, @code{gcc} has
21067been tested extensively at all optimization levels. There are some bugs
21068which appear only with optimization turned on, but there have also been
21069bugs which show up only in @emph{unoptimized} code. Selecting a lower
21070level of optimization does not improve the reliability of the code
21071generator, which in practice is highly reliable at all optimization
21072levels.
21073
21074Note regarding the use of @code{-O3}: The use of this optimization level
21075ought not to be automatically preferred over that of level @code{-O2},
21076since it often results in larger executables which may run more slowly.
21077See further discussion of this point in @ref{10f,,Inlining of Subprograms}.
21078
21079@node Debugging Optimized Code,Inlining of Subprograms,Optimization Levels,Performance Considerations
21080@anchor{gnat_ugn/gnat_and_program_execution id34}@anchor{1a7}@anchor{gnat_ugn/gnat_and_program_execution debugging-optimized-code}@anchor{1a8}
21081@subsubsection Debugging Optimized Code
21082
21083
21084@geindex Debugging optimized code
21085
21086@geindex Optimization and debugging
21087
21088Although it is possible to do a reasonable amount of debugging at
21089nonzero optimization levels,
21090the higher the level the more likely that
21091source-level constructs will have been eliminated by optimization.
21092For example, if a loop is strength-reduced, the loop
21093control variable may be completely eliminated and thus cannot be
21094displayed in the debugger.
21095This can only happen at @code{-O2} or @code{-O3}.
21096Explicit temporary variables that you code might be eliminated at
21097level @code{-O1} or higher.
21098
21099@geindex -g (gcc)
21100
21101The use of the @code{-g} switch,
21102which is needed for source-level debugging,
21103affects the size of the program executable on disk,
21104and indeed the debugging information can be quite large.
21105However, it has no effect on the generated code (and thus does not
21106degrade performance)
21107
21108Since the compiler generates debugging tables for a compilation unit before
21109it performs optimizations, the optimizing transformations may invalidate some
21110of the debugging data.  You therefore need to anticipate certain
21111anomalous situations that may arise while debugging optimized code.
21112These are the most common cases:
21113
21114
21115@itemize *
21116
21117@item
21118@emph{The 'hopping Program Counter':}  Repeated @code{step} or @code{next}
21119commands show
21120the PC bouncing back and forth in the code.  This may result from any of
21121the following optimizations:
21122
21123
21124@itemize -
21125
21126@item
21127@emph{Common subexpression elimination:} using a single instance of code for a
21128quantity that the source computes several times.  As a result you
21129may not be able to stop on what looks like a statement.
21130
21131@item
21132@emph{Invariant code motion:} moving an expression that does not change within a
21133loop, to the beginning of the loop.
21134
21135@item
21136@emph{Instruction scheduling:} moving instructions so as to
21137overlap loads and stores (typically) with other code, or in
21138general to move computations of values closer to their uses. Often
21139this causes you to pass an assignment statement without the assignment
21140happening and then later bounce back to the statement when the
21141value is actually needed.  Placing a breakpoint on a line of code
21142and then stepping over it may, therefore, not always cause all the
21143expected side-effects.
21144@end itemize
21145
21146@item
21147@emph{The 'big leap':} More commonly known as @emph{cross-jumping}, in which
21148two identical pieces of code are merged and the program counter suddenly
21149jumps to a statement that is not supposed to be executed, simply because
21150it (and the code following) translates to the same thing as the code
21151that @emph{was} supposed to be executed.  This effect is typically seen in
21152sequences that end in a jump, such as a @code{goto}, a @code{return}, or
21153a @code{break} in a C @code{switch} statement.
21154
21155@item
21156@emph{The 'roving variable':} The symptom is an unexpected value in a variable.
21157There are various reasons for this effect:
21158
21159
21160@itemize -
21161
21162@item
21163In a subprogram prologue, a parameter may not yet have been moved to its
21164'home'.
21165
21166@item
21167A variable may be dead, and its register re-used.  This is
21168probably the most common cause.
21169
21170@item
21171As mentioned above, the assignment of a value to a variable may
21172have been moved.
21173
21174@item
21175A variable may be eliminated entirely by value propagation or
21176other means.  In this case, GCC may incorrectly generate debugging
21177information for the variable
21178@end itemize
21179
21180In general, when an unexpected value appears for a local variable or parameter
21181you should first ascertain if that value was actually computed by
21182your program, as opposed to being incorrectly reported by the debugger.
21183Record fields or
21184array elements in an object designated by an access value
21185are generally less of a problem, once you have ascertained that the access
21186value is sensible.
21187Typically, this means checking variables in the preceding code and in the
21188calling subprogram to verify that the value observed is explainable from other
21189values (one must apply the procedure recursively to those
21190other values); or re-running the code and stopping a little earlier
21191(perhaps before the call) and stepping to better see how the variable obtained
21192the value in question; or continuing to step @emph{from} the point of the
21193strange value to see if code motion had simply moved the variable's
21194assignments later.
21195@end itemize
21196
21197In light of such anomalies, a recommended technique is to use @code{-O0}
21198early in the software development cycle, when extensive debugging capabilities
21199are most needed, and then move to @code{-O1} and later @code{-O2} as
21200the debugger becomes less critical.
21201Whether to use the @code{-g} switch in the release version is
21202a release management issue.
21203Note that if you use @code{-g} you can then use the @code{strip} program
21204on the resulting executable,
21205which removes both debugging information and global symbols.
21206
21207@node Inlining of Subprograms,Floating_Point_Operations,Debugging Optimized Code,Performance Considerations
21208@anchor{gnat_ugn/gnat_and_program_execution id35}@anchor{1a9}@anchor{gnat_ugn/gnat_and_program_execution inlining-of-subprograms}@anchor{10f}
21209@subsubsection Inlining of Subprograms
21210
21211
21212A call to a subprogram in the current unit is inlined if all the
21213following conditions are met:
21214
21215
21216@itemize *
21217
21218@item
21219The optimization level is at least @code{-O1}.
21220
21221@item
21222The called subprogram is suitable for inlining: It must be small enough
21223and not contain something that @code{gcc} cannot support in inlined
21224subprograms.
21225
21226@geindex pragma Inline
21227
21228@geindex Inline
21229
21230@item
21231Any one of the following applies: @code{pragma Inline} is applied to the
21232subprogram; the subprogram is local to the unit and called once from
21233within it; the subprogram is small and optimization level @code{-O2} is
21234specified; optimization level @code{-O3} is specified.
21235@end itemize
21236
21237Calls to subprograms in @emph{with}ed units are normally not inlined.
21238To achieve actual inlining (that is, replacement of the call by the code
21239in the body of the subprogram), the following conditions must all be true:
21240
21241
21242@itemize *
21243
21244@item
21245The optimization level is at least @code{-O1}.
21246
21247@item
21248The called subprogram is suitable for inlining: It must be small enough
21249and not contain something that @code{gcc} cannot support in inlined
21250subprograms.
21251
21252@item
21253There is a @code{pragma Inline} for the subprogram.
21254
21255@item
21256The @code{-gnatn} switch is used on the command line.
21257@end itemize
21258
21259Even if all these conditions are met, it may not be possible for
21260the compiler to inline the call, due to the length of the body,
21261or features in the body that make it impossible for the compiler
21262to do the inlining.
21263
21264Note that specifying the @code{-gnatn} switch causes additional
21265compilation dependencies. Consider the following:
21266
21267@quotation
21268
21269@example
21270package R is
21271   procedure Q;
21272   pragma Inline (Q);
21273end R;
21274package body R is
21275   ...
21276end R;
21277
21278with R;
21279procedure Main is
21280begin
21281   ...
21282   R.Q;
21283end Main;
21284@end example
21285@end quotation
21286
21287With the default behavior (no @code{-gnatn} switch specified), the
21288compilation of the @code{Main} procedure depends only on its own source,
21289@code{main.adb}, and the spec of the package in file @code{r.ads}. This
21290means that editing the body of @code{R} does not require recompiling
21291@code{Main}.
21292
21293On the other hand, the call @code{R.Q} is not inlined under these
21294circumstances. If the @code{-gnatn} switch is present when @code{Main}
21295is compiled, the call will be inlined if the body of @code{Q} is small
21296enough, but now @code{Main} depends on the body of @code{R} in
21297@code{r.adb} as well as on the spec. This means that if this body is edited,
21298the main program must be recompiled. Note that this extra dependency
21299occurs whether or not the call is in fact inlined by @code{gcc}.
21300
21301The use of front end inlining with @code{-gnatN} generates similar
21302additional dependencies.
21303
21304@geindex -fno-inline (gcc)
21305
21306Note: The @code{-fno-inline} switch overrides all other conditions and ensures that
21307no inlining occurs, unless requested with pragma Inline_Always for @code{gcc}
21308back-ends. The extra dependences resulting from @code{-gnatn} will still be active,
21309even if this switch is used to suppress the resulting inlining actions.
21310
21311@geindex -fno-inline-functions (gcc)
21312
21313Note: The @code{-fno-inline-functions} switch can be used to prevent
21314automatic inlining of subprograms if @code{-O3} is used.
21315
21316@geindex -fno-inline-small-functions (gcc)
21317
21318Note: The @code{-fno-inline-small-functions} switch can be used to prevent
21319automatic inlining of small subprograms if @code{-O2} is used.
21320
21321@geindex -fno-inline-functions-called-once (gcc)
21322
21323Note: The @code{-fno-inline-functions-called-once} switch
21324can be used to prevent inlining of subprograms local to the unit
21325and called once from within it if @code{-O1} is used.
21326
21327Note regarding the use of @code{-O3}: @code{-gnatn} is made up of two
21328sub-switches @code{-gnatn1} and @code{-gnatn2} that can be directly
21329specified in lieu of it, @code{-gnatn} being translated into one of them
21330based on the optimization level. With @code{-O2} or below, @code{-gnatn}
21331is equivalent to @code{-gnatn1} which activates pragma @code{Inline} with
21332moderate inlining across modules. With @code{-O3}, @code{-gnatn} is
21333equivalent to @code{-gnatn2} which activates pragma @code{Inline} with
21334full inlining across modules. If you have used pragma @code{Inline} in
21335appropriate cases, then it is usually much better to use @code{-O2}
21336and @code{-gnatn} and avoid the use of @code{-O3} which has the additional
21337effect of inlining subprograms you did not think should be inlined. We have
21338found that the use of @code{-O3} may slow down the compilation and increase
21339the code size by performing excessive inlining, leading to increased
21340instruction cache pressure from the increased code size and thus minor
21341performance improvements. So the bottom line here is that you should not
21342automatically assume that @code{-O3} is better than @code{-O2}, and
21343indeed you should use @code{-O3} only if tests show that it actually
21344improves performance for your program.
21345
21346@node Floating_Point_Operations,Vectorization of loops,Inlining of Subprograms,Performance Considerations
21347@anchor{gnat_ugn/gnat_and_program_execution id36}@anchor{1aa}@anchor{gnat_ugn/gnat_and_program_execution floating-point-operations}@anchor{1ab}
21348@subsubsection Floating_Point_Operations
21349
21350
21351@geindex Floating-Point Operations
21352
21353On almost all targets, GNAT maps Float and Long_Float to the 32-bit and
2135464-bit standard IEEE floating-point representations, and operations will
21355use standard IEEE arithmetic as provided by the processor. On most, but
21356not all, architectures, the attribute Machine_Overflows is False for these
21357types, meaning that the semantics of overflow is implementation-defined.
21358In the case of GNAT, these semantics correspond to the normal IEEE
21359treatment of infinities and NaN (not a number) values. For example,
213601.0 / 0.0 yields plus infinitiy and 0.0 / 0.0 yields a NaN. By
21361avoiding explicit overflow checks, the performance is greatly improved
21362on many targets. However, if required, floating-point overflow can be
21363enabled by the use of the pragma Check_Float_Overflow.
21364
21365Another consideration that applies specifically to x86 32-bit
21366architectures is which form of floating-point arithmetic is used.
21367By default the operations use the old style x86 floating-point,
21368which implements an 80-bit extended precision form (on these
21369architectures the type Long_Long_Float corresponds to that form).
21370In addition, generation of efficient code in this mode means that
21371the extended precision form will be used for intermediate results.
21372This may be helpful in improving the final precision of a complex
21373expression. However it means that the results obtained on the x86
21374will be different from those on other architectures, and for some
21375algorithms, the extra intermediate precision can be detrimental.
21376
21377In addition to this old-style floating-point, all modern x86 chips
21378implement an alternative floating-point operation model referred
21379to as SSE2. In this model there is no extended form, and furthermore
21380execution performance is significantly enhanced. To force GNAT to use
21381this more modern form, use both of the switches:
21382
21383@quotation
21384
21385-msse2 -mfpmath=sse
21386@end quotation
21387
21388A unit compiled with these switches will automatically use the more
21389efficient SSE2 instruction set for Float and Long_Float operations.
21390Note that the ABI has the same form for both floating-point models,
21391so it is permissible to mix units compiled with and without these
21392switches.
21393
21394@node Vectorization of loops,Other Optimization Switches,Floating_Point_Operations,Performance Considerations
21395@anchor{gnat_ugn/gnat_and_program_execution id37}@anchor{1ac}@anchor{gnat_ugn/gnat_and_program_execution vectorization-of-loops}@anchor{1ad}
21396@subsubsection Vectorization of loops
21397
21398
21399@geindex Optimization Switches
21400
21401You can take advantage of the auto-vectorizer present in the @code{gcc}
21402back end to vectorize loops with GNAT.  The corresponding command line switch
21403is @code{-ftree-vectorize} but, as it is enabled by default at @code{-O3}
21404and other aggressive optimizations helpful for vectorization also are enabled
21405by default at this level, using @code{-O3} directly is recommended.
21406
21407You also need to make sure that the target architecture features a supported
21408SIMD instruction set.  For example, for the x86 architecture, you should at
21409least specify @code{-msse2} to get significant vectorization (but you don't
21410need to specify it for x86-64 as it is part of the base 64-bit architecture).
21411Similarly, for the PowerPC architecture, you should specify @code{-maltivec}.
21412
21413The preferred loop form for vectorization is the @code{for} iteration scheme.
21414Loops with a @code{while} iteration scheme can also be vectorized if they are
21415very simple, but the vectorizer will quickly give up otherwise.  With either
21416iteration scheme, the flow of control must be straight, in particular no
21417@code{exit} statement may appear in the loop body.  The loop may however
21418contain a single nested loop, if it can be vectorized when considered alone:
21419
21420@quotation
21421
21422@example
21423A : array (1..4, 1..4) of Long_Float;
21424S : array (1..4) of Long_Float;
21425
21426procedure Sum is
21427begin
21428   for I in A'Range(1) loop
21429      for J in A'Range(2) loop
21430         S (I) := S (I) + A (I, J);
21431      end loop;
21432   end loop;
21433end Sum;
21434@end example
21435@end quotation
21436
21437The vectorizable operations depend on the targeted SIMD instruction set, but
21438the adding and some of the multiplying operators are generally supported, as
21439well as the logical operators for modular types. Note that compiling
21440with @code{-gnatp} might well reveal cases where some checks do thwart
21441vectorization.
21442
21443Type conversions may also prevent vectorization if they involve semantics that
21444are not directly supported by the code generator or the SIMD instruction set.
21445A typical example is direct conversion from floating-point to integer types.
21446The solution in this case is to use the following idiom:
21447
21448@quotation
21449
21450@example
21451Integer (S'Truncation (F))
21452@end example
21453@end quotation
21454
21455if @code{S} is the subtype of floating-point object @code{F}.
21456
21457In most cases, the vectorizable loops are loops that iterate over arrays.
21458All kinds of array types are supported, i.e. constrained array types with
21459static bounds:
21460
21461@quotation
21462
21463@example
21464type Array_Type is array (1 .. 4) of Long_Float;
21465@end example
21466@end quotation
21467
21468constrained array types with dynamic bounds:
21469
21470@quotation
21471
21472@example
21473type Array_Type is array (1 .. Q.N) of Long_Float;
21474
21475type Array_Type is array (Q.K .. 4) of Long_Float;
21476
21477type Array_Type is array (Q.K .. Q.N) of Long_Float;
21478@end example
21479@end quotation
21480
21481or unconstrained array types:
21482
21483@quotation
21484
21485@example
21486type Array_Type is array (Positive range <>) of Long_Float;
21487@end example
21488@end quotation
21489
21490The quality of the generated code decreases when the dynamic aspect of the
21491array type increases, the worst code being generated for unconstrained array
21492types.  This is so because, the less information the compiler has about the
21493bounds of the array, the more fallback code it needs to generate in order to
21494fix things up at run time.
21495
21496It is possible to specify that a given loop should be subject to vectorization
21497preferably to other optimizations by means of pragma @code{Loop_Optimize}:
21498
21499@quotation
21500
21501@example
21502pragma Loop_Optimize (Vector);
21503@end example
21504@end quotation
21505
21506placed immediately within the loop will convey the appropriate hint to the
21507compiler for this loop.
21508
21509It is also possible to help the compiler generate better vectorized code
21510for a given loop by asserting that there are no loop-carried dependencies
21511in the loop.  Consider for example the procedure:
21512
21513@quotation
21514
21515@example
21516type Arr is array (1 .. 4) of Long_Float;
21517
21518procedure Add (X, Y : not null access Arr; R : not null access Arr) is
21519begin
21520  for I in Arr'Range loop
21521    R(I) := X(I) + Y(I);
21522  end loop;
21523end;
21524@end example
21525@end quotation
21526
21527By default, the compiler cannot unconditionally vectorize the loop because
21528assigning to a component of the array designated by R in one iteration could
21529change the value read from the components of the array designated by X or Y
21530in a later iteration.  As a result, the compiler will generate two versions
21531of the loop in the object code, one vectorized and the other not vectorized,
21532as well as a test to select the appropriate version at run time.  This can
21533be overcome by another hint:
21534
21535@quotation
21536
21537@example
21538pragma Loop_Optimize (Ivdep);
21539@end example
21540@end quotation
21541
21542placed immediately within the loop will tell the compiler that it can safely
21543omit the non-vectorized version of the loop as well as the run-time test.
21544
21545@node Other Optimization Switches,Optimization and Strict Aliasing,Vectorization of loops,Performance Considerations
21546@anchor{gnat_ugn/gnat_and_program_execution other-optimization-switches}@anchor{1ae}@anchor{gnat_ugn/gnat_and_program_execution id38}@anchor{1af}
21547@subsubsection Other Optimization Switches
21548
21549
21550@geindex Optimization Switches
21551
21552Since GNAT uses the @code{gcc} back end, all the specialized
21553@code{gcc} optimization switches are potentially usable. These switches
21554have not been extensively tested with GNAT but can generally be expected
21555to work. Examples of switches in this category are @code{-funroll-loops}
21556and the various target-specific @code{-m} options (in particular, it has
21557been observed that @code{-march=xxx} can significantly improve performance
21558on appropriate machines). For full details of these switches, see
21559the @emph{Submodel Options} section in the @emph{Hardware Models and Configurations}
21560chapter of @cite{Using the GNU Compiler Collection (GCC)}.
21561
21562@node Optimization and Strict Aliasing,Aliased Variables and Optimization,Other Optimization Switches,Performance Considerations
21563@anchor{gnat_ugn/gnat_and_program_execution optimization-and-strict-aliasing}@anchor{f3}@anchor{gnat_ugn/gnat_and_program_execution id39}@anchor{1b0}
21564@subsubsection Optimization and Strict Aliasing
21565
21566
21567@geindex Aliasing
21568
21569@geindex Strict Aliasing
21570
21571@geindex No_Strict_Aliasing
21572
21573The strong typing capabilities of Ada allow an optimizer to generate
21574efficient code in situations where other languages would be forced to
21575make worst case assumptions preventing such optimizations. Consider
21576the following example:
21577
21578@quotation
21579
21580@example
21581procedure R is
21582   type Int1 is new Integer;
21583   type Int2 is new Integer;
21584   type Int1A is access Int1;
21585   type Int2A is access Int2;
21586   Int1V : Int1A;
21587   Int2V : Int2A;
21588   ...
21589
21590begin
21591   ...
21592   for J in Data'Range loop
21593      if Data (J) = Int1V.all then
21594         Int2V.all := Int2V.all + 1;
21595      end if;
21596   end loop;
21597   ...
21598end R;
21599@end example
21600@end quotation
21601
21602In this example, since the variable @code{Int1V} can only access objects
21603of type @code{Int1}, and @code{Int2V} can only access objects of type
21604@code{Int2}, there is no possibility that the assignment to
21605@code{Int2V.all} affects the value of @code{Int1V.all}. This means that
21606the compiler optimizer can "know" that the value @code{Int1V.all} is constant
21607for all iterations of the loop and avoid the extra memory reference
21608required to dereference it each time through the loop.
21609
21610This kind of optimization, called strict aliasing analysis, is
21611triggered by specifying an optimization level of @code{-O2} or
21612higher or @code{-Os} and allows GNAT to generate more efficient code
21613when access values are involved.
21614
21615However, although this optimization is always correct in terms of
21616the formal semantics of the Ada Reference Manual, difficulties can
21617arise if features like @code{Unchecked_Conversion} are used to break
21618the typing system. Consider the following complete program example:
21619
21620@quotation
21621
21622@example
21623package p1 is
21624   type int1 is new integer;
21625   type int2 is new integer;
21626   type a1 is access int1;
21627   type a2 is access int2;
21628end p1;
21629
21630with p1; use p1;
21631package p2 is
21632   function to_a2 (Input : a1) return a2;
21633end p2;
21634
21635with Unchecked_Conversion;
21636package body p2 is
21637   function to_a2 (Input : a1) return a2 is
21638      function to_a2u is
21639        new Unchecked_Conversion (a1, a2);
21640   begin
21641      return to_a2u (Input);
21642   end to_a2;
21643end p2;
21644
21645with p2; use p2;
21646with p1; use p1;
21647with Text_IO; use Text_IO;
21648procedure m is
21649   v1 : a1 := new int1;
21650   v2 : a2 := to_a2 (v1);
21651begin
21652   v1.all := 1;
21653   v2.all := 0;
21654   put_line (int1'image (v1.all));
21655end;
21656@end example
21657@end quotation
21658
21659This program prints out 0 in @code{-O0} or @code{-O1}
21660mode, but it prints out 1 in @code{-O2} mode. That's
21661because in strict aliasing mode, the compiler can and
21662does assume that the assignment to @code{v2.all} could not
21663affect the value of @code{v1.all}, since different types
21664are involved.
21665
21666This behavior is not a case of non-conformance with the standard, since
21667the Ada RM specifies that an unchecked conversion where the resulting
21668bit pattern is not a correct value of the target type can result in an
21669abnormal value and attempting to reference an abnormal value makes the
21670execution of a program erroneous.  That's the case here since the result
21671does not point to an object of type @code{int2}.  This means that the
21672effect is entirely unpredictable.
21673
21674However, although that explanation may satisfy a language
21675lawyer, in practice an applications programmer expects an
21676unchecked conversion involving pointers to create true
21677aliases and the behavior of printing 1 seems plain wrong.
21678In this case, the strict aliasing optimization is unwelcome.
21679
21680Indeed the compiler recognizes this possibility, and the
21681unchecked conversion generates a warning:
21682
21683@quotation
21684
21685@example
21686p2.adb:5:07: warning: possible aliasing problem with type "a2"
21687p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
21688p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
21689@end example
21690@end quotation
21691
21692Unfortunately the problem is recognized when compiling the body of
21693package @code{p2}, but the actual "bad" code is generated while
21694compiling the body of @code{m} and this latter compilation does not see
21695the suspicious @code{Unchecked_Conversion}.
21696
21697As implied by the warning message, there are approaches you can use to
21698avoid the unwanted strict aliasing optimization in a case like this.
21699
21700One possibility is to simply avoid the use of @code{-O2}, but
21701that is a bit drastic, since it throws away a number of useful
21702optimizations that do not involve strict aliasing assumptions.
21703
21704A less drastic approach is to compile the program using the
21705option @code{-fno-strict-aliasing}. Actually it is only the
21706unit containing the dereferencing of the suspicious pointer
21707that needs to be compiled. So in this case, if we compile
21708unit @code{m} with this switch, then we get the expected
21709value of zero printed. Analyzing which units might need
21710the switch can be painful, so a more reasonable approach
21711is to compile the entire program with options @code{-O2}
21712and @code{-fno-strict-aliasing}. If the performance is
21713satisfactory with this combination of options, then the
21714advantage is that the entire issue of possible "wrong"
21715optimization due to strict aliasing is avoided.
21716
21717To avoid the use of compiler switches, the configuration
21718pragma @code{No_Strict_Aliasing} with no parameters may be
21719used to specify that for all access types, the strict
21720aliasing optimization should be suppressed.
21721
21722However, these approaches are still overkill, in that they causes
21723all manipulations of all access values to be deoptimized. A more
21724refined approach is to concentrate attention on the specific
21725access type identified as problematic.
21726
21727First, if a careful analysis of uses of the pointer shows
21728that there are no possible problematic references, then
21729the warning can be suppressed by bracketing the
21730instantiation of @code{Unchecked_Conversion} to turn
21731the warning off:
21732
21733@quotation
21734
21735@example
21736pragma Warnings (Off);
21737function to_a2u is
21738  new Unchecked_Conversion (a1, a2);
21739pragma Warnings (On);
21740@end example
21741@end quotation
21742
21743Of course that approach is not appropriate for this particular
21744example, since indeed there is a problematic reference. In this
21745case we can take one of two other approaches.
21746
21747The first possibility is to move the instantiation of unchecked
21748conversion to the unit in which the type is declared. In
21749this example, we would move the instantiation of
21750@code{Unchecked_Conversion} from the body of package
21751@code{p2} to the spec of package @code{p1}. Now the
21752warning disappears. That's because any use of the
21753access type knows there is a suspicious unchecked
21754conversion, and the strict aliasing optimization
21755is automatically suppressed for the type.
21756
21757If it is not practical to move the unchecked conversion to the same unit
21758in which the destination access type is declared (perhaps because the
21759source type is not visible in that unit), you may use pragma
21760@code{No_Strict_Aliasing} for the type. This pragma must occur in the
21761same declarative sequence as the declaration of the access type:
21762
21763@quotation
21764
21765@example
21766type a2 is access int2;
21767pragma No_Strict_Aliasing (a2);
21768@end example
21769@end quotation
21770
21771Here again, the compiler now knows that the strict aliasing optimization
21772should be suppressed for any reference to type @code{a2} and the
21773expected behavior is obtained.
21774
21775Finally, note that although the compiler can generate warnings for
21776simple cases of unchecked conversions, there are tricker and more
21777indirect ways of creating type incorrect aliases which the compiler
21778cannot detect. Examples are the use of address overlays and unchecked
21779conversions involving composite types containing access types as
21780components. In such cases, no warnings are generated, but there can
21781still be aliasing problems. One safe coding practice is to forbid the
21782use of address clauses for type overlaying, and to allow unchecked
21783conversion only for primitive types. This is not really a significant
21784restriction since any possible desired effect can be achieved by
21785unchecked conversion of access values.
21786
21787The aliasing analysis done in strict aliasing mode can certainly
21788have significant benefits. We have seen cases of large scale
21789application code where the time is increased by up to 5% by turning
21790this optimization off. If you have code that includes significant
21791usage of unchecked conversion, you might want to just stick with
21792@code{-O1} and avoid the entire issue. If you get adequate
21793performance at this level of optimization level, that's probably
21794the safest approach. If tests show that you really need higher
21795levels of optimization, then you can experiment with @code{-O2}
21796and @code{-O2 -fno-strict-aliasing} to see how much effect this
21797has on size and speed of the code. If you really need to use
21798@code{-O2} with strict aliasing in effect, then you should
21799review any uses of unchecked conversion of access types,
21800particularly if you are getting the warnings described above.
21801
21802@node Aliased Variables and Optimization,Atomic Variables and Optimization,Optimization and Strict Aliasing,Performance Considerations
21803@anchor{gnat_ugn/gnat_and_program_execution aliased-variables-and-optimization}@anchor{1b1}@anchor{gnat_ugn/gnat_and_program_execution id40}@anchor{1b2}
21804@subsubsection Aliased Variables and Optimization
21805
21806
21807@geindex Aliasing
21808
21809There are scenarios in which programs may
21810use low level techniques to modify variables
21811that otherwise might be considered to be unassigned. For example,
21812a variable can be passed to a procedure by reference, which takes
21813the address of the parameter and uses the address to modify the
21814variable's value, even though it is passed as an IN parameter.
21815Consider the following example:
21816
21817@quotation
21818
21819@example
21820procedure P is
21821   Max_Length : constant Natural := 16;
21822   type Char_Ptr is access all Character;
21823
21824   procedure Get_String(Buffer: Char_Ptr; Size : Integer);
21825   pragma Import (C, Get_String, "get_string");
21826
21827   Name : aliased String (1 .. Max_Length) := (others => ' ');
21828   Temp : Char_Ptr;
21829
21830   function Addr (S : String) return Char_Ptr is
21831      function To_Char_Ptr is
21832        new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
21833   begin
21834      return To_Char_Ptr (S (S'First)'Address);
21835   end;
21836
21837begin
21838   Temp := Addr (Name);
21839   Get_String (Temp, Max_Length);
21840end;
21841@end example
21842@end quotation
21843
21844where Get_String is a C function that uses the address in Temp to
21845modify the variable @code{Name}. This code is dubious, and arguably
21846erroneous, and the compiler would be entitled to assume that
21847@code{Name} is never modified, and generate code accordingly.
21848
21849However, in practice, this would cause some existing code that
21850seems to work with no optimization to start failing at high
21851levels of optimzization.
21852
21853What the compiler does for such cases is to assume that marking
21854a variable as aliased indicates that some "funny business" may
21855be going on. The optimizer recognizes the aliased keyword and
21856inhibits optimizations that assume the value cannot be assigned.
21857This means that the above example will in fact "work" reliably,
21858that is, it will produce the expected results.
21859
21860@node Atomic Variables and Optimization,Passive Task Optimization,Aliased Variables and Optimization,Performance Considerations
21861@anchor{gnat_ugn/gnat_and_program_execution atomic-variables-and-optimization}@anchor{1b3}@anchor{gnat_ugn/gnat_and_program_execution id41}@anchor{1b4}
21862@subsubsection Atomic Variables and Optimization
21863
21864
21865@geindex Atomic
21866
21867There are two considerations with regard to performance when
21868atomic variables are used.
21869
21870First, the RM only guarantees that access to atomic variables
21871be atomic, it has nothing to say about how this is achieved,
21872though there is a strong implication that this should not be
21873achieved by explicit locking code. Indeed GNAT will never
21874generate any locking code for atomic variable access (it will
21875simply reject any attempt to make a variable or type atomic
21876if the atomic access cannot be achieved without such locking code).
21877
21878That being said, it is important to understand that you cannot
21879assume that the entire variable will always be accessed. Consider
21880this example:
21881
21882@quotation
21883
21884@example
21885type R is record
21886   A,B,C,D : Character;
21887end record;
21888for R'Size use 32;
21889for R'Alignment use 4;
21890
21891RV : R;
21892pragma Atomic (RV);
21893X : Character;
21894...
21895X := RV.B;
21896@end example
21897@end quotation
21898
21899You cannot assume that the reference to @code{RV.B}
21900will read the entire 32-bit
21901variable with a single load instruction. It is perfectly legitimate if
21902the hardware allows it to do a byte read of just the B field. This read
21903is still atomic, which is all the RM requires. GNAT can and does take
21904advantage of this, depending on the architecture and optimization level.
21905Any assumption to the contrary is non-portable and risky. Even if you
21906examine the assembly language and see a full 32-bit load, this might
21907change in a future version of the compiler.
21908
21909If your application requires that all accesses to @code{RV} in this
21910example be full 32-bit loads, you need to make a copy for the access
21911as in:
21912
21913@quotation
21914
21915@example
21916declare
21917   RV_Copy : constant R := RV;
21918begin
21919   X := RV_Copy.B;
21920end;
21921@end example
21922@end quotation
21923
21924Now the reference to RV must read the whole variable.
21925Actually one can imagine some compiler which figures
21926out that the whole copy is not required (because only
21927the B field is actually accessed), but GNAT
21928certainly won't do that, and we don't know of any
21929compiler that would not handle this right, and the
21930above code will in practice work portably across
21931all architectures (that permit the Atomic declaration).
21932
21933The second issue with atomic variables has to do with
21934the possible requirement of generating synchronization
21935code. For more details on this, consult the sections on
21936the pragmas Enable/Disable_Atomic_Synchronization in the
21937GNAT Reference Manual. If performance is critical, and
21938such synchronization code is not required, it may be
21939useful to disable it.
21940
21941@node Passive Task Optimization,,Atomic Variables and Optimization,Performance Considerations
21942@anchor{gnat_ugn/gnat_and_program_execution id42}@anchor{1b5}@anchor{gnat_ugn/gnat_and_program_execution passive-task-optimization}@anchor{1b6}
21943@subsubsection Passive Task Optimization
21944
21945
21946@geindex Passive Task
21947
21948A passive task is one which is sufficiently simple that
21949in theory a compiler could recognize it an implement it
21950efficiently without creating a new thread. The original design
21951of Ada 83 had in mind this kind of passive task optimization, but
21952only a few Ada 83 compilers attempted it. The problem was that
21953it was difficult to determine the exact conditions under which
21954the optimization was possible. The result is a very fragile
21955optimization where a very minor change in the program can
21956suddenly silently make a task non-optimizable.
21957
21958With the revisiting of this issue in Ada 95, there was general
21959agreement that this approach was fundamentally flawed, and the
21960notion of protected types was introduced. When using protected
21961types, the restrictions are well defined, and you KNOW that the
21962operations will be optimized, and furthermore this optimized
21963performance is fully portable.
21964
21965Although it would theoretically be possible for GNAT to attempt to
21966do this optimization, but it really doesn't make sense in the
21967context of Ada 95, and none of the Ada 95 compilers implement
21968this optimization as far as we know. In particular GNAT never
21969attempts to perform this optimization.
21970
21971In any new Ada 95 code that is written, you should always
21972use protected types in place of tasks that might be able to
21973be optimized in this manner.
21974Of course this does not help if you have legacy Ada 83 code
21975that depends on this optimization, but it is unusual to encounter
21976a case where the performance gains from this optimization
21977are significant.
21978
21979Your program should work correctly without this optimization. If
21980you have performance problems, then the most practical
21981approach is to figure out exactly where these performance problems
21982arise, and update those particular tasks to be protected types. Note
21983that typically clients of the tasks who call entries, will not have
21984to be modified, only the task definition itself.
21985
21986@node Text_IO Suggestions,Reducing Size of Executables with Unused Subprogram/Data Elimination,Performance Considerations,Improving Performance
21987@anchor{gnat_ugn/gnat_and_program_execution text-io-suggestions}@anchor{1b7}@anchor{gnat_ugn/gnat_and_program_execution id43}@anchor{1b8}
21988@subsection @code{Text_IO} Suggestions
21989
21990
21991@geindex Text_IO and performance
21992
21993The @code{Ada.Text_IO} package has fairly high overheads due in part to
21994the requirement of maintaining page and line counts. If performance
21995is critical, a recommendation is to use @code{Stream_IO} instead of
21996@code{Text_IO} for volume output, since this package has less overhead.
21997
21998If @code{Text_IO} must be used, note that by default output to the standard
21999output and standard error files is unbuffered (this provides better
22000behavior when output statements are used for debugging, or if the
22001progress of a program is observed by tracking the output, e.g. by
22002using the Unix @emph{tail -f} command to watch redirected output.
22003
22004If you are generating large volumes of output with @code{Text_IO} and
22005performance is an important factor, use a designated file instead
22006of the standard output file, or change the standard output file to
22007be buffered using @code{Interfaces.C_Streams.setvbuf}.
22008
22009@node Reducing Size of Executables with Unused Subprogram/Data Elimination,,Text_IO Suggestions,Improving Performance
22010@anchor{gnat_ugn/gnat_and_program_execution id44}@anchor{1b9}@anchor{gnat_ugn/gnat_and_program_execution reducing-size-of-executables-with-unused-subprogram-data-elimination}@anchor{1ba}
22011@subsection Reducing Size of Executables with Unused Subprogram/Data Elimination
22012
22013
22014@geindex Uunused subprogram/data elimination
22015
22016This section describes how you can eliminate unused subprograms and data from
22017your executable just by setting options at compilation time.
22018
22019@menu
22020* About unused subprogram/data elimination::
22021* Compilation options::
22022* Example of unused subprogram/data elimination::
22023
22024@end menu
22025
22026@node About unused subprogram/data elimination,Compilation options,,Reducing Size of Executables with Unused Subprogram/Data Elimination
22027@anchor{gnat_ugn/gnat_and_program_execution id45}@anchor{1bb}@anchor{gnat_ugn/gnat_and_program_execution about-unused-subprogram-data-elimination}@anchor{1bc}
22028@subsubsection About unused subprogram/data elimination
22029
22030
22031By default, an executable contains all code and data of its composing objects
22032(directly linked or coming from statically linked libraries), even data or code
22033never used by this executable.
22034
22035This feature will allow you to eliminate such unused code from your
22036executable, making it smaller (in disk and in memory).
22037
22038This functionality is available on all Linux platforms except for the IA-64
22039architecture and on all cross platforms using the ELF binary file format.
22040In both cases GNU binutils version 2.16 or later are required to enable it.
22041
22042@node Compilation options,Example of unused subprogram/data elimination,About unused subprogram/data elimination,Reducing Size of Executables with Unused Subprogram/Data Elimination
22043@anchor{gnat_ugn/gnat_and_program_execution id46}@anchor{1bd}@anchor{gnat_ugn/gnat_and_program_execution compilation-options}@anchor{1be}
22044@subsubsection Compilation options
22045
22046
22047The operation of eliminating the unused code and data from the final executable
22048is directly performed by the linker.
22049
22050@geindex -ffunction-sections (gcc)
22051
22052@geindex -fdata-sections (gcc)
22053
22054In order to do this, it has to work with objects compiled with the
22055following options:
22056@code{-ffunction-sections} @code{-fdata-sections}.
22057
22058These options are usable with C and Ada files.
22059They will place respectively each
22060function or data in a separate section in the resulting object file.
22061
22062Once the objects and static libraries are created with these options, the
22063linker can perform the dead code elimination. You can do this by setting
22064the @code{-Wl,--gc-sections} option to gcc command or in the
22065@code{-largs} section of @code{gnatmake}. This will perform a
22066garbage collection of code and data never referenced.
22067
22068If the linker performs a partial link (@code{-r} linker option), then you
22069will need to provide the entry point using the @code{-e} / @code{--entry}
22070linker option.
22071
22072Note that objects compiled without the @code{-ffunction-sections} and
22073@code{-fdata-sections} options can still be linked with the executable.
22074However, no dead code elimination will be performed on those objects (they will
22075be linked as is).
22076
22077The GNAT static library is now compiled with -ffunction-sections and
22078-fdata-sections on some platforms. This allows you to eliminate the unused code
22079and data of the GNAT library from your executable.
22080
22081@node Example of unused subprogram/data elimination,,Compilation options,Reducing Size of Executables with Unused Subprogram/Data Elimination
22082@anchor{gnat_ugn/gnat_and_program_execution id47}@anchor{1bf}@anchor{gnat_ugn/gnat_and_program_execution example-of-unused-subprogram-data-elimination}@anchor{1c0}
22083@subsubsection Example of unused subprogram/data elimination
22084
22085
22086Here is a simple example:
22087
22088@quotation
22089
22090@example
22091with Aux;
22092
22093procedure Test is
22094begin
22095   Aux.Used (10);
22096end Test;
22097
22098package Aux is
22099   Used_Data   : Integer;
22100   Unused_Data : Integer;
22101
22102   procedure Used   (Data : Integer);
22103   procedure Unused (Data : Integer);
22104end Aux;
22105
22106package body Aux is
22107   procedure Used (Data : Integer) is
22108   begin
22109      Used_Data := Data;
22110   end Used;
22111
22112   procedure Unused (Data : Integer) is
22113   begin
22114      Unused_Data := Data;
22115   end Unused;
22116end Aux;
22117@end example
22118@end quotation
22119
22120@code{Unused} and @code{Unused_Data} are never referenced in this code
22121excerpt, and hence they may be safely removed from the final executable.
22122
22123@quotation
22124
22125@example
22126$ gnatmake test
22127
22128$ nm test | grep used
22129020015f0 T aux__unused
2213002005d88 B aux__unused_data
22131020015cc T aux__used
2213202005d84 B aux__used_data
22133
22134$ gnatmake test -cargs -fdata-sections -ffunction-sections \\
22135     -largs -Wl,--gc-sections
22136
22137$ nm test | grep used
2213802005350 T aux__used
221390201ffe0 B aux__used_data
22140@end example
22141@end quotation
22142
22143It can be observed that the procedure @code{Unused} and the object
22144@code{Unused_Data} are removed by the linker when using the
22145appropriate options.
22146
22147@geindex Overflow checks
22148
22149@geindex Checks (overflow)
22150
22151
22152@node Overflow Check Handling in GNAT,Performing Dimensionality Analysis in GNAT,Improving Performance,GNAT and Program Execution
22153@anchor{gnat_ugn/gnat_and_program_execution id55}@anchor{16a}@anchor{gnat_ugn/gnat_and_program_execution overflow-check-handling-in-gnat}@anchor{27}
22154@section Overflow Check Handling in GNAT
22155
22156
22157This section explains how to control the handling of overflow checks.
22158
22159@menu
22160* Background::
22161* Management of Overflows in GNAT::
22162* Specifying the Desired Mode::
22163* Default Settings::
22164* Implementation Notes::
22165
22166@end menu
22167
22168@node Background,Management of Overflows in GNAT,,Overflow Check Handling in GNAT
22169@anchor{gnat_ugn/gnat_and_program_execution id56}@anchor{1c1}@anchor{gnat_ugn/gnat_and_program_execution background}@anchor{1c2}
22170@subsection Background
22171
22172
22173Overflow checks are checks that the compiler may make to ensure
22174that intermediate results are not out of range. For example:
22175
22176@quotation
22177
22178@example
22179A : Integer;
22180...
22181A := A + 1;
22182@end example
22183@end quotation
22184
22185If @code{A} has the value @code{Integer'Last}, then the addition may cause
22186overflow since the result is out of range of the type @code{Integer}.
22187In this case @code{Constraint_Error} will be raised if checks are
22188enabled.
22189
22190A trickier situation arises in examples like the following:
22191
22192@quotation
22193
22194@example
22195A, C : Integer;
22196...
22197A := (A + 1) + C;
22198@end example
22199@end quotation
22200
22201where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
22202Now the final result of the expression on the right hand side is
22203@code{Integer'Last} which is in range, but the question arises whether the
22204intermediate addition of @code{(A + 1)} raises an overflow error.
22205
22206The (perhaps surprising) answer is that the Ada language
22207definition does not answer this question. Instead it leaves
22208it up to the implementation to do one of two things if overflow
22209checks are enabled.
22210
22211
22212@itemize *
22213
22214@item
22215raise an exception (@code{Constraint_Error}), or
22216
22217@item
22218yield the correct mathematical result which is then used in
22219subsequent operations.
22220@end itemize
22221
22222If the compiler chooses the first approach, then the assignment of this
22223example will indeed raise @code{Constraint_Error} if overflow checking is
22224enabled, or result in erroneous execution if overflow checks are suppressed.
22225
22226But if the compiler
22227chooses the second approach, then it can perform both additions yielding
22228the correct mathematical result, which is in range, so no exception
22229will be raised, and the right result is obtained, regardless of whether
22230overflow checks are suppressed.
22231
22232Note that in the first example an
22233exception will be raised in either case, since if the compiler
22234gives the correct mathematical result for the addition, it will
22235be out of range of the target type of the assignment, and thus
22236fails the range check.
22237
22238This lack of specified behavior in the handling of overflow for
22239intermediate results is a source of non-portability, and can thus
22240be problematic when programs are ported. Most typically this arises
22241in a situation where the original compiler did not raise an exception,
22242and then the application is moved to a compiler where the check is
22243performed on the intermediate result and an unexpected exception is
22244raised.
22245
22246Furthermore, when using Ada 2012's preconditions and other
22247assertion forms, another issue arises. Consider:
22248
22249@quotation
22250
22251@example
22252procedure P (A, B : Integer) with
22253  Pre => A + B <= Integer'Last;
22254@end example
22255@end quotation
22256
22257One often wants to regard arithmetic in a context like this from
22258a mathematical point of view. So for example, if the two actual parameters
22259for a call to @code{P} are both @code{Integer'Last}, then
22260the precondition should be regarded as False. If we are executing
22261in a mode with run-time checks enabled for preconditions, then we would
22262like this precondition to fail, rather than raising an exception
22263because of the intermediate overflow.
22264
22265However, the language definition leaves the specification of
22266whether the above condition fails (raising @code{Assert_Error}) or
22267causes an intermediate overflow (raising @code{Constraint_Error})
22268up to the implementation.
22269
22270The situation is worse in a case such as the following:
22271
22272@quotation
22273
22274@example
22275procedure Q (A, B, C : Integer) with
22276  Pre => A + B + C <= Integer'Last;
22277@end example
22278@end quotation
22279
22280Consider the call
22281
22282@quotation
22283
22284@example
22285Q (A => Integer'Last, B => 1, C => -1);
22286@end example
22287@end quotation
22288
22289From a mathematical point of view the precondition
22290is True, but at run time we may (but are not guaranteed to) get an
22291exception raised because of the intermediate overflow (and we really
22292would prefer this precondition to be considered True at run time).
22293
22294@node Management of Overflows in GNAT,Specifying the Desired Mode,Background,Overflow Check Handling in GNAT
22295@anchor{gnat_ugn/gnat_and_program_execution id57}@anchor{1c3}@anchor{gnat_ugn/gnat_and_program_execution management-of-overflows-in-gnat}@anchor{1c4}
22296@subsection Management of Overflows in GNAT
22297
22298
22299To deal with the portability issue, and with the problem of
22300mathematical versus run-time interpretation of the expressions in
22301assertions, GNAT provides comprehensive control over the handling
22302of intermediate overflow. GNAT can operate in three modes, and
22303furthemore, permits separate selection of operating modes for
22304the expressions within assertions (here the term 'assertions'
22305is used in the technical sense, which includes preconditions and so forth)
22306and for expressions appearing outside assertions.
22307
22308The three modes are:
22309
22310
22311@itemize *
22312
22313@item
22314@emph{Use base type for intermediate operations} (@code{STRICT})
22315
22316In this mode, all intermediate results for predefined arithmetic
22317operators are computed using the base type, and the result must
22318be in range of the base type. If this is not the
22319case then either an exception is raised (if overflow checks are
22320enabled) or the execution is erroneous (if overflow checks are suppressed).
22321This is the normal default mode.
22322
22323@item
22324@emph{Most intermediate overflows avoided} (@code{MINIMIZED})
22325
22326In this mode, the compiler attempts to avoid intermediate overflows by
22327using a larger integer type, typically @code{Long_Long_Integer},
22328as the type in which arithmetic is
22329performed for predefined arithmetic operators. This may be slightly more
22330expensive at
22331run time (compared to suppressing intermediate overflow checks), though
22332the cost is negligible on modern 64-bit machines. For the examples given
22333earlier, no intermediate overflows would have resulted in exceptions,
22334since the intermediate results are all in the range of
22335@code{Long_Long_Integer} (typically 64-bits on nearly all implementations
22336of GNAT). In addition, if checks are enabled, this reduces the number of
22337checks that must be made, so this choice may actually result in an
22338improvement in space and time behavior.
22339
22340However, there are cases where @code{Long_Long_Integer} is not large
22341enough, consider the following example:
22342
22343@quotation
22344
22345@example
22346procedure R (A, B, C, D : Integer) with
22347  Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
22348@end example
22349@end quotation
22350
22351where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
22352Now the intermediate results are
22353out of the range of @code{Long_Long_Integer} even though the final result
22354is in range and the precondition is True (from a mathematical point
22355of view). In such a case, operating in this mode, an overflow occurs
22356for the intermediate computation (which is why this mode
22357says @emph{most} intermediate overflows are avoided). In this case,
22358an exception is raised if overflow checks are enabled, and the
22359execution is erroneous if overflow checks are suppressed.
22360
22361@item
22362@emph{All intermediate overflows avoided} (@code{ELIMINATED})
22363
22364In this mode, the compiler  avoids all intermediate overflows
22365by using arbitrary precision arithmetic as required. In this
22366mode, the above example with @code{A**2 * B**2} would
22367not cause intermediate overflow, because the intermediate result
22368would be evaluated using sufficient precision, and the result
22369of evaluating the precondition would be True.
22370
22371This mode has the advantage of avoiding any intermediate
22372overflows, but at the expense of significant run-time overhead,
22373including the use of a library (included automatically in this
22374mode) for multiple-precision arithmetic.
22375
22376This mode provides cleaner semantics for assertions, since now
22377the run-time behavior emulates true arithmetic behavior for the
22378predefined arithmetic operators, meaning that there is never a
22379conflict between the mathematical view of the assertion, and its
22380run-time behavior.
22381
22382Note that in this mode, the behavior is unaffected by whether or
22383not overflow checks are suppressed, since overflow does not occur.
22384It is possible for gigantic intermediate expressions to raise
22385@code{Storage_Error} as a result of attempting to compute the
22386results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
22387but overflow is impossible.
22388@end itemize
22389
22390Note that these modes apply only to the evaluation of predefined
22391arithmetic, membership, and comparison operators for signed integer
22392arithmetic.
22393
22394For fixed-point arithmetic, checks can be suppressed. But if checks
22395are enabled
22396then fixed-point values are always checked for overflow against the
22397base type for intermediate expressions (that is such checks always
22398operate in the equivalent of @code{STRICT} mode).
22399
22400For floating-point, on nearly all architectures, @code{Machine_Overflows}
22401is False, and IEEE infinities are generated, so overflow exceptions
22402are never raised. If you want to avoid infinities, and check that
22403final results of expressions are in range, then you can declare a
22404constrained floating-point type, and range checks will be carried
22405out in the normal manner (with infinite values always failing all
22406range checks).
22407
22408@node Specifying the Desired Mode,Default Settings,Management of Overflows in GNAT,Overflow Check Handling in GNAT
22409@anchor{gnat_ugn/gnat_and_program_execution specifying-the-desired-mode}@anchor{f8}@anchor{gnat_ugn/gnat_and_program_execution id58}@anchor{1c5}
22410@subsection Specifying the Desired Mode
22411
22412
22413@geindex pragma Overflow_Mode
22414
22415The desired mode of for handling intermediate overflow can be specified using
22416either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
22417The pragma has the form
22418
22419@quotation
22420
22421@example
22422pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
22423@end example
22424@end quotation
22425
22426where @code{MODE} is one of
22427
22428
22429@itemize *
22430
22431@item
22432@code{STRICT}:  intermediate overflows checked (using base type)
22433
22434@item
22435@code{MINIMIZED}: minimize intermediate overflows
22436
22437@item
22438@code{ELIMINATED}: eliminate intermediate overflows
22439@end itemize
22440
22441The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
22442@code{minimized} all have the same effect.
22443
22444If only the @code{General} parameter is present, then the given @code{MODE} applies
22445to expressions both within and outside assertions. If both arguments
22446are present, then @code{General} applies to expressions outside assertions,
22447and @code{Assertions} applies to expressions within assertions. For example:
22448
22449@quotation
22450
22451@example
22452pragma Overflow_Mode
22453  (General => Minimized, Assertions => Eliminated);
22454@end example
22455@end quotation
22456
22457specifies that general expressions outside assertions be evaluated
22458in 'minimize intermediate overflows' mode, and expressions within
22459assertions be evaluated in 'eliminate intermediate overflows' mode.
22460This is often a reasonable choice, avoiding excessive overhead
22461outside assertions, but assuring a high degree of portability
22462when importing code from another compiler, while incurring
22463the extra overhead for assertion expressions to ensure that
22464the behavior at run time matches the expected mathematical
22465behavior.
22466
22467The @code{Overflow_Mode} pragma has the same scoping and placement
22468rules as pragma @code{Suppress}, so it can occur either as a
22469configuration pragma, specifying a default for the whole
22470program, or in a declarative scope, where it applies to the
22471remaining declarations and statements in that scope.
22472
22473Note that pragma @code{Overflow_Mode} does not affect whether
22474overflow checks are enabled or suppressed. It only controls the
22475method used to compute intermediate values. To control whether
22476overflow checking is enabled or suppressed, use pragma @code{Suppress}
22477or @code{Unsuppress} in the usual manner.
22478
22479@geindex -gnato? (gcc)
22480
22481@geindex -gnato?? (gcc)
22482
22483Additionally, a compiler switch @code{-gnato?} or @code{-gnato??}
22484can be used to control the checking mode default (which can be subsequently
22485overridden using pragmas).
22486
22487Here @code{?} is one of the digits @code{1} through @code{3}:
22488
22489@quotation
22490
22491
22492@multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
22493@item
22494
22495@code{1}
22496
22497@tab
22498
22499use base type for intermediate operations (@code{STRICT})
22500
22501@item
22502
22503@code{2}
22504
22505@tab
22506
22507minimize intermediate overflows (@code{MINIMIZED})
22508
22509@item
22510
22511@code{3}
22512
22513@tab
22514
22515eliminate intermediate overflows (@code{ELIMINATED})
22516
22517@end multitable
22518
22519@end quotation
22520
22521As with the pragma, if only one digit appears then it applies to all
22522cases; if two digits are given, then the first applies outside
22523assertions, and the second within assertions. Thus the equivalent
22524of the example pragma above would be
22525@code{-gnato23}.
22526
22527If no digits follow the @code{-gnato}, then it is equivalent to
22528@code{-gnato11},
22529causing all intermediate operations to be computed using the base
22530type (@code{STRICT} mode).
22531
22532@node Default Settings,Implementation Notes,Specifying the Desired Mode,Overflow Check Handling in GNAT
22533@anchor{gnat_ugn/gnat_and_program_execution id59}@anchor{1c6}@anchor{gnat_ugn/gnat_and_program_execution default-settings}@anchor{1c7}
22534@subsection Default Settings
22535
22536
22537The default mode for overflow checks is
22538
22539@quotation
22540
22541@example
22542General => Strict
22543@end example
22544@end quotation
22545
22546which causes all computations both inside and outside assertions to use
22547the base type.
22548
22549This retains compatibility with previous versions of
22550GNAT which suppressed overflow checks by default and always
22551used the base type for computation of intermediate results.
22552
22553@c Sphinx allows no emphasis within :index: role. As a workaround we
22554@c point the index to "switch" and use emphasis for "-gnato".
22555
22556The
22557@geindex -gnato (gcc)
22558switch @code{-gnato} (with no digits following)
22559is equivalent to
22560
22561@quotation
22562
22563@example
22564General => Strict
22565@end example
22566@end quotation
22567
22568which causes overflow checking of all intermediate overflows
22569both inside and outside assertions against the base type.
22570
22571The pragma @code{Suppress (Overflow_Check)} disables overflow
22572checking, but it has no effect on the method used for computing
22573intermediate results.
22574
22575The pragma @code{Unsuppress (Overflow_Check)} enables overflow
22576checking, but it has no effect on the method used for computing
22577intermediate results.
22578
22579@node Implementation Notes,,Default Settings,Overflow Check Handling in GNAT
22580@anchor{gnat_ugn/gnat_and_program_execution implementation-notes}@anchor{1c8}@anchor{gnat_ugn/gnat_and_program_execution id60}@anchor{1c9}
22581@subsection Implementation Notes
22582
22583
22584In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
22585reasonably efficient, and can be generally used. It also helps
22586to ensure compatibility with code imported from some other
22587compiler to GNAT.
22588
22589Setting all intermediate overflows checking (@code{CHECKED} mode)
22590makes sense if you want to
22591make sure that your code is compatible with any other possible
22592Ada implementation. This may be useful in ensuring portability
22593for code that is to be exported to some other compiler than GNAT.
22594
22595The Ada standard allows the reassociation of expressions at
22596the same precedence level if no parentheses are present. For
22597example, @code{A+B+C} parses as though it were @code{(A+B)+C}, but
22598the compiler can reintepret this as @code{A+(B+C)}, possibly
22599introducing or eliminating an overflow exception. The GNAT
22600compiler never takes advantage of this freedom, and the
22601expression @code{A+B+C} will be evaluated as @code{(A+B)+C}.
22602If you need the other order, you can write the parentheses
22603explicitly @code{A+(B+C)} and GNAT will respect this order.
22604
22605The use of @code{ELIMINATED} mode will cause the compiler to
22606automatically include an appropriate arbitrary precision
22607integer arithmetic package. The compiler will make calls
22608to this package, though only in cases where it cannot be
22609sure that @code{Long_Long_Integer} is sufficient to guard against
22610intermediate overflows. This package does not use dynamic
22611alllocation, but it does use the secondary stack, so an
22612appropriate secondary stack package must be present (this
22613is always true for standard full Ada, but may require
22614specific steps for restricted run times such as ZFP).
22615
22616Although @code{ELIMINATED} mode causes expressions to use arbitrary
22617precision arithmetic, avoiding overflow, the final result
22618must be in an appropriate range. This is true even if the
22619final result is of type @code{[Long_[Long_]]Integer'Base}, which
22620still has the same bounds as its associated constrained
22621type at run-time.
22622
22623Currently, the @code{ELIMINATED} mode is only available on target
22624platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
22625platforms).
22626
22627@node Performing Dimensionality Analysis in GNAT,Stack Related Facilities,Overflow Check Handling in GNAT,GNAT and Program Execution
22628@anchor{gnat_ugn/gnat_and_program_execution id61}@anchor{16b}@anchor{gnat_ugn/gnat_and_program_execution performing-dimensionality-analysis-in-gnat}@anchor{28}
22629@section Performing Dimensionality Analysis in GNAT
22630
22631
22632@geindex Dimensionality analysis
22633
22634The GNAT compiler supports dimensionality checking. The user can
22635specify physical units for objects, and the compiler will verify that uses
22636of these objects are compatible with their dimensions, in a fashion that is
22637familiar to engineering practice. The dimensions of algebraic expressions
22638(including powers with static exponents) are computed from their constituents.
22639
22640@geindex Dimension_System aspect
22641
22642@geindex Dimension aspect
22643
22644This feature depends on Ada 2012 aspect specifications, and is available from
22645version 7.0.1 of GNAT onwards.
22646The GNAT-specific aspect @code{Dimension_System}
22647allows you to define a system of units; the aspect @code{Dimension}
22648then allows the user to declare dimensioned quantities within a given system.
22649(These aspects are described in the @emph{Implementation Defined Aspects}
22650chapter of the @emph{GNAT Reference Manual}).
22651
22652The major advantage of this model is that it does not require the declaration of
22653multiple operators for all possible combinations of types: it is only necessary
22654to use the proper subtypes in object declarations.
22655
22656@geindex System.Dim.Mks package (GNAT library)
22657
22658@geindex MKS_Type type
22659
22660The simplest way to impose dimensionality checking on a computation is to make
22661use of the package @code{System.Dim.Mks},
22662which is part of the GNAT library. This
22663package defines a floating-point type @code{MKS_Type},
22664for which a sequence of
22665dimension names are specified, together with their conventional abbreviations.
22666The following should be read together with the full specification of the
22667package, in file @code{s-dimmks.ads}.
22668
22669@quotation
22670
22671@geindex s-dimmks.ads file
22672
22673@example
22674type Mks_Type is new Long_Long_Float
22675  with
22676   Dimension_System => (
22677     (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
22678     (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
22679     (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
22680     (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
22681     (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
22682     (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
22683     (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
22684@end example
22685@end quotation
22686
22687The package then defines a series of subtypes that correspond to these
22688conventional units. For example:
22689
22690@quotation
22691
22692@example
22693subtype Length is Mks_Type
22694  with
22695   Dimension => (Symbol => 'm', Meter  => 1, others => 0);
22696@end example
22697@end quotation
22698
22699and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
22700@code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
22701@code{Luminous_Intensity} (the standard set of units of the SI system).
22702
22703The package also defines conventional names for values of each unit, for
22704example:
22705
22706@quotation
22707
22708@example
22709m   : constant Length           := 1.0;
22710kg  : constant Mass             := 1.0;
22711s   : constant Time             := 1.0;
22712A   : constant Electric_Current := 1.0;
22713@end example
22714@end quotation
22715
22716as well as useful multiples of these units:
22717
22718@quotation
22719
22720@example
22721 cm  : constant Length := 1.0E-02;
22722 g   : constant Mass   := 1.0E-03;
22723 min : constant Time   := 60.0;
22724 day : constant Time   := 60.0 * 24.0 * min;
22725...
22726@end example
22727@end quotation
22728
22729Using this package, you can then define a derived unit by
22730providing the aspect that
22731specifies its dimensions within the MKS system, as well as the string to
22732be used for output of a value of that unit:
22733
22734@quotation
22735
22736@example
22737subtype Acceleration is Mks_Type
22738  with Dimension => ("m/sec^2",
22739                     Meter => 1,
22740                     Second => -2,
22741                     others => 0);
22742@end example
22743@end quotation
22744
22745Here is a complete example of use:
22746
22747@quotation
22748
22749@example
22750with System.Dim.MKS; use System.Dim.Mks;
22751with System.Dim.Mks_IO; use System.Dim.Mks_IO;
22752with Text_IO; use Text_IO;
22753procedure Free_Fall is
22754  subtype Acceleration is Mks_Type
22755    with Dimension => ("m/sec^2", 1, 0, -2, others => 0);
22756  G : constant acceleration := 9.81 * m / (s ** 2);
22757  T : Time := 10.0*s;
22758  Distance : Length;
22759
22760begin
22761  Put ("Gravitational constant: ");
22762  Put (G, Aft => 2, Exp => 0); Put_Line ("");
22763  Distance := 0.5 * G * T ** 2;
22764  Put ("distance travelled in 10 seconds of free fall ");
22765  Put (Distance, Aft => 2, Exp => 0);
22766  Put_Line ("");
22767end Free_Fall;
22768@end example
22769@end quotation
22770
22771Execution of this program yields:
22772
22773@quotation
22774
22775@example
22776Gravitational constant:  9.81 m/sec^2
22777distance travelled in 10 seconds of free fall 490.50 m
22778@end example
22779@end quotation
22780
22781However, incorrect assignments such as:
22782
22783@quotation
22784
22785@example
22786Distance := 5.0;
22787Distance := 5.0 * kg;
22788@end example
22789@end quotation
22790
22791are rejected with the following diagnoses:
22792
22793@quotation
22794
22795@example
22796Distance := 5.0;
22797   >>> dimensions mismatch in assignment
22798   >>> left-hand side has dimension [L]
22799   >>> right-hand side is dimensionless
22800
22801Distance := 5.0 * kg:
22802   >>> dimensions mismatch in assignment
22803   >>> left-hand side has dimension [L]
22804   >>> right-hand side has dimension [M]
22805@end example
22806@end quotation
22807
22808The dimensions of an expression are properly displayed, even if there is
22809no explicit subtype for it. If we add to the program:
22810
22811@quotation
22812
22813@example
22814Put ("Final velocity: ");
22815Put (G * T, Aft =>2, Exp =>0);
22816Put_Line ("");
22817@end example
22818@end quotation
22819
22820then the output includes:
22821
22822@quotation
22823
22824@example
22825Final velocity: 98.10 m.s**(-1)
22826@end example
22827
22828@geindex Dimensionable type
22829
22830@geindex Dimensioned subtype
22831@end quotation
22832
22833The type @code{Mks_Type} is said to be a @emph{dimensionable type} since it has a
22834@code{Dimension_System} aspect, and the subtypes @code{Length}, @code{Mass}, etc.,
22835are said to be @emph{dimensioned subtypes} since each one has a @code{Dimension}
22836aspect.
22837
22838@quotation
22839
22840@geindex Dimension Vector (for a dimensioned subtype)
22841
22842@geindex Dimension aspect
22843
22844@geindex Dimension_System aspect
22845@end quotation
22846
22847The @code{Dimension} aspect of a dimensioned subtype @code{S} defines a mapping
22848from the base type's Unit_Names to integer (or, more generally, rational)
22849values. This mapping is the @emph{dimension vector} (also referred to as the
22850@emph{dimensionality}) for that subtype, denoted by @code{DV(S)}, and thus for each
22851object of that subtype. Intuitively, the value specified for each
22852@code{Unit_Name} is the exponent associated with that unit; a zero value
22853means that the unit is not used. For example:
22854
22855@quotation
22856
22857@example
22858declare
22859   Acc : Acceleration;
22860   ...
22861begin
22862   ...
22863end;
22864@end example
22865@end quotation
22866
22867Here @code{DV(Acc)} = @code{DV(Acceleration)} =
22868@code{(Meter=>1, Kilogram=>0, Second=>-2, Ampere=>0, Kelvin=>0, Mole=>0, Candela=>0)}.
22869Symbolically, we can express this as @code{Meter / Second**2}.
22870
22871The dimension vector of an arithmetic expression is synthesized from the
22872dimension vectors of its components, with compile-time dimensionality checks
22873that help prevent mismatches such as using an @code{Acceleration} where a
22874@code{Length} is required.
22875
22876The dimension vector of the result of an arithmetic expression @emph{expr}, or
22877@code{DV(@emph{expr})}, is defined as follows, assuming conventional
22878mathematical definitions for the vector operations that are used:
22879
22880
22881@itemize *
22882
22883@item
22884If @emph{expr} is of the type @emph{universal_real}, or is not of a dimensioned subtype,
22885then @emph{expr} is dimensionless; @code{DV(@emph{expr})} is the empty vector.
22886
22887@item
22888@code{DV(@emph{op expr})}, where @emph{op} is a unary operator, is @code{DV(@emph{expr})}
22889
22890@item
22891@code{DV(@emph{expr1 op expr2})} where @emph{op} is "+" or "-" is @code{DV(@emph{expr1})}
22892provided that @code{DV(@emph{expr1})} = @code{DV(@emph{expr2})}.
22893If this condition is not met then the construct is illegal.
22894
22895@item
22896@code{DV(@emph{expr1} * @emph{expr2})} is @code{DV(@emph{expr1})} + @code{DV(@emph{expr2})},
22897and @code{DV(@emph{expr1} / @emph{expr2})} = @code{DV(@emph{expr1})} - @code{DV(@emph{expr2})}.
22898In this context if one of the @emph{expr}s is dimensionless then its empty
22899dimension vector is treated as @code{(others => 0)}.
22900
22901@item
22902@code{DV(@emph{expr} ** @emph{power})} is @emph{power} * @code{DV(@emph{expr})},
22903provided that @emph{power} is a static rational value. If this condition is not
22904met then the construct is illegal.
22905@end itemize
22906
22907Note that, by the above rules, it is illegal to use binary "+" or "-" to
22908combine a dimensioned and dimensionless value.  Thus an expression such as
22909@code{acc-10.0} is illegal, where @code{acc} is an object of subtype
22910@code{Acceleration}.
22911
22912The dimensionality checks for relationals use the same rules as
22913for "+" and "-", except when comparing to a literal; thus
22914
22915@quotation
22916
22917@example
22918acc > len
22919@end example
22920@end quotation
22921
22922is equivalent to
22923
22924@quotation
22925
22926@example
22927acc-len > 0.0
22928@end example
22929@end quotation
22930
22931and is thus illegal, but
22932
22933@quotation
22934
22935@example
22936acc > 10.0
22937@end example
22938@end quotation
22939
22940is accepted with a warning. Analogously a conditional expression requires the
22941same dimension vector for each branch (with no exception for literals).
22942
22943The dimension vector of a type conversion @code{T(@emph{expr})} is defined
22944as follows, based on the nature of @code{T}:
22945
22946
22947@itemize *
22948
22949@item
22950If @code{T} is a dimensioned subtype then @code{DV(T(@emph{expr}))} is @code{DV(T)}
22951provided that either @emph{expr} is dimensionless or
22952@code{DV(T)} = @code{DV(@emph{expr})}. The conversion is illegal
22953if @emph{expr} is dimensioned and @code{DV(@emph{expr})} /= @code{DV(T)}.
22954Note that vector equality does not require that the corresponding
22955Unit_Names be the same.
22956
22957As a consequence of the above rule, it is possible to convert between
22958different dimension systems that follow the same international system
22959of units, with the seven physical components given in the standard order
22960(length, mass, time, etc.). Thus a length in meters can be converted to
22961a length in inches (with a suitable conversion factor) but cannot be
22962converted, for example, to a mass in pounds.
22963
22964@item
22965If @code{T} is the base type for @emph{expr} (and the dimensionless root type of
22966the dimension system), then @code{DV(T(@emph{expr}))} is @code{DV(expr)}.
22967Thus, if @emph{expr} is of a dimensioned subtype of @code{T}, the conversion may
22968be regarded as a "view conversion" that preserves dimensionality.
22969
22970This rule makes it possible to write generic code that can be instantiated
22971with compatible dimensioned subtypes.  The generic unit will contain
22972conversions that will consequently be present in instantiations, but
22973conversions to the base type will preserve dimensionality and make it
22974possible to write generic code that is correct with respect to
22975dimensionality.
22976
22977@item
22978Otherwise (i.e., @code{T} is neither a dimensioned subtype nor a dimensionable
22979base type), @code{DV(T(@emph{expr}))} is the empty vector. Thus a dimensioned
22980value can be explicitly converted to a non-dimensioned subtype, which
22981of course then escapes dimensionality analysis.
22982@end itemize
22983
22984The dimension vector for a type qualification @code{T'(@emph{expr})} is the same
22985as for the type conversion @code{T(@emph{expr})}.
22986
22987An assignment statement
22988
22989@quotation
22990
22991@example
22992Source := Target;
22993@end example
22994@end quotation
22995
22996requires @code{DV(Source)} = @code{DV(Target)}, and analogously for parameter
22997passing (the dimension vector for the actual parameter must be equal to the
22998dimension vector for the formal parameter).
22999
23000@node Stack Related Facilities,Memory Management Issues,Performing Dimensionality Analysis in GNAT,GNAT and Program Execution
23001@anchor{gnat_ugn/gnat_and_program_execution stack-related-facilities}@anchor{29}@anchor{gnat_ugn/gnat_and_program_execution id62}@anchor{16c}
23002@section Stack Related Facilities
23003
23004
23005This section describes some useful tools associated with stack
23006checking and analysis. In
23007particular, it deals with dynamic and static stack usage measurements.
23008
23009@menu
23010* Stack Overflow Checking::
23011* Static Stack Usage Analysis::
23012* Dynamic Stack Usage Analysis::
23013
23014@end menu
23015
23016@node Stack Overflow Checking,Static Stack Usage Analysis,,Stack Related Facilities
23017@anchor{gnat_ugn/gnat_and_program_execution id63}@anchor{1ca}@anchor{gnat_ugn/gnat_and_program_execution stack-overflow-checking}@anchor{f4}
23018@subsection Stack Overflow Checking
23019
23020
23021@geindex Stack Overflow Checking
23022
23023@geindex -fstack-check (gcc)
23024
23025For most operating systems, @code{gcc} does not perform stack overflow
23026checking by default. This means that if the main environment task or
23027some other task exceeds the available stack space, then unpredictable
23028behavior will occur. Most native systems offer some level of protection by
23029adding a guard page at the end of each task stack. This mechanism is usually
23030not enough for dealing properly with stack overflow situations because
23031a large local variable could "jump" above the guard page.
23032Furthermore, when the
23033guard page is hit, there may not be any space left on the stack for executing
23034the exception propagation code. Enabling stack checking avoids
23035such situations.
23036
23037To activate stack checking, compile all units with the @code{gcc} option
23038@code{-fstack-check}. For example:
23039
23040@quotation
23041
23042@example
23043$ gcc -c -fstack-check package1.adb
23044@end example
23045@end quotation
23046
23047Units compiled with this option will generate extra instructions to check
23048that any use of the stack (for procedure calls or for declaring local
23049variables in declare blocks) does not exceed the available stack space.
23050If the space is exceeded, then a @code{Storage_Error} exception is raised.
23051
23052For declared tasks, the default stack size is defined by the GNAT runtime,
23053whose size may be modified at bind time through the @code{-d} bind switch
23054(@ref{11f,,Switches for gnatbind}). Task specific stack sizes may be set using the
23055@code{Storage_Size} pragma.
23056
23057For the environment task, the stack size is determined by the operating system.
23058Consequently, to modify the size of the environment task please refer to your
23059operating system documentation.
23060
23061@node Static Stack Usage Analysis,Dynamic Stack Usage Analysis,Stack Overflow Checking,Stack Related Facilities
23062@anchor{gnat_ugn/gnat_and_program_execution id64}@anchor{1cb}@anchor{gnat_ugn/gnat_and_program_execution static-stack-usage-analysis}@anchor{f5}
23063@subsection Static Stack Usage Analysis
23064
23065
23066@geindex Static Stack Usage Analysis
23067
23068@geindex -fstack-usage
23069
23070A unit compiled with @code{-fstack-usage} will generate an extra file
23071that specifies
23072the maximum amount of stack used, on a per-function basis.
23073The file has the same
23074basename as the target object file with a @code{.su} extension.
23075Each line of this file is made up of three fields:
23076
23077
23078@itemize *
23079
23080@item
23081The name of the function.
23082
23083@item
23084A number of bytes.
23085
23086@item
23087One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
23088@end itemize
23089
23090The second field corresponds to the size of the known part of the function
23091frame.
23092
23093The qualifier @code{static} means that the function frame size
23094is purely static.
23095It usually means that all local variables have a static size.
23096In this case, the second field is a reliable measure of the function stack
23097utilization.
23098
23099The qualifier @code{dynamic} means that the function frame size is not static.
23100It happens mainly when some local variables have a dynamic size. When this
23101qualifier appears alone, the second field is not a reliable measure
23102of the function stack analysis. When it is qualified with  @code{bounded}, it
23103means that the second field is a reliable maximum of the function stack
23104utilization.
23105
23106A unit compiled with @code{-Wstack-usage} will issue a warning for each
23107subprogram whose stack usage might be larger than the specified amount of
23108bytes.  The wording is in keeping with the qualifier documented above.
23109
23110@node Dynamic Stack Usage Analysis,,Static Stack Usage Analysis,Stack Related Facilities
23111@anchor{gnat_ugn/gnat_and_program_execution id65}@anchor{1cc}@anchor{gnat_ugn/gnat_and_program_execution dynamic-stack-usage-analysis}@anchor{121}
23112@subsection Dynamic Stack Usage Analysis
23113
23114
23115It is possible to measure the maximum amount of stack used by a task, by
23116adding a switch to @code{gnatbind}, as:
23117
23118@quotation
23119
23120@example
23121$ gnatbind -u0 file
23122@end example
23123@end quotation
23124
23125With this option, at each task termination, its stack usage is  output on
23126@code{stderr}.
23127It is not always convenient to output the stack usage when the program
23128is still running. Hence, it is possible to delay this output until program
23129termination. for a given number of tasks specified as the argument of the
23130@code{-u} option. For instance:
23131
23132@quotation
23133
23134@example
23135$ gnatbind -u100 file
23136@end example
23137@end quotation
23138
23139will buffer the stack usage information of the first 100 tasks to terminate and
23140output this info at program termination. Results are displayed in four
23141columns:
23142
23143@quotation
23144
23145@example
23146Index | Task Name | Stack Size | Stack Usage
23147@end example
23148@end quotation
23149
23150where:
23151
23152
23153@itemize *
23154
23155@item
23156@emph{Index} is a number associated with each task.
23157
23158@item
23159@emph{Task Name} is the name of the task analyzed.
23160
23161@item
23162@emph{Stack Size} is the maximum size for the stack.
23163
23164@item
23165@emph{Stack Usage} is the measure done by the stack analyzer.
23166In order to prevent overflow, the stack
23167is not entirely analyzed, and it's not possible to know exactly how
23168much has actually been used.
23169@end itemize
23170
23171By default the environment task stack, the stack that contains the main unit,
23172is not processed. To enable processing of the environment task stack, the
23173environment variable GNAT_STACK_LIMIT needs to be set to the maximum size of
23174the environment task stack. This amount is given in kilobytes. For example:
23175
23176@quotation
23177
23178@example
23179$ set GNAT_STACK_LIMIT 1600
23180@end example
23181@end quotation
23182
23183would specify to the analyzer that the environment task stack has a limit
23184of 1.6 megabytes. Any stack usage beyond this will be ignored by the analysis.
23185
23186The package @code{GNAT.Task_Stack_Usage} provides facilities to get
23187stack-usage reports at run time. See its body for the details.
23188
23189@node Memory Management Issues,,Stack Related Facilities,GNAT and Program Execution
23190@anchor{gnat_ugn/gnat_and_program_execution id66}@anchor{16d}@anchor{gnat_ugn/gnat_and_program_execution memory-management-issues}@anchor{2a}
23191@section Memory Management Issues
23192
23193
23194This section describes some useful memory pools provided in the GNAT library
23195and in particular the GNAT Debug Pool facility, which can be used to detect
23196incorrect uses of access values (including 'dangling references').
23197
23198
23199@menu
23200* Some Useful Memory Pools::
23201* The GNAT Debug Pool Facility::
23202
23203@end menu
23204
23205@node Some Useful Memory Pools,The GNAT Debug Pool Facility,,Memory Management Issues
23206@anchor{gnat_ugn/gnat_and_program_execution id67}@anchor{1cd}@anchor{gnat_ugn/gnat_and_program_execution some-useful-memory-pools}@anchor{1ce}
23207@subsection Some Useful Memory Pools
23208
23209
23210@geindex Memory Pool
23211
23212@geindex storage
23213@geindex pool
23214
23215The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
23216storage pool. Allocations use the standard system call @code{malloc} while
23217deallocations use the standard system call @code{free}. No reclamation is
23218performed when the pool goes out of scope. For performance reasons, the
23219standard default Ada allocators/deallocators do not use any explicit storage
23220pools but if they did, they could use this storage pool without any change in
23221behavior. That is why this storage pool is used  when the user
23222manages to make the default implicit allocator explicit as in this example:
23223
23224@quotation
23225
23226@example
23227type T1 is access Something;
23228 -- no Storage pool is defined for T2
23229
23230type T2 is access Something_Else;
23231for T2'Storage_Pool use T1'Storage_Pool;
23232-- the above is equivalent to
23233for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
23234@end example
23235@end quotation
23236
23237The @code{System.Pool_Local} package offers the @code{Unbounded_Reclaim_Pool} storage
23238pool. The allocation strategy is similar to @code{Pool_Local}
23239except that the all
23240storage allocated with this pool is reclaimed when the pool object goes out of
23241scope. This pool provides a explicit mechanism similar to the implicit one
23242provided by several Ada 83 compilers for allocations performed through a local
23243access type and whose purpose was to reclaim memory when exiting the
23244scope of a given local access. As an example, the following program does not
23245leak memory even though it does not perform explicit deallocation:
23246
23247@quotation
23248
23249@example
23250with System.Pool_Local;
23251procedure Pooloc1 is
23252   procedure Internal is
23253      type A is access Integer;
23254      X : System.Pool_Local.Unbounded_Reclaim_Pool;
23255      for A'Storage_Pool use X;
23256      v : A;
23257   begin
23258      for I in  1 .. 50 loop
23259         v := new Integer;
23260      end loop;
23261   end Internal;
23262begin
23263   for I in  1 .. 100 loop
23264      Internal;
23265   end loop;
23266end Pooloc1;
23267@end example
23268@end quotation
23269
23270The @code{System.Pool_Size} package implements the @code{Stack_Bounded_Pool} used when
23271@code{Storage_Size} is specified for an access type.
23272The whole storage for the pool is
23273allocated at once, usually on the stack at the point where the access type is
23274elaborated. It is automatically reclaimed when exiting the scope where the
23275access type is defined. This package is not intended to be used directly by the
23276user and it is implicitly used for each such declaration:
23277
23278@quotation
23279
23280@example
23281type T1 is access Something;
23282for T1'Storage_Size use 10_000;
23283@end example
23284@end quotation
23285
23286@node The GNAT Debug Pool Facility,,Some Useful Memory Pools,Memory Management Issues
23287@anchor{gnat_ugn/gnat_and_program_execution id68}@anchor{1cf}@anchor{gnat_ugn/gnat_and_program_execution the-gnat-debug-pool-facility}@anchor{1d0}
23288@subsection The GNAT Debug Pool Facility
23289
23290
23291@geindex Debug Pool
23292
23293@geindex storage
23294@geindex pool
23295@geindex memory corruption
23296
23297The use of unchecked deallocation and unchecked conversion can easily
23298lead to incorrect memory references. The problems generated by such
23299references are usually difficult to tackle because the symptoms can be
23300very remote from the origin of the problem. In such cases, it is
23301very helpful to detect the problem as early as possible. This is the
23302purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
23303
23304In order to use the GNAT specific debugging pool, the user must
23305associate a debug pool object with each of the access types that may be
23306related to suspected memory problems. See Ada Reference Manual 13.11.
23307
23308@quotation
23309
23310@example
23311type Ptr is access Some_Type;
23312Pool : GNAT.Debug_Pools.Debug_Pool;
23313for Ptr'Storage_Pool use Pool;
23314@end example
23315@end quotation
23316
23317@code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
23318pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
23319allow the user to redefine allocation and deallocation strategies. They
23320also provide a checkpoint for each dereference, through the use of
23321the primitive operation @code{Dereference} which is implicitly called at
23322each dereference of an access value.
23323
23324Once an access type has been associated with a debug pool, operations on
23325values of the type may raise four distinct exceptions,
23326which correspond to four potential kinds of memory corruption:
23327
23328
23329@itemize *
23330
23331@item
23332@code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
23333
23334@item
23335@code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
23336
23337@item
23338@code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
23339
23340@item
23341@code{GNAT.Debug_Pools.Freeing_Deallocated_Storage}
23342@end itemize
23343
23344For types associated with a Debug_Pool, dynamic allocation is performed using
23345the standard GNAT allocation routine. References to all allocated chunks of
23346memory are kept in an internal dictionary. Several deallocation strategies are
23347provided, whereupon the user can choose to release the memory to the system,
23348keep it allocated for further invalid access checks, or fill it with an easily
23349recognizable pattern for debug sessions. The memory pattern is the old IBM
23350hexadecimal convention: @code{16#DEADBEEF#}.
23351
23352See the documentation in the file g-debpoo.ads for more information on the
23353various strategies.
23354
23355Upon each dereference, a check is made that the access value denotes a
23356properly allocated memory location. Here is a complete example of use of
23357@code{Debug_Pools}, that includes typical instances of  memory corruption:
23358
23359@quotation
23360
23361@example
23362with Gnat.Io; use Gnat.Io;
23363with Unchecked_Deallocation;
23364with Unchecked_Conversion;
23365with GNAT.Debug_Pools;
23366with System.Storage_Elements;
23367with Ada.Exceptions; use Ada.Exceptions;
23368procedure Debug_Pool_Test is
23369
23370   type T is access Integer;
23371   type U is access all T;
23372
23373   P : GNAT.Debug_Pools.Debug_Pool;
23374   for T'Storage_Pool use P;
23375
23376   procedure Free is new Unchecked_Deallocation (Integer, T);
23377   function UC is new Unchecked_Conversion (U, T);
23378   A, B : aliased T;
23379
23380   procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
23381
23382begin
23383   Info (P);
23384   A := new Integer;
23385   B := new Integer;
23386   B := A;
23387   Info (P);
23388   Free (A);
23389   begin
23390      Put_Line (Integer'Image(B.all));
23391   exception
23392      when E : others => Put_Line ("raised: " & Exception_Name (E));
23393   end;
23394   begin
23395      Free (B);
23396   exception
23397      when E : others => Put_Line ("raised: " & Exception_Name (E));
23398   end;
23399   B := UC(A'Access);
23400   begin
23401      Put_Line (Integer'Image(B.all));
23402   exception
23403      when E : others => Put_Line ("raised: " & Exception_Name (E));
23404   end;
23405   begin
23406      Free (B);
23407   exception
23408      when E : others => Put_Line ("raised: " & Exception_Name (E));
23409   end;
23410   Info (P);
23411end Debug_Pool_Test;
23412@end example
23413@end quotation
23414
23415The debug pool mechanism provides the following precise diagnostics on the
23416execution of this erroneous program:
23417
23418@quotation
23419
23420@example
23421Debug Pool info:
23422  Total allocated bytes :  0
23423  Total deallocated bytes :  0
23424  Current Water Mark:  0
23425  High Water Mark:  0
23426
23427Debug Pool info:
23428  Total allocated bytes :  8
23429  Total deallocated bytes :  0
23430  Current Water Mark:  8
23431  High Water Mark:  8
23432
23433raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
23434raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
23435raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
23436raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
23437Debug Pool info:
23438  Total allocated bytes :  8
23439  Total deallocated bytes :  4
23440  Current Water Mark:  4
23441  High Water Mark:  8
23442@end example
23443@end quotation
23444
23445
23446@c -- Non-breaking space in running text
23447@c -- E.g. Ada |nbsp| 95
23448
23449@node Platform-Specific Information,Example of Binder Output File,GNAT and Program Execution,Top
23450@anchor{gnat_ugn/platform_specific_information platform-specific-information}@anchor{d}@anchor{gnat_ugn/platform_specific_information doc}@anchor{1d1}@anchor{gnat_ugn/platform_specific_information id1}@anchor{1d2}
23451@chapter Platform-Specific Information
23452
23453
23454This appendix contains information relating to the implementation
23455of run-time libraries on various platforms and also covers
23456topics related to the GNAT implementation on Windows and Mac OS.
23457
23458@menu
23459* Run-Time Libraries::
23460* Specifying a Run-Time Library::
23461* GNU/Linux Topics::
23462* Microsoft Windows Topics::
23463* Mac OS Topics::
23464
23465@end menu
23466
23467@node Run-Time Libraries,Specifying a Run-Time Library,,Platform-Specific Information
23468@anchor{gnat_ugn/platform_specific_information id2}@anchor{1d3}@anchor{gnat_ugn/platform_specific_information run-time-libraries}@anchor{2b}
23469@section Run-Time Libraries
23470
23471
23472@geindex Tasking and threads libraries
23473
23474@geindex Threads libraries and tasking
23475
23476@geindex Run-time libraries (platform-specific information)
23477
23478The GNAT run-time implementation may vary with respect to both the
23479underlying threads library and the exception-handling scheme.
23480For threads support, the default run-time will bind to the thread
23481package of the underlying operating system.
23482
23483For exception handling, either or both of two models are supplied:
23484
23485@quotation
23486
23487@geindex Zero-Cost Exceptions
23488
23489@geindex ZCX (Zero-Cost Exceptions)
23490@end quotation
23491
23492
23493@itemize *
23494
23495@item
23496@strong{Zero-Cost Exceptions} ("ZCX"),
23497which uses binder-generated tables that
23498are interrogated at run time to locate a handler.
23499
23500@geindex setjmp/longjmp Exception Model
23501
23502@geindex SJLJ (setjmp/longjmp Exception Model)
23503
23504@item
23505@strong{setjmp / longjmp} ('SJLJ'),
23506which uses dynamically-set data to establish
23507the set of handlers
23508@end itemize
23509
23510Most programs should experience a substantial speed improvement by
23511being compiled with a ZCX run-time.
23512This is especially true for
23513tasking applications or applications with many exception handlers.@}
23514
23515This section summarizes which combinations of threads and exception support
23516are supplied on various GNAT platforms.
23517It then shows how to select a particular library either
23518permanently or temporarily,
23519explains the properties of (and tradeoffs among) the various threads
23520libraries, and provides some additional
23521information about several specific platforms.
23522
23523@menu
23524* Summary of Run-Time Configurations::
23525
23526@end menu
23527
23528@node Summary of Run-Time Configurations,,,Run-Time Libraries
23529@anchor{gnat_ugn/platform_specific_information summary-of-run-time-configurations}@anchor{1d4}@anchor{gnat_ugn/platform_specific_information id3}@anchor{1d5}
23530@subsection Summary of Run-Time Configurations
23531
23532
23533
23534@multitable {xxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxx} {xxxxxxxxxxxxxx}
23535@headitem
23536
23537Platform
23538
23539@tab
23540
23541Run-Time
23542
23543@tab
23544
23545Tasking
23546
23547@tab
23548
23549Exceptions
23550
23551@item
23552
23553GNU/Linux
23554
23555@tab
23556
23557rts-native
23558(default)
23559
23560@tab
23561
23562pthread library
23563
23564@tab
23565
23566ZCX
23567
23568@item
23569
23570rts-sjlj
23571
23572@tab
23573
23574pthread library
23575
23576@tab
23577
23578SJLJ
23579
23580@item
23581
23582Windows
23583
23584@tab
23585
23586rts-native
23587(default)
23588
23589@tab
23590
23591native Win32 threads
23592
23593@tab
23594
23595ZCX
23596
23597@item
23598
23599rts-sjlj
23600
23601@tab
23602
23603native Win32 threads
23604
23605@tab
23606
23607SJLJ
23608
23609@item
23610
23611Mac OS
23612
23613@tab
23614
23615rts-native
23616
23617@tab
23618
23619pthread library
23620
23621@tab
23622
23623ZCX
23624
23625@end multitable
23626
23627
23628@node Specifying a Run-Time Library,GNU/Linux Topics,Run-Time Libraries,Platform-Specific Information
23629@anchor{gnat_ugn/platform_specific_information specifying-a-run-time-library}@anchor{1d6}@anchor{gnat_ugn/platform_specific_information id4}@anchor{1d7}
23630@section Specifying a Run-Time Library
23631
23632
23633The @code{adainclude} subdirectory containing the sources of the GNAT
23634run-time library, and the @code{adalib} subdirectory containing the
23635@code{ALI} files and the static and/or shared GNAT library, are located
23636in the gcc target-dependent area:
23637
23638@quotation
23639
23640@example
23641target=$prefix/lib/gcc/gcc-*dumpmachine*/gcc-*dumpversion*/
23642@end example
23643@end quotation
23644
23645As indicated above, on some platforms several run-time libraries are supplied.
23646These libraries are installed in the target dependent area and
23647contain a complete source and binary subdirectory. The detailed description
23648below explains the differences between the different libraries in terms of
23649their thread support.
23650
23651The default run-time library (when GNAT is installed) is @emph{rts-native}.
23652This default run-time is selected by the means of soft links.
23653For example on x86-linux:
23654
23655@c --
23656@c --  $(target-dir)
23657@c --      |
23658@c --      +--- adainclude----------+
23659@c --      |                        |
23660@c --      +--- adalib-----------+  |
23661@c --      |                     |  |
23662@c --      +--- rts-native       |  |
23663@c --      |    |                |  |
23664@c --      |    +--- adainclude <---+
23665@c --      |    |                |
23666@c --      |    +--- adalib <----+
23667@c --      |
23668@c --      +--- rts-sjlj
23669@c --           |
23670@c --           +--- adainclude
23671@c --           |
23672@c --           +--- adalib
23673
23674
23675@example
23676               $(target-dir)
23677              __/ /      \ \___
23678      _______/   /        \    \_________________
23679     /          /          \                     \
23680    /          /            \                     \
23681ADAINCLUDE  ADALIB      rts-native             rts-sjlj
23682   :          :            /    \                 /   \
23683   :          :           /      \               /     \
23684   :          :          /        \             /       \
23685   :          :         /          \           /         \
23686   +-------------> adainclude     adalib   adainclude   adalib
23687              :                     ^
23688              :                     :
23689              +---------------------+
23690
23691              Run-Time Library Directory Structure
23692   (Upper-case names and dotted/dashed arrows represent soft links)
23693@end example
23694
23695If the @emph{rts-sjlj} library is to be selected on a permanent basis,
23696these soft links can be modified with the following commands:
23697
23698@quotation
23699
23700@example
23701$ cd $target
23702$ rm -f adainclude adalib
23703$ ln -s rts-sjlj/adainclude adainclude
23704$ ln -s rts-sjlj/adalib adalib
23705@end example
23706@end quotation
23707
23708Alternatively, you can specify @code{rts-sjlj/adainclude} in the file
23709@code{$target/ada_source_path} and @code{rts-sjlj/adalib} in
23710@code{$target/ada_object_path}.
23711
23712@geindex --RTS option
23713
23714Selecting another run-time library temporarily can be
23715achieved by using the @code{--RTS} switch, e.g., @code{--RTS=sjlj}
23716@anchor{gnat_ugn/platform_specific_information choosing-the-scheduling-policy}@anchor{1d8}
23717@geindex SCHED_FIFO scheduling policy
23718
23719@geindex SCHED_RR scheduling policy
23720
23721@geindex SCHED_OTHER scheduling policy
23722
23723@menu
23724* Choosing the Scheduling Policy::
23725
23726@end menu
23727
23728@node Choosing the Scheduling Policy,,,Specifying a Run-Time Library
23729@anchor{gnat_ugn/platform_specific_information id5}@anchor{1d9}
23730@subsection Choosing the Scheduling Policy
23731
23732
23733When using a POSIX threads implementation, you have a choice of several
23734scheduling policies: @code{SCHED_FIFO}, @code{SCHED_RR} and @code{SCHED_OTHER}.
23735
23736Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
23737or @code{SCHED_RR} requires special (e.g., root) privileges.
23738
23739@geindex pragma Time_Slice
23740
23741@geindex -T0 option
23742
23743@geindex pragma Task_Dispatching_Policy
23744
23745By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
23746@code{SCHED_FIFO},
23747you can use one of the following:
23748
23749
23750@itemize *
23751
23752@item
23753@code{pragma Time_Slice (0.0)}
23754
23755@item
23756the corresponding binder option @code{-T0}
23757
23758@item
23759@code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23760@end itemize
23761
23762To specify @code{SCHED_RR},
23763you should use @code{pragma Time_Slice} with a
23764value greater than 0.0, or else use the corresponding @code{-T}
23765binder option.
23766
23767To make sure a program is running as root, you can put something like
23768this in a library package body in your application:
23769
23770@quotation
23771
23772@example
23773function geteuid return Integer;
23774pragma Import (C, geteuid, "geteuid");
23775Ignore : constant Boolean :=
23776  (if geteuid = 0 then True else raise Program_Error with "must be root");
23777@end example
23778@end quotation
23779
23780It gets the effective user id, and if it's not 0 (i.e. root), it raises
23781Program_Error.
23782
23783@geindex Linux
23784
23785@geindex GNU/Linux
23786
23787@node GNU/Linux Topics,Microsoft Windows Topics,Specifying a Run-Time Library,Platform-Specific Information
23788@anchor{gnat_ugn/platform_specific_information id6}@anchor{1da}@anchor{gnat_ugn/platform_specific_information gnu-linux-topics}@anchor{1db}
23789@section GNU/Linux Topics
23790
23791
23792This section describes topics that are specific to GNU/Linux platforms.
23793
23794@menu
23795* Required Packages on GNU/Linux::
23796
23797@end menu
23798
23799@node Required Packages on GNU/Linux,,,GNU/Linux Topics
23800@anchor{gnat_ugn/platform_specific_information id7}@anchor{1dc}@anchor{gnat_ugn/platform_specific_information required-packages-on-gnu-linux}@anchor{1dd}
23801@subsection Required Packages on GNU/Linux
23802
23803
23804GNAT requires the C library developer's package to be installed.
23805The name of of that package depends on your GNU/Linux distribution:
23806
23807
23808@itemize *
23809
23810@item
23811RedHat, SUSE: @code{glibc-devel};
23812
23813@item
23814Debian, Ubuntu: @code{libc6-dev} (normally installed by default).
23815@end itemize
23816
23817If using the 32-bit version of GNAT on a 64-bit version of GNU/Linux,
23818you'll need the 32-bit version of the glibc and glibc-devel packages:
23819
23820
23821@itemize *
23822
23823@item
23824RedHat, SUSE: @code{glibc.i686}, @code{glibc-devel.i686}
23825
23826@item
23827Debian, Ubuntu: @code{libc6:i386}, @code{libc6-dev:i386}
23828@end itemize
23829
23830Other GNU/Linux distributions might be choosing a different name
23831for that package.
23832
23833@geindex Windows
23834
23835@node Microsoft Windows Topics,Mac OS Topics,GNU/Linux Topics,Platform-Specific Information
23836@anchor{gnat_ugn/platform_specific_information microsoft-windows-topics}@anchor{2c}@anchor{gnat_ugn/platform_specific_information id8}@anchor{1de}
23837@section Microsoft Windows Topics
23838
23839
23840This section describes topics that are specific to the Microsoft Windows
23841platforms.
23842
23843
23844
23845
23846
23847@menu
23848* Using GNAT on Windows::
23849* Using a network installation of GNAT::
23850* CONSOLE and WINDOWS subsystems::
23851* Temporary Files::
23852* Disabling Command Line Argument Expansion::
23853* Mixed-Language Programming on Windows::
23854* Windows Specific Add-Ons::
23855
23856@end menu
23857
23858@node Using GNAT on Windows,Using a network installation of GNAT,,Microsoft Windows Topics
23859@anchor{gnat_ugn/platform_specific_information using-gnat-on-windows}@anchor{1df}@anchor{gnat_ugn/platform_specific_information id9}@anchor{1e0}
23860@subsection Using GNAT on Windows
23861
23862
23863One of the strengths of the GNAT technology is that its tool set
23864(@code{gcc}, @code{gnatbind}, @code{gnatlink}, @code{gnatmake}, the
23865@code{gdb} debugger, etc.) is used in the same way regardless of the
23866platform.
23867
23868On Windows this tool set is complemented by a number of Microsoft-specific
23869tools that have been provided to facilitate interoperability with Windows
23870when this is required. With these tools:
23871
23872
23873@itemize *
23874
23875@item
23876You can build applications using the @code{CONSOLE} or @code{WINDOWS}
23877subsystems.
23878
23879@item
23880You can use any Dynamically Linked Library (DLL) in your Ada code (both
23881relocatable and non-relocatable DLLs are supported).
23882
23883@item
23884You can build Ada DLLs for use in other applications. These applications
23885can be written in a language other than Ada (e.g., C, C++, etc). Again both
23886relocatable and non-relocatable Ada DLLs are supported.
23887
23888@item
23889You can include Windows resources in your Ada application.
23890
23891@item
23892You can use or create COM/DCOM objects.
23893@end itemize
23894
23895Immediately below are listed all known general GNAT-for-Windows restrictions.
23896Other restrictions about specific features like Windows Resources and DLLs
23897are listed in separate sections below.
23898
23899
23900@itemize *
23901
23902@item
23903It is not possible to use @code{GetLastError} and @code{SetLastError}
23904when tasking, protected records, or exceptions are used. In these
23905cases, in order to implement Ada semantics, the GNAT run-time system
23906calls certain Win32 routines that set the last error variable to 0 upon
23907success. It should be possible to use @code{GetLastError} and
23908@code{SetLastError} when tasking, protected record, and exception
23909features are not used, but it is not guaranteed to work.
23910
23911@item
23912It is not possible to link against Microsoft C++ libraries except for
23913import libraries. Interfacing must be done by the mean of DLLs.
23914
23915@item
23916It is possible to link against Microsoft C libraries. Yet the preferred
23917solution is to use C/C++ compiler that comes with GNAT, since it
23918doesn't require having two different development environments and makes the
23919inter-language debugging experience smoother.
23920
23921@item
23922When the compilation environment is located on FAT32 drives, users may
23923experience recompilations of the source files that have not changed if
23924Daylight Saving Time (DST) state has changed since the last time files
23925were compiled. NTFS drives do not have this problem.
23926
23927@item
23928No components of the GNAT toolset use any entries in the Windows
23929registry. The only entries that can be created are file associations and
23930PATH settings, provided the user has chosen to create them at installation
23931time, as well as some minimal book-keeping information needed to correctly
23932uninstall or integrate different GNAT products.
23933@end itemize
23934
23935@node Using a network installation of GNAT,CONSOLE and WINDOWS subsystems,Using GNAT on Windows,Microsoft Windows Topics
23936@anchor{gnat_ugn/platform_specific_information id10}@anchor{1e1}@anchor{gnat_ugn/platform_specific_information using-a-network-installation-of-gnat}@anchor{1e2}
23937@subsection Using a network installation of GNAT
23938
23939
23940Make sure the system on which GNAT is installed is accessible from the
23941current machine, i.e., the install location is shared over the network.
23942Shared resources are accessed on Windows by means of UNC paths, which
23943have the format @code{\\\\server\\sharename\\path}
23944
23945In order to use such a network installation, simply add the UNC path of the
23946@code{bin} directory of your GNAT installation in front of your PATH. For
23947example, if GNAT is installed in @code{\GNAT} directory of a share location
23948called @code{c-drive} on a machine @code{LOKI}, the following command will
23949make it available:
23950
23951@quotation
23952
23953@example
23954$ path \\loki\c-drive\gnat\bin;%path%`
23955@end example
23956@end quotation
23957
23958Be aware that every compilation using the network installation results in the
23959transfer of large amounts of data across the network and will likely cause
23960serious performance penalty.
23961
23962@node CONSOLE and WINDOWS subsystems,Temporary Files,Using a network installation of GNAT,Microsoft Windows Topics
23963@anchor{gnat_ugn/platform_specific_information id11}@anchor{1e3}@anchor{gnat_ugn/platform_specific_information console-and-windows-subsystems}@anchor{1e4}
23964@subsection CONSOLE and WINDOWS subsystems
23965
23966
23967@geindex CONSOLE Subsystem
23968
23969@geindex WINDOWS Subsystem
23970
23971@geindex -mwindows
23972
23973There are two main subsystems under Windows. The @code{CONSOLE} subsystem
23974(which is the default subsystem) will always create a console when
23975launching the application. This is not something desirable when the
23976application has a Windows GUI. To get rid of this console the
23977application must be using the @code{WINDOWS} subsystem. To do so
23978the @code{-mwindows} linker option must be specified.
23979
23980@quotation
23981
23982@example
23983$ gnatmake winprog -largs -mwindows
23984@end example
23985@end quotation
23986
23987@node Temporary Files,Disabling Command Line Argument Expansion,CONSOLE and WINDOWS subsystems,Microsoft Windows Topics
23988@anchor{gnat_ugn/platform_specific_information id12}@anchor{1e5}@anchor{gnat_ugn/platform_specific_information temporary-files}@anchor{1e6}
23989@subsection Temporary Files
23990
23991
23992@geindex Temporary files
23993
23994It is possible to control where temporary files gets created by setting
23995the
23996@geindex TMP
23997@geindex environment variable; TMP
23998@code{TMP} environment variable. The file will be created:
23999
24000
24001@itemize *
24002
24003@item
24004Under the directory pointed to by the
24005@geindex TMP
24006@geindex environment variable; TMP
24007@code{TMP} environment variable if
24008this directory exists.
24009
24010@item
24011Under @code{c:\temp}, if the
24012@geindex TMP
24013@geindex environment variable; TMP
24014@code{TMP} environment variable is not
24015set (or not pointing to a directory) and if this directory exists.
24016
24017@item
24018Under the current working directory otherwise.
24019@end itemize
24020
24021This allows you to determine exactly where the temporary
24022file will be created. This is particularly useful in networked
24023environments where you may not have write access to some
24024directories.
24025
24026@node Disabling Command Line Argument Expansion,Mixed-Language Programming on Windows,Temporary Files,Microsoft Windows Topics
24027@anchor{gnat_ugn/platform_specific_information disabling-command-line-argument-expansion}@anchor{1e7}
24028@subsection Disabling Command Line Argument Expansion
24029
24030
24031@geindex Command Line Argument Expansion
24032
24033By default, an executable compiled for the Windows platform will do
24034the following postprocessing on the arguments passed on the command
24035line:
24036
24037
24038@itemize *
24039
24040@item
24041If the argument contains the characters @code{*} and/or @code{?}, then
24042file expansion will be attempted. For example, if the current directory
24043contains @code{a.txt} and @code{b.txt}, then when calling:
24044
24045@example
24046$ my_ada_program *.txt
24047@end example
24048
24049The following arguments will effectively be passed to the main program
24050(for example when using @code{Ada.Command_Line.Argument}):
24051
24052@example
24053Ada.Command_Line.Argument (1) -> "a.txt"
24054Ada.Command_Line.Argument (2) -> "b.txt"
24055@end example
24056
24057@item
24058Filename expansion can be disabled for a given argument by using single
24059quotes. Thus, calling:
24060
24061@example
24062$ my_ada_program '*.txt'
24063@end example
24064
24065will result in:
24066
24067@example
24068Ada.Command_Line.Argument (1) -> "*.txt"
24069@end example
24070@end itemize
24071
24072Note that if the program is launched from a shell such as Cygwin Bash
24073then quote removal might be performed by the shell.
24074
24075In some contexts it might be useful to disable this feature (for example if
24076the program performs its own argument expansion). In order to do this, a C
24077symbol needs to be defined and set to @code{0}. You can do this by
24078adding the following code fragment in one of your Ada units:
24079
24080@example
24081Do_Argv_Expansion : Integer := 0;
24082pragma Export (C, Do_Argv_Expansion, "__gnat_do_argv_expansion");
24083@end example
24084
24085The results of previous examples will be respectively:
24086
24087@example
24088Ada.Command_Line.Argument (1) -> "*.txt"
24089@end example
24090
24091and:
24092
24093@example
24094Ada.Command_Line.Argument (1) -> "'*.txt'"
24095@end example
24096
24097@node Mixed-Language Programming on Windows,Windows Specific Add-Ons,Disabling Command Line Argument Expansion,Microsoft Windows Topics
24098@anchor{gnat_ugn/platform_specific_information id13}@anchor{1e8}@anchor{gnat_ugn/platform_specific_information mixed-language-programming-on-windows}@anchor{1e9}
24099@subsection Mixed-Language Programming on Windows
24100
24101
24102Developing pure Ada applications on Windows is no different than on
24103other GNAT-supported platforms. However, when developing or porting an
24104application that contains a mix of Ada and C/C++, the choice of your
24105Windows C/C++ development environment conditions your overall
24106interoperability strategy.
24107
24108If you use @code{gcc} or Microsoft C to compile the non-Ada part of
24109your application, there are no Windows-specific restrictions that
24110affect the overall interoperability with your Ada code. If you do want
24111to use the Microsoft tools for your C++ code, you have two choices:
24112
24113
24114@itemize *
24115
24116@item
24117Encapsulate your C++ code in a DLL to be linked with your Ada
24118application. In this case, use the Microsoft or whatever environment to
24119build the DLL and use GNAT to build your executable
24120(@ref{1ea,,Using DLLs with GNAT}).
24121
24122@item
24123Or you can encapsulate your Ada code in a DLL to be linked with the
24124other part of your application. In this case, use GNAT to build the DLL
24125(@ref{1eb,,Building DLLs with GNAT Project files}) and use the Microsoft
24126or whatever environment to build your executable.
24127@end itemize
24128
24129In addition to the description about C main in
24130@ref{44,,Mixed Language Programming} section, if the C main uses a
24131stand-alone library it is required on x86-windows to
24132setup the SEH context. For this the C main must looks like this:
24133
24134@quotation
24135
24136@example
24137/* main.c */
24138extern void adainit (void);
24139extern void adafinal (void);
24140extern void __gnat_initialize(void*);
24141extern void call_to_ada (void);
24142
24143int main (int argc, char *argv[])
24144@{
24145  int SEH [2];
24146
24147  /* Initialize the SEH context */
24148  __gnat_initialize (&SEH);
24149
24150  adainit();
24151
24152  /* Then call Ada services in the stand-alone library */
24153
24154  call_to_ada();
24155
24156  adafinal();
24157@}
24158@end example
24159@end quotation
24160
24161Note that this is not needed on x86_64-windows where the Windows
24162native SEH support is used.
24163
24164@menu
24165* Windows Calling Conventions::
24166* Introduction to Dynamic Link Libraries (DLLs): Introduction to Dynamic Link Libraries DLLs.
24167* Using DLLs with GNAT::
24168* Building DLLs with GNAT Project files::
24169* Building DLLs with GNAT::
24170* Building DLLs with gnatdll::
24171* Ada DLLs and Finalization::
24172* Creating a Spec for Ada DLLs::
24173* GNAT and Windows Resources::
24174* Using GNAT DLLs from Microsoft Visual Studio Applications::
24175* Debugging a DLL::
24176* Setting Stack Size from gnatlink::
24177* Setting Heap Size from gnatlink::
24178
24179@end menu
24180
24181@node Windows Calling Conventions,Introduction to Dynamic Link Libraries DLLs,,Mixed-Language Programming on Windows
24182@anchor{gnat_ugn/platform_specific_information windows-calling-conventions}@anchor{1ec}@anchor{gnat_ugn/platform_specific_information id14}@anchor{1ed}
24183@subsubsection Windows Calling Conventions
24184
24185
24186@geindex Stdcall
24187
24188@geindex APIENTRY
24189
24190This section pertain only to Win32. On Win64 there is a single native
24191calling convention. All convention specifiers are ignored on this
24192platform.
24193
24194When a subprogram @code{F} (caller) calls a subprogram @code{G}
24195(callee), there are several ways to push @code{G}'s parameters on the
24196stack and there are several possible scenarios to clean up the stack
24197upon @code{G}'s return. A calling convention is an agreed upon software
24198protocol whereby the responsibilities between the caller (@code{F}) and
24199the callee (@code{G}) are clearly defined. Several calling conventions
24200are available for Windows:
24201
24202
24203@itemize *
24204
24205@item
24206@code{C} (Microsoft defined)
24207
24208@item
24209@code{Stdcall} (Microsoft defined)
24210
24211@item
24212@code{Win32} (GNAT specific)
24213
24214@item
24215@code{DLL} (GNAT specific)
24216@end itemize
24217
24218@menu
24219* C Calling Convention::
24220* Stdcall Calling Convention::
24221* Win32 Calling Convention::
24222* DLL Calling Convention::
24223
24224@end menu
24225
24226@node C Calling Convention,Stdcall Calling Convention,,Windows Calling Conventions
24227@anchor{gnat_ugn/platform_specific_information c-calling-convention}@anchor{1ee}@anchor{gnat_ugn/platform_specific_information id15}@anchor{1ef}
24228@subsubsection @code{C} Calling Convention
24229
24230
24231This is the default calling convention used when interfacing to C/C++
24232routines compiled with either @code{gcc} or Microsoft Visual C++.
24233
24234In the @code{C} calling convention subprogram parameters are pushed on the
24235stack by the caller from right to left. The caller itself is in charge of
24236cleaning up the stack after the call. In addition, the name of a routine
24237with @code{C} calling convention is mangled by adding a leading underscore.
24238
24239The name to use on the Ada side when importing (or exporting) a routine
24240with @code{C} calling convention is the name of the routine. For
24241instance the C function:
24242
24243@quotation
24244
24245@example
24246int get_val (long);
24247@end example
24248@end quotation
24249
24250should be imported from Ada as follows:
24251
24252@quotation
24253
24254@example
24255function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24256pragma Import (C, Get_Val, External_Name => "get_val");
24257@end example
24258@end quotation
24259
24260Note that in this particular case the @code{External_Name} parameter could
24261have been omitted since, when missing, this parameter is taken to be the
24262name of the Ada entity in lower case. When the @code{Link_Name} parameter
24263is missing, as in the above example, this parameter is set to be the
24264@code{External_Name} with a leading underscore.
24265
24266When importing a variable defined in C, you should always use the @code{C}
24267calling convention unless the object containing the variable is part of a
24268DLL (in which case you should use the @code{Stdcall} calling
24269convention, @ref{1f0,,Stdcall Calling Convention}).
24270
24271@node Stdcall Calling Convention,Win32 Calling Convention,C Calling Convention,Windows Calling Conventions
24272@anchor{gnat_ugn/platform_specific_information stdcall-calling-convention}@anchor{1f0}@anchor{gnat_ugn/platform_specific_information id16}@anchor{1f1}
24273@subsubsection @code{Stdcall} Calling Convention
24274
24275
24276This convention, which was the calling convention used for Pascal
24277programs, is used by Microsoft for all the routines in the Win32 API for
24278efficiency reasons. It must be used to import any routine for which this
24279convention was specified.
24280
24281In the @code{Stdcall} calling convention subprogram parameters are pushed
24282on the stack by the caller from right to left. The callee (and not the
24283caller) is in charge of cleaning the stack on routine exit. In addition,
24284the name of a routine with @code{Stdcall} calling convention is mangled by
24285adding a leading underscore (as for the @code{C} calling convention) and a
24286trailing @code{@@@emph{nn}}, where @code{nn} is the overall size (in
24287bytes) of the parameters passed to the routine.
24288
24289The name to use on the Ada side when importing a C routine with a
24290@code{Stdcall} calling convention is the name of the C routine. The leading
24291underscore and trailing @code{@@@emph{nn}} are added automatically by
24292the compiler. For instance the Win32 function:
24293
24294@quotation
24295
24296@example
24297APIENTRY int get_val (long);
24298@end example
24299@end quotation
24300
24301should be imported from Ada as follows:
24302
24303@quotation
24304
24305@example
24306function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24307pragma Import (Stdcall, Get_Val);
24308--  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
24309@end example
24310@end quotation
24311
24312As for the @code{C} calling convention, when the @code{External_Name}
24313parameter is missing, it is taken to be the name of the Ada entity in lower
24314case. If instead of writing the above import pragma you write:
24315
24316@quotation
24317
24318@example
24319function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24320pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
24321@end example
24322@end quotation
24323
24324then the imported routine is @code{_retrieve_val@@4}. However, if instead
24325of specifying the @code{External_Name} parameter you specify the
24326@code{Link_Name} as in the following example:
24327
24328@quotation
24329
24330@example
24331function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
24332pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
24333@end example
24334@end quotation
24335
24336then the imported routine is @code{retrieve_val}, that is, there is no
24337decoration at all. No leading underscore and no Stdcall suffix
24338@code{@@@emph{nn}}.
24339
24340This is especially important as in some special cases a DLL's entry
24341point name lacks a trailing @code{@@@emph{nn}} while the exported
24342name generated for a call has it.
24343
24344It is also possible to import variables defined in a DLL by using an
24345import pragma for a variable. As an example, if a DLL contains a
24346variable defined as:
24347
24348@quotation
24349
24350@example
24351int my_var;
24352@end example
24353@end quotation
24354
24355then, to access this variable from Ada you should write:
24356
24357@quotation
24358
24359@example
24360My_Var : Interfaces.C.int;
24361pragma Import (Stdcall, My_Var);
24362@end example
24363@end quotation
24364
24365Note that to ease building cross-platform bindings this convention
24366will be handled as a @code{C} calling convention on non-Windows platforms.
24367
24368@node Win32 Calling Convention,DLL Calling Convention,Stdcall Calling Convention,Windows Calling Conventions
24369@anchor{gnat_ugn/platform_specific_information win32-calling-convention}@anchor{1f2}@anchor{gnat_ugn/platform_specific_information id17}@anchor{1f3}
24370@subsubsection @code{Win32} Calling Convention
24371
24372
24373This convention, which is GNAT-specific is fully equivalent to the
24374@code{Stdcall} calling convention described above.
24375
24376@node DLL Calling Convention,,Win32 Calling Convention,Windows Calling Conventions
24377@anchor{gnat_ugn/platform_specific_information id18}@anchor{1f4}@anchor{gnat_ugn/platform_specific_information dll-calling-convention}@anchor{1f5}
24378@subsubsection @code{DLL} Calling Convention
24379
24380
24381This convention, which is GNAT-specific is fully equivalent to the
24382@code{Stdcall} calling convention described above.
24383
24384@node Introduction to Dynamic Link Libraries DLLs,Using DLLs with GNAT,Windows Calling Conventions,Mixed-Language Programming on Windows
24385@anchor{gnat_ugn/platform_specific_information id19}@anchor{1f6}@anchor{gnat_ugn/platform_specific_information introduction-to-dynamic-link-libraries-dlls}@anchor{1f7}
24386@subsubsection Introduction to Dynamic Link Libraries (DLLs)
24387
24388
24389@geindex DLL
24390
24391A Dynamically Linked Library (DLL) is a library that can be shared by
24392several applications running under Windows. A DLL can contain any number of
24393routines and variables.
24394
24395One advantage of DLLs is that you can change and enhance them without
24396forcing all the applications that depend on them to be relinked or
24397recompiled. However, you should be aware than all calls to DLL routines are
24398slower since, as you will understand below, such calls are indirect.
24399
24400To illustrate the remainder of this section, suppose that an application
24401wants to use the services of a DLL @code{API.dll}. To use the services
24402provided by @code{API.dll} you must statically link against the DLL or
24403an import library which contains a jump table with an entry for each
24404routine and variable exported by the DLL. In the Microsoft world this
24405import library is called @code{API.lib}. When using GNAT this import
24406library is called either @code{libAPI.dll.a}, @code{libapi.dll.a},
24407@code{libAPI.a} or @code{libapi.a} (names are case insensitive).
24408
24409After you have linked your application with the DLL or the import library
24410and you run your application, here is what happens:
24411
24412
24413@itemize *
24414
24415@item
24416Your application is loaded into memory.
24417
24418@item
24419The DLL @code{API.dll} is mapped into the address space of your
24420application. This means that:
24421
24422
24423@itemize -
24424
24425@item
24426The DLL will use the stack of the calling thread.
24427
24428@item
24429The DLL will use the virtual address space of the calling process.
24430
24431@item
24432The DLL will allocate memory from the virtual address space of the calling
24433process.
24434
24435@item
24436Handles (pointers) can be safely exchanged between routines in the DLL
24437routines and routines in the application using the DLL.
24438@end itemize
24439
24440@item
24441The entries in the jump table (from the import library @code{libAPI.dll.a}
24442or @code{API.lib} or automatically created when linking against a DLL)
24443which is part of your application are initialized with the addresses
24444of the routines and variables in @code{API.dll}.
24445
24446@item
24447If present in @code{API.dll}, routines @code{DllMain} or
24448@code{DllMainCRTStartup} are invoked. These routines typically contain
24449the initialization code needed for the well-being of the routines and
24450variables exported by the DLL.
24451@end itemize
24452
24453There is an additional point which is worth mentioning. In the Windows
24454world there are two kind of DLLs: relocatable and non-relocatable
24455DLLs. Non-relocatable DLLs can only be loaded at a very specific address
24456in the target application address space. If the addresses of two
24457non-relocatable DLLs overlap and these happen to be used by the same
24458application, a conflict will occur and the application will run
24459incorrectly. Hence, when possible, it is always preferable to use and
24460build relocatable DLLs. Both relocatable and non-relocatable DLLs are
24461supported by GNAT. Note that the @code{-s} linker option (see GNU Linker
24462User's Guide) removes the debugging symbols from the DLL but the DLL can
24463still be relocated.
24464
24465As a side note, an interesting difference between Microsoft DLLs and
24466Unix shared libraries, is the fact that on most Unix systems all public
24467routines are exported by default in a Unix shared library, while under
24468Windows it is possible (but not required) to list exported routines in
24469a definition file (see @ref{1f8,,The Definition File}).
24470
24471@node Using DLLs with GNAT,Building DLLs with GNAT Project files,Introduction to Dynamic Link Libraries DLLs,Mixed-Language Programming on Windows
24472@anchor{gnat_ugn/platform_specific_information id20}@anchor{1f9}@anchor{gnat_ugn/platform_specific_information using-dlls-with-gnat}@anchor{1ea}
24473@subsubsection Using DLLs with GNAT
24474
24475
24476To use the services of a DLL, say @code{API.dll}, in your Ada application
24477you must have:
24478
24479
24480@itemize *
24481
24482@item
24483The Ada spec for the routines and/or variables you want to access in
24484@code{API.dll}. If not available this Ada spec must be built from the C/C++
24485header files provided with the DLL.
24486
24487@item
24488The import library (@code{libAPI.dll.a} or @code{API.lib}). As previously
24489mentioned an import library is a statically linked library containing the
24490import table which will be filled at load time to point to the actual
24491@code{API.dll} routines. Sometimes you don't have an import library for the
24492DLL you want to use. The following sections will explain how to build
24493one. Note that this is optional.
24494
24495@item
24496The actual DLL, @code{API.dll}.
24497@end itemize
24498
24499Once you have all the above, to compile an Ada application that uses the
24500services of @code{API.dll} and whose main subprogram is @code{My_Ada_App},
24501you simply issue the command
24502
24503@quotation
24504
24505@example
24506$ gnatmake my_ada_app -largs -lAPI
24507@end example
24508@end quotation
24509
24510The argument @code{-largs -lAPI} at the end of the @code{gnatmake} command
24511tells the GNAT linker to look for an import library. The linker will
24512look for a library name in this specific order:
24513
24514
24515@itemize *
24516
24517@item
24518@code{libAPI.dll.a}
24519
24520@item
24521@code{API.dll.a}
24522
24523@item
24524@code{libAPI.a}
24525
24526@item
24527@code{API.lib}
24528
24529@item
24530@code{libAPI.dll}
24531
24532@item
24533@code{API.dll}
24534@end itemize
24535
24536The first three are the GNU style import libraries. The third is the
24537Microsoft style import libraries. The last two are the actual DLL names.
24538
24539Note that if the Ada package spec for @code{API.dll} contains the
24540following pragma
24541
24542@quotation
24543
24544@example
24545pragma Linker_Options ("-lAPI");
24546@end example
24547@end quotation
24548
24549you do not have to add @code{-largs -lAPI} at the end of the
24550@code{gnatmake} command.
24551
24552If any one of the items above is missing you will have to create it
24553yourself. The following sections explain how to do so using as an
24554example a fictitious DLL called @code{API.dll}.
24555
24556@menu
24557* Creating an Ada Spec for the DLL Services::
24558* Creating an Import Library::
24559
24560@end menu
24561
24562@node Creating an Ada Spec for the DLL Services,Creating an Import Library,,Using DLLs with GNAT
24563@anchor{gnat_ugn/platform_specific_information id21}@anchor{1fa}@anchor{gnat_ugn/platform_specific_information creating-an-ada-spec-for-the-dll-services}@anchor{1fb}
24564@subsubsection Creating an Ada Spec for the DLL Services
24565
24566
24567A DLL typically comes with a C/C++ header file which provides the
24568definitions of the routines and variables exported by the DLL. The Ada
24569equivalent of this header file is a package spec that contains definitions
24570for the imported entities. If the DLL you intend to use does not come with
24571an Ada spec you have to generate one such spec yourself. For example if
24572the header file of @code{API.dll} is a file @code{api.h} containing the
24573following two definitions:
24574
24575@quotation
24576
24577@example
24578int some_var;
24579int get (char *);
24580@end example
24581@end quotation
24582
24583then the equivalent Ada spec could be:
24584
24585@quotation
24586
24587@example
24588with Interfaces.C.Strings;
24589package API is
24590   use Interfaces;
24591
24592   Some_Var : C.int;
24593   function Get (Str : C.Strings.Chars_Ptr) return C.int;
24594
24595private
24596   pragma Import (C, Get);
24597   pragma Import (DLL, Some_Var);
24598end API;
24599@end example
24600@end quotation
24601
24602@node Creating an Import Library,,Creating an Ada Spec for the DLL Services,Using DLLs with GNAT
24603@anchor{gnat_ugn/platform_specific_information id22}@anchor{1fc}@anchor{gnat_ugn/platform_specific_information creating-an-import-library}@anchor{1fd}
24604@subsubsection Creating an Import Library
24605
24606
24607@geindex Import library
24608
24609If a Microsoft-style import library @code{API.lib} or a GNAT-style
24610import library @code{libAPI.dll.a} or @code{libAPI.a} is available
24611with @code{API.dll} you can skip this section. You can also skip this
24612section if @code{API.dll} or @code{libAPI.dll} is built with GNU tools
24613as in this case it is possible to link directly against the
24614DLL. Otherwise read on.
24615
24616@geindex Definition file
24617@anchor{gnat_ugn/platform_specific_information the-definition-file}@anchor{1f8}
24618@subsubheading The Definition File
24619
24620
24621As previously mentioned, and unlike Unix systems, the list of symbols
24622that are exported from a DLL must be provided explicitly in Windows.
24623The main goal of a definition file is precisely that: list the symbols
24624exported by a DLL. A definition file (usually a file with a @code{.def}
24625suffix) has the following structure:
24626
24627@quotation
24628
24629@example
24630[LIBRARY `@w{`}name`@w{`}]
24631[DESCRIPTION `@w{`}string`@w{`}]
24632EXPORTS
24633   `@w{`}symbol1`@w{`}
24634   `@w{`}symbol2`@w{`}
24635   ...
24636@end example
24637@end quotation
24638
24639
24640@table @asis
24641
24642@item @emph{LIBRARY name}
24643
24644This section, which is optional, gives the name of the DLL.
24645
24646@item @emph{DESCRIPTION string}
24647
24648This section, which is optional, gives a description string that will be
24649embedded in the import library.
24650
24651@item @emph{EXPORTS}
24652
24653This section gives the list of exported symbols (procedures, functions or
24654variables). For instance in the case of @code{API.dll} the @code{EXPORTS}
24655section of @code{API.def} looks like:
24656
24657@example
24658EXPORTS
24659   some_var
24660   get
24661@end example
24662@end table
24663
24664Note that you must specify the correct suffix (@code{@@@emph{nn}})
24665(see @ref{1ec,,Windows Calling Conventions}) for a Stdcall
24666calling convention function in the exported symbols list.
24667
24668There can actually be other sections in a definition file, but these
24669sections are not relevant to the discussion at hand.
24670@anchor{gnat_ugn/platform_specific_information create-def-file-automatically}@anchor{1fe}
24671@subsubheading Creating a Definition File Automatically
24672
24673
24674You can automatically create the definition file @code{API.def}
24675(see @ref{1f8,,The Definition File}) from a DLL.
24676For that use the @code{dlltool} program as follows:
24677
24678@quotation
24679
24680@example
24681$ dlltool API.dll -z API.def --export-all-symbols
24682@end example
24683
24684Note that if some routines in the DLL have the @code{Stdcall} convention
24685(@ref{1ec,,Windows Calling Conventions}) with stripped @code{@@@emph{nn}}
24686suffix then you'll have to edit @code{api.def} to add it, and specify
24687@code{-k} to @code{gnatdll} when creating the import library.
24688
24689Here are some hints to find the right @code{@@@emph{nn}} suffix.
24690
24691
24692@itemize -
24693
24694@item
24695If you have the Microsoft import library (.lib), it is possible to get
24696the right symbols by using Microsoft @code{dumpbin} tool (see the
24697corresponding Microsoft documentation for further details).
24698
24699@example
24700$ dumpbin /exports api.lib
24701@end example
24702
24703@item
24704If you have a message about a missing symbol at link time the compiler
24705tells you what symbol is expected. You just have to go back to the
24706definition file and add the right suffix.
24707@end itemize
24708@end quotation
24709@anchor{gnat_ugn/platform_specific_information gnat-style-import-library}@anchor{1ff}
24710@subsubheading GNAT-Style Import Library
24711
24712
24713To create a static import library from @code{API.dll} with the GNAT tools
24714you should create the .def file, then use @code{gnatdll} tool
24715(see @ref{200,,Using gnatdll}) as follows:
24716
24717@quotation
24718
24719@example
24720$ gnatdll -e API.def -d API.dll
24721@end example
24722
24723@code{gnatdll} takes as input a definition file @code{API.def} and the
24724name of the DLL containing the services listed in the definition file
24725@code{API.dll}. The name of the static import library generated is
24726computed from the name of the definition file as follows: if the
24727definition file name is @code{xyz.def}, the import library name will
24728be @code{libxyz.a}. Note that in the previous example option
24729@code{-e} could have been removed because the name of the definition
24730file (before the @code{.def} suffix) is the same as the name of the
24731DLL (@ref{200,,Using gnatdll} for more information about @code{gnatdll}).
24732@end quotation
24733@anchor{gnat_ugn/platform_specific_information msvs-style-import-library}@anchor{201}
24734@subsubheading Microsoft-Style Import Library
24735
24736
24737A Microsoft import library is needed only if you plan to make an
24738Ada DLL available to applications developed with Microsoft
24739tools (@ref{1e9,,Mixed-Language Programming on Windows}).
24740
24741To create a Microsoft-style import library for @code{API.dll} you
24742should create the .def file, then build the actual import library using
24743Microsoft's @code{lib} utility:
24744
24745@quotation
24746
24747@example
24748$ lib -machine:IX86 -def:API.def -out:API.lib
24749@end example
24750
24751If you use the above command the definition file @code{API.def} must
24752contain a line giving the name of the DLL:
24753
24754@example
24755LIBRARY      "API"
24756@end example
24757
24758See the Microsoft documentation for further details about the usage of
24759@code{lib}.
24760@end quotation
24761
24762@node Building DLLs with GNAT Project files,Building DLLs with GNAT,Using DLLs with GNAT,Mixed-Language Programming on Windows
24763@anchor{gnat_ugn/platform_specific_information id23}@anchor{202}@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat-project-files}@anchor{1eb}
24764@subsubsection Building DLLs with GNAT Project files
24765
24766
24767@geindex DLLs
24768@geindex building
24769
24770There is nothing specific to Windows in the build process.
24771See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24772chapter of the @emph{GPRbuild User's Guide}.
24773
24774Due to a system limitation, it is not possible under Windows to create threads
24775when inside the @code{DllMain} routine which is used for auto-initialization
24776of shared libraries, so it is not possible to have library level tasks in SALs.
24777
24778@node Building DLLs with GNAT,Building DLLs with gnatdll,Building DLLs with GNAT Project files,Mixed-Language Programming on Windows
24779@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnat}@anchor{203}@anchor{gnat_ugn/platform_specific_information id24}@anchor{204}
24780@subsubsection Building DLLs with GNAT
24781
24782
24783@geindex DLLs
24784@geindex building
24785
24786This section explain how to build DLLs using the GNAT built-in DLL
24787support. With the following procedure it is straight forward to build
24788and use DLLs with GNAT.
24789
24790
24791@itemize *
24792
24793@item
24794Building object files.
24795The first step is to build all objects files that are to be included
24796into the DLL. This is done by using the standard @code{gnatmake} tool.
24797
24798@item
24799Building the DLL.
24800To build the DLL you must use the @code{gcc} @code{-shared} and
24801@code{-shared-libgcc} options. It is quite simple to use this method:
24802
24803@example
24804$ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o ...
24805@end example
24806
24807It is important to note that in this case all symbols found in the
24808object files are automatically exported. It is possible to restrict
24809the set of symbols to export by passing to @code{gcc} a definition
24810file (see @ref{1f8,,The Definition File}).
24811For example:
24812
24813@example
24814$ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o ...
24815@end example
24816
24817If you use a definition file you must export the elaboration procedures
24818for every package that required one. Elaboration procedures are named
24819using the package name followed by "_E".
24820
24821@item
24822Preparing DLL to be used.
24823For the DLL to be used by client programs the bodies must be hidden
24824from it and the .ali set with read-only attribute. This is very important
24825otherwise GNAT will recompile all packages and will not actually use
24826the code in the DLL. For example:
24827
24828@example
24829$ mkdir apilib
24830$ copy *.ads *.ali api.dll apilib
24831$ attrib +R apilib\\*.ali
24832@end example
24833@end itemize
24834
24835At this point it is possible to use the DLL by directly linking
24836against it. Note that you must use the GNAT shared runtime when using
24837GNAT shared libraries. This is achieved by using the @code{-shared} binder
24838option.
24839
24840@quotation
24841
24842@example
24843$ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
24844@end example
24845@end quotation
24846
24847@node Building DLLs with gnatdll,Ada DLLs and Finalization,Building DLLs with GNAT,Mixed-Language Programming on Windows
24848@anchor{gnat_ugn/platform_specific_information building-dlls-with-gnatdll}@anchor{205}@anchor{gnat_ugn/platform_specific_information id25}@anchor{206}
24849@subsubsection Building DLLs with gnatdll
24850
24851
24852@geindex DLLs
24853@geindex building
24854
24855Note that it is preferred to use GNAT Project files
24856(@ref{1eb,,Building DLLs with GNAT Project files}) or the built-in GNAT
24857DLL support (@ref{203,,Building DLLs with GNAT}) or to build DLLs.
24858
24859This section explains how to build DLLs containing Ada code using
24860@code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
24861remainder of this section.
24862
24863The steps required to build an Ada DLL that is to be used by Ada as well as
24864non-Ada applications are as follows:
24865
24866
24867@itemize *
24868
24869@item
24870You need to mark each Ada entity exported by the DLL with a @code{C} or
24871@code{Stdcall} calling convention to avoid any Ada name mangling for the
24872entities exported by the DLL
24873(see @ref{207,,Exporting Ada Entities}). You can
24874skip this step if you plan to use the Ada DLL only from Ada applications.
24875
24876@item
24877Your Ada code must export an initialization routine which calls the routine
24878@code{adainit} generated by @code{gnatbind} to perform the elaboration of
24879the Ada code in the DLL (@ref{208,,Ada DLLs and Elaboration}). The initialization
24880routine exported by the Ada DLL must be invoked by the clients of the DLL
24881to initialize the DLL.
24882
24883@item
24884When useful, the DLL should also export a finalization routine which calls
24885routine @code{adafinal} generated by @code{gnatbind} to perform the
24886finalization of the Ada code in the DLL (@ref{209,,Ada DLLs and Finalization}).
24887The finalization routine exported by the Ada DLL must be invoked by the
24888clients of the DLL when the DLL services are no further needed.
24889
24890@item
24891You must provide a spec for the services exported by the Ada DLL in each
24892of the programming languages to which you plan to make the DLL available.
24893
24894@item
24895You must provide a definition file listing the exported entities
24896(@ref{1f8,,The Definition File}).
24897
24898@item
24899Finally you must use @code{gnatdll} to produce the DLL and the import
24900library (@ref{200,,Using gnatdll}).
24901@end itemize
24902
24903Note that a relocatable DLL stripped using the @code{strip}
24904binutils tool will not be relocatable anymore. To build a DLL without
24905debug information pass @code{-largs -s} to @code{gnatdll}. This
24906restriction does not apply to a DLL built using a Library Project.
24907See the @emph{Library Projects} section in the @emph{GNAT Project Manager}
24908chapter of the @emph{GPRbuild User's Guide}.
24909
24910@c Limitations_When_Using_Ada_DLLs_from Ada:
24911
24912@menu
24913* Limitations When Using Ada DLLs from Ada::
24914* Exporting Ada Entities::
24915* Ada DLLs and Elaboration::
24916
24917@end menu
24918
24919@node Limitations When Using Ada DLLs from Ada,Exporting Ada Entities,,Building DLLs with gnatdll
24920@anchor{gnat_ugn/platform_specific_information limitations-when-using-ada-dlls-from-ada}@anchor{20a}
24921@subsubsection Limitations When Using Ada DLLs from Ada
24922
24923
24924When using Ada DLLs from Ada applications there is a limitation users
24925should be aware of. Because on Windows the GNAT run-time is not in a DLL of
24926its own, each Ada DLL includes a part of the GNAT run-time. Specifically,
24927each Ada DLL includes the services of the GNAT run-time that are necessary
24928to the Ada code inside the DLL. As a result, when an Ada program uses an
24929Ada DLL there are two independent GNAT run-times: one in the Ada DLL and
24930one in the main program.
24931
24932It is therefore not possible to exchange GNAT run-time objects between the
24933Ada DLL and the main Ada program. Example of GNAT run-time objects are file
24934handles (e.g., @code{Text_IO.File_Type}), tasks types, protected objects
24935types, etc.
24936
24937It is completely safe to exchange plain elementary, array or record types,
24938Windows object handles, etc.
24939
24940@node Exporting Ada Entities,Ada DLLs and Elaboration,Limitations When Using Ada DLLs from Ada,Building DLLs with gnatdll
24941@anchor{gnat_ugn/platform_specific_information exporting-ada-entities}@anchor{207}@anchor{gnat_ugn/platform_specific_information id26}@anchor{20b}
24942@subsubsection Exporting Ada Entities
24943
24944
24945@geindex Export table
24946
24947Building a DLL is a way to encapsulate a set of services usable from any
24948application. As a result, the Ada entities exported by a DLL should be
24949exported with the @code{C} or @code{Stdcall} calling conventions to avoid
24950any Ada name mangling. As an example here is an Ada package
24951@code{API}, spec and body, exporting two procedures, a function, and a
24952variable:
24953
24954@quotation
24955
24956@example
24957with Interfaces.C; use Interfaces;
24958package API is
24959   Count : C.int := 0;
24960   function Factorial (Val : C.int) return C.int;
24961
24962   procedure Initialize_API;
24963   procedure Finalize_API;
24964   --  Initialization & Finalization routines. More in the next section.
24965private
24966   pragma Export (C, Initialize_API);
24967   pragma Export (C, Finalize_API);
24968   pragma Export (C, Count);
24969   pragma Export (C, Factorial);
24970end API;
24971@end example
24972
24973@example
24974package body API is
24975   function Factorial (Val : C.int) return C.int is
24976      Fact : C.int := 1;
24977   begin
24978      Count := Count + 1;
24979      for K in 1 .. Val loop
24980         Fact := Fact * K;
24981      end loop;
24982      return Fact;
24983   end Factorial;
24984
24985   procedure Initialize_API is
24986      procedure Adainit;
24987      pragma Import (C, Adainit);
24988   begin
24989      Adainit;
24990   end Initialize_API;
24991
24992   procedure Finalize_API is
24993      procedure Adafinal;
24994      pragma Import (C, Adafinal);
24995   begin
24996      Adafinal;
24997   end Finalize_API;
24998end API;
24999@end example
25000@end quotation
25001
25002If the Ada DLL you are building will only be used by Ada applications
25003you do not have to export Ada entities with a @code{C} or @code{Stdcall}
25004convention. As an example, the previous package could be written as
25005follows:
25006
25007@quotation
25008
25009@example
25010package API is
25011   Count : Integer := 0;
25012   function Factorial (Val : Integer) return Integer;
25013
25014   procedure Initialize_API;
25015   procedure Finalize_API;
25016   --  Initialization and Finalization routines.
25017end API;
25018@end example
25019
25020@example
25021package body API is
25022   function Factorial (Val : Integer) return Integer is
25023      Fact : Integer := 1;
25024   begin
25025      Count := Count + 1;
25026      for K in 1 .. Val loop
25027         Fact := Fact * K;
25028      end loop;
25029      return Fact;
25030   end Factorial;
25031
25032   ...
25033   --  The remainder of this package body is unchanged.
25034end API;
25035@end example
25036@end quotation
25037
25038Note that if you do not export the Ada entities with a @code{C} or
25039@code{Stdcall} convention you will have to provide the mangled Ada names
25040in the definition file of the Ada DLL
25041(@ref{20c,,Creating the Definition File}).
25042
25043@node Ada DLLs and Elaboration,,Exporting Ada Entities,Building DLLs with gnatdll
25044@anchor{gnat_ugn/platform_specific_information ada-dlls-and-elaboration}@anchor{208}@anchor{gnat_ugn/platform_specific_information id27}@anchor{20d}
25045@subsubsection Ada DLLs and Elaboration
25046
25047
25048@geindex DLLs and elaboration
25049
25050The DLL that you are building contains your Ada code as well as all the
25051routines in the Ada library that are needed by it. The first thing a
25052user of your DLL must do is elaborate the Ada code
25053(@ref{f,,Elaboration Order Handling in GNAT}).
25054
25055To achieve this you must export an initialization routine
25056(@code{Initialize_API} in the previous example), which must be invoked
25057before using any of the DLL services. This elaboration routine must call
25058the Ada elaboration routine @code{adainit} generated by the GNAT binder
25059(@ref{b4,,Binding with Non-Ada Main Programs}). See the body of
25060@code{Initialize_Api} for an example. Note that the GNAT binder is
25061automatically invoked during the DLL build process by the @code{gnatdll}
25062tool (@ref{200,,Using gnatdll}).
25063
25064When a DLL is loaded, Windows systematically invokes a routine called
25065@code{DllMain}. It would therefore be possible to call @code{adainit}
25066directly from @code{DllMain} without having to provide an explicit
25067initialization routine. Unfortunately, it is not possible to call
25068@code{adainit} from the @code{DllMain} if your program has library level
25069tasks because access to the @code{DllMain} entry point is serialized by
25070the system (that is, only a single thread can execute 'through' it at a
25071time), which means that the GNAT run-time will deadlock waiting for the
25072newly created task to complete its initialization.
25073
25074@node Ada DLLs and Finalization,Creating a Spec for Ada DLLs,Building DLLs with gnatdll,Mixed-Language Programming on Windows
25075@anchor{gnat_ugn/platform_specific_information id28}@anchor{20e}@anchor{gnat_ugn/platform_specific_information ada-dlls-and-finalization}@anchor{209}
25076@subsubsection Ada DLLs and Finalization
25077
25078
25079@geindex DLLs and finalization
25080
25081When the services of an Ada DLL are no longer needed, the client code should
25082invoke the DLL finalization routine, if available. The DLL finalization
25083routine is in charge of releasing all resources acquired by the DLL. In the
25084case of the Ada code contained in the DLL, this is achieved by calling
25085routine @code{adafinal} generated by the GNAT binder
25086(@ref{b4,,Binding with Non-Ada Main Programs}).
25087See the body of @code{Finalize_Api} for an
25088example. As already pointed out the GNAT binder is automatically invoked
25089during the DLL build process by the @code{gnatdll} tool
25090(@ref{200,,Using gnatdll}).
25091
25092@node Creating a Spec for Ada DLLs,GNAT and Windows Resources,Ada DLLs and Finalization,Mixed-Language Programming on Windows
25093@anchor{gnat_ugn/platform_specific_information id29}@anchor{20f}@anchor{gnat_ugn/platform_specific_information creating-a-spec-for-ada-dlls}@anchor{210}
25094@subsubsection Creating a Spec for Ada DLLs
25095
25096
25097To use the services exported by the Ada DLL from another programming
25098language (e.g., C), you have to translate the specs of the exported Ada
25099entities in that language. For instance in the case of @code{API.dll},
25100the corresponding C header file could look like:
25101
25102@quotation
25103
25104@example
25105extern int *_imp__count;
25106#define count (*_imp__count)
25107int factorial (int);
25108@end example
25109@end quotation
25110
25111It is important to understand that when building an Ada DLL to be used by
25112other Ada applications, you need two different specs for the packages
25113contained in the DLL: one for building the DLL and the other for using
25114the DLL. This is because the @code{DLL} calling convention is needed to
25115use a variable defined in a DLL, but when building the DLL, the variable
25116must have either the @code{Ada} or @code{C} calling convention. As an
25117example consider a DLL comprising the following package @code{API}:
25118
25119@quotation
25120
25121@example
25122package API is
25123   Count : Integer := 0;
25124   ...
25125   --  Remainder of the package omitted.
25126end API;
25127@end example
25128@end quotation
25129
25130After producing a DLL containing package @code{API}, the spec that
25131must be used to import @code{API.Count} from Ada code outside of the
25132DLL is:
25133
25134@quotation
25135
25136@example
25137package API is
25138   Count : Integer;
25139   pragma Import (DLL, Count);
25140end API;
25141@end example
25142@end quotation
25143
25144@menu
25145* Creating the Definition File::
25146* Using gnatdll::
25147
25148@end menu
25149
25150@node Creating the Definition File,Using gnatdll,,Creating a Spec for Ada DLLs
25151@anchor{gnat_ugn/platform_specific_information creating-the-definition-file}@anchor{20c}@anchor{gnat_ugn/platform_specific_information id30}@anchor{211}
25152@subsubsection Creating the Definition File
25153
25154
25155The definition file is the last file needed to build the DLL. It lists
25156the exported symbols. As an example, the definition file for a DLL
25157containing only package @code{API} (where all the entities are exported
25158with a @code{C} calling convention) is:
25159
25160@quotation
25161
25162@example
25163EXPORTS
25164    count
25165    factorial
25166    finalize_api
25167    initialize_api
25168@end example
25169@end quotation
25170
25171If the @code{C} calling convention is missing from package @code{API},
25172then the definition file contains the mangled Ada names of the above
25173entities, which in this case are:
25174
25175@quotation
25176
25177@example
25178EXPORTS
25179    api__count
25180    api__factorial
25181    api__finalize_api
25182    api__initialize_api
25183@end example
25184@end quotation
25185
25186@node Using gnatdll,,Creating the Definition File,Creating a Spec for Ada DLLs
25187@anchor{gnat_ugn/platform_specific_information using-gnatdll}@anchor{200}@anchor{gnat_ugn/platform_specific_information id31}@anchor{212}
25188@subsubsection Using @code{gnatdll}
25189
25190
25191@geindex gnatdll
25192
25193@code{gnatdll} is a tool to automate the DLL build process once all the Ada
25194and non-Ada sources that make up your DLL have been compiled.
25195@code{gnatdll} is actually in charge of two distinct tasks: build the
25196static import library for the DLL and the actual DLL. The form of the
25197@code{gnatdll} command is
25198
25199@quotation
25200
25201@example
25202$ gnatdll [ switches ] list-of-files [ -largs opts ]
25203@end example
25204@end quotation
25205
25206where @code{list-of-files} is a list of ALI and object files. The object
25207file list must be the exact list of objects corresponding to the non-Ada
25208sources whose services are to be included in the DLL. The ALI file list
25209must be the exact list of ALI files for the corresponding Ada sources
25210whose services are to be included in the DLL. If @code{list-of-files} is
25211missing, only the static import library is generated.
25212
25213You may specify any of the following switches to @code{gnatdll}:
25214
25215@quotation
25216
25217@geindex -a (gnatdll)
25218@end quotation
25219
25220
25221@table @asis
25222
25223@item @code{-a[@emph{address}]}
25224
25225Build a non-relocatable DLL at @code{address}. If @code{address} is not
25226specified the default address @code{0x11000000} will be used. By default,
25227when this switch is missing, @code{gnatdll} builds relocatable DLL. We
25228advise the reader to build relocatable DLL.
25229
25230@geindex -b (gnatdll)
25231
25232@item @code{-b @emph{address}}
25233
25234Set the relocatable DLL base address. By default the address is
25235@code{0x11000000}.
25236
25237@geindex -bargs (gnatdll)
25238
25239@item @code{-bargs @emph{opts}}
25240
25241Binder options. Pass @code{opts} to the binder.
25242
25243@geindex -d (gnatdll)
25244
25245@item @code{-d @emph{dllfile}}
25246
25247@code{dllfile} is the name of the DLL. This switch must be present for
25248@code{gnatdll} to do anything. The name of the generated import library is
25249obtained algorithmically from @code{dllfile} as shown in the following
25250example: if @code{dllfile} is @code{xyz.dll}, the import library name is
25251@code{libxyz.dll.a}. The name of the definition file to use (if not specified
25252by option @code{-e}) is obtained algorithmically from @code{dllfile}
25253as shown in the following example:
25254if @code{dllfile} is @code{xyz.dll}, the definition
25255file used is @code{xyz.def}.
25256
25257@geindex -e (gnatdll)
25258
25259@item @code{-e @emph{deffile}}
25260
25261@code{deffile} is the name of the definition file.
25262
25263@geindex -g (gnatdll)
25264
25265@item @code{-g}
25266
25267Generate debugging information. This information is stored in the object
25268file and copied from there to the final DLL file by the linker,
25269where it can be read by the debugger. You must use the
25270@code{-g} switch if you plan on using the debugger or the symbolic
25271stack traceback.
25272
25273@geindex -h (gnatdll)
25274
25275@item @code{-h}
25276
25277Help mode. Displays @code{gnatdll} switch usage information.
25278
25279@geindex -I (gnatdll)
25280
25281@item @code{-I@emph{dir}}
25282
25283Direct @code{gnatdll} to search the @code{dir} directory for source and
25284object files needed to build the DLL.
25285(@ref{89,,Search Paths and the Run-Time Library (RTL)}).
25286
25287@geindex -k (gnatdll)
25288
25289@item @code{-k}
25290
25291Removes the @code{@@@emph{nn}} suffix from the import library's exported
25292names, but keeps them for the link names. You must specify this
25293option if you want to use a @code{Stdcall} function in a DLL for which
25294the @code{@@@emph{nn}} suffix has been removed. This is the case for most
25295of the Windows NT DLL for example. This option has no effect when
25296@code{-n} option is specified.
25297
25298@geindex -l (gnatdll)
25299
25300@item @code{-l @emph{file}}
25301
25302The list of ALI and object files used to build the DLL are listed in
25303@code{file}, instead of being given in the command line. Each line in
25304@code{file} contains the name of an ALI or object file.
25305
25306@geindex -n (gnatdll)
25307
25308@item @code{-n}
25309
25310No Import. Do not create the import library.
25311
25312@geindex -q (gnatdll)
25313
25314@item @code{-q}
25315
25316Quiet mode. Do not display unnecessary messages.
25317
25318@geindex -v (gnatdll)
25319
25320@item @code{-v}
25321
25322Verbose mode. Display extra information.
25323
25324@geindex -largs (gnatdll)
25325
25326@item @code{-largs @emph{opts}}
25327
25328Linker options. Pass @code{opts} to the linker.
25329@end table
25330
25331@subsubheading @code{gnatdll} Example
25332
25333
25334As an example the command to build a relocatable DLL from @code{api.adb}
25335once @code{api.adb} has been compiled and @code{api.def} created is
25336
25337@quotation
25338
25339@example
25340$ gnatdll -d api.dll api.ali
25341@end example
25342@end quotation
25343
25344The above command creates two files: @code{libapi.dll.a} (the import
25345library) and @code{api.dll} (the actual DLL). If you want to create
25346only the DLL, just type:
25347
25348@quotation
25349
25350@example
25351$ gnatdll -d api.dll -n api.ali
25352@end example
25353@end quotation
25354
25355Alternatively if you want to create just the import library, type:
25356
25357@quotation
25358
25359@example
25360$ gnatdll -d api.dll
25361@end example
25362@end quotation
25363
25364@subsubheading @code{gnatdll} behind the Scenes
25365
25366
25367This section details the steps involved in creating a DLL. @code{gnatdll}
25368does these steps for you. Unless you are interested in understanding what
25369goes on behind the scenes, you should skip this section.
25370
25371We use the previous example of a DLL containing the Ada package @code{API},
25372to illustrate the steps necessary to build a DLL. The starting point is a
25373set of objects that will make up the DLL and the corresponding ALI
25374files. In the case of this example this means that @code{api.o} and
25375@code{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
25376the following:
25377
25378
25379@itemize *
25380
25381@item
25382@code{gnatdll} builds the base file (@code{api.base}). A base file gives
25383the information necessary to generate relocation information for the
25384DLL.
25385
25386@example
25387$ gnatbind -n api
25388$ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
25389@end example
25390
25391In addition to the base file, the @code{gnatlink} command generates an
25392output file @code{api.jnk} which can be discarded. The @code{-mdll} switch
25393asks @code{gnatlink} to generate the routines @code{DllMain} and
25394@code{DllMainCRTStartup} that are called by the Windows loader when the DLL
25395is loaded into memory.
25396
25397@item
25398@code{gnatdll} uses @code{dlltool} (see @ref{213,,Using dlltool}) to build the
25399export table (@code{api.exp}). The export table contains the relocation
25400information in a form which can be used during the final link to ensure
25401that the Windows loader is able to place the DLL anywhere in memory.
25402
25403@example
25404$ dlltool --dllname api.dll --def api.def --base-file api.base \\
25405          --output-exp api.exp
25406@end example
25407
25408@item
25409@code{gnatdll} builds the base file using the new export table. Note that
25410@code{gnatbind} must be called once again since the binder generated file
25411has been deleted during the previous call to @code{gnatlink}.
25412
25413@example
25414$ gnatbind -n api
25415$ gnatlink api -o api.jnk api.exp -mdll
25416      -Wl,--base-file,api.base
25417@end example
25418
25419@item
25420@code{gnatdll} builds the new export table using the new base file and
25421generates the DLL import library @code{libAPI.dll.a}.
25422
25423@example
25424$ dlltool --dllname api.dll --def api.def --base-file api.base \\
25425          --output-exp api.exp --output-lib libAPI.a
25426@end example
25427
25428@item
25429Finally @code{gnatdll} builds the relocatable DLL using the final export
25430table.
25431
25432@example
25433$ gnatbind -n api
25434$ gnatlink api api.exp -o api.dll -mdll
25435@end example
25436@end itemize
25437@anchor{gnat_ugn/platform_specific_information using-dlltool}@anchor{213}
25438@subsubheading Using @code{dlltool}
25439
25440
25441@code{dlltool} is the low-level tool used by @code{gnatdll} to build
25442DLLs and static import libraries. This section summarizes the most
25443common @code{dlltool} switches. The form of the @code{dlltool} command
25444is
25445
25446@quotation
25447
25448@example
25449$ dlltool [`switches`]
25450@end example
25451@end quotation
25452
25453@code{dlltool} switches include:
25454
25455@geindex --base-file (dlltool)
25456
25457
25458@table @asis
25459
25460@item @code{--base-file @emph{basefile}}
25461
25462Read the base file @code{basefile} generated by the linker. This switch
25463is used to create a relocatable DLL.
25464@end table
25465
25466@geindex --def (dlltool)
25467
25468
25469@table @asis
25470
25471@item @code{--def @emph{deffile}}
25472
25473Read the definition file.
25474@end table
25475
25476@geindex --dllname (dlltool)
25477
25478
25479@table @asis
25480
25481@item @code{--dllname @emph{name}}
25482
25483Gives the name of the DLL. This switch is used to embed the name of the
25484DLL in the static import library generated by @code{dlltool} with switch
25485@code{--output-lib}.
25486@end table
25487
25488@geindex -k (dlltool)
25489
25490
25491@table @asis
25492
25493@item @code{-k}
25494
25495Kill @code{@@@emph{nn}} from exported names
25496(@ref{1ec,,Windows Calling Conventions}
25497for a discussion about @code{Stdcall}-style symbols.
25498@end table
25499
25500@geindex --help (dlltool)
25501
25502
25503@table @asis
25504
25505@item @code{--help}
25506
25507Prints the @code{dlltool} switches with a concise description.
25508@end table
25509
25510@geindex --output-exp (dlltool)
25511
25512
25513@table @asis
25514
25515@item @code{--output-exp @emph{exportfile}}
25516
25517Generate an export file @code{exportfile}. The export file contains the
25518export table (list of symbols in the DLL) and is used to create the DLL.
25519@end table
25520
25521@geindex --output-lib (dlltool)
25522
25523
25524@table @asis
25525
25526@item @code{--output-lib @emph{libfile}}
25527
25528Generate a static import library @code{libfile}.
25529@end table
25530
25531@geindex -v (dlltool)
25532
25533
25534@table @asis
25535
25536@item @code{-v}
25537
25538Verbose mode.
25539@end table
25540
25541@geindex --as (dlltool)
25542
25543
25544@table @asis
25545
25546@item @code{--as @emph{assembler-name}}
25547
25548Use @code{assembler-name} as the assembler. The default is @code{as}.
25549@end table
25550
25551@node GNAT and Windows Resources,Using GNAT DLLs from Microsoft Visual Studio Applications,Creating a Spec for Ada DLLs,Mixed-Language Programming on Windows
25552@anchor{gnat_ugn/platform_specific_information gnat-and-windows-resources}@anchor{214}@anchor{gnat_ugn/platform_specific_information id32}@anchor{215}
25553@subsubsection GNAT and Windows Resources
25554
25555
25556@geindex Resources
25557@geindex windows
25558
25559Resources are an easy way to add Windows specific objects to your
25560application. The objects that can be added as resources include:
25561
25562
25563@itemize *
25564
25565@item
25566menus
25567
25568@item
25569accelerators
25570
25571@item
25572dialog boxes
25573
25574@item
25575string tables
25576
25577@item
25578bitmaps
25579
25580@item
25581cursors
25582
25583@item
25584icons
25585
25586@item
25587fonts
25588
25589@item
25590version information
25591@end itemize
25592
25593For example, a version information resource can be defined as follow and
25594embedded into an executable or DLL:
25595
25596A version information resource can be used to embed information into an
25597executable or a DLL. These information can be viewed using the file properties
25598from the Windows Explorer. Here is an example of a version information
25599resource:
25600
25601@quotation
25602
25603@example
256041 VERSIONINFO
25605FILEVERSION     1,0,0,0
25606PRODUCTVERSION  1,0,0,0
25607BEGIN
25608  BLOCK "StringFileInfo"
25609  BEGIN
25610    BLOCK "080904E4"
25611    BEGIN
25612      VALUE "CompanyName", "My Company Name"
25613      VALUE "FileDescription", "My application"
25614      VALUE "FileVersion", "1.0"
25615      VALUE "InternalName", "my_app"
25616      VALUE "LegalCopyright", "My Name"
25617      VALUE "OriginalFilename", "my_app.exe"
25618      VALUE "ProductName", "My App"
25619      VALUE "ProductVersion", "1.0"
25620    END
25621  END
25622
25623  BLOCK "VarFileInfo"
25624  BEGIN
25625    VALUE "Translation", 0x809, 1252
25626  END
25627END
25628@end example
25629@end quotation
25630
25631The value @code{0809} (langID) is for the U.K English language and
25632@code{04E4} (charsetID), which is equal to @code{1252} decimal, for
25633multilingual.
25634
25635This section explains how to build, compile and use resources. Note that this
25636section does not cover all resource objects, for a complete description see
25637the corresponding Microsoft documentation.
25638
25639@menu
25640* Building Resources::
25641* Compiling Resources::
25642* Using Resources::
25643
25644@end menu
25645
25646@node Building Resources,Compiling Resources,,GNAT and Windows Resources
25647@anchor{gnat_ugn/platform_specific_information building-resources}@anchor{216}@anchor{gnat_ugn/platform_specific_information id33}@anchor{217}
25648@subsubsection Building Resources
25649
25650
25651@geindex Resources
25652@geindex building
25653
25654A resource file is an ASCII file. By convention resource files have an
25655@code{.rc} extension.
25656The easiest way to build a resource file is to use Microsoft tools
25657such as @code{imagedit.exe} to build bitmaps, icons and cursors and
25658@code{dlgedit.exe} to build dialogs.
25659It is always possible to build an @code{.rc} file yourself by writing a
25660resource script.
25661
25662It is not our objective to explain how to write a resource file. A
25663complete description of the resource script language can be found in the
25664Microsoft documentation.
25665
25666@node Compiling Resources,Using Resources,Building Resources,GNAT and Windows Resources
25667@anchor{gnat_ugn/platform_specific_information compiling-resources}@anchor{218}@anchor{gnat_ugn/platform_specific_information id34}@anchor{219}
25668@subsubsection Compiling Resources
25669
25670
25671@geindex rc
25672
25673@geindex windres
25674
25675@geindex Resources
25676@geindex compiling
25677
25678This section describes how to build a GNAT-compatible (COFF) object file
25679containing the resources. This is done using the Resource Compiler
25680@code{windres} as follows:
25681
25682@quotation
25683
25684@example
25685$ windres -i myres.rc -o myres.o
25686@end example
25687@end quotation
25688
25689By default @code{windres} will run @code{gcc} to preprocess the @code{.rc}
25690file. You can specify an alternate preprocessor (usually named
25691@code{cpp.exe}) using the @code{windres} @code{--preprocessor}
25692parameter. A list of all possible options may be obtained by entering
25693the command @code{windres} @code{--help}.
25694
25695It is also possible to use the Microsoft resource compiler @code{rc.exe}
25696to produce a @code{.res} file (binary resource file). See the
25697corresponding Microsoft documentation for further details. In this case
25698you need to use @code{windres} to translate the @code{.res} file to a
25699GNAT-compatible object file as follows:
25700
25701@quotation
25702
25703@example
25704$ windres -i myres.res -o myres.o
25705@end example
25706@end quotation
25707
25708@node Using Resources,,Compiling Resources,GNAT and Windows Resources
25709@anchor{gnat_ugn/platform_specific_information using-resources}@anchor{21a}@anchor{gnat_ugn/platform_specific_information id35}@anchor{21b}
25710@subsubsection Using Resources
25711
25712
25713@geindex Resources
25714@geindex using
25715
25716To include the resource file in your program just add the
25717GNAT-compatible object file for the resource(s) to the linker
25718arguments. With @code{gnatmake} this is done by using the @code{-largs}
25719option:
25720
25721@quotation
25722
25723@example
25724$ gnatmake myprog -largs myres.o
25725@end example
25726@end quotation
25727
25728@node Using GNAT DLLs from Microsoft Visual Studio Applications,Debugging a DLL,GNAT and Windows Resources,Mixed-Language Programming on Windows
25729@anchor{gnat_ugn/platform_specific_information using-gnat-dll-from-msvs}@anchor{21c}@anchor{gnat_ugn/platform_specific_information using-gnat-dlls-from-microsoft-visual-studio-applications}@anchor{21d}
25730@subsubsection Using GNAT DLLs from Microsoft Visual Studio Applications
25731
25732
25733@geindex Microsoft Visual Studio
25734@geindex use with GNAT DLLs
25735
25736This section describes a common case of mixed GNAT/Microsoft Visual Studio
25737application development, where the main program is developed using MSVS, and
25738is linked with a DLL developed using GNAT. Such a mixed application should
25739be developed following the general guidelines outlined above; below is the
25740cookbook-style sequence of steps to follow:
25741
25742
25743@enumerate
25744
25745@item
25746First develop and build the GNAT shared library using a library project
25747(let's assume the project is @code{mylib.gpr}, producing the library @code{libmylib.dll}):
25748@end enumerate
25749
25750@quotation
25751
25752@example
25753$ gprbuild -p mylib.gpr
25754@end example
25755@end quotation
25756
25757
25758@enumerate 2
25759
25760@item
25761Produce a .def file for the symbols you need to interface with, either by
25762hand or automatically with possibly some manual adjustments
25763(see @ref{1fe,,Creating Definition File Automatically}):
25764@end enumerate
25765
25766@quotation
25767
25768@example
25769$ dlltool libmylib.dll -z libmylib.def --export-all-symbols
25770@end example
25771@end quotation
25772
25773
25774@enumerate 3
25775
25776@item
25777Make sure that MSVS command-line tools are accessible on the path.
25778
25779@item
25780Create the Microsoft-style import library (see @ref{201,,MSVS-Style Import Library}):
25781@end enumerate
25782
25783@quotation
25784
25785@example
25786$ lib -machine:IX86 -def:libmylib.def -out:libmylib.lib
25787@end example
25788@end quotation
25789
25790If you are using a 64-bit toolchain, the above becomes...
25791
25792@quotation
25793
25794@example
25795$ lib -machine:X64 -def:libmylib.def -out:libmylib.lib
25796@end example
25797@end quotation
25798
25799
25800@enumerate 5
25801
25802@item
25803Build the C main
25804@end enumerate
25805
25806@quotation
25807
25808@example
25809$ cl /O2 /MD main.c libmylib.lib
25810@end example
25811@end quotation
25812
25813
25814@enumerate 6
25815
25816@item
25817Before running the executable, make sure you have set the PATH to the DLL,
25818or copy the DLL into into the directory containing the .exe.
25819@end enumerate
25820
25821@node Debugging a DLL,Setting Stack Size from gnatlink,Using GNAT DLLs from Microsoft Visual Studio Applications,Mixed-Language Programming on Windows
25822@anchor{gnat_ugn/platform_specific_information id36}@anchor{21e}@anchor{gnat_ugn/platform_specific_information debugging-a-dll}@anchor{21f}
25823@subsubsection Debugging a DLL
25824
25825
25826@geindex DLL debugging
25827
25828Debugging a DLL is similar to debugging a standard program. But
25829we have to deal with two different executable parts: the DLL and the
25830program that uses it. We have the following four possibilities:
25831
25832
25833@itemize *
25834
25835@item
25836The program and the DLL are built with GCC/GNAT.
25837
25838@item
25839The program is built with foreign tools and the DLL is built with
25840GCC/GNAT.
25841
25842@item
25843The program is built with GCC/GNAT and the DLL is built with
25844foreign tools.
25845@end itemize
25846
25847In this section we address only cases one and two above.
25848There is no point in trying to debug
25849a DLL with GNU/GDB, if there is no GDB-compatible debugging
25850information in it. To do so you must use a debugger compatible with the
25851tools suite used to build the DLL.
25852
25853@menu
25854* Program and DLL Both Built with GCC/GNAT::
25855* Program Built with Foreign Tools and DLL Built with GCC/GNAT::
25856
25857@end menu
25858
25859@node Program and DLL Both Built with GCC/GNAT,Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Debugging a DLL
25860@anchor{gnat_ugn/platform_specific_information id37}@anchor{220}@anchor{gnat_ugn/platform_specific_information program-and-dll-both-built-with-gcc-gnat}@anchor{221}
25861@subsubsection Program and DLL Both Built with GCC/GNAT
25862
25863
25864This is the simplest case. Both the DLL and the program have @code{GDB}
25865compatible debugging information. It is then possible to break anywhere in
25866the process. Let's suppose here that the main procedure is named
25867@code{ada_main} and that in the DLL there is an entry point named
25868@code{ada_dll}.
25869
25870The DLL (@ref{1f7,,Introduction to Dynamic Link Libraries (DLLs)}) and
25871program must have been built with the debugging information (see GNAT -g
25872switch). Here are the step-by-step instructions for debugging it:
25873
25874
25875@itemize *
25876
25877@item
25878Launch @code{GDB} on the main program.
25879
25880@example
25881$ gdb -nw ada_main
25882@end example
25883
25884@item
25885Start the program and stop at the beginning of the main procedure
25886
25887@example
25888(gdb) start
25889@end example
25890
25891This step is required to be able to set a breakpoint inside the DLL. As long
25892as the program is not run, the DLL is not loaded. This has the
25893consequence that the DLL debugging information is also not loaded, so it is not
25894possible to set a breakpoint in the DLL.
25895
25896@item
25897Set a breakpoint inside the DLL
25898
25899@example
25900(gdb) break ada_dll
25901(gdb) cont
25902@end example
25903@end itemize
25904
25905At this stage a breakpoint is set inside the DLL. From there on
25906you can use the standard approach to debug the whole program
25907(@ref{24,,Running and Debugging Ada Programs}).
25908
25909@node Program Built with Foreign Tools and DLL Built with GCC/GNAT,,Program and DLL Both Built with GCC/GNAT,Debugging a DLL
25910@anchor{gnat_ugn/platform_specific_information program-built-with-foreign-tools-and-dll-built-with-gcc-gnat}@anchor{222}@anchor{gnat_ugn/platform_specific_information id38}@anchor{223}
25911@subsubsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
25912
25913
25914In this case things are slightly more complex because it is not possible to
25915start the main program and then break at the beginning to load the DLL and the
25916associated DLL debugging information. It is not possible to break at the
25917beginning of the program because there is no @code{GDB} debugging information,
25918and therefore there is no direct way of getting initial control. This
25919section addresses this issue by describing some methods that can be used
25920to break somewhere in the DLL to debug it.
25921
25922First suppose that the main procedure is named @code{main} (this is for
25923example some C code built with Microsoft Visual C) and that there is a
25924DLL named @code{test.dll} containing an Ada entry point named
25925@code{ada_dll}.
25926
25927The DLL (see @ref{1f7,,Introduction to Dynamic Link Libraries (DLLs)}) must have
25928been built with debugging information (see the GNAT @code{-g} option).
25929
25930@subsubheading Debugging the DLL Directly
25931
25932
25933
25934@itemize *
25935
25936@item
25937Find out the executable starting address
25938
25939@example
25940$ objdump --file-header main.exe
25941@end example
25942
25943The starting address is reported on the last line. For example:
25944
25945@example
25946main.exe:     file format pei-i386
25947architecture: i386, flags 0x0000010a:
25948EXEC_P, HAS_DEBUG, D_PAGED
25949start address 0x00401010
25950@end example
25951
25952@item
25953Launch the debugger on the executable.
25954
25955@example
25956$ gdb main.exe
25957@end example
25958
25959@item
25960Set a breakpoint at the starting address, and launch the program.
25961
25962@example
25963$ (gdb) break *0x00401010
25964$ (gdb) run
25965@end example
25966
25967The program will stop at the given address.
25968
25969@item
25970Set a breakpoint on a DLL subroutine.
25971
25972@example
25973(gdb) break ada_dll.adb:45
25974@end example
25975
25976Or if you want to break using a symbol on the DLL, you need first to
25977select the Ada language (language used by the DLL).
25978
25979@example
25980(gdb) set language ada
25981(gdb) break ada_dll
25982@end example
25983
25984@item
25985Continue the program.
25986
25987@example
25988(gdb) cont
25989@end example
25990
25991This will run the program until it reaches the breakpoint that has been
25992set. From that point you can use the standard way to debug a program
25993as described in (@ref{24,,Running and Debugging Ada Programs}).
25994@end itemize
25995
25996It is also possible to debug the DLL by attaching to a running process.
25997
25998@subsubheading Attaching to a Running Process
25999
26000
26001@geindex DLL debugging
26002@geindex attach to process
26003
26004With @code{GDB} it is always possible to debug a running process by
26005attaching to it. It is possible to debug a DLL this way. The limitation
26006of this approach is that the DLL must run long enough to perform the
26007attach operation. It may be useful for instance to insert a time wasting
26008loop in the code of the DLL to meet this criterion.
26009
26010
26011@itemize *
26012
26013@item
26014Launch the main program @code{main.exe}.
26015
26016@example
26017$ main
26018@end example
26019
26020@item
26021Use the Windows @emph{Task Manager} to find the process ID. Let's say
26022that the process PID for @code{main.exe} is 208.
26023
26024@item
26025Launch gdb.
26026
26027@example
26028$ gdb
26029@end example
26030
26031@item
26032Attach to the running process to be debugged.
26033
26034@example
26035(gdb) attach 208
26036@end example
26037
26038@item
26039Load the process debugging information.
26040
26041@example
26042(gdb) symbol-file main.exe
26043@end example
26044
26045@item
26046Break somewhere in the DLL.
26047
26048@example
26049(gdb) break ada_dll
26050@end example
26051
26052@item
26053Continue process execution.
26054
26055@example
26056(gdb) cont
26057@end example
26058@end itemize
26059
26060This last step will resume the process execution, and stop at
26061the breakpoint we have set. From there you can use the standard
26062approach to debug a program as described in
26063@ref{24,,Running and Debugging Ada Programs}.
26064
26065@node Setting Stack Size from gnatlink,Setting Heap Size from gnatlink,Debugging a DLL,Mixed-Language Programming on Windows
26066@anchor{gnat_ugn/platform_specific_information setting-stack-size-from-gnatlink}@anchor{136}@anchor{gnat_ugn/platform_specific_information id39}@anchor{224}
26067@subsubsection Setting Stack Size from @code{gnatlink}
26068
26069
26070It is possible to specify the program stack size at link time. On modern
26071versions of Windows, starting with XP, this is mostly useful to set the size of
26072the main stack (environment task). The other task stacks are set with pragma
26073Storage_Size or with the @emph{gnatbind -d} command.
26074
26075Since older versions of Windows (2000, NT4, etc.) do not allow setting the
26076reserve size of individual tasks, the link-time stack size applies to all
26077tasks, and pragma Storage_Size has no effect.
26078In particular, Stack Overflow checks are made against this
26079link-time specified size.
26080
26081This setting can be done with @code{gnatlink} using either of the following:
26082
26083
26084@itemize *
26085
26086@item
26087@code{-Xlinker} linker option
26088
26089@example
26090$ gnatlink hello -Xlinker --stack=0x10000,0x1000
26091@end example
26092
26093This sets the stack reserve size to 0x10000 bytes and the stack commit
26094size to 0x1000 bytes.
26095
26096@item
26097@code{-Wl} linker option
26098
26099@example
26100$ gnatlink hello -Wl,--stack=0x1000000
26101@end example
26102
26103This sets the stack reserve size to 0x1000000 bytes. Note that with
26104@code{-Wl} option it is not possible to set the stack commit size
26105because the comma is a separator for this option.
26106@end itemize
26107
26108@node Setting Heap Size from gnatlink,,Setting Stack Size from gnatlink,Mixed-Language Programming on Windows
26109@anchor{gnat_ugn/platform_specific_information setting-heap-size-from-gnatlink}@anchor{137}@anchor{gnat_ugn/platform_specific_information id40}@anchor{225}
26110@subsubsection Setting Heap Size from @code{gnatlink}
26111
26112
26113Under Windows systems, it is possible to specify the program heap size from
26114@code{gnatlink} using either of the following:
26115
26116
26117@itemize *
26118
26119@item
26120@code{-Xlinker} linker option
26121
26122@example
26123$ gnatlink hello -Xlinker --heap=0x10000,0x1000
26124@end example
26125
26126This sets the heap reserve size to 0x10000 bytes and the heap commit
26127size to 0x1000 bytes.
26128
26129@item
26130@code{-Wl} linker option
26131
26132@example
26133$ gnatlink hello -Wl,--heap=0x1000000
26134@end example
26135
26136This sets the heap reserve size to 0x1000000 bytes. Note that with
26137@code{-Wl} option it is not possible to set the heap commit size
26138because the comma is a separator for this option.
26139@end itemize
26140
26141@node Windows Specific Add-Ons,,Mixed-Language Programming on Windows,Microsoft Windows Topics
26142@anchor{gnat_ugn/platform_specific_information windows-specific-add-ons}@anchor{226}@anchor{gnat_ugn/platform_specific_information win32-specific-addons}@anchor{227}
26143@subsection Windows Specific Add-Ons
26144
26145
26146This section describes the Windows specific add-ons.
26147
26148@menu
26149* Win32Ada::
26150* wPOSIX::
26151
26152@end menu
26153
26154@node Win32Ada,wPOSIX,,Windows Specific Add-Ons
26155@anchor{gnat_ugn/platform_specific_information win32ada}@anchor{228}@anchor{gnat_ugn/platform_specific_information id41}@anchor{229}
26156@subsubsection Win32Ada
26157
26158
26159Win32Ada is a binding for the Microsoft Win32 API. This binding can be
26160easily installed from the provided installer. To use the Win32Ada
26161binding you need to use a project file, and adding a single with_clause
26162will give you full access to the Win32Ada binding sources and ensure
26163that the proper libraries are passed to the linker.
26164
26165@quotation
26166
26167@example
26168with "win32ada";
26169project P is
26170   for Sources use ...;
26171end P;
26172@end example
26173@end quotation
26174
26175To build the application you just need to call gprbuild for the
26176application's project, here p.gpr:
26177
26178@quotation
26179
26180@example
26181gprbuild p.gpr
26182@end example
26183@end quotation
26184
26185@node wPOSIX,,Win32Ada,Windows Specific Add-Ons
26186@anchor{gnat_ugn/platform_specific_information id42}@anchor{22a}@anchor{gnat_ugn/platform_specific_information wposix}@anchor{22b}
26187@subsubsection wPOSIX
26188
26189
26190wPOSIX is a minimal POSIX binding whose goal is to help with building
26191cross-platforms applications. This binding is not complete though, as
26192the Win32 API does not provide the necessary support for all POSIX APIs.
26193
26194To use the wPOSIX binding you need to use a project file, and adding
26195a single with_clause will give you full access to the wPOSIX binding
26196sources and ensure that the proper libraries are passed to the linker.
26197
26198@quotation
26199
26200@example
26201with "wposix";
26202project P is
26203   for Sources use ...;
26204end P;
26205@end example
26206@end quotation
26207
26208To build the application you just need to call gprbuild for the
26209application's project, here p.gpr:
26210
26211@quotation
26212
26213@example
26214gprbuild p.gpr
26215@end example
26216@end quotation
26217
26218@node Mac OS Topics,,Microsoft Windows Topics,Platform-Specific Information
26219@anchor{gnat_ugn/platform_specific_information mac-os-topics}@anchor{2d}@anchor{gnat_ugn/platform_specific_information id43}@anchor{22c}
26220@section Mac OS Topics
26221
26222
26223@geindex OS X
26224
26225This section describes topics that are specific to Apple's OS X
26226platform.
26227
26228@menu
26229* Codesigning the Debugger::
26230
26231@end menu
26232
26233@node Codesigning the Debugger,,,Mac OS Topics
26234@anchor{gnat_ugn/platform_specific_information codesigning-the-debugger}@anchor{22d}
26235@subsection Codesigning the Debugger
26236
26237
26238The Darwin Kernel requires the debugger to have special permissions
26239before it is allowed to control other processes. These permissions
26240are granted by codesigning the GDB executable. Without these
26241permissions, the debugger will report error messages such as:
26242
26243@example
26244Starting program: /x/y/foo
26245Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
26246(please check gdb is codesigned - see taskgated(8))
26247@end example
26248
26249Codesigning requires a certificate.  The following procedure explains
26250how to create one:
26251
26252
26253@itemize *
26254
26255@item
26256Start the Keychain Access application (in
26257/Applications/Utilities/Keychain Access.app)
26258
26259@item
26260Select the Keychain Access -> Certificate Assistant ->
26261Create a Certificate... menu
26262
26263@item
26264Then:
26265
26266
26267@itemize *
26268
26269@item
26270Choose a name for the new certificate (this procedure will use
26271"gdb-cert" as an example)
26272
26273@item
26274Set "Identity Type" to "Self Signed Root"
26275
26276@item
26277Set "Certificate Type" to "Code Signing"
26278
26279@item
26280Activate the "Let me override defaults" option
26281@end itemize
26282
26283@item
26284Click several times on "Continue" until the "Specify a Location
26285For The Certificate" screen appears, then set "Keychain" to "System"
26286
26287@item
26288Click on "Continue" until the certificate is created
26289
26290@item
26291Finally, in the view, double-click on the new certificate,
26292and set "When using this certificate" to "Always Trust"
26293
26294@item
26295Exit the Keychain Access application and restart the computer
26296(this is unfortunately required)
26297@end itemize
26298
26299Once a certificate has been created, the debugger can be codesigned
26300as follow. In a Terminal, run the following command:
26301
26302@quotation
26303
26304@example
26305$ codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
26306@end example
26307@end quotation
26308
26309where "gdb-cert" should be replaced by the actual certificate
26310name chosen above, and <gnat_install_prefix> should be replaced by
26311the location where you installed GNAT.  Also, be sure that users are
26312in the Unix group @code{_developer}.
26313
26314@node Example of Binder Output File,Elaboration Order Handling in GNAT,Platform-Specific Information,Top
26315@anchor{gnat_ugn/example_of_binder_output example-of-binder-output-file}@anchor{e}@anchor{gnat_ugn/example_of_binder_output doc}@anchor{22e}@anchor{gnat_ugn/example_of_binder_output id1}@anchor{22f}
26316@chapter Example of Binder Output File
26317
26318
26319@geindex Binder output (example)
26320
26321This Appendix displays the source code for the output file
26322generated by @emph{gnatbind} for a simple 'Hello World' program.
26323Comments have been added for clarification purposes.
26324
26325@example
26326--  The package is called Ada_Main unless this name is actually used
26327--  as a unit name in the partition, in which case some other unique
26328--  name is used.
26329
26330pragma Ada_95;
26331with System;
26332package ada_main is
26333   pragma Warnings (Off);
26334
26335   --  The main program saves the parameters (argument count,
26336   --  argument values, environment pointer) in global variables
26337   --  for later access by other units including
26338   --  Ada.Command_Line.
26339
26340   gnat_argc : Integer;
26341   gnat_argv : System.Address;
26342   gnat_envp : System.Address;
26343
26344   --  The actual variables are stored in a library routine. This
26345   --  is useful for some shared library situations, where there
26346   --  are problems if variables are not in the library.
26347
26348   pragma Import (C, gnat_argc);
26349   pragma Import (C, gnat_argv);
26350   pragma Import (C, gnat_envp);
26351
26352   --  The exit status is similarly an external location
26353
26354   gnat_exit_status : Integer;
26355   pragma Import (C, gnat_exit_status);
26356
26357   GNAT_Version : constant String :=
26358                    "GNAT Version: Pro 7.4.0w (20141119-49)" & ASCII.NUL;
26359   pragma Export (C, GNAT_Version, "__gnat_version");
26360
26361   Ada_Main_Program_Name : constant String := "_ada_hello" & ASCII.NUL;
26362   pragma Export (C, Ada_Main_Program_Name, "__gnat_ada_main_program_name");
26363
26364   --  This is the generated adainit routine that performs
26365   --  initialization at the start of execution. In the case
26366   --  where Ada is the main program, this main program makes
26367   --  a call to adainit at program startup.
26368
26369   procedure adainit;
26370   pragma Export (C, adainit, "adainit");
26371
26372   --  This is the generated adafinal routine that performs
26373   --  finalization at the end of execution. In the case where
26374   --  Ada is the main program, this main program makes a call
26375   --  to adafinal at program termination.
26376
26377   procedure adafinal;
26378   pragma Export (C, adafinal, "adafinal");
26379
26380   --  This routine is called at the start of execution. It is
26381   --  a dummy routine that is used by the debugger to breakpoint
26382   --  at the start of execution.
26383
26384   --  This is the actual generated main program (it would be
26385   --  suppressed if the no main program switch were used). As
26386   --  required by standard system conventions, this program has
26387   --  the external name main.
26388
26389   function main
26390     (argc : Integer;
26391      argv : System.Address;
26392      envp : System.Address)
26393      return Integer;
26394   pragma Export (C, main, "main");
26395
26396   --  The following set of constants give the version
26397   --  identification values for every unit in the bound
26398   --  partition. This identification is computed from all
26399   --  dependent semantic units, and corresponds to the
26400   --  string that would be returned by use of the
26401   --  Body_Version or Version attributes.
26402
26403   --  The following Export pragmas export the version numbers
26404   --  with symbolic names ending in B (for body) or S
26405   --  (for spec) so that they can be located in a link. The
26406   --  information provided here is sufficient to track down
26407   --  the exact versions of units used in a given build.
26408
26409   type Version_32 is mod 2 ** 32;
26410   u00001 : constant Version_32 := 16#8ad6e54a#;
26411   pragma Export (C, u00001, "helloB");
26412   u00002 : constant Version_32 := 16#fbff4c67#;
26413   pragma Export (C, u00002, "system__standard_libraryB");
26414   u00003 : constant Version_32 := 16#1ec6fd90#;
26415   pragma Export (C, u00003, "system__standard_libraryS");
26416   u00004 : constant Version_32 := 16#3ffc8e18#;
26417   pragma Export (C, u00004, "adaS");
26418   u00005 : constant Version_32 := 16#28f088c2#;
26419   pragma Export (C, u00005, "ada__text_ioB");
26420   u00006 : constant Version_32 := 16#f372c8ac#;
26421   pragma Export (C, u00006, "ada__text_ioS");
26422   u00007 : constant Version_32 := 16#2c143749#;
26423   pragma Export (C, u00007, "ada__exceptionsB");
26424   u00008 : constant Version_32 := 16#f4f0cce8#;
26425   pragma Export (C, u00008, "ada__exceptionsS");
26426   u00009 : constant Version_32 := 16#a46739c0#;
26427   pragma Export (C, u00009, "ada__exceptions__last_chance_handlerB");
26428   u00010 : constant Version_32 := 16#3aac8c92#;
26429   pragma Export (C, u00010, "ada__exceptions__last_chance_handlerS");
26430   u00011 : constant Version_32 := 16#1d274481#;
26431   pragma Export (C, u00011, "systemS");
26432   u00012 : constant Version_32 := 16#a207fefe#;
26433   pragma Export (C, u00012, "system__soft_linksB");
26434   u00013 : constant Version_32 := 16#467d9556#;
26435   pragma Export (C, u00013, "system__soft_linksS");
26436   u00014 : constant Version_32 := 16#b01dad17#;
26437   pragma Export (C, u00014, "system__parametersB");
26438   u00015 : constant Version_32 := 16#630d49fe#;
26439   pragma Export (C, u00015, "system__parametersS");
26440   u00016 : constant Version_32 := 16#b19b6653#;
26441   pragma Export (C, u00016, "system__secondary_stackB");
26442   u00017 : constant Version_32 := 16#b6468be8#;
26443   pragma Export (C, u00017, "system__secondary_stackS");
26444   u00018 : constant Version_32 := 16#39a03df9#;
26445   pragma Export (C, u00018, "system__storage_elementsB");
26446   u00019 : constant Version_32 := 16#30e40e85#;
26447   pragma Export (C, u00019, "system__storage_elementsS");
26448   u00020 : constant Version_32 := 16#41837d1e#;
26449   pragma Export (C, u00020, "system__stack_checkingB");
26450   u00021 : constant Version_32 := 16#93982f69#;
26451   pragma Export (C, u00021, "system__stack_checkingS");
26452   u00022 : constant Version_32 := 16#393398c1#;
26453   pragma Export (C, u00022, "system__exception_tableB");
26454   u00023 : constant Version_32 := 16#b33e2294#;
26455   pragma Export (C, u00023, "system__exception_tableS");
26456   u00024 : constant Version_32 := 16#ce4af020#;
26457   pragma Export (C, u00024, "system__exceptionsB");
26458   u00025 : constant Version_32 := 16#75442977#;
26459   pragma Export (C, u00025, "system__exceptionsS");
26460   u00026 : constant Version_32 := 16#37d758f1#;
26461   pragma Export (C, u00026, "system__exceptions__machineS");
26462   u00027 : constant Version_32 := 16#b895431d#;
26463   pragma Export (C, u00027, "system__exceptions_debugB");
26464   u00028 : constant Version_32 := 16#aec55d3f#;
26465   pragma Export (C, u00028, "system__exceptions_debugS");
26466   u00029 : constant Version_32 := 16#570325c8#;
26467   pragma Export (C, u00029, "system__img_intB");
26468   u00030 : constant Version_32 := 16#1ffca443#;
26469   pragma Export (C, u00030, "system__img_intS");
26470   u00031 : constant Version_32 := 16#b98c3e16#;
26471   pragma Export (C, u00031, "system__tracebackB");
26472   u00032 : constant Version_32 := 16#831a9d5a#;
26473   pragma Export (C, u00032, "system__tracebackS");
26474   u00033 : constant Version_32 := 16#9ed49525#;
26475   pragma Export (C, u00033, "system__traceback_entriesB");
26476   u00034 : constant Version_32 := 16#1d7cb2f1#;
26477   pragma Export (C, u00034, "system__traceback_entriesS");
26478   u00035 : constant Version_32 := 16#8c33a517#;
26479   pragma Export (C, u00035, "system__wch_conB");
26480   u00036 : constant Version_32 := 16#065a6653#;
26481   pragma Export (C, u00036, "system__wch_conS");
26482   u00037 : constant Version_32 := 16#9721e840#;
26483   pragma Export (C, u00037, "system__wch_stwB");
26484   u00038 : constant Version_32 := 16#2b4b4a52#;
26485   pragma Export (C, u00038, "system__wch_stwS");
26486   u00039 : constant Version_32 := 16#92b797cb#;
26487   pragma Export (C, u00039, "system__wch_cnvB");
26488   u00040 : constant Version_32 := 16#09eddca0#;
26489   pragma Export (C, u00040, "system__wch_cnvS");
26490   u00041 : constant Version_32 := 16#6033a23f#;
26491   pragma Export (C, u00041, "interfacesS");
26492   u00042 : constant Version_32 := 16#ece6fdb6#;
26493   pragma Export (C, u00042, "system__wch_jisB");
26494   u00043 : constant Version_32 := 16#899dc581#;
26495   pragma Export (C, u00043, "system__wch_jisS");
26496   u00044 : constant Version_32 := 16#10558b11#;
26497   pragma Export (C, u00044, "ada__streamsB");
26498   u00045 : constant Version_32 := 16#2e6701ab#;
26499   pragma Export (C, u00045, "ada__streamsS");
26500   u00046 : constant Version_32 := 16#db5c917c#;
26501   pragma Export (C, u00046, "ada__io_exceptionsS");
26502   u00047 : constant Version_32 := 16#12c8cd7d#;
26503   pragma Export (C, u00047, "ada__tagsB");
26504   u00048 : constant Version_32 := 16#ce72c228#;
26505   pragma Export (C, u00048, "ada__tagsS");
26506   u00049 : constant Version_32 := 16#c3335bfd#;
26507   pragma Export (C, u00049, "system__htableB");
26508   u00050 : constant Version_32 := 16#99e5f76b#;
26509   pragma Export (C, u00050, "system__htableS");
26510   u00051 : constant Version_32 := 16#089f5cd0#;
26511   pragma Export (C, u00051, "system__string_hashB");
26512   u00052 : constant Version_32 := 16#3bbb9c15#;
26513   pragma Export (C, u00052, "system__string_hashS");
26514   u00053 : constant Version_32 := 16#807fe041#;
26515   pragma Export (C, u00053, "system__unsigned_typesS");
26516   u00054 : constant Version_32 := 16#d27be59e#;
26517   pragma Export (C, u00054, "system__val_lluB");
26518   u00055 : constant Version_32 := 16#fa8db733#;
26519   pragma Export (C, u00055, "system__val_lluS");
26520   u00056 : constant Version_32 := 16#27b600b2#;
26521   pragma Export (C, u00056, "system__val_utilB");
26522   u00057 : constant Version_32 := 16#b187f27f#;
26523   pragma Export (C, u00057, "system__val_utilS");
26524   u00058 : constant Version_32 := 16#d1060688#;
26525   pragma Export (C, u00058, "system__case_utilB");
26526   u00059 : constant Version_32 := 16#392e2d56#;
26527   pragma Export (C, u00059, "system__case_utilS");
26528   u00060 : constant Version_32 := 16#84a27f0d#;
26529   pragma Export (C, u00060, "interfaces__c_streamsB");
26530   u00061 : constant Version_32 := 16#8bb5f2c0#;
26531   pragma Export (C, u00061, "interfaces__c_streamsS");
26532   u00062 : constant Version_32 := 16#6db6928f#;
26533   pragma Export (C, u00062, "system__crtlS");
26534   u00063 : constant Version_32 := 16#4e6a342b#;
26535   pragma Export (C, u00063, "system__file_ioB");
26536   u00064 : constant Version_32 := 16#ba56a5e4#;
26537   pragma Export (C, u00064, "system__file_ioS");
26538   u00065 : constant Version_32 := 16#b7ab275c#;
26539   pragma Export (C, u00065, "ada__finalizationB");
26540   u00066 : constant Version_32 := 16#19f764ca#;
26541   pragma Export (C, u00066, "ada__finalizationS");
26542   u00067 : constant Version_32 := 16#95817ed8#;
26543   pragma Export (C, u00067, "system__finalization_rootB");
26544   u00068 : constant Version_32 := 16#52d53711#;
26545   pragma Export (C, u00068, "system__finalization_rootS");
26546   u00069 : constant Version_32 := 16#769e25e6#;
26547   pragma Export (C, u00069, "interfaces__cB");
26548   u00070 : constant Version_32 := 16#4a38bedb#;
26549   pragma Export (C, u00070, "interfaces__cS");
26550   u00071 : constant Version_32 := 16#07e6ee66#;
26551   pragma Export (C, u00071, "system__os_libB");
26552   u00072 : constant Version_32 := 16#d7b69782#;
26553   pragma Export (C, u00072, "system__os_libS");
26554   u00073 : constant Version_32 := 16#1a817b8e#;
26555   pragma Export (C, u00073, "system__stringsB");
26556   u00074 : constant Version_32 := 16#639855e7#;
26557   pragma Export (C, u00074, "system__stringsS");
26558   u00075 : constant Version_32 := 16#e0b8de29#;
26559   pragma Export (C, u00075, "system__file_control_blockS");
26560   u00076 : constant Version_32 := 16#b5b2aca1#;
26561   pragma Export (C, u00076, "system__finalization_mastersB");
26562   u00077 : constant Version_32 := 16#69316dc1#;
26563   pragma Export (C, u00077, "system__finalization_mastersS");
26564   u00078 : constant Version_32 := 16#57a37a42#;
26565   pragma Export (C, u00078, "system__address_imageB");
26566   u00079 : constant Version_32 := 16#bccbd9bb#;
26567   pragma Export (C, u00079, "system__address_imageS");
26568   u00080 : constant Version_32 := 16#7268f812#;
26569   pragma Export (C, u00080, "system__img_boolB");
26570   u00081 : constant Version_32 := 16#e8fe356a#;
26571   pragma Export (C, u00081, "system__img_boolS");
26572   u00082 : constant Version_32 := 16#d7aac20c#;
26573   pragma Export (C, u00082, "system__ioB");
26574   u00083 : constant Version_32 := 16#8365b3ce#;
26575   pragma Export (C, u00083, "system__ioS");
26576   u00084 : constant Version_32 := 16#6d4d969a#;
26577   pragma Export (C, u00084, "system__storage_poolsB");
26578   u00085 : constant Version_32 := 16#e87cc305#;
26579   pragma Export (C, u00085, "system__storage_poolsS");
26580   u00086 : constant Version_32 := 16#e34550ca#;
26581   pragma Export (C, u00086, "system__pool_globalB");
26582   u00087 : constant Version_32 := 16#c88d2d16#;
26583   pragma Export (C, u00087, "system__pool_globalS");
26584   u00088 : constant Version_32 := 16#9d39c675#;
26585   pragma Export (C, u00088, "system__memoryB");
26586   u00089 : constant Version_32 := 16#445a22b5#;
26587   pragma Export (C, u00089, "system__memoryS");
26588   u00090 : constant Version_32 := 16#6a859064#;
26589   pragma Export (C, u00090, "system__storage_pools__subpoolsB");
26590   u00091 : constant Version_32 := 16#e3b008dc#;
26591   pragma Export (C, u00091, "system__storage_pools__subpoolsS");
26592   u00092 : constant Version_32 := 16#63f11652#;
26593   pragma Export (C, u00092, "system__storage_pools__subpools__finalizationB");
26594   u00093 : constant Version_32 := 16#fe2f4b3a#;
26595   pragma Export (C, u00093, "system__storage_pools__subpools__finalizationS");
26596
26597   --  BEGIN ELABORATION ORDER
26598   --  ada%s
26599   --  interfaces%s
26600   --  system%s
26601   --  system.case_util%s
26602   --  system.case_util%b
26603   --  system.htable%s
26604   --  system.img_bool%s
26605   --  system.img_bool%b
26606   --  system.img_int%s
26607   --  system.img_int%b
26608   --  system.io%s
26609   --  system.io%b
26610   --  system.parameters%s
26611   --  system.parameters%b
26612   --  system.crtl%s
26613   --  interfaces.c_streams%s
26614   --  interfaces.c_streams%b
26615   --  system.standard_library%s
26616   --  system.exceptions_debug%s
26617   --  system.exceptions_debug%b
26618   --  system.storage_elements%s
26619   --  system.storage_elements%b
26620   --  system.stack_checking%s
26621   --  system.stack_checking%b
26622   --  system.string_hash%s
26623   --  system.string_hash%b
26624   --  system.htable%b
26625   --  system.strings%s
26626   --  system.strings%b
26627   --  system.os_lib%s
26628   --  system.traceback_entries%s
26629   --  system.traceback_entries%b
26630   --  ada.exceptions%s
26631   --  system.soft_links%s
26632   --  system.unsigned_types%s
26633   --  system.val_llu%s
26634   --  system.val_util%s
26635   --  system.val_util%b
26636   --  system.val_llu%b
26637   --  system.wch_con%s
26638   --  system.wch_con%b
26639   --  system.wch_cnv%s
26640   --  system.wch_jis%s
26641   --  system.wch_jis%b
26642   --  system.wch_cnv%b
26643   --  system.wch_stw%s
26644   --  system.wch_stw%b
26645   --  ada.exceptions.last_chance_handler%s
26646   --  ada.exceptions.last_chance_handler%b
26647   --  system.address_image%s
26648   --  system.exception_table%s
26649   --  system.exception_table%b
26650   --  ada.io_exceptions%s
26651   --  ada.tags%s
26652   --  ada.streams%s
26653   --  ada.streams%b
26654   --  interfaces.c%s
26655   --  system.exceptions%s
26656   --  system.exceptions%b
26657   --  system.exceptions.machine%s
26658   --  system.finalization_root%s
26659   --  system.finalization_root%b
26660   --  ada.finalization%s
26661   --  ada.finalization%b
26662   --  system.storage_pools%s
26663   --  system.storage_pools%b
26664   --  system.finalization_masters%s
26665   --  system.storage_pools.subpools%s
26666   --  system.storage_pools.subpools.finalization%s
26667   --  system.storage_pools.subpools.finalization%b
26668   --  system.memory%s
26669   --  system.memory%b
26670   --  system.standard_library%b
26671   --  system.pool_global%s
26672   --  system.pool_global%b
26673   --  system.file_control_block%s
26674   --  system.file_io%s
26675   --  system.secondary_stack%s
26676   --  system.file_io%b
26677   --  system.storage_pools.subpools%b
26678   --  system.finalization_masters%b
26679   --  interfaces.c%b
26680   --  ada.tags%b
26681   --  system.soft_links%b
26682   --  system.os_lib%b
26683   --  system.secondary_stack%b
26684   --  system.address_image%b
26685   --  system.traceback%s
26686   --  ada.exceptions%b
26687   --  system.traceback%b
26688   --  ada.text_io%s
26689   --  ada.text_io%b
26690   --  hello%b
26691   --  END ELABORATION ORDER
26692
26693end ada_main;
26694@end example
26695
26696@example
26697pragma Ada_95;
26698--  The following source file name pragmas allow the generated file
26699--  names to be unique for different main programs. They are needed
26700--  since the package name will always be Ada_Main.
26701
26702pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
26703pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
26704
26705pragma Suppress (Overflow_Check);
26706with Ada.Exceptions;
26707
26708--  Generated package body for Ada_Main starts here
26709
26710package body ada_main is
26711   pragma Warnings (Off);
26712
26713   --  These values are reference counter associated to units which have
26714   --  been elaborated. It is also used to avoid elaborating the
26715   --  same unit twice.
26716
26717   E72 : Short_Integer; pragma Import (Ada, E72, "system__os_lib_E");
26718   E13 : Short_Integer; pragma Import (Ada, E13, "system__soft_links_E");
26719   E23 : Short_Integer; pragma Import (Ada, E23, "system__exception_table_E");
26720   E46 : Short_Integer; pragma Import (Ada, E46, "ada__io_exceptions_E");
26721   E48 : Short_Integer; pragma Import (Ada, E48, "ada__tags_E");
26722   E45 : Short_Integer; pragma Import (Ada, E45, "ada__streams_E");
26723   E70 : Short_Integer; pragma Import (Ada, E70, "interfaces__c_E");
26724   E25 : Short_Integer; pragma Import (Ada, E25, "system__exceptions_E");
26725   E68 : Short_Integer; pragma Import (Ada, E68, "system__finalization_root_E");
26726   E66 : Short_Integer; pragma Import (Ada, E66, "ada__finalization_E");
26727   E85 : Short_Integer; pragma Import (Ada, E85, "system__storage_pools_E");
26728   E77 : Short_Integer; pragma Import (Ada, E77, "system__finalization_masters_E");
26729   E91 : Short_Integer; pragma Import (Ada, E91, "system__storage_pools__subpools_E");
26730   E87 : Short_Integer; pragma Import (Ada, E87, "system__pool_global_E");
26731   E75 : Short_Integer; pragma Import (Ada, E75, "system__file_control_block_E");
26732   E64 : Short_Integer; pragma Import (Ada, E64, "system__file_io_E");
26733   E17 : Short_Integer; pragma Import (Ada, E17, "system__secondary_stack_E");
26734   E06 : Short_Integer; pragma Import (Ada, E06, "ada__text_io_E");
26735
26736   Local_Priority_Specific_Dispatching : constant String := "";
26737   Local_Interrupt_States : constant String := "";
26738
26739   Is_Elaborated : Boolean := False;
26740
26741   procedure finalize_library is
26742   begin
26743      E06 := E06 - 1;
26744      declare
26745         procedure F1;
26746         pragma Import (Ada, F1, "ada__text_io__finalize_spec");
26747      begin
26748         F1;
26749      end;
26750      E77 := E77 - 1;
26751      E91 := E91 - 1;
26752      declare
26753         procedure F2;
26754         pragma Import (Ada, F2, "system__file_io__finalize_body");
26755      begin
26756         E64 := E64 - 1;
26757         F2;
26758      end;
26759      declare
26760         procedure F3;
26761         pragma Import (Ada, F3, "system__file_control_block__finalize_spec");
26762      begin
26763         E75 := E75 - 1;
26764         F3;
26765      end;
26766      E87 := E87 - 1;
26767      declare
26768         procedure F4;
26769         pragma Import (Ada, F4, "system__pool_global__finalize_spec");
26770      begin
26771         F4;
26772      end;
26773      declare
26774         procedure F5;
26775         pragma Import (Ada, F5, "system__storage_pools__subpools__finalize_spec");
26776      begin
26777         F5;
26778      end;
26779      declare
26780         procedure F6;
26781         pragma Import (Ada, F6, "system__finalization_masters__finalize_spec");
26782      begin
26783         F6;
26784      end;
26785      declare
26786         procedure Reraise_Library_Exception_If_Any;
26787         pragma Import (Ada, Reraise_Library_Exception_If_Any, "__gnat_reraise_library_exception_if_any");
26788      begin
26789         Reraise_Library_Exception_If_Any;
26790      end;
26791   end finalize_library;
26792
26793   -------------
26794   -- adainit --
26795   -------------
26796
26797   procedure adainit is
26798
26799      Main_Priority : Integer;
26800      pragma Import (C, Main_Priority, "__gl_main_priority");
26801      Time_Slice_Value : Integer;
26802      pragma Import (C, Time_Slice_Value, "__gl_time_slice_val");
26803      WC_Encoding : Character;
26804      pragma Import (C, WC_Encoding, "__gl_wc_encoding");
26805      Locking_Policy : Character;
26806      pragma Import (C, Locking_Policy, "__gl_locking_policy");
26807      Queuing_Policy : Character;
26808      pragma Import (C, Queuing_Policy, "__gl_queuing_policy");
26809      Task_Dispatching_Policy : Character;
26810      pragma Import (C, Task_Dispatching_Policy, "__gl_task_dispatching_policy");
26811      Priority_Specific_Dispatching : System.Address;
26812      pragma Import (C, Priority_Specific_Dispatching, "__gl_priority_specific_dispatching");
26813      Num_Specific_Dispatching : Integer;
26814      pragma Import (C, Num_Specific_Dispatching, "__gl_num_specific_dispatching");
26815      Main_CPU : Integer;
26816      pragma Import (C, Main_CPU, "__gl_main_cpu");
26817      Interrupt_States : System.Address;
26818      pragma Import (C, Interrupt_States, "__gl_interrupt_states");
26819      Num_Interrupt_States : Integer;
26820      pragma Import (C, Num_Interrupt_States, "__gl_num_interrupt_states");
26821      Unreserve_All_Interrupts : Integer;
26822      pragma Import (C, Unreserve_All_Interrupts, "__gl_unreserve_all_interrupts");
26823      Detect_Blocking : Integer;
26824      pragma Import (C, Detect_Blocking, "__gl_detect_blocking");
26825      Default_Stack_Size : Integer;
26826      pragma Import (C, Default_Stack_Size, "__gl_default_stack_size");
26827      Leap_Seconds_Support : Integer;
26828      pragma Import (C, Leap_Seconds_Support, "__gl_leap_seconds_support");
26829
26830      procedure Runtime_Initialize;
26831      pragma Import (C, Runtime_Initialize, "__gnat_runtime_initialize");
26832
26833      Finalize_Library_Objects : No_Param_Proc;
26834      pragma Import (C, Finalize_Library_Objects, "__gnat_finalize_library_objects");
26835
26836   --  Start of processing for adainit
26837
26838   begin
26839
26840      --  Record various information for this partition.  The values
26841      --  are derived by the binder from information stored in the ali
26842      --  files by the compiler.
26843
26844      if Is_Elaborated then
26845         return;
26846      end if;
26847      Is_Elaborated := True;
26848      Main_Priority := -1;
26849      Time_Slice_Value := -1;
26850      WC_Encoding := 'b';
26851      Locking_Policy := ' ';
26852      Queuing_Policy := ' ';
26853      Task_Dispatching_Policy := ' ';
26854      Priority_Specific_Dispatching :=
26855        Local_Priority_Specific_Dispatching'Address;
26856      Num_Specific_Dispatching := 0;
26857      Main_CPU := -1;
26858      Interrupt_States := Local_Interrupt_States'Address;
26859      Num_Interrupt_States := 0;
26860      Unreserve_All_Interrupts := 0;
26861      Detect_Blocking := 0;
26862      Default_Stack_Size := -1;
26863      Leap_Seconds_Support := 0;
26864
26865      Runtime_Initialize;
26866
26867      Finalize_Library_Objects := finalize_library'access;
26868
26869      --  Now we have the elaboration calls for all units in the partition.
26870      --  The Elab_Spec and Elab_Body attributes generate references to the
26871      --  implicit elaboration procedures generated by the compiler for
26872      --  each unit that requires elaboration. Increment a counter of
26873      --  reference for each unit.
26874
26875      System.Soft_Links'Elab_Spec;
26876      System.Exception_Table'Elab_Body;
26877      E23 := E23 + 1;
26878      Ada.Io_Exceptions'Elab_Spec;
26879      E46 := E46 + 1;
26880      Ada.Tags'Elab_Spec;
26881      Ada.Streams'Elab_Spec;
26882      E45 := E45 + 1;
26883      Interfaces.C'Elab_Spec;
26884      System.Exceptions'Elab_Spec;
26885      E25 := E25 + 1;
26886      System.Finalization_Root'Elab_Spec;
26887      E68 := E68 + 1;
26888      Ada.Finalization'Elab_Spec;
26889      E66 := E66 + 1;
26890      System.Storage_Pools'Elab_Spec;
26891      E85 := E85 + 1;
26892      System.Finalization_Masters'Elab_Spec;
26893      System.Storage_Pools.Subpools'Elab_Spec;
26894      System.Pool_Global'Elab_Spec;
26895      E87 := E87 + 1;
26896      System.File_Control_Block'Elab_Spec;
26897      E75 := E75 + 1;
26898      System.File_Io'Elab_Body;
26899      E64 := E64 + 1;
26900      E91 := E91 + 1;
26901      System.Finalization_Masters'Elab_Body;
26902      E77 := E77 + 1;
26903      E70 := E70 + 1;
26904      Ada.Tags'Elab_Body;
26905      E48 := E48 + 1;
26906      System.Soft_Links'Elab_Body;
26907      E13 := E13 + 1;
26908      System.Os_Lib'Elab_Body;
26909      E72 := E72 + 1;
26910      System.Secondary_Stack'Elab_Body;
26911      E17 := E17 + 1;
26912      Ada.Text_Io'Elab_Spec;
26913      Ada.Text_Io'Elab_Body;
26914      E06 := E06 + 1;
26915   end adainit;
26916
26917   --------------
26918   -- adafinal --
26919   --------------
26920
26921   procedure adafinal is
26922      procedure s_stalib_adafinal;
26923      pragma Import (C, s_stalib_adafinal, "system__standard_library__adafinal");
26924
26925      procedure Runtime_Finalize;
26926      pragma Import (C, Runtime_Finalize, "__gnat_runtime_finalize");
26927
26928   begin
26929      if not Is_Elaborated then
26930         return;
26931      end if;
26932      Is_Elaborated := False;
26933      Runtime_Finalize;
26934      s_stalib_adafinal;
26935   end adafinal;
26936
26937   --  We get to the main program of the partition by using
26938   --  pragma Import because if we try to with the unit and
26939   --  call it Ada style, then not only do we waste time
26940   --  recompiling it, but also, we don't really know the right
26941   --  switches (e.g.@@: identifier character set) to be used
26942   --  to compile it.
26943
26944   procedure Ada_Main_Program;
26945   pragma Import (Ada, Ada_Main_Program, "_ada_hello");
26946
26947   ----------
26948   -- main --
26949   ----------
26950
26951   --  main is actually a function, as in the ANSI C standard,
26952   --  defined to return the exit status. The three parameters
26953   --  are the argument count, argument values and environment
26954   --  pointer.
26955
26956   function main
26957     (argc : Integer;
26958      argv : System.Address;
26959      envp : System.Address)
26960      return Integer
26961   is
26962      --  The initialize routine performs low level system
26963      --  initialization using a standard library routine which
26964      --  sets up signal handling and performs any other
26965      --  required setup. The routine can be found in file
26966      --  a-init.c.
26967
26968      procedure initialize;
26969      pragma Import (C, initialize, "__gnat_initialize");
26970
26971      --  The finalize routine performs low level system
26972      --  finalization using a standard library routine. The
26973      --  routine is found in file a-final.c and in the standard
26974      --  distribution is a dummy routine that does nothing, so
26975      --  really this is a hook for special user finalization.
26976
26977      procedure finalize;
26978      pragma Import (C, finalize, "__gnat_finalize");
26979
26980      --  The following is to initialize the SEH exceptions
26981
26982      SEH : aliased array (1 .. 2) of Integer;
26983
26984      Ensure_Reference : aliased System.Address := Ada_Main_Program_Name'Address;
26985      pragma Volatile (Ensure_Reference);
26986
26987   --  Start of processing for main
26988
26989   begin
26990      --  Save global variables
26991
26992      gnat_argc := argc;
26993      gnat_argv := argv;
26994      gnat_envp := envp;
26995
26996      --  Call low level system initialization
26997
26998      Initialize (SEH'Address);
26999
27000      --  Call our generated Ada initialization routine
27001
27002      adainit;
27003
27004      --  Now we call the main program of the partition
27005
27006      Ada_Main_Program;
27007
27008      --  Perform Ada finalization
27009
27010      adafinal;
27011
27012      --  Perform low level system finalization
27013
27014      Finalize;
27015
27016      --  Return the proper exit status
27017      return (gnat_exit_status);
27018   end;
27019
27020--  This section is entirely comments, so it has no effect on the
27021--  compilation of the Ada_Main package. It provides the list of
27022--  object files and linker options, as well as some standard
27023--  libraries needed for the link. The gnatlink utility parses
27024--  this b~hello.adb file to read these comment lines to generate
27025--  the appropriate command line arguments for the call to the
27026--  system linker. The BEGIN/END lines are used for sentinels for
27027--  this parsing operation.
27028
27029--  The exact file names will of course depend on the environment,
27030--  host/target and location of files on the host system.
27031
27032-- BEGIN Object file/option list
27033   --   ./hello.o
27034   --   -L./
27035   --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
27036   --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
27037-- END Object file/option list
27038
27039end ada_main;
27040@end example
27041
27042The Ada code in the above example is exactly what is generated by the
27043binder. We have added comments to more clearly indicate the function
27044of each part of the generated @code{Ada_Main} package.
27045
27046The code is standard Ada in all respects, and can be processed by any
27047tools that handle Ada. In particular, it is possible to use the debugger
27048in Ada mode to debug the generated @code{Ada_Main} package. For example,
27049suppose that for reasons that you do not understand, your program is crashing
27050during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
27051you can place a breakpoint on the call:
27052
27053@quotation
27054
27055@example
27056Ada.Text_Io'Elab_Body;
27057@end example
27058@end quotation
27059
27060and trace the elaboration routine for this package to find out where
27061the problem might be (more usually of course you would be debugging
27062elaboration code in your own application).
27063
27064@c -- Example: A |withing| unit has a |with| clause, it |withs| a |withed| unit
27065
27066@node Elaboration Order Handling in GNAT,Inline Assembler,Example of Binder Output File,Top
27067@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order-handling-in-gnat}@anchor{f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat doc}@anchor{230}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id1}@anchor{231}
27068@chapter Elaboration Order Handling in GNAT
27069
27070
27071@geindex Order of elaboration
27072
27073@geindex Elaboration control
27074
27075This appendix describes the handling of elaboration code in Ada and GNAT, and
27076discusses how the order of elaboration of program units can be controlled in
27077GNAT, either automatically or with explicit programming features.
27078
27079@menu
27080* Elaboration Code::
27081* Elaboration Order::
27082* Checking the Elaboration Order::
27083* Controlling the Elaboration Order in Ada::
27084* Controlling the Elaboration Order in GNAT::
27085* Common Elaboration-model Traits::
27086* Dynamic Elaboration Model in GNAT::
27087* Static Elaboration Model in GNAT::
27088* SPARK Elaboration Model in GNAT::
27089* Legacy Elaboration Model in GNAT::
27090* Mixing Elaboration Models::
27091* Elaboration Circularities::
27092* Resolving Elaboration Circularities::
27093* Resolving Task Issues::
27094* Elaboration-related Compiler Switches::
27095* Summary of Procedures for Elaboration Control::
27096* Inspecting the Chosen Elaboration Order::
27097
27098@end menu
27099
27100@node Elaboration Code,Elaboration Order,,Elaboration Order Handling in GNAT
27101@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-code}@anchor{232}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id2}@anchor{233}
27102@section Elaboration Code
27103
27104
27105Ada defines the term @emph{execution} as the process by which a construct achieves
27106its run-time effect. This process is also referred to as @strong{elaboration} for
27107declarations and @emph{evaluation} for expressions.
27108
27109The execution model in Ada allows for certain sections of an Ada program to be
27110executed prior to execution of the program itself, primarily with the intent of
27111initializing data. These sections are referred to as @strong{elaboration code}.
27112Elaboration code is executed as follows:
27113
27114
27115@itemize *
27116
27117@item
27118All partitions of an Ada program are executed in parallel with one another,
27119possibly in a separate address space, and possibly on a separate computer.
27120
27121@item
27122The execution of a partition involves running the environment task for that
27123partition.
27124
27125@item
27126The environment task executes all elaboration code (if available) for all
27127units within that partition. This code is said to be executed at
27128@strong{elaboration time}.
27129
27130@item
27131The environment task executes the Ada program (if available) for that
27132partition.
27133@end itemize
27134
27135In addition to the Ada terminology, this appendix defines the following terms:
27136
27137
27138@itemize *
27139
27140@item
27141@emph{Scenario}
27142
27143A construct that is elaborated or executed by elaboration code is referred to
27144as an @emph{elaboration scenario} or simply a @strong{scenario}. GNAT recognizes the
27145following scenarios:
27146
27147
27148@itemize -
27149
27150@item
27151@code{'Access} of entries, operators, and subprograms
27152
27153@item
27154Activation of tasks
27155
27156@item
27157Calls to entries, operators, and subprograms
27158
27159@item
27160Instantiations of generic templates
27161@end itemize
27162
27163@item
27164@emph{Target}
27165
27166A construct elaborated by a scenario is referred to as @emph{elaboration target}
27167or simply @strong{target}. GNAT recognizes the following targets:
27168
27169
27170@itemize -
27171
27172@item
27173For @code{'Access} of entries, operators, and subprograms, the target is the
27174entry, operator, or subprogram being aliased.
27175
27176@item
27177For activation of tasks, the target is the task body
27178
27179@item
27180For calls to entries, operators, and subprograms, the target is the entry,
27181operator, or subprogram being invoked.
27182
27183@item
27184For instantiations of generic templates, the target is the generic template
27185being instantiated.
27186@end itemize
27187@end itemize
27188
27189Elaboration code may appear in two distinct contexts:
27190
27191
27192@itemize *
27193
27194@item
27195@emph{Library level}
27196
27197A scenario appears at the library level when it is encapsulated by a package
27198[body] compilation unit, ignoring any other package [body] declarations in
27199between.
27200
27201@example
27202with Server;
27203package Client is
27204   procedure Proc;
27205
27206   package Nested is
27207      Val : ... := Server.Func;
27208   end Nested;
27209end Client;
27210@end example
27211
27212In the example above, the call to @code{Server.Func} is an elaboration scenario
27213because it appears at the library level of package @code{Client}. Note that the
27214declaration of package @code{Nested} is ignored according to the definition
27215given above. As a result, the call to @code{Server.Func} will be executed when
27216the spec of unit @code{Client} is elaborated.
27217
27218@item
27219@emph{Package body statements}
27220
27221A scenario appears within the statement sequence of a package body when it is
27222bounded by the region starting from the @code{begin} keyword of the package body
27223and ending at the @code{end} keyword of the package body.
27224
27225@example
27226package body Client is
27227   procedure Proc is
27228   begin
27229      ...
27230   end Proc;
27231begin
27232   Proc;
27233end Client;
27234@end example
27235
27236In the example above, the call to @code{Proc} is an elaboration scenario because
27237it appears within the statement sequence of package body @code{Client}. As a
27238result, the call to @code{Proc} will be executed when the body of @code{Client} is
27239elaborated.
27240@end itemize
27241
27242@node Elaboration Order,Checking the Elaboration Order,Elaboration Code,Elaboration Order Handling in GNAT
27243@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-order}@anchor{234}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id3}@anchor{235}
27244@section Elaboration Order
27245
27246
27247The sequence by which the elaboration code of all units within a partition is
27248executed is referred to as @strong{elaboration order}.
27249
27250Within a single unit, elaboration code is executed in sequential order.
27251
27252@example
27253package body Client is
27254   Result : ... := Server.Func;
27255
27256   procedure Proc is
27257      package Inst is new Server.Gen;
27258   begin
27259      Inst.Eval (Result);
27260   end Proc;
27261begin
27262   Proc;
27263end Client;
27264@end example
27265
27266In the example above, the elaboration order within package body @code{Client} is
27267as follows:
27268
27269
27270@enumerate
27271
27272@item
27273The object declaration of @code{Result} is elaborated.
27274
27275
27276@itemize *
27277
27278@item
27279Function @code{Server.Func} is invoked.
27280@end itemize
27281
27282@item
27283The subprogram body of @code{Proc} is elaborated.
27284
27285@item
27286Procedure @code{Proc} is invoked.
27287
27288
27289@itemize *
27290
27291@item
27292Generic unit @code{Server.Gen} is instantiated as @code{Inst}.
27293
27294@item
27295Instance @code{Inst} is elaborated.
27296
27297@item
27298Procedure @code{Inst.Eval} is invoked.
27299@end itemize
27300@end enumerate
27301
27302The elaboration order of all units within a partition depends on the following
27303factors:
27304
27305
27306@itemize *
27307
27308@item
27309@emph{with}ed units
27310
27311@item
27312purity of units
27313
27314@item
27315preelaborability of units
27316
27317@item
27318presence of elaboration control pragmas
27319@end itemize
27320
27321A program may have several elaboration orders depending on its structure.
27322
27323@example
27324package Server is
27325   function Func (Index : Integer) return Integer;
27326end Server;
27327@end example
27328
27329@example
27330package body Server is
27331   Results : array (1 .. 5) of Integer := (1, 2, 3, 4, 5);
27332
27333   function Func (Index : Integer) return Integer is
27334   begin
27335      return Results (Index);
27336   end Func;
27337end Server;
27338@end example
27339
27340@example
27341with Server;
27342package Client is
27343   Val : constant Integer := Server.Func (3);
27344end Client;
27345@end example
27346
27347@example
27348with Client;
27349procedure Main is begin null; end Main;
27350@end example
27351
27352The following elaboration order exhibits a fundamental problem referred to as
27353@emph{access-before-elaboration} or simply @strong{ABE}.
27354
27355@example
27356spec of Server
27357spec of Client
27358body of Server
27359body of Main
27360@end example
27361
27362The elaboration of @code{Server}'s spec materializes function @code{Func}, making it
27363callable. The elaboration of @code{Client}'s spec elaborates the declaration of
27364@code{Val}. This invokes function @code{Server.Func}, however the body of
27365@code{Server.Func} has not been elaborated yet because @code{Server}'s body comes
27366after @code{Client}'s spec in the elaboration order. As a result, the value of
27367constant @code{Val} is now undefined.
27368
27369Without any guarantees from the language, an undetected ABE problem may hinder
27370proper initialization of data, which in turn may lead to undefined behavior at
27371run time. To prevent such ABE problems, Ada employs dynamic checks in the same
27372vein as index or null exclusion checks. A failed ABE check raises exception
27373@code{Program_Error}.
27374
27375The following elaboration order avoids the ABE problem and the program can be
27376successfully elaborated.
27377
27378@example
27379spec of Server
27380body of Server
27381spec of Client
27382body of Main
27383@end example
27384
27385Ada states that a total elaboration order must exist, but it does not define
27386what this order is. A compiler is thus tasked with choosing a suitable
27387elaboration order which satisfies the dependencies imposed by @emph{with} clauses,
27388unit categorization, and elaboration control pragmas. Ideally an order which
27389avoids ABE problems should be chosen, however a compiler may not always find
27390such an order due to complications with respect to control and data flow.
27391
27392@node Checking the Elaboration Order,Controlling the Elaboration Order in Ada,Elaboration Order,Elaboration Order Handling in GNAT
27393@anchor{gnat_ugn/elaboration_order_handling_in_gnat id4}@anchor{236}@anchor{gnat_ugn/elaboration_order_handling_in_gnat checking-the-elaboration-order}@anchor{237}
27394@section Checking the Elaboration Order
27395
27396
27397To avoid placing the entire elaboration order burden on the programmer, Ada
27398provides three lines of defense:
27399
27400
27401@itemize *
27402
27403@item
27404@emph{Static semantics}
27405
27406Static semantic rules restrict the possible choice of elaboration order. For
27407instance, if unit Client @emph{with}s unit Server, then the spec of Server is
27408always elaborated prior to Client. The same principle applies to child units
27409- the spec of a parent unit is always elaborated prior to the child unit.
27410
27411@item
27412@emph{Dynamic semantics}
27413
27414Dynamic checks are performed at run time, to ensure that a target is
27415elaborated prior to a scenario that executes it, thus avoiding ABE problems.
27416A failed run-time check raises exception @code{Program_Error}. The following
27417restrictions apply:
27418
27419
27420@itemize -
27421
27422@item
27423@emph{Restrictions on calls}
27424
27425An entry, operator, or subprogram can be called from elaboration code only
27426when the corresponding body has been elaborated.
27427
27428@item
27429@emph{Restrictions on instantiations}
27430
27431A generic unit can be instantiated by elaboration code only when the
27432corresponding body has been elaborated.
27433
27434@item
27435@emph{Restrictions on task activation}
27436
27437A task can be activated by elaboration code only when the body of the
27438associated task type has been elaborated.
27439@end itemize
27440
27441The restrictions above can be summarized by the following rule:
27442
27443@emph{If a target has a body, then this body must be elaborated prior to the
27444execution of the scenario that invokes, instantiates, or activates the
27445target.}
27446
27447@item
27448@emph{Elaboration control}
27449
27450Pragmas are provided for the programmer to specify the desired elaboration
27451order.
27452@end itemize
27453
27454@node Controlling the Elaboration Order in Ada,Controlling the Elaboration Order in GNAT,Checking the Elaboration Order,Elaboration Order Handling in GNAT
27455@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-ada}@anchor{238}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id5}@anchor{239}
27456@section Controlling the Elaboration Order in Ada
27457
27458
27459Ada provides several idioms and pragmas to aid the programmer with specifying
27460the desired elaboration order and avoiding ABE problems altogether.
27461
27462
27463@itemize *
27464
27465@item
27466@emph{Packages without a body}
27467
27468A library package which does not require a completing body does not suffer
27469from ABE problems.
27470
27471@example
27472package Pack is
27473   generic
27474      type Element is private;
27475   package Containers is
27476      type Element_Array is array (1 .. 10) of Element;
27477   end Containers;
27478end Pack;
27479@end example
27480
27481In the example above, package @code{Pack} does not require a body because it
27482does not contain any constructs which require completion in a body. As a
27483result, generic @code{Pack.Containers} can be instantiated without encountering
27484any ABE problems.
27485@end itemize
27486
27487@geindex pragma Pure
27488
27489
27490@itemize *
27491
27492@item
27493@emph{pragma Pure}
27494
27495Pragma @code{Pure} places sufficient restrictions on a unit to guarantee that no
27496scenario within the unit can result in an ABE problem.
27497@end itemize
27498
27499@geindex pragma Preelaborate
27500
27501
27502@itemize *
27503
27504@item
27505@emph{pragma Preelaborate}
27506
27507Pragma @code{Preelaborate} is slightly less restrictive than pragma @code{Pure},
27508but still strong enough to prevent ABE problems within a unit.
27509@end itemize
27510
27511@geindex pragma Elaborate_Body
27512
27513
27514@itemize *
27515
27516@item
27517@emph{pragma Elaborate_Body}
27518
27519Pragma @code{Elaborate_Body} requires that the body of a unit is elaborated
27520immediately after its spec. This restriction guarantees that no client
27521scenario can execute a server target before the target body has been
27522elaborated because the spec and body are effectively "glued" together.
27523
27524@example
27525package Server is
27526   pragma Elaborate_Body;
27527
27528   function Func return Integer;
27529end Server;
27530@end example
27531
27532@example
27533package body Server is
27534   function Func return Integer is
27535   begin
27536      ...
27537   end Func;
27538end Server;
27539@end example
27540
27541@example
27542with Server;
27543package Client is
27544   Val : constant Integer := Server.Func;
27545end Client;
27546@end example
27547
27548In the example above, pragma @code{Elaborate_Body} guarantees the following
27549elaboration order:
27550
27551@example
27552spec of Server
27553body of Server
27554spec of Client
27555@end example
27556
27557because the spec of @code{Server} must be elaborated prior to @code{Client} by
27558virtue of the @emph{with} clause, and in addition the body of @code{Server} must be
27559elaborated immediately after the spec of @code{Server}.
27560
27561Removing pragma @code{Elaborate_Body} could result in the following incorrect
27562elaboration order:
27563
27564@example
27565spec of Server
27566spec of Client
27567body of Server
27568@end example
27569
27570where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func} has
27571not been elaborated yet.
27572@end itemize
27573
27574The pragmas outlined above allow a server unit to guarantee safe elaboration
27575use by client units. Thus it is a good rule to mark units as @code{Pure} or
27576@code{Preelaborate}, and if this is not possible, mark them as @code{Elaborate_Body}.
27577
27578There are however situations where @code{Pure}, @code{Preelaborate}, and
27579@code{Elaborate_Body} are not applicable. Ada provides another set of pragmas for
27580use by client units to help ensure the elaboration safety of server units they
27581depend on.
27582
27583@geindex pragma Elaborate (Unit)
27584
27585
27586@itemize *
27587
27588@item
27589@emph{pragma Elaborate (Unit)}
27590
27591Pragma @code{Elaborate} can be placed in the context clauses of a unit, after a
27592@emph{with} clause. It guarantees that both the spec and body of its argument will
27593be elaborated prior to the unit with the pragma. Note that other unrelated
27594units may be elaborated in between the spec and the body.
27595
27596@example
27597package Server is
27598   function Func return Integer;
27599end Server;
27600@end example
27601
27602@example
27603package body Server is
27604   function Func return Integer is
27605   begin
27606      ...
27607   end Func;
27608end Server;
27609@end example
27610
27611@example
27612with Server;
27613pragma Elaborate (Server);
27614package Client is
27615   Val : constant Integer := Server.Func;
27616end Client;
27617@end example
27618
27619In the example above, pragma @code{Elaborate} guarantees the following
27620elaboration order:
27621
27622@example
27623spec of Server
27624body of Server
27625spec of Client
27626@end example
27627
27628Removing pragma @code{Elaborate} could result in the following incorrect
27629elaboration order:
27630
27631@example
27632spec of Server
27633spec of Client
27634body of Server
27635@end example
27636
27637where @code{Client} invokes @code{Server.Func}, but the body of @code{Server.Func}
27638has not been elaborated yet.
27639@end itemize
27640
27641@geindex pragma Elaborate_All (Unit)
27642
27643
27644@itemize *
27645
27646@item
27647@emph{pragma Elaborate_All (Unit)}
27648
27649Pragma @code{Elaborate_All} is placed in the context clauses of a unit, after
27650a @emph{with} clause. It guarantees that both the spec and body of its argument
27651will be elaborated prior to the unit with the pragma, as well as all units
27652@emph{with}ed by the spec and body of the argument, recursively. Note that other
27653unrelated units may be elaborated in between the spec and the body.
27654
27655@example
27656package Math is
27657   function Factorial (Val : Natural) return Natural;
27658end Math;
27659@end example
27660
27661@example
27662package body Math is
27663   function Factorial (Val : Natural) return Natural is
27664   begin
27665      ...;
27666   end Factorial;
27667end Math;
27668@end example
27669
27670@example
27671package Computer is
27672   type Operation_Kind is (None, Op_Factorial);
27673
27674   function Compute
27675     (Val : Natural;
27676      Op  : Operation_Kind) return Natural;
27677end Computer;
27678@end example
27679
27680@example
27681with Math;
27682package body Computer is
27683   function Compute
27684     (Val : Natural;
27685      Op  : Operation_Kind) return Natural
27686   is
27687      if Op = Op_Factorial then
27688         return Math.Factorial (Val);
27689      end if;
27690
27691      return 0;
27692   end Compute;
27693end Computer;
27694@end example
27695
27696@example
27697with Computer;
27698pragma Elaborate_All (Computer);
27699package Client is
27700   Val : constant Natural :=
27701           Computer.Compute (123, Computer.Op_Factorial);
27702end Client;
27703@end example
27704
27705In the example above, pragma @code{Elaborate_All} can result in the following
27706elaboration order:
27707
27708@example
27709spec of Math
27710body of Math
27711spec of Computer
27712body of Computer
27713spec of Client
27714@end example
27715
27716Note that there are several allowable suborders for the specs and bodies of
27717@code{Math} and @code{Computer}, but the point is that these specs and bodies will
27718be elaborated prior to @code{Client}.
27719
27720Removing pragma @code{Elaborate_All} could result in the following incorrect
27721elaboration order
27722
27723@example
27724spec of Math
27725spec of Computer
27726body of Computer
27727spec of Client
27728body of Math
27729@end example
27730
27731where @code{Client} invokes @code{Computer.Compute}, which in turn invokes
27732@code{Math.Factorial}, but the body of @code{Math.Factorial} has not been
27733elaborated yet.
27734@end itemize
27735
27736All pragmas shown above can be summarized by the following rule:
27737
27738@emph{If a client unit elaborates a server target directly or indirectly, then if
27739the server unit requires a body and does not have pragma Pure, Preelaborate,
27740or Elaborate_Body, then the client unit should have pragma Elaborate or
27741Elaborate_All for the server unit.}
27742
27743If the rule outlined above is not followed, then a program may fall in one of
27744the following states:
27745
27746
27747@itemize *
27748
27749@item
27750@emph{No elaboration order exists}
27751
27752In this case a compiler must diagnose the situation, and refuse to build an
27753executable program.
27754
27755@item
27756@emph{One or more incorrect elaboration orders exist}
27757
27758In this case a compiler can build an executable program, but
27759@code{Program_Error} will be raised when the program is run.
27760
27761@item
27762@emph{Several elaboration orders exist, some correct, some incorrect}
27763
27764In this case the programmer has not controlled the elaboration order. As a
27765result, a compiler may or may not pick one of the correct orders, and the
27766program may or may not raise @code{Program_Error} when it is run. This is the
27767worst possible state because the program may fail on another compiler, or
27768even another version of the same compiler.
27769
27770@item
27771@emph{One or more correct orders exist}
27772
27773In this case a compiler can build an executable program, and the program is
27774run successfully. This state may be guaranteed by following the outlined
27775rules, or may be the result of good program architecture.
27776@end itemize
27777
27778Note that one additional advantage of using @code{Elaborate} and @code{Elaborate_All}
27779is that the program continues to stay in the last state (one or more correct
27780orders exist) even if maintenance changes the bodies of targets.
27781
27782@node Controlling the Elaboration Order in GNAT,Common Elaboration-model Traits,Controlling the Elaboration Order in Ada,Elaboration Order Handling in GNAT
27783@anchor{gnat_ugn/elaboration_order_handling_in_gnat id6}@anchor{23a}@anchor{gnat_ugn/elaboration_order_handling_in_gnat controlling-the-elaboration-order-in-gnat}@anchor{23b}
27784@section Controlling the Elaboration Order in GNAT
27785
27786
27787In addition to Ada semantics and rules synthesized from them, GNAT offers
27788three elaboration models to aid the programmer with specifying the correct
27789elaboration order and to diagnose elaboration problems.
27790
27791@geindex Dynamic elaboration model
27792
27793
27794@itemize *
27795
27796@item
27797@emph{Dynamic elaboration model}
27798
27799This is the most permissive of the three elaboration models. When the
27800dynamic model is in effect, GNAT assumes that all code within all units in
27801a partition is elaboration code. GNAT performs very few diagnostics and
27802generates run-time checks to verify the elaboration order of a program. This
27803behavior is identical to that specified by the Ada Reference Manual. The
27804dynamic model is enabled with compiler switch @code{-gnatE}.
27805@end itemize
27806
27807@geindex Static elaboration model
27808
27809
27810@itemize *
27811
27812@item
27813@emph{Static elaboration model}
27814
27815This is the middle ground of the three models. When the static model is in
27816effect, GNAT performs extensive diagnostics on a unit-by-unit basis for all
27817scenarios that elaborate or execute internal targets. GNAT also generates
27818run-time checks for all external targets and for all scenarios that may
27819exhibit ABE problems. Finally, GNAT installs implicit @code{Elaborate} and
27820@code{Elaborate_All} pragmas for server units based on the dependencies of
27821client units. The static model is the default model in GNAT.
27822@end itemize
27823
27824@geindex SPARK elaboration model
27825
27826
27827@itemize *
27828
27829@item
27830@emph{SPARK elaboration model}
27831
27832This is the most conservative of the three models and enforces the SPARK
27833rules of elaboration as defined in the SPARK Reference Manual, section 7.7.
27834The SPARK model is in effect only when a scenario and a target reside in a
27835region subject to SPARK_Mode On, otherwise the dynamic or static model is in
27836effect.
27837@end itemize
27838
27839@geindex Legacy elaboration model
27840
27841
27842@itemize *
27843
27844@item
27845@emph{Legacy elaboration model}
27846
27847In addition to the three elaboration models outlined above, GNAT provides the
27848elaboration model of pre-18.x versions referred to as @cite{legacy elaboration model}. The legacy elaboration model is enabled with compiler switch
27849@code{-gnatH}.
27850@end itemize
27851
27852@geindex Relaxed elaboration mode
27853
27854The dynamic, legacy, and static models can be relaxed using compiler switch
27855@code{-gnatJ}, making them more permissive. Note that in this mode, GNAT
27856may not diagnose certain elaboration issues or install run-time checks.
27857
27858@node Common Elaboration-model Traits,Dynamic Elaboration Model in GNAT,Controlling the Elaboration Order in GNAT,Elaboration Order Handling in GNAT
27859@anchor{gnat_ugn/elaboration_order_handling_in_gnat common-elaboration-model-traits}@anchor{23c}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id7}@anchor{23d}
27860@section Common Elaboration-model Traits
27861
27862
27863All three GNAT models are able to detect elaboration problems related to
27864dispatching calls and a particular kind of ABE referred to as @emph{guaranteed ABE}.
27865
27866
27867@itemize *
27868
27869@item
27870@emph{Dispatching calls}
27871
27872GNAT installs run-time checks for each primitive subprogram of each tagged
27873type defined in a partition on the assumption that a dispatching call
27874invoked at elaboration time will execute one of these primitives. As a
27875result, a dispatching call that executes a primitive whose body has not
27876been elaborated yet will raise exception @code{Program_Error} at run time. The
27877checks can be suppressed using pragma @code{Suppress (Elaboration_Check)}.
27878
27879@item
27880@emph{Guaranteed ABE}
27881
27882A guaranteed ABE arises when the body of a target is not elaborated early
27883enough, and causes all scenarios that directly execute the target to fail.
27884
27885@example
27886package body Guaranteed_ABE is
27887   function ABE return Integer;
27888
27889   Val : constant Integer := ABE;
27890
27891   function ABE return Integer is
27892   begin
27893      ...
27894   end ABE;
27895end Guaranteed_ABE;
27896@end example
27897
27898In the example above, the elaboration of @code{Guaranteed_ABE}'s body elaborates
27899the declaration of @code{Val}. This invokes function @code{ABE}, however the body
27900of @code{ABE} has not been elaborated yet. GNAT emits similar diagnostics in all
27901three models:
27902
27903@example
279041. package body Guaranteed_ABE is
279052.    function ABE return Integer;
279063.
279074.    Val : constant Integer := ABE;
27908                                |
27909   >>> warning: cannot call "ABE" before body seen
27910   >>> warning: Program_Error will be raised at run time
27911
279125.
279136.    function ABE return Integer is
279147.    begin
279158.       ...
279169.    end ABE;
2791710. end Guaranteed_ABE;
27918@end example
27919@end itemize
27920
27921Note that GNAT emits warnings rather than hard errors whenever it encounters an
27922elaboration problem. This is because the elaboration model in effect may be too
27923conservative, or a particular scenario may not be elaborated or executed due to
27924data and control flow. The warnings can be suppressed selectively with @code{pragma
27925Warnigns (Off)} or globally with compiler switch @code{-gnatwL}.
27926
27927@node Dynamic Elaboration Model in GNAT,Static Elaboration Model in GNAT,Common Elaboration-model Traits,Elaboration Order Handling in GNAT
27928@anchor{gnat_ugn/elaboration_order_handling_in_gnat dynamic-elaboration-model-in-gnat}@anchor{23e}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id8}@anchor{23f}
27929@section Dynamic Elaboration Model in GNAT
27930
27931
27932The dynamic model assumes that all code within all units in a partition is
27933elaboration code. As a result, run-time checks are installed for each scenario
27934regardless of whether the target is internal or external. The checks can be
27935suppressed using pragma @code{Suppress (Elaboration_Check)}. This behavior is
27936identical to that specified by the Ada Reference Manual. The following example
27937showcases run-time checks installed by GNAT to verify the elaboration state of
27938package @code{Dynamic_Model}.
27939
27940@example
27941with Server;
27942package body Dynamic_Model is
27943   procedure API is
27944   begin
27945      ...
27946   end API;
27947
27948   <check that the body of Server.Gen is elaborated>
27949   package Inst is new Server.Gen;
27950
27951   T : Server.Task_Type;
27952
27953begin
27954   <check that the body of Server.Task_Type is elaborated>
27955
27956   <check that the body of Server.Proc is elaborated>
27957   Server.Proc;
27958end Dynamic_Model;
27959@end example
27960
27961The checks verify that the body of a target has been successfully elaborated
27962before a scenario activates, calls, or instantiates a target.
27963
27964Note that no scenario within package @code{Dynamic_Model} calls procedure @code{API}.
27965In fact, procedure @code{API} may not be invoked by elaboration code within the
27966partition, however the dynamic model assumes that this can happen.
27967
27968The dynamic model emits very few diagnostics, but can make suggestions on
27969missing @code{Elaborate} and @code{Elaborate_All} pragmas for library-level
27970scenarios. This information is available when compiler switch @code{-gnatel}
27971is in effect.
27972
27973@example
279741. with Server;
279752. package body Dynamic_Model is
279763.    Val : constant Integer := Server.Func;
27977                                      |
27978   >>> info: call to "Func" during elaboration
27979   >>> info: missing pragma "Elaborate_All" for unit "Server"
27980
279814. end Dynamic_Model;
27982@end example
27983
27984@node Static Elaboration Model in GNAT,SPARK Elaboration Model in GNAT,Dynamic Elaboration Model in GNAT,Elaboration Order Handling in GNAT
27985@anchor{gnat_ugn/elaboration_order_handling_in_gnat static-elaboration-model-in-gnat}@anchor{240}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id9}@anchor{241}
27986@section Static Elaboration Model in GNAT
27987
27988
27989In contrast to the dynamic model, the static model is more precise in its
27990analysis of elaboration code. The model makes a clear distinction between
27991internal and external targets, and resorts to different diagnostics and
27992run-time checks based on the nature of the target.
27993
27994
27995@itemize *
27996
27997@item
27998@emph{Internal targets}
27999
28000The static model performs extensive diagnostics on scenarios which elaborate
28001or execute internal targets. The warnings resulting from these diagnostics
28002are enabled by default, but can be suppressed selectively with @code{pragma
28003Warnings (Off)} or globally with compiler switch @code{-gnatwL}.
28004
28005@example
28006 1. package body Static_Model is
28007 2.    generic
28008 3.       with function Func return Integer;
28009 4.    package Gen is
28010 5.       Val : constant Integer := Func;
28011 6.    end Gen;
28012 7.
28013 8.    function ABE return Integer;
28014 9.
2801510.    function Cause_ABE return Boolean is
2801611.       package Inst is new Gen (ABE);
28017          |
28018    >>> warning: in instantiation at line 5
28019    >>> warning: cannot call "ABE" before body seen
28020    >>> warning: Program_Error may be raised at run time
28021    >>> warning:   body of unit "Static_Model" elaborated
28022    >>> warning:   function "Cause_ABE" called at line 16
28023    >>> warning:   function "ABE" called at line 5, instance at line 11
28024
2802512.    begin
2802613.       ...
2802714.    end Cause_ABE;
2802815.
2802916.    Val : constant Boolean := Cause_ABE;
2803017.
2803118.    function ABE return Integer is
2803219.    begin
2803320.       ...
2803421.    end ABE;
2803522. end Static_Model;
28036@end example
28037
28038The example above illustrates an ABE problem within package @code{Static_Model},
28039which is hidden by several layers of indirection. The elaboration of package
28040body @code{Static_Model} elaborates the declaration of @code{Val}. This invokes
28041function @code{Cause_ABE}, which instantiates generic unit @code{Gen} as @code{Inst}.
28042The elaboration of @code{Inst} invokes function @code{ABE}, however the body of
28043@code{ABE} has not been elaborated yet.
28044
28045@item
28046@emph{External targets}
28047
28048The static model installs run-time checks to verify the elaboration status
28049of server targets only when the scenario that elaborates or executes that
28050target is part of the elaboration code of the client unit. The checks can be
28051suppressed using pragma @code{Suppress (Elaboration_Check)}.
28052
28053@example
28054with Server;
28055package body Static_Model is
28056   generic
28057      with function Func return Integer;
28058   package Gen is
28059      Val : constant Integer := Func;
28060   end Gen;
28061
28062   function Call_Func return Boolean is
28063      <check that the body of Server.Func is elaborated>
28064      package Inst is new Gen (Server.Func);
28065   begin
28066      ...
28067   end Call_Func;
28068
28069   Val : constant Boolean := Call_Func;
28070end Static_Model;
28071@end example
28072
28073In the example above, the elaboration of package body @code{Static_Model}
28074elaborates the declaration of @code{Val}. This invokes function @code{Call_Func},
28075which instantiates generic unit @code{Gen} as @code{Inst}. The elaboration of
28076@code{Inst} invokes function @code{Server.Func}. Since @code{Server.Func} is an
28077external target, GNAT installs a run-time check to verify that its body has
28078been elaborated.
28079
28080In addition to checks, the static model installs implicit @code{Elaborate} and
28081@code{Elaborate_All} pragmas to guarantee safe elaboration use of server units.
28082This information is available when compiler switch @code{-gnatel} is in
28083effect.
28084
28085@example
28086 1. with Server;
28087 2. package body Static_Model is
28088 3.    generic
28089 4.       with function Func return Integer;
28090 5.    package Gen is
28091 6.       Val : constant Integer := Func;
28092 7.    end Gen;
28093 8.
28094 9.    function Call_Func return Boolean is
2809510.       package Inst is new Gen (Server.Func);
28096          |
28097    >>> info: instantiation of "Gen" during elaboration
28098    >>> info: in instantiation at line 6
28099    >>> info: call to "Func" during elaboration
28100    >>> info: in instantiation at line 6
28101    >>> info: implicit pragma "Elaborate_All" generated for unit "Server"
28102    >>> info:   body of unit "Static_Model" elaborated
28103    >>> info:   function "Call_Func" called at line 15
28104    >>> info:   function "Func" called at line 6, instance at line 10
28105
2810611.    begin
2810712.       ...
2810813.    end Call_Func;
2810914.
2811015.    Val : constant Boolean := Call_Func;
28111                                 |
28112    >>> info: call to "Call_Func" during elaboration
28113
2811416. end Static_Model;
28115@end example
28116
28117In the example above, the elaboration of package body @code{Static_Model}
28118elaborates the declaration of @code{Val}. This invokes function @code{Call_Func},
28119which instantiates generic unit @code{Gen} as @code{Inst}. The elaboration of
28120@code{Inst} invokes function @code{Server.Func}. Since @code{Server.Func} is an
28121external target, GNAT installs an implicit @code{Elaborate_All} pragma for unit
28122@code{Server}. The pragma guarantees that both the spec and body of @code{Server},
28123along with any additional dependencies that @code{Server} may require, are
28124elaborated prior to the body of @code{Static_Model}.
28125@end itemize
28126
28127@node SPARK Elaboration Model in GNAT,Legacy Elaboration Model in GNAT,Static Elaboration Model in GNAT,Elaboration Order Handling in GNAT
28128@anchor{gnat_ugn/elaboration_order_handling_in_gnat id10}@anchor{242}@anchor{gnat_ugn/elaboration_order_handling_in_gnat spark-elaboration-model-in-gnat}@anchor{243}
28129@section SPARK Elaboration Model in GNAT
28130
28131
28132The SPARK model is identical to the static model in its handling of internal
28133targets. The SPARK model, however, requires explicit @code{Elaborate} or
28134@code{Elaborate_All} pragmas to be present in the program when a target is
28135external, and compiler switch @code{-gnatd.v} is in effect.
28136
28137@example
281381. with Server;
281392. package body SPARK_Model with SPARK_Mode is
281403.    Val : constant Integer := Server.Func;
28141                                      |
28142   >>> call to "Func" during elaboration in SPARK
28143   >>> unit "SPARK_Model" requires pragma "Elaborate_All" for "Server"
28144   >>>   body of unit "SPARK_Model" elaborated
28145   >>>   function "Func" called at line 3
28146
281474. end SPARK_Model;
28148@end example
28149
28150@node Legacy Elaboration Model in GNAT,Mixing Elaboration Models,SPARK Elaboration Model in GNAT,Elaboration Order Handling in GNAT
28151@anchor{gnat_ugn/elaboration_order_handling_in_gnat legacy-elaboration-model-in-gnat}@anchor{244}
28152@section Legacy Elaboration Model in GNAT
28153
28154
28155The legacy elaboration model is provided for compatibility with code bases
28156developed with pre-18.x versions of GNAT. It is similar in functionality to
28157the dynamic and static models of post-18.x version of GNAT, but may differ
28158in terms of diagnostics and run-time checks. The legacy elaboration model is
28159enabled with compiler switch @code{-gnatH}.
28160
28161@node Mixing Elaboration Models,Elaboration Circularities,Legacy Elaboration Model in GNAT,Elaboration Order Handling in GNAT
28162@anchor{gnat_ugn/elaboration_order_handling_in_gnat mixing-elaboration-models}@anchor{245}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id11}@anchor{246}
28163@section Mixing Elaboration Models
28164
28165
28166It is possible to mix units compiled with a different elaboration model,
28167however the following rules must be observed:
28168
28169
28170@itemize *
28171
28172@item
28173A client unit compiled with the dynamic model can only @emph{with} a server unit
28174that meets at least one of the following criteria:
28175
28176
28177@itemize -
28178
28179@item
28180The server unit is compiled with the dynamic model.
28181
28182@item
28183The server unit is a GNAT implementation unit from the Ada, GNAT,
28184Interfaces, or System hierarchies.
28185
28186@item
28187The server unit has pragma @code{Pure} or @code{Preelaborate}.
28188
28189@item
28190The client unit has an explicit @code{Elaborate_All} pragma for the server
28191unit.
28192@end itemize
28193@end itemize
28194
28195These rules ensure that elaboration checks are not omitted. If the rules are
28196violated, the binder emits a warning:
28197
28198@example
28199warning: "x.ads" has dynamic elaboration checks and with's
28200warning:   "y.ads" which has static elaboration checks
28201@end example
28202
28203The warnings can be suppressed by binder switch @code{-ws}.
28204
28205@node Elaboration Circularities,Resolving Elaboration Circularities,Mixing Elaboration Models,Elaboration Order Handling in GNAT
28206@anchor{gnat_ugn/elaboration_order_handling_in_gnat id12}@anchor{247}@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-circularities}@anchor{248}
28207@section Elaboration Circularities
28208
28209
28210If the binder cannot find an acceptable elaboration order, it outputs detailed
28211diagnostics describing an @strong{elaboration circularity}.
28212
28213@example
28214package Server is
28215   function Func return Integer;
28216end Server;
28217@end example
28218
28219@example
28220with Client;
28221package body Server is
28222   function Func return Integer is
28223   begin
28224      ...
28225   end Func;
28226end Server;
28227@end example
28228
28229@example
28230with Server;
28231package Client is
28232   Val : constant Integer := Server.Func;
28233end Client;
28234@end example
28235
28236@example
28237with Client;
28238procedure Main is begin null; end Main;
28239@end example
28240
28241@example
28242error: elaboration circularity detected
28243info:    "server (body)" must be elaborated before "client (spec)"
28244info:       reason: implicit Elaborate_All in unit "client (spec)"
28245info:       recompile "client (spec)" with -gnatel for full details
28246info:          "server (body)"
28247info:             must be elaborated along with its spec:
28248info:          "server (spec)"
28249info:             which is withed by:
28250info:          "client (spec)"
28251info:    "client (spec)" must be elaborated before "server (body)"
28252info:       reason: with clause
28253@end example
28254
28255In the example above, @code{Client} must be elaborated prior to @code{Main} by virtue
28256of a @emph{with} clause. The elaboration of @code{Client} invokes @code{Server.Func}, and
28257static model generates an implicit @code{Elaborate_All} pragma for @code{Server}. The
28258pragma implies that both the spec and body of @code{Server}, along with any units
28259they @emph{with}, must be elaborated prior to @code{Client}. However, @code{Server}'s body
28260@emph{with}s @code{Client}, implying that @code{Client} must be elaborated prior to
28261@code{Server}. The end result is that @code{Client} must be elaborated prior to
28262@code{Client}, and this leads to a circularity.
28263
28264@node Resolving Elaboration Circularities,Resolving Task Issues,Elaboration Circularities,Elaboration Order Handling in GNAT
28265@anchor{gnat_ugn/elaboration_order_handling_in_gnat id13}@anchor{249}@anchor{gnat_ugn/elaboration_order_handling_in_gnat resolving-elaboration-circularities}@anchor{24a}
28266@section Resolving Elaboration Circularities
28267
28268
28269When faced with an elaboration circularity, a programmer has several options
28270available.
28271
28272
28273@itemize *
28274
28275@item
28276@emph{Fix the program}
28277
28278The most desirable option from the point of view of long-term maintenance
28279is to rearrange the program so that the elaboration problems are avoided.
28280One useful technique is to place the elaboration code into separate child
28281packages. Another is to move some of the initialization code to explicitly
28282invoked subprograms, where the program controls the order of initialization
28283explicitly. Although this is the most desirable option, it may be impractical
28284and involve too much modification, especially in the case of complex legacy
28285code.
28286
28287@item
28288@emph{Switch to more permissive elaboration model}
28289
28290If the compilation was performed using the static model, enable the dynamic
28291model with compiler switch @code{-gnatE}. GNAT will no longer generate
28292implicit @code{Elaborate} and @code{Elaborate_All} pragmas, resulting in a behavior
28293identical to that specified by the Ada Reference Manual. The binder will
28294generate an executable program that may or may not raise @code{Program_Error},
28295and it is the programmer's responsibility to ensure that it does not raise
28296@code{Program_Error}.
28297
28298If the compilation was performed using a post-18.x version of GNAT, consider
28299using the legacy elaboration model, in the following order:
28300
28301
28302@itemize -
28303
28304@item
28305Use the legacy static elaboration model, with compiler switch
28306@code{-gnatH}.
28307
28308@item
28309Use the legacy dynamic elaboration model, with compiler switches
28310@code{-gnatH} @code{-gnatE}.
28311
28312@item
28313Use the relaxed legacy static elaboration model, with compiler switches
28314@code{-gnatH} @code{-gnatJ}.
28315
28316@item
28317Use the relaxed legacy dynamic elaboration model, with compiler switches
28318@code{-gnatH} @code{-gnatJ} @code{-gnatE}.
28319@end itemize
28320
28321@item
28322@emph{Suppress all elaboration checks}
28323
28324The drawback of run-time checks is that they generate overhead at run time,
28325both in space and time. If the programmer is absolutely sure that a program
28326will not raise an elaboration-related @code{Program_Error}, then using the
28327pragma @code{Suppress (Elaboration_Check)} globally (as a configuration pragma)
28328will eliminate all run-time checks.
28329
28330@item
28331@emph{Suppress elaboration checks selectively}
28332
28333If a scenario cannot possibly lead to an elaboration @code{Program_Error},
28334and the binder nevertheless complains about implicit @code{Elaborate} and
28335@code{Elaborate_All} pragmas that lead to elaboration circularities, it
28336is possible to suppress the generation of implicit @code{Elaborate} and
28337@code{Elaborate_All} pragmas, as well as run-time checks. Clearly this can
28338be unsafe, and it is the responsibility of the programmer to make sure
28339that the resulting program has no elaboration anomalies. Pragma
28340@code{Suppress (Elaboration_Check)} can be used with different levels of
28341granularity to achieve these effects.
28342
28343
28344@itemize -
28345
28346@item
28347@emph{Target suppression}
28348
28349When the pragma is placed in a declarative part, without a second argument
28350naming an entity, it will suppress implicit @code{Elaborate} and
28351@code{Elaborate_All} pragma generation, as well as run-time checks, on all
28352targets within the region.
28353
28354@example
28355package Range_Suppress is
28356   pragma Suppress (Elaboration_Check);
28357
28358   function Func return Integer;
28359
28360   generic
28361   procedure Gen;
28362
28363   pragma Unsuppress (Elaboration_Check);
28364
28365   task type Tsk;
28366end Range_Suppress;
28367@end example
28368
28369In the example above, a pair of Suppress/Unsuppress pragmas define a region
28370of suppression within package @code{Range_Suppress}. As a result, no implicit
28371@code{Elaborate} and @code{Elaborate_All} pragmas, nor any run-time checks, will
28372be generated by callers of @code{Func} and instantiators of @code{Gen}. Note that
28373task type @code{Tsk} is not within this region.
28374
28375An alternative to the region-based suppression is to use multiple
28376@code{Suppress} pragmas with arguments naming specific entities for which
28377elaboration checks should be suppressed:
28378
28379@example
28380package Range_Suppress is
28381   function Func return Integer;
28382   pragma Suppress (Elaboration_Check, Func);
28383
28384   generic
28385   procedure Gen;
28386   pragma Suppress (Elaboration_Check, Gen);
28387
28388   task type Tsk;
28389end Range_Suppress;
28390@end example
28391
28392@item
28393@emph{Scenario suppression}
28394
28395When the pragma @code{Suppress} is placed in a declarative or statement
28396part, without an entity argument, it will suppress implicit @code{Elaborate}
28397and @code{Elaborate_All} pragma generation, as well as run-time checks, on
28398all scenarios within the region.
28399
28400@example
28401with Server;
28402package body Range_Suppress is
28403   pragma Suppress (Elaboration_Check);
28404
28405   function Func return Integer is
28406   begin
28407      return Server.Func;
28408   end Func;
28409
28410   procedure Gen is
28411   begin
28412      Server.Proc;
28413   end Gen;
28414
28415   pragma Unsuppress (Elaboration_Check);
28416
28417   task body Tsk is
28418   begin
28419      Server.Proc;
28420   end Tsk;
28421end Range_Suppress;
28422@end example
28423
28424In the example above, a pair of Suppress/Unsuppress pragmas define a region
28425of suppression within package body @code{Range_Suppress}. As a result, the
28426calls to @code{Server.Func} in @code{Func} and @code{Server.Proc} in @code{Gen} will
28427not generate any implicit @code{Elaborate} and @code{Elaborate_All} pragmas or
28428run-time checks.
28429@end itemize
28430@end itemize
28431
28432@node Resolving Task Issues,Elaboration-related Compiler Switches,Resolving Elaboration Circularities,Elaboration Order Handling in GNAT
28433@anchor{gnat_ugn/elaboration_order_handling_in_gnat id14}@anchor{24b}@anchor{gnat_ugn/elaboration_order_handling_in_gnat resolving-task-issues}@anchor{24c}
28434@section Resolving Task Issues
28435
28436
28437The model of execution in Ada dictates that elaboration must first take place,
28438and only then can the main program be started. Tasks which are activated during
28439elaboration violate this model and may lead to serious concurrent problems at
28440elaboration time.
28441
28442A task can be activated in two different ways:
28443
28444
28445@itemize *
28446
28447@item
28448The task is created by an allocator in which case it is activated immediately
28449after the allocator is evaluated.
28450
28451@item
28452The task is declared at the library level or within some nested master in
28453which case it is activated before starting execution of the statement
28454sequence of the master defining the task.
28455@end itemize
28456
28457Since the elaboration of a partition is performed by the environment task
28458servicing that partition, any tasks activated during elaboration may be in
28459a race with the environment task, and lead to unpredictable state and behavior.
28460The static model seeks to avoid such interactions by assuming that all code in
28461the task body is executed at elaboration time, if the task was activated by
28462elaboration code.
28463
28464@example
28465package Decls is
28466   task Lib_Task is
28467      entry Start;
28468   end Lib_Task;
28469
28470   type My_Int is new Integer;
28471
28472   function Ident (M : My_Int) return My_Int;
28473end Decls;
28474@end example
28475
28476@example
28477with Utils;
28478package body Decls is
28479   task body Lib_Task is
28480   begin
28481      accept Start;
28482      Utils.Put_Val (2);
28483   end Lib_Task;
28484
28485   function Ident (M : My_Int) return My_Int is
28486   begin
28487      return M;
28488   end Ident;
28489end Decls;
28490@end example
28491
28492@example
28493with Decls;
28494package Utils is
28495   procedure Put_Val (Arg : Decls.My_Int);
28496end Utils;
28497@end example
28498
28499@example
28500with Ada.Text_IO; use Ada.Text_IO;
28501package body Utils is
28502   procedure Put_Val (Arg : Decls.My_Int) is
28503   begin
28504      Put_Line (Arg'Img);
28505   end Put_Val;
28506end Utils;
28507@end example
28508
28509@example
28510with Decls;
28511procedure Main is
28512begin
28513   Decls.Lib_Task.Start;
28514end Main;
28515@end example
28516
28517When the above example is compiled with the static model, an elaboration
28518circularity arises:
28519
28520@example
28521error: elaboration circularity detected
28522info:    "decls (body)" must be elaborated before "decls (body)"
28523info:       reason: implicit Elaborate_All in unit "decls (body)"
28524info:       recompile "decls (body)" with -gnatel for full details
28525info:          "decls (body)"
28526info:             must be elaborated along with its spec:
28527info:          "decls (spec)"
28528info:             which is withed by:
28529info:          "utils (spec)"
28530info:             which is withed by:
28531info:          "decls (body)"
28532@end example
28533
28534In the above example, @code{Decls} must be elaborated prior to @code{Main} by virtue
28535of a with clause. The elaboration of @code{Decls} activates task @code{Lib_Task}. The
28536static model conservatibely assumes that all code within the body of
28537@code{Lib_Task} is executed, and generates an implicit @code{Elaborate_All} pragma
28538for @code{Units} due to the call to @code{Utils.Put_Val}. The pragma implies that
28539both the spec and body of @code{Utils}, along with any units they @emph{with},
28540must be elaborated prior to @code{Decls}. However, @code{Utils}'s spec @emph{with}s
28541@code{Decls}, implying that @code{Decls} must be elaborated before @code{Utils}. The end
28542result is that @code{Utils} must be elaborated prior to @code{Utils}, and this
28543leads to a circularity.
28544
28545In reality, the example above will not exhibit an ABE problem at run time.
28546When the body of task @code{Lib_Task} is activated, execution will wait for entry
28547@code{Start} to be accepted, and the call to @code{Utils.Put_Val} will not take place
28548at elaboration time. Task @code{Lib_Task} will resume its execution after the main
28549program is executed because @code{Main} performs a rendezvous with
28550@code{Lib_Task.Start}, and at that point all units have already been elaborated.
28551As a result, the static model may seem overly conservative, partly because it
28552does not take control and data flow into account.
28553
28554When faced with a task elaboration circularity, a programmer has several
28555options available:
28556
28557
28558@itemize *
28559
28560@item
28561@emph{Use the dynamic model}
28562
28563The dynamic model does not generate implicit @code{Elaborate} and
28564@code{Elaborate_All} pragmas. Instead, it will install checks prior to every
28565call in the example above, thus verifying the successful elaboration of
28566@code{Utils.Put_Val} in case the call to it takes place at elaboration time.
28567The dynamic model is enabled with compiler switch @code{-gnatE}.
28568
28569@item
28570@emph{Isolate the tasks}
28571
28572Relocating tasks in their own separate package could decouple them from
28573dependencies that would otherwise cause an elaboration circularity. The
28574example above can be rewritten as follows:
28575
28576@example
28577package Decls1 is                --  new
28578   task Lib_Task is
28579      entry Start;
28580   end Lib_Task;
28581end Decls1;
28582@end example
28583
28584@example
28585with Utils;
28586package body Decls1 is           --  new
28587   task body Lib_Task is
28588   begin
28589      accept Start;
28590      Utils.Put_Val (2);
28591   end Lib_Task;
28592end Decls1;
28593@end example
28594
28595@example
28596package Decls2 is                --  new
28597   type My_Int is new Integer;
28598   function Ident (M : My_Int) return My_Int;
28599end Decls2;
28600@end example
28601
28602@example
28603with Utils;
28604package body Decls2 is           --  new
28605   function Ident (M : My_Int) return My_Int is
28606   begin
28607      return M;
28608   end Ident;
28609end Decls2;
28610@end example
28611
28612@example
28613with Decls2;
28614package Utils is
28615   procedure Put_Val (Arg : Decls2.My_Int);
28616end Utils;
28617@end example
28618
28619@example
28620with Ada.Text_IO; use Ada.Text_IO;
28621package body Utils is
28622   procedure Put_Val (Arg : Decls2.My_Int) is
28623   begin
28624      Put_Line (Arg'Img);
28625   end Put_Val;
28626end Utils;
28627@end example
28628
28629@example
28630with Decls1;
28631procedure Main is
28632begin
28633   Decls1.Lib_Task.Start;
28634end Main;
28635@end example
28636
28637@item
28638@emph{Declare the tasks}
28639
28640The original example uses a single task declaration for @code{Lib_Task}. An
28641explicit task type declaration and a properly placed task object could avoid
28642the dependencies that would otherwise cause an elaboration circularity. The
28643example can be rewritten as follows:
28644
28645@example
28646package Decls is
28647   task type Lib_Task is         --  new
28648      entry Start;
28649   end Lib_Task;
28650
28651   type My_Int is new Integer;
28652
28653   function Ident (M : My_Int) return My_Int;
28654end Decls;
28655@end example
28656
28657@example
28658with Utils;
28659package body Decls is
28660   task body Lib_Task is
28661   begin
28662      accept Start;
28663      Utils.Put_Val (2);
28664   end Lib_Task;
28665
28666   function Ident (M : My_Int) return My_Int is
28667   begin
28668      return M;
28669   end Ident;
28670end Decls;
28671@end example
28672
28673@example
28674with Decls;
28675package Utils is
28676   procedure Put_Val (Arg : Decls.My_Int);
28677end Utils;
28678@end example
28679
28680@example
28681with Ada.Text_IO; use Ada.Text_IO;
28682package body Utils is
28683   procedure Put_Val (Arg : Decls.My_Int) is
28684   begin
28685      Put_Line (Arg'Img);
28686   end Put_Val;
28687end Utils;
28688@end example
28689
28690@example
28691with Decls;
28692package Obj_Decls is             --  new
28693   Task_Obj : Decls.Lib_Task;
28694end Obj_Decls;
28695@end example
28696
28697@example
28698with Obj_Decls;
28699procedure Main is
28700begin
28701   Obj_Decls.Task_Obj.Start;     --  new
28702end Main;
28703@end example
28704
28705@item
28706@emph{Use restriction No_Entry_Calls_In_Elaboration_Code}
28707
28708The issue exhibited in the original example under this section revolves
28709around the body of @code{Lib_Task} blocking on an accept statement. There is
28710no rule to prevent elaboration code from performing entry calls, however in
28711practice this is highly unusual. In addition, the pattern of starting tasks
28712at elaboration time and then immediately blocking on accept or select
28713statements is quite common.
28714
28715If a programmer knows that elaboration code will not perform any entry
28716calls, then the programmer can indicate that the static model should not
28717process the remainder of a task body once an accept or select statement has
28718been encountered. This behavior can be specified by a configuration pragma:
28719
28720@example
28721pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
28722@end example
28723
28724In addition to the change in behavior with respect to task bodies, the
28725static model will verify that no entry calls take place at elaboration time.
28726@end itemize
28727
28728@node Elaboration-related Compiler Switches,Summary of Procedures for Elaboration Control,Resolving Task Issues,Elaboration Order Handling in GNAT
28729@anchor{gnat_ugn/elaboration_order_handling_in_gnat elaboration-related-compiler-switches}@anchor{24d}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id15}@anchor{24e}
28730@section Elaboration-related Compiler Switches
28731
28732
28733GNAT has several switches that affect the elaboration model and consequently
28734the elaboration order chosen by the binder.
28735
28736@geindex -gnatE (gnat)
28737
28738
28739@table @asis
28740
28741@item @code{-gnatE}
28742
28743Dynamic elaboration checking mode enabled
28744
28745When this switch is in effect, GNAT activates the dynamic elaboration model.
28746@end table
28747
28748@geindex -gnatel (gnat)
28749
28750
28751@table @asis
28752
28753@item @code{-gnatel}
28754
28755Turn on info messages on generated Elaborate[_All] pragmas
28756
28757When this switch is in effect, GNAT will emit the following supplementary
28758information depending on the elaboration model in effect.
28759
28760
28761@itemize -
28762
28763@item
28764@emph{Dynamic model}
28765
28766GNAT will indicate missing @code{Elaborate} and @code{Elaborate_All} pragmas for
28767all library-level scenarios within the partition.
28768
28769@item
28770@emph{Static model}
28771
28772GNAT will indicate all scenarios executed during elaboration. In addition,
28773it will provide detailed traceback when an implicit @code{Elaborate} or
28774@code{Elaborate_All} pragma is generated.
28775
28776@item
28777@emph{SPARK model}
28778
28779GNAT will indicate how an elaboration requirement is met by the context of
28780a unit. This diagnostic requires compiler switch @code{-gnatd.v}.
28781
28782@example
287831. with Server; pragma Elaborate_All (Server);
287842. package Client with SPARK_Mode is
287853.    Val : constant Integer := Server.Func;
28786                                      |
28787   >>> info: call to "Func" during elaboration in SPARK
28788   >>> info: "Elaborate_All" requirement for unit "Server" met by pragma at line 1
28789
287904. end Client;
28791@end example
28792@end itemize
28793@end table
28794
28795@geindex -gnatH (gnat)
28796
28797
28798@table @asis
28799
28800@item @code{-gnatH}
28801
28802Legacy elaboration checking mode enabled
28803
28804When this switch is in effect, GNAT will utilize the pre-18.x elaboration
28805model.
28806@end table
28807
28808@geindex -gnatJ (gnat)
28809
28810
28811@table @asis
28812
28813@item @code{-gnatJ}
28814
28815Relaxed elaboration checking mode enabled
28816
28817When this switch is in effect, GNAT will not process certain scenarios,
28818resulting in a more permissive elaboration model. Note that this may
28819eliminate some diagnostics and run-time checks.
28820@end table
28821
28822@geindex -gnatw.f (gnat)
28823
28824
28825@table @asis
28826
28827@item @code{-gnatw.f}
28828
28829Turn on warnings for suspicious Subp'Access
28830
28831When this switch is in effect, GNAT will treat @code{'Access} of an entry,
28832operator, or subprogram as a potential call to the target and issue warnings:
28833
28834@example
28835 1. package body Attribute_Call is
28836 2.    function Func return Integer;
28837 3.    type Func_Ptr is access function return Integer;
28838 4.
28839 5.    Ptr : constant Func_Ptr := Func'Access;
28840                                      |
28841    >>> warning: "Access" attribute of "Func" before body seen
28842    >>> warning: possible Program_Error on later references
28843    >>> warning:   body of unit "Attribute_Call" elaborated
28844    >>> warning:   "Access" of "Func" taken at line 5
28845
28846 6.
28847 7.    function Func return Integer is
28848 8.    begin
28849 9.       ...
2885010.    end Func;
2885111. end Attribute_Call;
28852@end example
28853
28854In the example above, the elaboration of declaration @code{Ptr} is assigned
28855@code{Func'Access} before the body of @code{Func} has been elaborated.
28856@end table
28857
28858@geindex -gnatwl (gnat)
28859
28860
28861@table @asis
28862
28863@item @code{-gnatwl}
28864
28865Turn on warnings for elaboration problems
28866
28867When this switch is in effect, GNAT emits diagnostics in the form of warnings
28868concerning various elaboration problems. The warnings are enabled by default.
28869The switch is provided in case all warnings are suppressed, but elaboration
28870warnings are still desired.
28871
28872@item @code{-gnatwL}
28873
28874Turn off warnings for elaboration problems
28875
28876When this switch is in effect, GNAT no longer emits any diagnostics in the
28877form of warnings. Selective suppression of elaboration problems is possible
28878using @code{pragma Warnings (Off)}.
28879
28880@example
28881 1. package body Selective_Suppression is
28882 2.    function ABE return Integer;
28883 3.
28884 4.    Val_1 : constant Integer := ABE;
28885                                   |
28886    >>> warning: cannot call "ABE" before body seen
28887    >>> warning: Program_Error will be raised at run time
28888
28889 5.
28890 6.    pragma Warnings (Off);
28891 7.    Val_2 : constant Integer := ABE;
28892 8.    pragma Warnings (On);
28893 9.
2889410.    function ABE return Integer is
2889511.    begin
2889612.       ...
2889713.    end ABE;
2889814. end Selective_Suppression;
28899@end example
28900
28901Note that suppressing elaboration warnings does not eliminate run-time
28902checks. The example above will still fail at run time with an ABE.
28903@end table
28904
28905@node Summary of Procedures for Elaboration Control,Inspecting the Chosen Elaboration Order,Elaboration-related Compiler Switches,Elaboration Order Handling in GNAT
28906@anchor{gnat_ugn/elaboration_order_handling_in_gnat summary-of-procedures-for-elaboration-control}@anchor{24f}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id16}@anchor{250}
28907@section Summary of Procedures for Elaboration Control
28908
28909
28910A programmer should first compile the program with the default options, using
28911none of the binder or compiler switches. If the binder succeeds in finding an
28912elaboration order, then apart from possible cases involing dispatching calls
28913and access-to-subprogram types, the program is free of elaboration errors.
28914
28915If it is important for the program to be portable to compilers other than GNAT,
28916then the programmer should use compiler switch @code{-gnatel} and consider
28917the messages about missing or implicitly created @code{Elaborate} and
28918@code{Elaborate_All} pragmas.
28919
28920If the binder reports an elaboration circularity, the programmer has several
28921options:
28922
28923
28924@itemize *
28925
28926@item
28927Ensure that elaboration warnings are enabled. This will allow the static
28928model to output trace information of elaboration issues. The trace
28929information could shed light on previously unforeseen dependencies, as well
28930as their origins. Elaboration warnings are enabled with compiler switch
28931@code{-gnatwl}.
28932
28933@item
28934Use switch @code{-gnatel} to obtain messages on generated implicit
28935@code{Elaborate} and @code{Elaborate_All} pragmas. The trace information could
28936indicate why a server unit must be elaborated prior to a client unit.
28937
28938@item
28939If the warnings produced by the static model indicate that a task is
28940involved, consider the options in section @ref{24b,,Resolving Task Issues}.
28941
28942@item
28943If none of the steps outlined above resolve the circularity, use a more
28944permissive elaboration model, in the following order:
28945
28946
28947@itemize -
28948
28949@item
28950Use the dynamic elaboration model, with compiler switch @code{-gnatE}.
28951
28952@item
28953Use the legacy static elaboration model, with compiler switch
28954@code{-gnatH}.
28955
28956@item
28957Use the legacy dynamic elaboration model, with compiler switches
28958@code{-gnatH} @code{-gnatE}.
28959
28960@item
28961Use the relaxed legacy static elaboration model, with compiler switches
28962@code{-gnatH} @code{-gnatJ}.
28963
28964@item
28965Use the relaxed legacy dynamic elaboration model, with compiler switches
28966@code{-gnatH} @code{-gnatJ} @code{-gnatE}.
28967@end itemize
28968@end itemize
28969
28970@node Inspecting the Chosen Elaboration Order,,Summary of Procedures for Elaboration Control,Elaboration Order Handling in GNAT
28971@anchor{gnat_ugn/elaboration_order_handling_in_gnat inspecting-the-chosen-elaboration-order}@anchor{251}@anchor{gnat_ugn/elaboration_order_handling_in_gnat id17}@anchor{252}
28972@section Inspecting the Chosen Elaboration Order
28973
28974
28975To see the elaboration order chosen by the binder, inspect the contents of file
28976@cite{b~xxx.adb}. On certain targets, this file appears as @cite{b_xxx.adb}. The
28977elaboration order appears as a sequence of calls to @code{Elab_Body} and
28978@code{Elab_Spec}, interspersed with assignments to @cite{Exxx} which indicates that a
28979particular unit is elaborated. For example:
28980
28981@example
28982System.Soft_Links'Elab_Body;
28983E14 := True;
28984System.Secondary_Stack'Elab_Body;
28985E18 := True;
28986System.Exception_Table'Elab_Body;
28987E24 := True;
28988Ada.Io_Exceptions'Elab_Spec;
28989E67 := True;
28990Ada.Tags'Elab_Spec;
28991Ada.Streams'Elab_Spec;
28992E43 := True;
28993Interfaces.C'Elab_Spec;
28994E69 := True;
28995System.Finalization_Root'Elab_Spec;
28996E60 := True;
28997System.Os_Lib'Elab_Body;
28998E71 := True;
28999System.Finalization_Implementation'Elab_Spec;
29000System.Finalization_Implementation'Elab_Body;
29001E62 := True;
29002Ada.Finalization'Elab_Spec;
29003E58 := True;
29004Ada.Finalization.List_Controller'Elab_Spec;
29005E76 := True;
29006System.File_Control_Block'Elab_Spec;
29007E74 := True;
29008System.File_Io'Elab_Body;
29009E56 := True;
29010Ada.Tags'Elab_Body;
29011E45 := True;
29012Ada.Text_Io'Elab_Spec;
29013Ada.Text_Io'Elab_Body;
29014E07 := True;
29015@end example
29016
29017Note also binder switch @code{-l}, which outputs the chosen elaboration
29018order and provides a more readable form of the above:
29019
29020@example
29021ada (spec)
29022interfaces (spec)
29023system (spec)
29024system.case_util (spec)
29025system.case_util (body)
29026system.concat_2 (spec)
29027system.concat_2 (body)
29028system.concat_3 (spec)
29029system.concat_3 (body)
29030system.htable (spec)
29031system.parameters (spec)
29032system.parameters (body)
29033system.crtl (spec)
29034interfaces.c_streams (spec)
29035interfaces.c_streams (body)
29036system.restrictions (spec)
29037system.restrictions (body)
29038system.standard_library (spec)
29039system.exceptions (spec)
29040system.exceptions (body)
29041system.storage_elements (spec)
29042system.storage_elements (body)
29043system.secondary_stack (spec)
29044system.stack_checking (spec)
29045system.stack_checking (body)
29046system.string_hash (spec)
29047system.string_hash (body)
29048system.htable (body)
29049system.strings (spec)
29050system.strings (body)
29051system.traceback (spec)
29052system.traceback (body)
29053system.traceback_entries (spec)
29054system.traceback_entries (body)
29055ada.exceptions (spec)
29056ada.exceptions.last_chance_handler (spec)
29057system.soft_links (spec)
29058system.soft_links (body)
29059ada.exceptions.last_chance_handler (body)
29060system.secondary_stack (body)
29061system.exception_table (spec)
29062system.exception_table (body)
29063ada.io_exceptions (spec)
29064ada.tags (spec)
29065ada.streams (spec)
29066interfaces.c (spec)
29067interfaces.c (body)
29068system.finalization_root (spec)
29069system.finalization_root (body)
29070system.memory (spec)
29071system.memory (body)
29072system.standard_library (body)
29073system.os_lib (spec)
29074system.os_lib (body)
29075system.unsigned_types (spec)
29076system.stream_attributes (spec)
29077system.stream_attributes (body)
29078system.finalization_implementation (spec)
29079system.finalization_implementation (body)
29080ada.finalization (spec)
29081ada.finalization (body)
29082ada.finalization.list_controller (spec)
29083ada.finalization.list_controller (body)
29084system.file_control_block (spec)
29085system.file_io (spec)
29086system.file_io (body)
29087system.val_uns (spec)
29088system.val_util (spec)
29089system.val_util (body)
29090system.val_uns (body)
29091system.wch_con (spec)
29092system.wch_con (body)
29093system.wch_cnv (spec)
29094system.wch_jis (spec)
29095system.wch_jis (body)
29096system.wch_cnv (body)
29097system.wch_stw (spec)
29098system.wch_stw (body)
29099ada.tags (body)
29100ada.exceptions (body)
29101ada.text_io (spec)
29102ada.text_io (body)
29103text_io (spec)
29104gdbstr (body)
29105@end example
29106
29107@node Inline Assembler,GNU Free Documentation License,Elaboration Order Handling in GNAT,Top
29108@anchor{gnat_ugn/inline_assembler inline-assembler}@anchor{10}@anchor{gnat_ugn/inline_assembler doc}@anchor{253}@anchor{gnat_ugn/inline_assembler id1}@anchor{254}
29109@chapter Inline Assembler
29110
29111
29112@geindex Inline Assembler
29113
29114If you need to write low-level software that interacts directly
29115with the hardware, Ada provides two ways to incorporate assembly
29116language code into your program.  First, you can import and invoke
29117external routines written in assembly language, an Ada feature fully
29118supported by GNAT.  However, for small sections of code it may be simpler
29119or more efficient to include assembly language statements directly
29120in your Ada source program, using the facilities of the implementation-defined
29121package @code{System.Machine_Code}, which incorporates the gcc
29122Inline Assembler.  The Inline Assembler approach offers a number of advantages,
29123including the following:
29124
29125
29126@itemize *
29127
29128@item
29129No need to use non-Ada tools
29130
29131@item
29132Consistent interface over different targets
29133
29134@item
29135Automatic usage of the proper calling conventions
29136
29137@item
29138Access to Ada constants and variables
29139
29140@item
29141Definition of intrinsic routines
29142
29143@item
29144Possibility of inlining a subprogram comprising assembler code
29145
29146@item
29147Code optimizer can take Inline Assembler code into account
29148@end itemize
29149
29150This appendix presents a series of examples to show you how to use
29151the Inline Assembler.  Although it focuses on the Intel x86,
29152the general approach applies also to other processors.
29153It is assumed that you are familiar with Ada
29154and with assembly language programming.
29155
29156@menu
29157* Basic Assembler Syntax::
29158* A Simple Example of Inline Assembler::
29159* Output Variables in Inline Assembler::
29160* Input Variables in Inline Assembler::
29161* Inlining Inline Assembler Code::
29162* Other Asm Functionality::
29163
29164@end menu
29165
29166@node Basic Assembler Syntax,A Simple Example of Inline Assembler,,Inline Assembler
29167@anchor{gnat_ugn/inline_assembler id2}@anchor{255}@anchor{gnat_ugn/inline_assembler basic-assembler-syntax}@anchor{256}
29168@section Basic Assembler Syntax
29169
29170
29171The assembler used by GNAT and gcc is based not on the Intel assembly
29172language, but rather on a language that descends from the AT&T Unix
29173assembler @code{as} (and which is often referred to as 'AT&T syntax').
29174The following table summarizes the main features of @code{as} syntax
29175and points out the differences from the Intel conventions.
29176See the gcc @code{as} and @code{gas} (an @code{as} macro
29177pre-processor) documentation for further information.
29178
29179
29180@display
29181@emph{Register names}@w{ }
29182@display
29183gcc / @code{as}: Prefix with '%'; for example @code{%eax}@w{ }
29184Intel: No extra punctuation; for example @code{eax}@w{ }
29185@end display
29186@end display
29187
29188
29189
29190
29191@display
29192@emph{Immediate operand}@w{ }
29193@display
29194gcc / @code{as}: Prefix with '$'; for example @code{$4}@w{ }
29195Intel: No extra punctuation; for example @code{4}@w{ }
29196@end display
29197@end display
29198
29199
29200
29201
29202@display
29203@emph{Address}@w{ }
29204@display
29205gcc / @code{as}: Prefix with '$'; for example @code{$loc}@w{ }
29206Intel: No extra punctuation; for example @code{loc}@w{ }
29207@end display
29208@end display
29209
29210
29211
29212
29213@display
29214@emph{Memory contents}@w{ }
29215@display
29216gcc / @code{as}: No extra punctuation; for example @code{loc}@w{ }
29217Intel: Square brackets; for example @code{[loc]}@w{ }
29218@end display
29219@end display
29220
29221
29222
29223
29224@display
29225@emph{Register contents}@w{ }
29226@display
29227gcc / @code{as}: Parentheses; for example @code{(%eax)}@w{ }
29228Intel: Square brackets; for example @code{[eax]}@w{ }
29229@end display
29230@end display
29231
29232
29233
29234
29235@display
29236@emph{Hexadecimal numbers}@w{ }
29237@display
29238gcc / @code{as}: Leading '0x' (C language syntax); for example @code{0xA0}@w{ }
29239Intel: Trailing 'h'; for example @code{A0h}@w{ }
29240@end display
29241@end display
29242
29243
29244
29245
29246@display
29247@emph{Operand size}@w{ }
29248@display
29249gcc / @code{as}: Explicit in op code; for example @code{movw} to move a 16-bit word@w{ }
29250Intel: Implicit, deduced by assembler; for example @code{mov}@w{ }
29251@end display
29252@end display
29253
29254
29255
29256
29257@display
29258@emph{Instruction repetition}@w{ }
29259@display
29260gcc / @code{as}: Split into two lines; for example@w{ }
29261@display
29262@code{rep}@w{ }
29263@code{stosl}@w{ }
29264@end display
29265Intel: Keep on one line; for example @code{rep stosl}@w{ }
29266@end display
29267@end display
29268
29269
29270
29271
29272@display
29273@emph{Order of operands}@w{ }
29274@display
29275gcc / @code{as}: Source first; for example @code{movw $4, %eax}@w{ }
29276Intel: Destination first; for example @code{mov eax, 4}@w{ }
29277@end display
29278@end display
29279
29280
29281
29282@node A Simple Example of Inline Assembler,Output Variables in Inline Assembler,Basic Assembler Syntax,Inline Assembler
29283@anchor{gnat_ugn/inline_assembler a-simple-example-of-inline-assembler}@anchor{257}@anchor{gnat_ugn/inline_assembler id3}@anchor{258}
29284@section A Simple Example of Inline Assembler
29285
29286
29287The following example will generate a single assembly language statement,
29288@code{nop}, which does nothing.  Despite its lack of run-time effect,
29289the example will be useful in illustrating the basics of
29290the Inline Assembler facility.
29291
29292@quotation
29293
29294@example
29295with System.Machine_Code; use System.Machine_Code;
29296procedure Nothing is
29297begin
29298   Asm ("nop");
29299end Nothing;
29300@end example
29301@end quotation
29302
29303@code{Asm} is a procedure declared in package @code{System.Machine_Code};
29304here it takes one parameter, a @emph{template string} that must be a static
29305expression and that will form the generated instruction.
29306@code{Asm} may be regarded as a compile-time procedure that parses
29307the template string and additional parameters (none here),
29308from which it generates a sequence of assembly language instructions.
29309
29310The examples in this chapter will illustrate several of the forms
29311for invoking @code{Asm}; a complete specification of the syntax
29312is found in the @code{Machine_Code_Insertions} section of the
29313@cite{GNAT Reference Manual}.
29314
29315Under the standard GNAT conventions, the @code{Nothing} procedure
29316should be in a file named @code{nothing.adb}.
29317You can build the executable in the usual way:
29318
29319@quotation
29320
29321@example
29322$ gnatmake nothing
29323@end example
29324@end quotation
29325
29326However, the interesting aspect of this example is not its run-time behavior
29327but rather the generated assembly code.
29328To see this output, invoke the compiler as follows:
29329
29330@quotation
29331
29332@example
29333$  gcc -c -S -fomit-frame-pointer -gnatp nothing.adb
29334@end example
29335@end quotation
29336
29337where the options are:
29338
29339
29340@itemize *
29341
29342@item
29343
29344@table @asis
29345
29346@item @code{-c}
29347
29348compile only (no bind or link)
29349@end table
29350
29351@item
29352
29353@table @asis
29354
29355@item @code{-S}
29356
29357generate assembler listing
29358@end table
29359
29360@item
29361
29362@table @asis
29363
29364@item @code{-fomit-frame-pointer}
29365
29366do not set up separate stack frames
29367@end table
29368
29369@item
29370
29371@table @asis
29372
29373@item @code{-gnatp}
29374
29375do not add runtime checks
29376@end table
29377@end itemize
29378
29379This gives a human-readable assembler version of the code. The resulting
29380file will have the same name as the Ada source file, but with a @code{.s}
29381extension. In our example, the file @code{nothing.s} has the following
29382contents:
29383
29384@quotation
29385
29386@example
29387.file "nothing.adb"
29388gcc2_compiled.:
29389___gnu_compiled_ada:
29390.text
29391   .align 4
29392.globl __ada_nothing
29393__ada_nothing:
29394#APP
29395   nop
29396#NO_APP
29397   jmp L1
29398   .align 2,0x90
29399L1:
29400   ret
29401@end example
29402@end quotation
29403
29404The assembly code you included is clearly indicated by
29405the compiler, between the @code{#APP} and @code{#NO_APP}
29406delimiters. The character before the 'APP' and 'NOAPP'
29407can differ on different targets. For example, GNU/Linux uses '#APP' while
29408on NT you will see '/APP'.
29409
29410If you make a mistake in your assembler code (such as using the
29411wrong size modifier, or using a wrong operand for the instruction) GNAT
29412will report this error in a temporary file, which will be deleted when
29413the compilation is finished.  Generating an assembler file will help
29414in such cases, since you can assemble this file separately using the
29415@code{as} assembler that comes with gcc.
29416
29417Assembling the file using the command
29418
29419@quotation
29420
29421@example
29422$ as nothing.s
29423@end example
29424@end quotation
29425
29426will give you error messages whose lines correspond to the assembler
29427input file, so you can easily find and correct any mistakes you made.
29428If there are no errors, @code{as} will generate an object file
29429@code{nothing.out}.
29430
29431@node Output Variables in Inline Assembler,Input Variables in Inline Assembler,A Simple Example of Inline Assembler,Inline Assembler
29432@anchor{gnat_ugn/inline_assembler id4}@anchor{259}@anchor{gnat_ugn/inline_assembler output-variables-in-inline-assembler}@anchor{25a}
29433@section Output Variables in Inline Assembler
29434
29435
29436The examples in this section, showing how to access the processor flags,
29437illustrate how to specify the destination operands for assembly language
29438statements.
29439
29440@quotation
29441
29442@example
29443with Interfaces; use Interfaces;
29444with Ada.Text_IO; use Ada.Text_IO;
29445with System.Machine_Code; use System.Machine_Code;
29446procedure Get_Flags is
29447   Flags : Unsigned_32;
29448   use ASCII;
29449begin
29450   Asm ("pushfl"          & LF & HT & -- push flags on stack
29451        "popl %%eax"      & LF & HT & -- load eax with flags
29452        "movl %%eax, %0",             -- store flags in variable
29453        Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29454   Put_Line ("Flags register:" & Flags'Img);
29455end Get_Flags;
29456@end example
29457@end quotation
29458
29459In order to have a nicely aligned assembly listing, we have separated
29460multiple assembler statements in the Asm template string with linefeed
29461(ASCII.LF) and horizontal tab (ASCII.HT) characters.
29462The resulting section of the assembly output file is:
29463
29464@quotation
29465
29466@example
29467#APP
29468   pushfl
29469   popl %eax
29470   movl %eax, -40(%ebp)
29471#NO_APP
29472@end example
29473@end quotation
29474
29475It would have been legal to write the Asm invocation as:
29476
29477@quotation
29478
29479@example
29480Asm ("pushfl popl %%eax movl %%eax, %0")
29481@end example
29482@end quotation
29483
29484but in the generated assembler file, this would come out as:
29485
29486@quotation
29487
29488@example
29489#APP
29490   pushfl popl %eax movl %eax, -40(%ebp)
29491#NO_APP
29492@end example
29493@end quotation
29494
29495which is not so convenient for the human reader.
29496
29497We use Ada comments
29498at the end of each line to explain what the assembler instructions
29499actually do.  This is a useful convention.
29500
29501When writing Inline Assembler instructions, you need to precede each register
29502and variable name with a percent sign.  Since the assembler already requires
29503a percent sign at the beginning of a register name, you need two consecutive
29504percent signs for such names in the Asm template string, thus @code{%%eax}.
29505In the generated assembly code, one of the percent signs will be stripped off.
29506
29507Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
29508variables: operands you later define using @code{Input} or @code{Output}
29509parameters to @code{Asm}.
29510An output variable is illustrated in
29511the third statement in the Asm template string:
29512
29513@quotation
29514
29515@example
29516movl %%eax, %0
29517@end example
29518@end quotation
29519
29520The intent is to store the contents of the eax register in a variable that can
29521be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
29522necessarily work, since the compiler might optimize by using a register
29523to hold Flags, and the expansion of the @code{movl} instruction would not be
29524aware of this optimization.  The solution is not to store the result directly
29525but rather to advise the compiler to choose the correct operand form;
29526that is the purpose of the @code{%0} output variable.
29527
29528Information about the output variable is supplied in the @code{Outputs}
29529parameter to @code{Asm}:
29530
29531@quotation
29532
29533@example
29534Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29535@end example
29536@end quotation
29537
29538The output is defined by the @code{Asm_Output} attribute of the target type;
29539the general format is
29540
29541@quotation
29542
29543@example
29544Type'Asm_Output (constraint_string, variable_name)
29545@end example
29546@end quotation
29547
29548The constraint string directs the compiler how
29549to store/access the associated variable.  In the example
29550
29551@quotation
29552
29553@example
29554Unsigned_32'Asm_Output ("=m", Flags);
29555@end example
29556@end quotation
29557
29558the @code{"m"} (memory) constraint tells the compiler that the variable
29559@code{Flags} should be stored in a memory variable, thus preventing
29560the optimizer from keeping it in a register.  In contrast,
29561
29562@quotation
29563
29564@example
29565Unsigned_32'Asm_Output ("=r", Flags);
29566@end example
29567@end quotation
29568
29569uses the @code{"r"} (register) constraint, telling the compiler to
29570store the variable in a register.
29571
29572If the constraint is preceded by the equal character '=', it tells
29573the compiler that the variable will be used to store data into it.
29574
29575In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
29576allowing the optimizer to choose whatever it deems best.
29577
29578There are a fairly large number of constraints, but the ones that are
29579most useful (for the Intel x86 processor) are the following:
29580
29581@quotation
29582
29583
29584@multitable {xxxxxxxx} {xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx}
29585@item
29586
29587@emph{=}
29588
29589@tab
29590
29591output constraint
29592
29593@item
29594
29595@emph{g}
29596
29597@tab
29598
29599global (i.e., can be stored anywhere)
29600
29601@item
29602
29603@emph{m}
29604
29605@tab
29606
29607in memory
29608
29609@item
29610
29611@emph{I}
29612
29613@tab
29614
29615a constant
29616
29617@item
29618
29619@emph{a}
29620
29621@tab
29622
29623use eax
29624
29625@item
29626
29627@emph{b}
29628
29629@tab
29630
29631use ebx
29632
29633@item
29634
29635@emph{c}
29636
29637@tab
29638
29639use ecx
29640
29641@item
29642
29643@emph{d}
29644
29645@tab
29646
29647use edx
29648
29649@item
29650
29651@emph{S}
29652
29653@tab
29654
29655use esi
29656
29657@item
29658
29659@emph{D}
29660
29661@tab
29662
29663use edi
29664
29665@item
29666
29667@emph{r}
29668
29669@tab
29670
29671use one of eax, ebx, ecx or edx
29672
29673@item
29674
29675@emph{q}
29676
29677@tab
29678
29679use one of eax, ebx, ecx, edx, esi or edi
29680
29681@end multitable
29682
29683@end quotation
29684
29685The full set of constraints is described in the gcc and @code{as}
29686documentation; note that it is possible to combine certain constraints
29687in one constraint string.
29688
29689You specify the association of an output variable with an assembler operand
29690through the @code{%@emph{n}} notation, where @emph{n} is a non-negative
29691integer.  Thus in
29692
29693@quotation
29694
29695@example
29696Asm ("pushfl"          & LF & HT & -- push flags on stack
29697     "popl %%eax"      & LF & HT & -- load eax with flags
29698     "movl %%eax, %0",             -- store flags in variable
29699     Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29700@end example
29701@end quotation
29702
29703@code{%0} will be replaced in the expanded code by the appropriate operand,
29704whatever
29705the compiler decided for the @code{Flags} variable.
29706
29707In general, you may have any number of output variables:
29708
29709
29710@itemize *
29711
29712@item
29713Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
29714
29715@item
29716Specify the @code{Outputs} parameter as a parenthesized comma-separated list
29717of @code{Asm_Output} attributes
29718@end itemize
29719
29720For example:
29721
29722@quotation
29723
29724@example
29725Asm ("movl %%eax, %0" & LF & HT &
29726     "movl %%ebx, %1" & LF & HT &
29727     "movl %%ecx, %2",
29728     Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
29729                 Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
29730                 Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
29731@end example
29732@end quotation
29733
29734where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
29735in the Ada program.
29736
29737As a variation on the @code{Get_Flags} example, we can use the constraints
29738string to direct the compiler to store the eax register into the @code{Flags}
29739variable, instead of including the store instruction explicitly in the
29740@code{Asm} template string:
29741
29742@quotation
29743
29744@example
29745with Interfaces; use Interfaces;
29746with Ada.Text_IO; use Ada.Text_IO;
29747with System.Machine_Code; use System.Machine_Code;
29748procedure Get_Flags_2 is
29749   Flags : Unsigned_32;
29750   use ASCII;
29751begin
29752   Asm ("pushfl"      & LF & HT & -- push flags on stack
29753        "popl %%eax",             -- save flags in eax
29754        Outputs => Unsigned_32'Asm_Output ("=a", Flags));
29755   Put_Line ("Flags register:" & Flags'Img);
29756end Get_Flags_2;
29757@end example
29758@end quotation
29759
29760The @code{"a"} constraint tells the compiler that the @code{Flags}
29761variable will come from the eax register. Here is the resulting code:
29762
29763@quotation
29764
29765@example
29766#APP
29767   pushfl
29768   popl %eax
29769#NO_APP
29770   movl %eax,-40(%ebp)
29771@end example
29772@end quotation
29773
29774The compiler generated the store of eax into Flags after
29775expanding the assembler code.
29776
29777Actually, there was no need to pop the flags into the eax register;
29778more simply, we could just pop the flags directly into the program variable:
29779
29780@quotation
29781
29782@example
29783with Interfaces; use Interfaces;
29784with Ada.Text_IO; use Ada.Text_IO;
29785with System.Machine_Code; use System.Machine_Code;
29786procedure Get_Flags_3 is
29787   Flags : Unsigned_32;
29788   use ASCII;
29789begin
29790   Asm ("pushfl"  & LF & HT & -- push flags on stack
29791        "pop %0",             -- save flags in Flags
29792        Outputs => Unsigned_32'Asm_Output ("=g", Flags));
29793   Put_Line ("Flags register:" & Flags'Img);
29794end Get_Flags_3;
29795@end example
29796@end quotation
29797
29798@node Input Variables in Inline Assembler,Inlining Inline Assembler Code,Output Variables in Inline Assembler,Inline Assembler
29799@anchor{gnat_ugn/inline_assembler id5}@anchor{25b}@anchor{gnat_ugn/inline_assembler input-variables-in-inline-assembler}@anchor{25c}
29800@section Input Variables in Inline Assembler
29801
29802
29803The example in this section illustrates how to specify the source operands
29804for assembly language statements.
29805The program simply increments its input value by 1:
29806
29807@quotation
29808
29809@example
29810with Interfaces; use Interfaces;
29811with Ada.Text_IO; use Ada.Text_IO;
29812with System.Machine_Code; use System.Machine_Code;
29813procedure Increment is
29814
29815   function Incr (Value : Unsigned_32) return Unsigned_32 is
29816      Result : Unsigned_32;
29817   begin
29818      Asm ("incl %0",
29819           Outputs => Unsigned_32'Asm_Output ("=a", Result),
29820           Inputs  => Unsigned_32'Asm_Input ("a", Value));
29821      return Result;
29822   end Incr;
29823
29824   Value : Unsigned_32;
29825
29826begin
29827   Value := 5;
29828   Put_Line ("Value before is" & Value'Img);
29829   Value := Incr (Value);
29830  Put_Line ("Value after is" & Value'Img);
29831end Increment;
29832@end example
29833@end quotation
29834
29835The @code{Outputs} parameter to @code{Asm} specifies
29836that the result will be in the eax register and that it is to be stored
29837in the @code{Result} variable.
29838
29839The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
29840but with an @code{Asm_Input} attribute.
29841The @code{"="} constraint, indicating an output value, is not present.
29842
29843You can have multiple input variables, in the same way that you can have more
29844than one output variable.
29845
29846The parameter count (%0, %1) etc, still starts at the first output statement,
29847and continues with the input statements.
29848
29849Just as the @code{Outputs} parameter causes the register to be stored into the
29850target variable after execution of the assembler statements, so does the
29851@code{Inputs} parameter cause its variable to be loaded into the register
29852before execution of the assembler statements.
29853
29854Thus the effect of the @code{Asm} invocation is:
29855
29856
29857@itemize *
29858
29859@item
29860load the 32-bit value of @code{Value} into eax
29861
29862@item
29863execute the @code{incl %eax} instruction
29864
29865@item
29866store the contents of eax into the @code{Result} variable
29867@end itemize
29868
29869The resulting assembler file (with @code{-O2} optimization) contains:
29870
29871@quotation
29872
29873@example
29874_increment__incr.1:
29875   subl $4,%esp
29876   movl 8(%esp),%eax
29877#APP
29878   incl %eax
29879#NO_APP
29880   movl %eax,%edx
29881   movl %ecx,(%esp)
29882   addl $4,%esp
29883   ret
29884@end example
29885@end quotation
29886
29887@node Inlining Inline Assembler Code,Other Asm Functionality,Input Variables in Inline Assembler,Inline Assembler
29888@anchor{gnat_ugn/inline_assembler id6}@anchor{25d}@anchor{gnat_ugn/inline_assembler inlining-inline-assembler-code}@anchor{25e}
29889@section Inlining Inline Assembler Code
29890
29891
29892For a short subprogram such as the @code{Incr} function in the previous
29893section, the overhead of the call and return (creating / deleting the stack
29894frame) can be significant, compared to the amount of code in the subprogram
29895body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
29896which directs the compiler to expand invocations of the subprogram at the
29897point(s) of call, instead of setting up a stack frame for out-of-line calls.
29898Here is the resulting program:
29899
29900@quotation
29901
29902@example
29903with Interfaces; use Interfaces;
29904with Ada.Text_IO; use Ada.Text_IO;
29905with System.Machine_Code; use System.Machine_Code;
29906procedure Increment_2 is
29907
29908   function Incr (Value : Unsigned_32) return Unsigned_32 is
29909      Result : Unsigned_32;
29910   begin
29911      Asm ("incl %0",
29912           Outputs => Unsigned_32'Asm_Output ("=a", Result),
29913           Inputs  => Unsigned_32'Asm_Input ("a", Value));
29914      return Result;
29915   end Incr;
29916   pragma Inline (Increment);
29917
29918   Value : Unsigned_32;
29919
29920begin
29921   Value := 5;
29922   Put_Line ("Value before is" & Value'Img);
29923   Value := Increment (Value);
29924   Put_Line ("Value after is" & Value'Img);
29925end Increment_2;
29926@end example
29927@end quotation
29928
29929Compile the program with both optimization (@code{-O2}) and inlining
29930(@code{-gnatn}) enabled.
29931
29932The @code{Incr} function is still compiled as usual, but at the
29933point in @code{Increment} where our function used to be called:
29934
29935@quotation
29936
29937@example
29938pushl %edi
29939call _increment__incr.1
29940@end example
29941@end quotation
29942
29943the code for the function body directly appears:
29944
29945@quotation
29946
29947@example
29948movl %esi,%eax
29949#APP
29950   incl %eax
29951#NO_APP
29952   movl %eax,%edx
29953@end example
29954@end quotation
29955
29956thus saving the overhead of stack frame setup and an out-of-line call.
29957
29958@node Other Asm Functionality,,Inlining Inline Assembler Code,Inline Assembler
29959@anchor{gnat_ugn/inline_assembler other-asm-functionality}@anchor{25f}@anchor{gnat_ugn/inline_assembler id7}@anchor{260}
29960@section Other @code{Asm} Functionality
29961
29962
29963This section describes two important parameters to the @code{Asm}
29964procedure: @code{Clobber}, which identifies register usage;
29965and @code{Volatile}, which inhibits unwanted optimizations.
29966
29967@menu
29968* The Clobber Parameter::
29969* The Volatile Parameter::
29970
29971@end menu
29972
29973@node The Clobber Parameter,The Volatile Parameter,,Other Asm Functionality
29974@anchor{gnat_ugn/inline_assembler the-clobber-parameter}@anchor{261}@anchor{gnat_ugn/inline_assembler id8}@anchor{262}
29975@subsection The @code{Clobber} Parameter
29976
29977
29978One of the dangers of intermixing assembly language and a compiled language
29979such as Ada is that the compiler needs to be aware of which registers are
29980being used by the assembly code.  In some cases, such as the earlier examples,
29981the constraint string is sufficient to indicate register usage (e.g.,
29982@code{"a"} for
29983the eax register).  But more generally, the compiler needs an explicit
29984identification of the registers that are used by the Inline Assembly
29985statements.
29986
29987Using a register that the compiler doesn't know about
29988could be a side effect of an instruction (like @code{mull}
29989storing its result in both eax and edx).
29990It can also arise from explicit register usage in your
29991assembly code; for example:
29992
29993@quotation
29994
29995@example
29996Asm ("movl %0, %%ebx" & LF & HT &
29997     "movl %%ebx, %1",
29998     Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
29999     Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
30000@end example
30001@end quotation
30002
30003where the compiler (since it does not analyze the @code{Asm} template string)
30004does not know you are using the ebx register.
30005
30006In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
30007to identify the registers that will be used by your assembly code:
30008
30009@quotation
30010
30011@example
30012Asm ("movl %0, %%ebx" & LF & HT &
30013     "movl %%ebx, %1",
30014     Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
30015     Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
30016     Clobber => "ebx");
30017@end example
30018@end quotation
30019
30020The Clobber parameter is a static string expression specifying the
30021register(s) you are using.  Note that register names are @emph{not} prefixed
30022by a percent sign. Also, if more than one register is used then their names
30023are separated by commas; e.g., @code{"eax, ebx"}
30024
30025The @code{Clobber} parameter has several additional uses:
30026
30027
30028@itemize *
30029
30030@item
30031Use 'register' name @code{cc} to indicate that flags might have changed
30032
30033@item
30034Use 'register' name @code{memory} if you changed a memory location
30035@end itemize
30036
30037@node The Volatile Parameter,,The Clobber Parameter,Other Asm Functionality
30038@anchor{gnat_ugn/inline_assembler the-volatile-parameter}@anchor{263}@anchor{gnat_ugn/inline_assembler id9}@anchor{264}
30039@subsection The @code{Volatile} Parameter
30040
30041
30042@geindex Volatile parameter
30043
30044Compiler optimizations in the presence of Inline Assembler may sometimes have
30045unwanted effects.  For example, when an @code{Asm} invocation with an input
30046variable is inside a loop, the compiler might move the loading of the input
30047variable outside the loop, regarding it as a one-time initialization.
30048
30049If this effect is not desired, you can disable such optimizations by setting
30050the @code{Volatile} parameter to @code{True}; for example:
30051
30052@quotation
30053
30054@example
30055Asm ("movl %0, %%ebx" & LF & HT &
30056     "movl %%ebx, %1",
30057     Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
30058     Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
30059     Clobber  => "ebx",
30060     Volatile => True);
30061@end example
30062@end quotation
30063
30064By default, @code{Volatile} is set to @code{False} unless there is no
30065@code{Outputs} parameter.
30066
30067Although setting @code{Volatile} to @code{True} prevents unwanted
30068optimizations, it will also disable other optimizations that might be
30069important for efficiency. In general, you should set @code{Volatile}
30070to @code{True} only if the compiler's optimizations have created
30071problems.
30072
30073@node GNU Free Documentation License,Index,Inline Assembler,Top
30074@anchor{share/gnu_free_documentation_license gnu-fdl}@anchor{1}@anchor{share/gnu_free_documentation_license doc}@anchor{265}@anchor{share/gnu_free_documentation_license gnu-free-documentation-license}@anchor{266}
30075@chapter GNU Free Documentation License
30076
30077
30078Version 1.3, 3 November 2008
30079
30080Copyright  2000, 2001, 2002, 2007, 2008  Free Software Foundation, Inc
30081@indicateurl{http://fsf.org/}
30082
30083Everyone is permitted to copy and distribute verbatim copies of this
30084license document, but changing it is not allowed.
30085
30086@strong{Preamble}
30087
30088The purpose of this License is to make a manual, textbook, or other
30089functional and useful document "free" in the sense of freedom: to
30090assure everyone the effective freedom to copy and redistribute it,
30091with or without modifying it, either commercially or noncommercially.
30092Secondarily, this License preserves for the author and publisher a way
30093to get credit for their work, while not being considered responsible
30094for modifications made by others.
30095
30096This License is a kind of "copyleft", which means that derivative
30097works of the document must themselves be free in the same sense.  It
30098complements the GNU General Public License, which is a copyleft
30099license designed for free software.
30100
30101We have designed this License in order to use it for manuals for free
30102software, because free software needs free documentation: a free
30103program should come with manuals providing the same freedoms that the
30104software does.  But this License is not limited to software manuals;
30105it can be used for any textual work, regardless of subject matter or
30106whether it is published as a printed book.  We recommend this License
30107principally for works whose purpose is instruction or reference.
30108
30109@strong{1. APPLICABILITY AND DEFINITIONS}
30110
30111This License applies to any manual or other work, in any medium, that
30112contains a notice placed by the copyright holder saying it can be
30113distributed under the terms of this License.  Such a notice grants a
30114world-wide, royalty-free license, unlimited in duration, to use that
30115work under the conditions stated herein.  The @strong{Document}, below,
30116refers to any such manual or work.  Any member of the public is a
30117licensee, and is addressed as "@strong{you}".  You accept the license if you
30118copy, modify or distribute the work in a way requiring permission
30119under copyright law.
30120
30121A "@strong{Modified Version}" of the Document means any work containing the
30122Document or a portion of it, either copied verbatim, or with
30123modifications and/or translated into another language.
30124
30125A "@strong{Secondary Section}" is a named appendix or a front-matter section of
30126the Document that deals exclusively with the relationship of the
30127publishers or authors of the Document to the Document's overall subject
30128(or to related matters) and contains nothing that could fall directly
30129within that overall subject.  (Thus, if the Document is in part a
30130textbook of mathematics, a Secondary Section may not explain any
30131mathematics.)  The relationship could be a matter of historical
30132connection with the subject or with related matters, or of legal,
30133commercial, philosophical, ethical or political position regarding
30134them.
30135
30136The "@strong{Invariant Sections}" are certain Secondary Sections whose titles
30137are designated, as being those of Invariant Sections, in the notice
30138that says that the Document is released under this License.  If a
30139section does not fit the above definition of Secondary then it is not
30140allowed to be designated as Invariant.  The Document may contain zero
30141Invariant Sections.  If the Document does not identify any Invariant
30142Sections then there are none.
30143
30144The "@strong{Cover Texts}" are certain short passages of text that are listed,
30145as Front-Cover Texts or Back-Cover Texts, in the notice that says that
30146the Document is released under this License.  A Front-Cover Text may
30147be at most 5 words, and a Back-Cover Text may be at most 25 words.
30148
30149A "@strong{Transparent}" copy of the Document means a machine-readable copy,
30150represented in a format whose specification is available to the
30151general public, that is suitable for revising the document
30152straightforwardly with generic text editors or (for images composed of
30153pixels) generic paint programs or (for drawings) some widely available
30154drawing editor, and that is suitable for input to text formatters or
30155for automatic translation to a variety of formats suitable for input
30156to text formatters.  A copy made in an otherwise Transparent file
30157format whose markup, or absence of markup, has been arranged to thwart
30158or discourage subsequent modification by readers is not Transparent.
30159An image format is not Transparent if used for any substantial amount
30160of text.  A copy that is not "Transparent" is called @strong{Opaque}.
30161
30162Examples of suitable formats for Transparent copies include plain
30163ASCII without markup, Texinfo input format, LaTeX input format, SGML
30164or XML using a publicly available DTD, and standard-conforming simple
30165HTML, PostScript or PDF designed for human modification.  Examples of
30166transparent image formats include PNG, XCF and JPG.  Opaque formats
30167include proprietary formats that can be read and edited only by
30168proprietary word processors, SGML or XML for which the DTD and/or
30169processing tools are not generally available, and the
30170machine-generated HTML, PostScript or PDF produced by some word
30171processors for output purposes only.
30172
30173The "@strong{Title Page}" means, for a printed book, the title page itself,
30174plus such following pages as are needed to hold, legibly, the material
30175this License requires to appear in the title page.  For works in
30176formats which do not have any title page as such, "Title Page" means
30177the text near the most prominent appearance of the work's title,
30178preceding the beginning of the body of the text.
30179
30180The "@strong{publisher}" means any person or entity that distributes
30181copies of the Document to the public.
30182
30183A section "@strong{Entitled XYZ}" means a named subunit of the Document whose
30184title either is precisely XYZ or contains XYZ in parentheses following
30185text that translates XYZ in another language.  (Here XYZ stands for a
30186specific section name mentioned below, such as "@strong{Acknowledgements}",
30187"@strong{Dedications}", "@strong{Endorsements}", or "@strong{History}".)
30188To "@strong{Preserve the Title}"
30189of such a section when you modify the Document means that it remains a
30190section "Entitled XYZ" according to this definition.
30191
30192The Document may include Warranty Disclaimers next to the notice which
30193states that this License applies to the Document.  These Warranty
30194Disclaimers are considered to be included by reference in this
30195License, but only as regards disclaiming warranties: any other
30196implication that these Warranty Disclaimers may have is void and has
30197no effect on the meaning of this License.
30198
30199@strong{2. VERBATIM COPYING}
30200
30201You may copy and distribute the Document in any medium, either
30202commercially or noncommercially, provided that this License, the
30203copyright notices, and the license notice saying this License applies
30204to the Document are reproduced in all copies, and that you add no other
30205conditions whatsoever to those of this License.  You may not use
30206technical measures to obstruct or control the reading or further
30207copying of the copies you make or distribute.  However, you may accept
30208compensation in exchange for copies.  If you distribute a large enough
30209number of copies you must also follow the conditions in section 3.
30210
30211You may also lend copies, under the same conditions stated above, and
30212you may publicly display copies.
30213
30214@strong{3. COPYING IN QUANTITY}
30215
30216If you publish printed copies (or copies in media that commonly have
30217printed covers) of the Document, numbering more than 100, and the
30218Document's license notice requires Cover Texts, you must enclose the
30219copies in covers that carry, clearly and legibly, all these Cover
30220Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on
30221the back cover.  Both covers must also clearly and legibly identify
30222you as the publisher of these copies.  The front cover must present
30223the full title with all words of the title equally prominent and
30224visible.  You may add other material on the covers in addition.
30225Copying with changes limited to the covers, as long as they preserve
30226the title of the Document and satisfy these conditions, can be treated
30227as verbatim copying in other respects.
30228
30229If the required texts for either cover are too voluminous to fit
30230legibly, you should put the first ones listed (as many as fit
30231reasonably) on the actual cover, and continue the rest onto adjacent
30232pages.
30233
30234If you publish or distribute Opaque copies of the Document numbering
30235more than 100, you must either include a machine-readable Transparent
30236copy along with each Opaque copy, or state in or with each Opaque copy
30237a computer-network location from which the general network-using
30238public has access to download using public-standard network protocols
30239a complete Transparent copy of the Document, free of added material.
30240If you use the latter option, you must take reasonably prudent steps,
30241when you begin distribution of Opaque copies in quantity, to ensure
30242that this Transparent copy will remain thus accessible at the stated
30243location until at least one year after the last time you distribute an
30244Opaque copy (directly or through your agents or retailers) of that
30245edition to the public.
30246
30247It is requested, but not required, that you contact the authors of the
30248Document well before redistributing any large number of copies, to give
30249them a chance to provide you with an updated version of the Document.
30250
30251@strong{4. MODIFICATIONS}
30252
30253You may copy and distribute a Modified Version of the Document under
30254the conditions of sections 2 and 3 above, provided that you release
30255the Modified Version under precisely this License, with the Modified
30256Version filling the role of the Document, thus licensing distribution
30257and modification of the Modified Version to whoever possesses a copy
30258of it.  In addition, you must do these things in the Modified Version:
30259
30260
30261@enumerate A
30262
30263@item
30264Use in the Title Page (and on the covers, if any) a title distinct
30265from that of the Document, and from those of previous versions
30266(which should, if there were any, be listed in the History section
30267of the Document).  You may use the same title as a previous version
30268if the original publisher of that version gives permission.
30269
30270@item
30271List on the Title Page, as authors, one or more persons or entities
30272responsible for authorship of the modifications in the Modified
30273Version, together with at least five of the principal authors of the
30274Document (all of its principal authors, if it has fewer than five),
30275unless they release you from this requirement.
30276
30277@item
30278State on the Title page the name of the publisher of the
30279Modified Version, as the publisher.
30280
30281@item
30282Preserve all the copyright notices of the Document.
30283
30284@item
30285Add an appropriate copyright notice for your modifications
30286adjacent to the other copyright notices.
30287
30288@item
30289Include, immediately after the copyright notices, a license notice
30290giving the public permission to use the Modified Version under the
30291terms of this License, in the form shown in the Addendum below.
30292
30293@item
30294Preserve in that license notice the full lists of Invariant Sections
30295and required Cover Texts given in the Document's license notice.
30296
30297@item
30298Include an unaltered copy of this License.
30299
30300@item
30301Preserve the section Entitled "History", Preserve its Title, and add
30302to it an item stating at least the title, year, new authors, and
30303publisher of the Modified Version as given on the Title Page.  If
30304there is no section Entitled "History" in the Document, create one
30305stating the title, year, authors, and publisher of the Document as
30306given on its Title Page, then add an item describing the Modified
30307Version as stated in the previous sentence.
30308
30309@item
30310Preserve the network location, if any, given in the Document for
30311public access to a Transparent copy of the Document, and likewise
30312the network locations given in the Document for previous versions
30313it was based on.  These may be placed in the "History" section.
30314You may omit a network location for a work that was published at
30315least four years before the Document itself, or if the original
30316publisher of the version it refers to gives permission.
30317
30318@item
30319For any section Entitled "Acknowledgements" or "Dedications",
30320Preserve the Title of the section, and preserve in the section all
30321the substance and tone of each of the contributor acknowledgements
30322and/or dedications given therein.
30323
30324@item
30325Preserve all the Invariant Sections of the Document,
30326unaltered in their text and in their titles.  Section numbers
30327or the equivalent are not considered part of the section titles.
30328
30329@item
30330Delete any section Entitled "Endorsements".  Such a section
30331may not be included in the Modified Version.
30332
30333@item
30334Do not retitle any existing section to be Entitled "Endorsements"
30335or to conflict in title with any Invariant Section.
30336
30337@item
30338Preserve any Warranty Disclaimers.
30339@end enumerate
30340
30341If the Modified Version includes new front-matter sections or
30342appendices that qualify as Secondary Sections and contain no material
30343copied from the Document, you may at your option designate some or all
30344of these sections as invariant.  To do this, add their titles to the
30345list of Invariant Sections in the Modified Version's license notice.
30346These titles must be distinct from any other section titles.
30347
30348You may add a section Entitled "Endorsements", provided it contains
30349nothing but endorsements of your Modified Version by various
30350parties---for example, statements of peer review or that the text has
30351been approved by an organization as the authoritative definition of a
30352standard.
30353
30354You may add a passage of up to five words as a Front-Cover Text, and a
30355passage of up to 25 words as a Back-Cover Text, to the end of the list
30356of Cover Texts in the Modified Version.  Only one passage of
30357Front-Cover Text and one of Back-Cover Text may be added by (or
30358through arrangements made by) any one entity.  If the Document already
30359includes a cover text for the same cover, previously added by you or
30360by arrangement made by the same entity you are acting on behalf of,
30361you may not add another; but you may replace the old one, on explicit
30362permission from the previous publisher that added the old one.
30363
30364The author(s) and publisher(s) of the Document do not by this License
30365give permission to use their names for publicity for or to assert or
30366imply endorsement of any Modified Version.
30367
30368@strong{5. COMBINING DOCUMENTS}
30369
30370You may combine the Document with other documents released under this
30371License, under the terms defined in section 4 above for modified
30372versions, provided that you include in the combination all of the
30373Invariant Sections of all of the original documents, unmodified, and
30374list them all as Invariant Sections of your combined work in its
30375license notice, and that you preserve all their Warranty Disclaimers.
30376
30377The combined work need only contain one copy of this License, and
30378multiple identical Invariant Sections may be replaced with a single
30379copy.  If there are multiple Invariant Sections with the same name but
30380different contents, make the title of each such section unique by
30381adding at the end of it, in parentheses, the name of the original
30382author or publisher of that section if known, or else a unique number.
30383Make the same adjustment to the section titles in the list of
30384Invariant Sections in the license notice of the combined work.
30385
30386In the combination, you must combine any sections Entitled "History"
30387in the various original documents, forming one section Entitled
30388"History"; likewise combine any sections Entitled "Acknowledgements",
30389and any sections Entitled "Dedications".  You must delete all sections
30390Entitled "Endorsements".
30391
30392@strong{6. COLLECTIONS OF DOCUMENTS}
30393
30394You may make a collection consisting of the Document and other documents
30395released under this License, and replace the individual copies of this
30396License in the various documents with a single copy that is included in
30397the collection, provided that you follow the rules of this License for
30398verbatim copying of each of the documents in all other respects.
30399
30400You may extract a single document from such a collection, and distribute
30401it individually under this License, provided you insert a copy of this
30402License into the extracted document, and follow this License in all
30403other respects regarding verbatim copying of that document.
30404
30405@strong{7. AGGREGATION WITH INDEPENDENT WORKS}
30406
30407A compilation of the Document or its derivatives with other separate
30408and independent documents or works, in or on a volume of a storage or
30409distribution medium, is called an "aggregate" if the copyright
30410resulting from the compilation is not used to limit the legal rights
30411of the compilation's users beyond what the individual works permit.
30412When the Document is included in an aggregate, this License does not
30413apply to the other works in the aggregate which are not themselves
30414derivative works of the Document.
30415
30416If the Cover Text requirement of section 3 is applicable to these
30417copies of the Document, then if the Document is less than one half of
30418the entire aggregate, the Document's Cover Texts may be placed on
30419covers that bracket the Document within the aggregate, or the
30420electronic equivalent of covers if the Document is in electronic form.
30421Otherwise they must appear on printed covers that bracket the whole
30422aggregate.
30423
30424@strong{8. TRANSLATION}
30425
30426Translation is considered a kind of modification, so you may
30427distribute translations of the Document under the terms of section 4.
30428Replacing Invariant Sections with translations requires special
30429permission from their copyright holders, but you may include
30430translations of some or all Invariant Sections in addition to the
30431original versions of these Invariant Sections.  You may include a
30432translation of this License, and all the license notices in the
30433Document, and any Warranty Disclaimers, provided that you also include
30434the original English version of this License and the original versions
30435of those notices and disclaimers.  In case of a disagreement between
30436the translation and the original version of this License or a notice
30437or disclaimer, the original version will prevail.
30438
30439If a section in the Document is Entitled "Acknowledgements",
30440"Dedications", or "History", the requirement (section 4) to Preserve
30441its Title (section 1) will typically require changing the actual
30442title.
30443
30444@strong{9. TERMINATION}
30445
30446You may not copy, modify, sublicense, or distribute the Document
30447except as expressly provided under this License.  Any attempt
30448otherwise to copy, modify, sublicense, or distribute it is void, and
30449will automatically terminate your rights under this License.
30450
30451However, if you cease all violation of this License, then your license
30452from a particular copyright holder is reinstated (a) provisionally,
30453unless and until the copyright holder explicitly and finally
30454terminates your license, and (b) permanently, if the copyright holder
30455fails to notify you of the violation by some reasonable means prior to
3045660 days after the cessation.
30457
30458Moreover, your license from a particular copyright holder is
30459reinstated permanently if the copyright holder notifies you of the
30460violation by some reasonable means, this is the first time you have
30461received notice of violation of this License (for any work) from that
30462copyright holder, and you cure the violation prior to 30 days after
30463your receipt of the notice.
30464
30465Termination of your rights under this section does not terminate the
30466licenses of parties who have received copies or rights from you under
30467this License.  If your rights have been terminated and not permanently
30468reinstated, receipt of a copy of some or all of the same material does
30469not give you any rights to use it.
30470
30471@strong{10. FUTURE REVISIONS OF THIS LICENSE}
30472
30473The Free Software Foundation may publish new, revised versions
30474of the GNU Free Documentation License from time to time.  Such new
30475versions will be similar in spirit to the present version, but may
30476differ in detail to address new problems or concerns.  See
30477@indicateurl{http://www.gnu.org/copyleft/}.
30478
30479Each version of the License is given a distinguishing version number.
30480If the Document specifies that a particular numbered version of this
30481License "or any later version" applies to it, you have the option of
30482following the terms and conditions either of that specified version or
30483of any later version that has been published (not as a draft) by the
30484Free Software Foundation.  If the Document does not specify a version
30485number of this License, you may choose any version ever published (not
30486as a draft) by the Free Software Foundation.  If the Document
30487specifies that a proxy can decide which future versions of this
30488License can be used, that proxy's public statement of acceptance of a
30489version permanently authorizes you to choose that version for the
30490Document.
30491
30492@strong{11. RELICENSING}
30493
30494"Massive Multiauthor Collaboration Site" (or "MMC Site") means any
30495World Wide Web server that publishes copyrightable works and also
30496provides prominent facilities for anybody to edit those works.  A
30497public wiki that anybody can edit is an example of such a server.  A
30498"Massive Multiauthor Collaboration" (or "MMC") contained in the
30499site means any set of copyrightable works thus published on the MMC
30500site.
30501
30502"CC-BY-SA" means the Creative Commons Attribution-Share Alike 3.0
30503license published by Creative Commons Corporation, a not-for-profit
30504corporation with a principal place of business in San Francisco,
30505California, as well as future copyleft versions of that license
30506published by that same organization.
30507
30508"Incorporate" means to publish or republish a Document, in whole or
30509in part, as part of another Document.
30510
30511An MMC is "eligible for relicensing" if it is licensed under this
30512License, and if all works that were first published under this License
30513somewhere other than this MMC, and subsequently incorporated in whole
30514or in part into the MMC, (1) had no cover texts or invariant sections,
30515and (2) were thus incorporated prior to November 1, 2008.
30516
30517The operator of an MMC Site may republish an MMC contained in the site
30518under CC-BY-SA on the same site at any time before August 1, 2009,
30519provided the MMC is eligible for relicensing.
30520
30521@strong{ADDENDUM: How to use this License for your documents}
30522
30523To use this License in a document you have written, include a copy of
30524the License in the document and put the following copyright and
30525license notices just after the title page:
30526
30527@quotation
30528
30529Copyright © YEAR  YOUR NAME.
30530Permission is granted to copy, distribute and/or modify this document
30531under the terms of the GNU Free Documentation License, Version 1.3
30532or any later version published by the Free Software Foundation;
30533with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
30534A copy of the license is included in the section entitled "GNU
30535Free Documentation License".
30536@end quotation
30537
30538If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts,
30539replace the "with ... Texts." line with this:
30540
30541@quotation
30542
30543with the Invariant Sections being LIST THEIR TITLES, with the
30544Front-Cover Texts being LIST, and with the Back-Cover Texts being LIST.
30545@end quotation
30546
30547If you have Invariant Sections without Cover Texts, or some other
30548combination of the three, merge those two alternatives to suit the
30549situation.
30550
30551If your document contains nontrivial examples of program code, we
30552recommend releasing these examples in parallel under your choice of
30553free software license, such as the GNU General Public License,
30554to permit their use in free software.
30555
30556@node Index,,GNU Free Documentation License,Top
30557@unnumbered Index
30558
30559
30560@printindex ge
30561
30562@anchor{de}@w{                              }
30563@anchor{gnat_ugn/gnat_utility_programs switches-related-to-project-files}@w{                              }
30564
30565@c %**end of body
30566@bye
30567